var $j = jQuery;
$j(document).ready(function () {
	setTimeout(initOverLabels, 50); //setTimeout is used to prevent labels from covering saved input values
	$j("table.stripe tr:odd").addClass("alt");
	generateSprites("#home #upper-content .col1 .buttons", "current-", 250);
	generateSprites("#home #lower-content .button-grid ul", "current-", 400);
	generateSprites("#main-nav ul", "current-", 450);
	helpPopups();
	targetBlank();
	productImgGallery();
	initPrintLink();
	openTrackingFormInNewWindow();
	updateSettings();
	handle_attachment_links();
});

function updateSettings(){
  $j("#insurance_charge").blur(function(){
    $j(this).parents('form').submit();
  })
}


function handle_attachment_links(){
  $j('a.add_attachment').live('click', function(){
    $j(this).parents('tr').after("<tr><td class='label'>Attach a file</td><td><input type='file' name='attachments[]' /></td><td><a href='#' class='remove_attachment'>Remove</a></td></tr><tr><td colspan='3'><a href='#' class='add_attachment'>Attach another file</a></td></tr>");
    return false;
  });

  $j('a.remove_attachment').live('click', function(){
    $j(this).parents('tr').next().remove();
    $j(this).parents('tr').remove();
    return false;
  });
}

function updateCategory(category_id){
	document.getElementById("category_id").value = category_id;
}

/* BEGIN css sprites 2 nav behavior
http://www.alistapart.com/articles/sprites2
=========================== */
function generateSprites(parent, selectedPrefix, hoverSpeed) {
	// throw the parent object's class into a variable
	var parentClass = $j(parent).attr("class");
	// start a loop that cycles through each of the li elements inside the parent element
	$j(parent).children("li").each(function() {
		// create a few variables that we'll need during this function:
		// myClass = the class of the object we're currently inspecting
		// current = what the selected class should look like for the parent of the object we're currently inspecting
		var myClass = ($j(this).attr("class"))
		var current = parent.substring(1) + " current-" + ($j(this).attr("class"));
		// turn on nav events for element this loop identifies
		attachNavEvents(parent, myClass, hoverSpeed);
		// let's hide the CSS-defined background image, but only if this isn't the currently-selected item
		if (parentClass != current) {
			if($j(this).children("a").hasClass('active')) {
				//
			}
			else {
				$j(this).children("a").css({backgroundImage:"none"});
			}
		}
	});
}
function attachNavEvents(parent, myClass, hoverSpeed) {
	$j(parent + " ." + myClass).mouseover(function() {
		// create pseudo-link
		$j(this).append('<div class="nav-' + myClass + '"></div>');
		// fade in the pseudo-link
		$j("div.nav-" + myClass).css({display:"none"}).fadeIn(hoverSpeed);
	}).mouseout(function() {
		// fade out & destroy pseudo-link
		$j("div.nav-" + myClass).fadeOut(hoverSpeed, function() {
			$j(this).remove();
		});
	});
}
/* END css sprites 2
=========================== */

/* BEGIN labels over inputs
=========================== */
function initOverLabels () {
	if (!document.getElementById) return;
	var labels, id, field;
	// Set focus and blur handlers to hide and show
	// LABELs with 'overlabel' class names.
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		if (labels[i].className == 'overlabel') {
			// Skip labels that do not have a named association with another field.
			id = labels[i].htmlFor || labels[i].getAttribute('for');
			if (!id || !(field = document.getElementById(id))) {
				continue;
			}
			// Change the applied class to hover the label
			// over the form field.
			labels[i].className = 'overlabel-apply';
			// Hide any fields having an initial value.
			if (field.value !== '') {
				hideLabel(field.getAttribute('id'), true);
			}
			// Set handlers to show and hide labels.
			field.onfocus = function () {
				hideLabel(this.getAttribute('id'), true);
			};
			field.onblur = function () {
				if (this.value === '') {
					hideLabel(this.getAttribute('id'), false);
				}
			};
			// Handle clicks to LABEL elements (for Safari).
			labels[i].onclick = function () {
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id))) {
					field.focus();
				}
			};
		}
	}
};
function hideLabel(field_id, hide) {
	var field_for;
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		field_for = labels[i].htmlFor || labels[i].getAttribute('for');
		if (field_for == field_id) {
			labels[i].style.left = (hide) ? '-32767px' : '4px';
			return true;
		}
	}
}
/* END labels over inputs
=========================== */

function equalHeight(group) {
	// http://www.cssnewbie.com/example/equal-heights/
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

function helpPopups() {
	$j("span.help_content").addClass("help_content_with_script");
	$j("span.help").css({
		display:"inline-block"
	});
	var containerDiv = document.getElementById("content");
	if (containerDiv) {
		var spanList = containerDiv.getElementsByTagName("span");
		var closeButton = $j("<span><b>Close</b></span>").prependTo("span.help_content");
		$j("span.help_content span").addClass("close_button");
		$j("span.help_content span.close_button b").click(function() {
			this.parentNode.parentNode.style.display = "none";
			showIE6Selects();
		});
		for(var i=0;i<spanList.length;i++) {
			if (spanList[i].className == "help") {
				spanList[i].onclick = function() {
					var helpContentSpan = this.nextSibling.nextSibling;
					helpContentSpan.style.display = "block";
					//Hide selects from IE
					$j("select").addClass("hide_from_ie6");
				}
			}
		}
		$j("body").click(function(e) {
			var obj;
			if(window.event) {
				var e = window.event;
				obj = e.srcElement;
			}
			else {
				e = e;
				obj = e.target;
			}
			if((obj.nodeName == "DIV") || (obj.nodeName == "BODY")) {
				$j("span.help_content").css("display","none");
				showIE6Selects();
			}
		});
		function showIE6Selects() {
			//Show hidden selects in IE
			$j("select").removeClass("hide_from_ie6");
		}
	}
}

function targetBlank() {
	$j('a[rel="external"]').click( function() {
		window.open( $(this).attr('href') );
		return false;
	});
}

function productImgGallery() {
	// Add active class to the first thumb image
	$j('#product-image-thumbs ul img:first').addClass('active');
	$j('#product-image-thumbs ul a').click( function(e) {
		// Get the image that was clicked on
		var thumbImg = $j(e.target);
		// Clear all active classes
		$j('#product-image-thumbs ul img').removeClass('active');
		// Add active class to clicked image
		thumbImg.addClass('active');
		// Set the large image path to the href of the anchor
		$j('#full-product-image img')[0].src = thumbImg.parent()[0].href;
		return false;
	});
}

function initPrintLink() {
	var printLinkText = 'Print';
	var printLinkHtml = '<p class="print"><a href="#">' + printLinkText + '</a></p>';
	var checkoutReceiptContainer = $j('#content .confirm-receipt .shipping-billing-info');
	$j('#breadcrumbs').append(printLinkHtml);
	if (checkoutReceiptContainer) {
		var printReceiptLinkText = 'Print this page';
		var printReceiptLinkHtml = '<p class="print"><a href="#">' + printReceiptLinkText + '</a></p>';
		checkoutReceiptContainer.prepend(printReceiptLinkHtml);
	}
	$j('p.print a').click(function () {
		window.print();
		return false;
	});
}

function openTrackingFormInNewWindow() {
	var submitAnchor = $j('form.track a.button');
	var submitInput = $j('form.track input.button');
	submitInput.addClass('none');
	submitAnchor.removeClass('none');
	submitAnchor.addClass('block');
	submitAnchor.click(function () {
		var trackingNumberVal = $j('#tracking-number').val();
		if(trackingNumberVal) {
			window.open('http://fedex.com/Tracking?cntry_code=us&language=english&tracknumber_list=' + trackingNumberVal);
		}
	});
}

/* Shared Hide/Show stuff on areas with saved addresses and billing methods */
function hideContainer(hiddenContainerId) {
	hiddenContainerId.hide();
	clearInputValues(hiddenContainerId);
}
function slideContainerUp(slideUpContainerId) {
	slideUpContainerId.slideUp(500);
	clearInputValues(slideUpContainerId);
}
function slideContainerDown(slideDownContainerId) {
	slideDownContainerId.slideDown(500);
}

function clearInputValues(clearedHiddenContainer) {
	if(clearedHiddenContainer[0]) {
		var inputList = clearedHiddenContainer[0].getElementsByTagName('input');
		var selectList = clearedHiddenContainer[0].getElementsByTagName('select');
		for (var i = 0; i < inputList.length; i++) {
			if (inputList[i].type != 'checkbox' && inputList[i].type != 'hidden'){
				inputList[i].value = '';
			}
		}
		for (var j = 0; j < selectList.length; j++) {
			selectList[j].value = '';
		}
	}
}

/* Admin
================================== */
$j(document).ready(function () {
	$j('#content .product-list li:nth-child(5n)').addClass('first');
});


