var idgw = null;

function IdgWidget() {

	this.isbns = null;
	this.isbnArray = null;
	this.currIsbn = -1;

	this.backgroundColors = null;
	this.bgColorArray = null;
	this.currBgColor = -1;
	
	this.fontColors = null;
	this.fontColorArray = null;
	this.currFontColor = -1;
	
	this.isbnDelay = 5000;
	this.loadCtr = 0;
	this.loadErrorCtr = 0;

	this.widgetDiv = document.getElementById("idgWidgetDiv");
	this.widgetTable = document.getElementById("idgWidgetTable");

	this.codeDiv = document.getElementById("idgCodeDiv");
	this.codeSnippet = document.getElementById("idgCodeSnippet");
	this.copyInst = document.getElementById("idgCopyInst");
	
	this.coverImg = document.getElementById("idgCoverImg");

	this.addCell = document.getElementById("idgAddCell");
	this.emailCell = document.getElementById("idgEmailCell");
	this.buyCell = document.getElementById("idgBuyCell");
	this.readCell = document.getElementById("idgReadCell");

	this.emailLink = document.getElementById("idgEmailLink");
	this.emailLinkText = document.getElementById("idgEmailLinkText");
	this.emailSendLink = document.getElementById("idgEmailSendLink");
	this.emailSendLinkText = document.getElementById("idgEmailSendLinkText");
	this.buyLink = document.getElementById("idgBuyLink");
	this.buyLinkText = document.getElementById("idgBuyLinkText");
	this.readLink = document.getElementById("idgReadLink");
	this.readLinkText = document.getElementById("idgReadLinkText");
	this.addLink = document.getElementById("idgAddLink");
	this.addLinkText = document.getElementById("idgAddLinkText");

	this.emailFrame = document.getElementById("idgEmailFrame");
	this.emailButtonRow = document.getElementById("idgEmailButtonRow");
	this.buyReadRow = document.getElementById("idgBuyReadRow");
	this.emailFormRow = document.getElementById("idgEmailFormRow");
	this.toEmailAddress = document.getElementById("idgToEmailAddress");
	this.fromEmailAddress = document.getElementById("idgFromEmailAddress");
}

function IdgInitWidget(domainName, cpid, isbns, fontColors, fontFamily, backgroundColors, width, showButtons, delay) {

	if (showButtons == null) {
		showButtons = "ab";
	}
	
	IdgInitWidgetCode("idgWidgetHtml", domainName, cpid, fontFamily, width, showButtons);
	IdgInitWidgetCode("idgWidgetCode", domainName, cpid, fontFamily, width, showButtons);
	IdgInitWidgetCode("idgGetPageUrl", domainName, cpid, fontFamily, width, showButtons);
	IdgInitWidgetCode("idgEmailUrl", domainName, cpid, fontFamily, width, showButtons);
	IdgInitWidgetCode("idgBuyLinkUrl", domainName, cpid, fontFamily, width, showButtons);
	IdgInitWidgetCode("idgReadLinkUrl", domainName, cpid, fontFamily, width, showButtons);
	
	document.getElementById("idgWidgetDiv").innerHTML = idgWidgetHtml;

	idgw = new IdgWidget();
		
	idgw.widgetDiv.style.width = (width + 6) + "px";
	idgw.widgetDiv.style.fontFamily = fontFamily;

	if (delay) {
		idgw.isbnDelay = delay;
	}

	idgw.toEmailAddress.style.width = ((width - 10) + "px");
	idgw.fromEmailAddress.style.width = ((width - 63) + "px");
	
	idgw.isbns = isbns;
	idgw.isbnArray = isbns.split(",");
	
	idgw.fontColors = fontColors;
	idgw.fontColorArray = fontColors.split(",");
	
	idgw.backgroundColors = backgroundColors;
	idgw.bgColorArray = backgroundColors.split(",");
	
	if (idgw.isbnArray.length > 1) {
		idgw.coverImg.style.cursor = "pointer";
	}
	
	IdgLoadNextIsbn();
}

function IdgLoadNextIsbn(ctr) {

	if (!ctr || (ctr == idgw.loadCtr)) {
		if (idgw.codeDiv.style.display == 'none' && idgw.emailFormRow.style.display == 'none') {
			idgw.currIsbn++;
			
			if (idgw.currIsbn == idgw.isbnArray.length) {
				idgw.currIsbn = 0;
			}
			
			idgw.coverImg.src = idgGetPageUrl.replace(/{ISBN}/g, idgw.isbnArray[idgw.currIsbn]);
		}
	}	
}

function IdgHandleLoadError() {

	
	var isbnInError = idgw.currIsbn;
	
	idgw.loadErrorCtr++;
	
	if (idgw.loadErrorCtr < (idgw.isbnArray.length * 3)) {
		IdgLoadNextIsbn();
	}
	else {
		idgw.widgetDiv.style.visibility = 'none';
		throw new Error("Unable to load cover images.");
	}
}

function IdgInitWidgetCode(widgetCode, domainName, cpid, fontFamily, width, showButtons) {

	var fontSize = "8pt";
	
	if (width < 145) {
		fontSize = "5.5pt";
	}
	else if (width < 170) {
		fontSize = "6pt";
	}

	var showAddButton   = showButtons.indexOf("a") > -1;
	var showEmailButton = showButtons.indexOf("e") > -1;
	var showBuyButton   = showButtons.indexOf("b") > -1;
	
	eval(widgetCode + " = " + widgetCode + ".replace(/{ADDBUTTON}/g, " + (showAddButton ? "idgWidgetAddButton" : "\"\"") + ");");
	eval(widgetCode + " = " + widgetCode + ".replace(/{EMAILBUTTON}/g, " + (showEmailButton ? "idgWidgetEmailButton" : "\"\"") + ");");
	eval(widgetCode + " = " + widgetCode + ".replace(/{BUYBUTTON}/g, " + (showBuyButton ? "idgWidgetBuyButton" : "\"\"") + ");");
		
	eval(widgetCode + " = " + widgetCode + ".replace(/{BUTTONDIVIDER1}/g, " + (showAddButton && showEmailButton ? "idgWidgetButtonDivider" : "\"\"") + ");");
	eval(widgetCode + " = " + widgetCode + ".replace(/{BUTTONDIVIDER2}/g, " + (showBuyButton ? "idgWidgetButtonDivider" : "\"\"") + ");");
		
	eval(widgetCode + " = " + widgetCode + ".replace(/{DOMAINNAME}/g, domainName);");
	eval(widgetCode + " = " + widgetCode + ".replace(/{WIDGETID}/g, cpid);");
	eval(widgetCode + " = " + widgetCode + ".replace(/{WIDTH}/g, width);");
	eval(widgetCode + " = " + widgetCode + ".replace(/{FONTSIZE}/g, fontSize);");
	eval(widgetCode + " = " + widgetCode + ".replace(/{FONTFAMILY}/g, fontFamily);");
	eval(widgetCode + " = " + widgetCode + ".replace(/{SHOWBUTTONS}/g, showButtons);");
}

function IdgShowWidget() {

	idgw.currBgColor++;
	
	if (idgw.currBgColor >= idgw.bgColorArray.length) {
		idgw.currBgColor = 0;
	}
	
	idgw.widgetTable.style.backgroundColor = idgw.bgColorArray[idgw.currBgColor];
	
	idgw.currFontColor++;
	
	if (idgw.currFontColor >= idgw.fontColorArray.length) {
		idgw.currFontColor = 0;
	}
	
	if (idgw.addLink) {
		idgw.addLink.style.color = idgw.fontColorArray[idgw.currFontColor];
	}

	if (idgw.emailLink) {
		idgw.emailLink.style.color = idgw.fontColorArray[idgw.currFontColor];
	}

	if (idgw.emailSendLink) {
		idgw.emailSendLink.style.color = idgw.fontColorArray[idgw.currFontColor];
	}

	if (idgw.buyLink) {
		idgw.buyLink.style.color = idgw.fontColorArray[idgw.currFontColor];
		idgw.buyLink.href = idgBuyLinkUrl.replace(/{ISBN}/g, idgw.isbnArray[idgw.currIsbn]);
	}
	
	idgw.readLink.style.color = idgw.fontColorArray[idgw.currFontColor];
	idgw.readLink.href = idgReadLinkUrl.replace(/{ISBN}/g, idgw.isbnArray[idgw.currIsbn]).replace(/{BGCOLOR}/g, escape(idgw.bgColorArray[idgw.currBgColor]));

	idgw.widgetDiv.style.visibility = 'visible';
	
	idgw.codeDiv.style.width = (idgw.coverImg.width - 3) + "px";
	idgw.codeDiv.style.height = (idgw.coverImg.height - 3) + "px";
	
	idgw.coverImg.style.width = idgw.coverImg.width + "px";
	idgw.coverImg.style.height = idgw.coverImg.height + "px";

	var longButtonWidth = idgw.coverImg.width - 12;
	var shortButtonWidth = (idgw.coverImg.width - 24) / 2;

	if (!idgw.addCell && !idgw.emailCell) {
		idgw.emailButtonRow.style.display = "none";
	}
	else if (idgw.addCell && idgw.emailCell) {
		idgw.emailCell.style.width = shortButtonWidth + "px";
		idgw.addCell.style.width = shortButtonWidth + "px";
	}
	else if (idgw.addCell) {
		idgw.addCell.style.width = longButtonWidth + "px";
	}
	else {
		idgw.emailCell.style.width = longButtonWidth + "px";
	}

	if (idgw.buyCell) {
		idgw.buyCell.style.width = shortButtonWidth + "px";
		idgw.readCell.style.width = shortButtonWidth + "px";
	}
	else {
		idgw.readCell.style.width = longButtonWidth + "px";
	}
	
	var codeSnippet = idgWidgetCode.replace(/{ISBN}/g, idgw.isbnArray[idgw.currIsbn]);
	codeSnippet = codeSnippet.replace(/{BGCOLOR}/g, idgw.bgColorArray[idgw.currBgColor]);
	codeSnippet = codeSnippet.replace(/{FONTCOLOR}/g, idgw.fontColorArray[idgw.currFontColor]);

	idgw.codeSnippet.value = codeSnippet; 
	idgw.loadErrorCtr = 0;

	if (idgw.isbnArray.length > 1) {
		idgw.loadCtr++;
		setTimeout("IdgLoadNextIsbn(" + idgw.loadCtr + ");", idgw.isbnDelay);
	}
}

function IdgToggleCode() {

	idgw.loadCtr++;
	
	if (idgw.codeDiv.style.display == 'none') {
		var width = idgw.coverImg.width;
		var height = idgw.coverImg.height;
		
		idgw.coverImg.style.display = "none";
		idgw.codeDiv.style.display = "block";

		idgw.codeSnippet.style.width = (width - 8) + "px";
		idgw.codeSnippet.style.height = (height - (idgw.codeSnippet.offsetTop - idgw.copyInst.offsetTop) - 8) + "px";
		idgw.addLinkText.innerHTML = "Show cover";
	}
	else {
		idgw.codeDiv.style.display = "none";
		idgw.coverImg.style.display = "block";
		idgw.addLinkText.innerHTML = "Add to site";

		setTimeout("IdgLoadNextIsbn(" + idgw.loadCtr + ");", idgw.isbnDelay);
	}
}

function IdgToggleEmail(show) {

	idgw.loadCtr++;
	
	if (show) {
		idgw.emailButtonRow.style.display = "none";
		idgw.buyReadRow.style.display = "none";
		idgw.emailFormRow.style.display = "";
			
		idgw.toEmailAddress.select();
		idgw.toEmailAddress.focus();
	}
	else {
		idgw.emailFormRow.style.display = "none";
		idgw.emailButtonRow.style.display = "";
		idgw.buyReadRow.style.display = "";

		idgw.toEmailAddress.value = "To Address";
		idgw.toEmailAddress.style.color = "";

		idgw.fromEmailAddress.style.color = "";

		setTimeout("IdgLoadNextIsbn(" + idgw.loadCtr + ");", idgw.isbnDelay);
	}
}

function IdgSendEmail(event, addressBox) {

	if (!event || (event.keyCode == 13)) {
		if (addressBox && addressBox.id == "idgToEmailAddress") {
			idgw.fromEmailAddress.focus();
			idgw.fromEmailAddress.select();
		}
		else { 
			var validToAddress = idgValidateAddress(idgw.toEmailAddress.value, true);
			var validFromAddress = idgValidateAddress(idgw.fromEmailAddress.value, false);
	
			if (validToAddress) {
				var url = idgEmailUrl.replace(/TO/g, idgw.toEmailAddress.value.replace(/,/g, ";"));
				url = url.replace(/{ISBN}/g, idgw.isbnArray[idgw.currIsbn]).replace(/{BGCOLOR}/g, idgw.bgColorArray[idgw.currBgColor]);
				
				if (validFromAddress) {
					url = url.replace(/FROM/g, idgw.fromEmailAddress.value);
				}
				else {
					url = url.replace(/FROM/g, "");
				}
	
				if (validFromAddress || idgw.fromEmailAddress.value == "From Address" || idgw.fromEmailAddress.value == "") {
					idgw.emailFrame.src = url; 
					
					setTimeout("IdgToggleEmail(false);", 1000);
	
					idgw.toEmailAddress.value = "SENDING EMAIL";
				}
				else {
					setTimeout("idgEmailError('" + idgw.toEmailAddress.value + "', '" + idgw.fromEmailAddress.value + "', false);", 1000);
					idgw.fromEmailAddress.style.color = "red";
					idgw.fromEmailAddress.value = "INVALID ADDRESS";
				}
			}
			else if ((idgw.toEmailAddress.value == "") || (idgw.toEmailAddress.value == "To Address")) {
				IdgToggleEmail(false);
			}
			else {
				setTimeout("idgEmailError('" + idgw.toEmailAddress.value + "', '" + idgw.fromEmailAddress.value + "', true);", 1000);
				idgw.toEmailAddress.style.color = "red";
				idgw.toEmailAddress.value = "INVALID ADDRESS";
			}
		}
	}
}

function idgValidateAddress(addresses, allowMulti) {

	var valid = true;
	
	if (addresses != null) {
		addresses = addresses.replace(/,/g, ";");
		
		var addressArray = addresses.split(";");

		if ((addressArray.length <= 1) || allowMulti) {
			var emailRegExp = new RegExp("^[a-zA-Z0-9]+(([.][a-zA-Z0-9]+)*|[a-zA-Z0-9]*)@.+[.][a-zA-Z0-9]+$");
			
			for (var i = 0; i < addressArray.length && valid; i++) {
				valid = emailRegExp.test(addressArray[i]);
			}
		}
		else {
			valid = false;
		}
	}
	else {
		valid = false;
	}
	
	return valid;
}

function idgEmailError(toAddress, fromAddress, focusOnTo) {
	
	idgw.toEmailAddress.style.color = "";
	idgw.toEmailAddress.value = toAddress;
	idgw.fromEmailAddress.style.color = "";
	idgw.fromEmailAddress.value = fromAddress;
	
	if (focusOnTo) {
		idgw.toEmailAddress.select();
		idgw.toEmailAddress.focus();
	}
	else {
		idgw.fromEmailAddress.select();
		idgw.fromEmailAddress.focus();
	}
}

var idgGetPageUrl = "http://{DOMAINNAME}/csd/{WIDGETID}/GetPage?pISBN={ISBN}&pPageID=1&pWidth={WIDTH}";
var idgEmailUrl   = "http://{DOMAINNAME}/servlet/EmailWidget?isbn={ISBN}&to=TO&from=FROM&color={BGCOLOR}";
var idgBuyLinkUrl     = "http://{DOMAINNAME}/widget/?isbn={ISBN}&cpid={WIDGETID}&buy";
var idgReadLinkUrl    = "http://{DOMAINNAME}/widget/?isbn={ISBN}&cpid={WIDGETID}&color={BGCOLOR}";

var idgWidgetHtml =
	'<center>' +
		'<table id="idgWidgetTable" border="0" cellpadding="0" cellspacing="3">' +
			'<tr>' +
				'<td style="text-align: center;">' +
					'<img id="idgCoverImg" src="" onload="IdgShowWidget();" onclick="IdgLoadNextIsbn();" onerror="IdgHandleLoadError();"/>' +
					'<div id="idgCodeDiv" style="padding: 2px; display: none; background-color: #CCC;">' +
						'<div id="idgCopyInst" style="font-size: 6pt; text-align: left;">' +
							'<b>Add this book to your site</b><br/>Copy the HTML snippet below and paste into your web page.' +
						'</div>' +
						'<textarea id="idgCodeSnippet" style="font-size: 6pt;" onclick="this.select();"></textarea>' +
					'</div>' +
				'</td>' +
			'</tr>' +
			'<tr>' +
				'<td>' +
					'<table cellspacing="0" cellpadding="0" border="0" style="width: 100%;">' +
						'<tr id="idgEmailButtonRow">' +
							'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-left.png">&nbsp;</td>' +
							'{ADDBUTTON}' +
							'{BUTTONDIVIDER1}' +
							'{EMAILBUTTON}' +
							'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-right.png">&nbsp;</td>' +
						'</tr>' +
						'<tr id="idgEmailFormRow" style="display: none;">' +
							'<td colspan="5">' +
								'<table border="0" cellspacing="0" cellpadding="0" style="width: 100%;">' +
									'<tr>' +
										'<td colspan="4" style="height: 26px; padding: 0px 2px;" background="http://{DOMAINNAME}/widget/images/background.png">' +
											'<input type="text" id="idgToEmailAddress" value="To Address" onkeypress="IdgSendEmail(event, this);" style="font-size: {FONTSIZE};"/>' +
											'<iframe id="idgEmailFrame" style="display: none;"></iframe>' +
										'</td>' +
									'</tr>' +
									'<tr>' +
										'<td style="height: 26px; padding: 0px 2px;" background="http://{DOMAINNAME}/widget/images/background.png">' +
											'<input type="text" id="idgFromEmailAddress" value="From Address" onkeypress="IdgSendEmail(event, this);" style="font-size: {FONTSIZE};"/>' +
										'</td>' +
										'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-left.png">&nbsp;</td>' +
										'<td background="http://{DOMAINNAME}/widget/images/button.png" style="text-align: center; height: 26px; width: 40px;">' +
											'<a id="idgEmailSendLink" style="text-decoration: none; font-size: {FONTSIZE};" href="javascript: IdgSendEmail();">' +
												'<div id="idgEmailSendLinkText" style="width: 100%; cursor: pointer; white-space: nowrap;">Send</div>' +
											'</a>' +
										'</td>' +
										'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-right.png">&nbsp;</td>' +
									'</tr>' +
								'</table>' +
							'</td>' +
						'</tr>' +
						'<tr id="idgBuyReadRow">' +
							'<td colspan="5">' +
								'<table border="0" cellspacing="0" cellpadding="0" style="width: 100%;">' +
									'<tr>' +
										'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-left.png">&nbsp;</td>' +
										'{BUYBUTTON}' +
										'{BUTTONDIVIDER2}' +
										'<td id="idgReadCell" background="http://{DOMAINNAME}/widget/images/button.png" style="text-align: center; height: 26px;">' +
											'<a id="idgReadLink" style="text-decoration: none; font-size: {FONTSIZE};" href="" target="idgRead">' +
												'<div id="idgReadLinkText" style="width: 100%; cursor: pointer;">Read</div>' +
											'</a>' +
										'</td>' +
										'<td style="width: 6px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-right.png">&nbsp;</td>' +
									'</tr>' +
								'</table>' +
							'</td>' +
						'</tr>' +
					'</table>' +
				'</td>' +
			'</tr>' +
		'</table>' +
		'<a href="http://www.ingramdigital.com" style="font-size: 6pt; color: #aaa;" target="idg">Powered by Ingram Digital</a>' +
	'</center>';
	
var idgWidgetButtonDivider =
	'<td style="width: 12px; height: 26px;" background="http://{DOMAINNAME}/widget/images/button-divider.png">&nbsp;</td>';
	
var idgWidgetAddButton =
	'<td id="idgAddCell" background="http://{DOMAINNAME}/widget/images/button.png" style="text-align: center; height: 26px;">' +
		'<a id="idgAddLink" style="text-decoration: none; font-size: {FONTSIZE};" href="javascript: IdgToggleCode();">' +
			'<div id="idgAddLinkText" style="width: 100%; cursor: pointer; white-space: nowrap;">Add to site</div>' +
		'</a>' +
	'</td>';

var idgWidgetEmailButton =
	'<td id="idgEmailCell" background="http://{DOMAINNAME}/widget/images/button.png" style="text-align: center; height: 26px;">' +
		'<a id="idgEmailLink" style="text-decoration: none; font-size: {FONTSIZE};" href="javascript: IdgToggleEmail(true);">' +
			'<div id="idgEmailLinkText" style="width: 100%; cursor: pointer; white-space: nowrap;">Email</div>' +
		'</a>' +
	'</td>';

var idgWidgetBuyButton =
	'<td id="idgBuyCell" background="http://{DOMAINNAME}/widget/images/button.png" style="text-align: center; height: 26px;">' +
		'<a id="idgBuyLink" style="text-decoration: none; font-size: {FONTSIZE};" href="" target="idgBuy">' +
			'<div id="idgBuyLinkText" style="width: 100%; cursor: pointer;">Buy</div>' +
		'</a>' +
	'</td>';

var idgWidgetCode =
	'<div id="idgWidgetDiv" style="visibility: hidden;">\n' +
	'  <script src="http://{DOMAINNAME}/widget/idg-widget.js" language="javascript"></script>\n' +
	'  <script language="javascript">\n' +
	'    var isbn = "{ISBN}";\n' +
	'    var fontColor = "{FONTCOLOR}";\n' +
	'    var fontFamily = "{FONTFAMILY}";\n' +
	'    var backgroundColor = "{BGCOLOR}";\n' +
	'    var imageWidth = {WIDTH};\n' +
	'    var domainName = "{DOMAINNAME}";\n' +
	'    var cpid = "{WIDGETID}";\n' +
	'    IdgInitWidget(domainName, cpid, isbn, fontColor, fontFamily, backgroundColor, imageWidth, "{SHOWBUTTONS}", 5000);\n' +
	'  </script>\n' +
	'</div>';

