/**
 * This adds a trim() method to the global javascript String object
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
};

// this adds a handy console logger for all browsers...except IE, but this won't barf in IE.
function log(message){
	if(typeof(window["console"]) != "undefined"){
		if(console.log){
			console.log(message);
		}
	}
}

function showErrorMessage(msg) {
	// Could not determine the source of this IE7 bug.  Thanks, Microsoft.
	// Therefore, IE people get an ugly alert box instead of a pretty facebox.
	if ($.browser.msie) {
		alert(msg);
	} else {
		facebox_error(msg);
	}
}

function showInfoMessage(msg) {
	facebox_info(msg);
}

function facebox_error(msg) {
	var html = '\
	<table> \
		<tr> \
			<td><img src="/img/48/stock_dialog-error.png" style="width: 48px; height: 48px" alt="error"/></td> \
			<td>' + msg + '</td> \
		</tr> \
	</table>';
	$.facebox(html);
}

function facebox_info(msg) {
	var html = '\
	<table> \
		<tr> \
			<td style="padding: 5px"><img src="/img/24/about_24x24.png" style="width: 24px; height: 24px" alt="information"/></td> \
			<td>' + msg + '</td> \
		</tr> \
	</table>';
	$.facebox(html);
}

function displayExceptionTag() {
	$("#exception").each(function(i) {
		$.facebox($(this).html());
	});
}

function showVideo(name) {
	window.open('/Video.action?name=' + name, 'Video_Tutorial', 'width=1024,height=618,resizeable=yes,scrollbars=no,location=no,directories=no,status=no,menubar=no,copyhistory=no');
}

//var artWindowOptions = 'width=800,height=600,location=no,menubar=no,status=no,toolbar=no';
var artWindowOptions = 'fullscreen=yes';

function showTitleArt(titleId) {
	$.facebox(function() {
		$.get('/Art.action', {titleId: titleId}, function(data) {
			$.facebox(data)
		})
	})
}

function showProductArt(productId, repackaged) {
	$.facebox(function() {
		$.get('/Art.action', {productId: productId, repackaged: repackaged}, function(data) {
			$.facebox(data)
		})
	})
}

function showRatingsForTitle(titleId) {
	$.facebox(function() {
		$.get("/Ratings.action", {showRatingsForTitle: true, titleId: titleId}, function(html) {
			$.facebox(html, "ratingDialog")
		})
	})
}

// this function should eventually replace
function showSwitchCartDialog(title) {
	if(title === undefined) title = "Switch Cart"
	$.get("/cart/switch", {}, function(data, textStatus) {
		$('<div id="switchCartDialog">').append(data).dialog({
			modal: true,
			title: title,
			width: 500,
			height: 500,
			bgiframe: true,
			resizable: true,
			close: function(event, ui) {
				$(this).remove();
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		});
	});
}

function startPinger() {
	window.setInterval(ping, 1800000);
}

function ping() {
   $.ajax({type: "GET", url: "/img/ping-me.gif?" + new Date().getTime()});
}

if (typeof(MessageFormat) == 'undefined') {
	MessageFormat = new Object();
	MessageFormat.format = function(s) {
		var i = 1;
		while (i < arguments.length) s = s.replace("{" + (i - 1) + "}", arguments[i++]);
		return s;
	}
}

function checkQty(textbox) {
	var inputValue = $(textbox).val();
	var newValue = Math.abs(inputValue);
	if (isNaN(newValue)) {
		$(textbox).val("");
	} else {
		$(textbox).val(newValue);
		if (newValue > 1000) {
			alert('\
WARNING:  You are \
ordering more than 1000 copies of one title.\n\n \
Your order will still be processed with this quantity, \
but this warning is simply to prevent accidental large orders.\n\n \
If you have questions, please contact customer service \
for assistance.');
		}
	}
}

var tooltipOptions = {
	ajaxCache:false,
	// trigger: ['mouseover','blur'],
	trigger: 'hover',
	closeWhenOthersOpen: true,
	fill: '#FFF',
	width: '450px',
	shrinkToFit:true,
	cornerRadius: 10,
	strokeWidth: 0,
	shadow: true,
	shadowOffsetX: 3,
	shadowOffsetY: 3,
	shadowBlur: 8,
	shadowColor: 'rgba(0,0,0,.9)',
	shadowOverlap: false,
	noShadowOpts: {strokeStyle: '#999', strokeWidth: 2},
	positions: ['right', 'top', 'most']
};

var messageTooltipOptions = {
	ajaxCache:false,
	// trigger: ['mouseover','blur'],
	trigger: 'hover',
	closeWhenOthersOpen: true,
	fill: '#FFF',
	width: '450px',
	shrinkToFit:true,
	cornerRadius: 10,
	strokeWidth: 0,
	shadow: true,
	shadowOffsetX: 3,
	shadowOffsetY: 3,
	shadowBlur: 8,
	shadowColor: 'rgba(0,0,0,.9)',
	shadowOverlap: false,
	noShadowOpts: {strokeStyle: '#999', strokeWidth: 2},
	positions: ['right', 'top', 'most']
};

function appendProductCheckSymbols(element, productId, productCheck) {
	if ((productCheck.userCarts > 0) && (productCheck.otherCarts > 0)) {
		$("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product is already in one of your carts, and another user's cart, too.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/combocartcheck.png")
						.attr("alt", "cart alert")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?bothCarts=&productId=' + productId}))
				).appendTo(element);
	} else if (productCheck.userCarts > 0) {
		$("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product is already in one of your carts.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/usercartcheck.png")
						.attr("alt", "cart alert")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?userCarts=&productId=' + productId}))
				).appendTo(element);
	} else if (productCheck.otherCarts > 0) {
		var a = $("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product is in another user's cart.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/customercartcheck.png")
						.attr("alt", "cart alert")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?otherCarts=&productId=' + productId}))
				).appendTo(element);
	}

	if (productCheck.catalogs > 0) {
		$("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product is in a custom catalog.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/catalogCheck.gif")
						.attr("alt", "catalog alert")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?catalogs=&productId=' + productId}))
				).appendTo(element);
	}

	if (productCheck.userOrders > 0) {
		$("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product is in a custom catalog.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/userpreviouspurchase.png")
						.attr("alt", "purchase alert")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?userOrders=&productId=' + productId}))
				).appendTo(element);
	} else if (productCheck.otherOrders > 0) {
		$("<a>")
				.attr("href", "/PurchaseHistory?productId=" + productId)
				.attr("target", "PurchaseHistory")
			//.attr("title", "This product was previously purchased by another account.  Click for details.")
				.append(
				$("<img>")
						.addClass("icon16")
						.attr("src", "/img/16/customerpreviouspurchase.png")
						.attr("alt", "previously purchased")
						.bt(jQuery.extend(tooltipOptions, {ajaxPath: '/PurchaseHistory?otherOrders=&productId=' + productId}))
				).appendTo(element);
	}

}

$(document).ready(function() {
	var alertsDiv = $("#systemAlerts");
	if(alertsDiv.length > 0) {
		$("div", alertsDiv).each(function () {
			var alert = $(this);
			alert.dialog({
				modal: true,
				buttons: { "Ok": function() { $(this).dialog("close"); } },
				close: function() {
					//Ajax call to record the confirmation
					$.post("/system/alerts", { recordConfirmation: "", alertId: alert.attr("id")});
				}
			});
		});
	}
});

$(document).ready(function() {
	$("span.message").each(function (i) {
		$(this).bt($(this).attr("title"), messageTooltipOptions);
	});
});
