var xmlHttp;



function GetXmlHttpObject()
{

	var xmlHttp=null;
	
	try
	
	  {
	
	  // Firefox, Opera 8.0+, Safari
	
	  xmlHttp=new XMLHttpRequest();
	
	  }
	
	catch (e)
	
	  {
	
	  // Internet Explorer
	
	  try
	
	    {
	
	    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	
	    }
	
	  catch (e)
	
	    {
	
	    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	
	    }
	
	  }
	
	return xmlHttp;

}



/*===================================================================================================================

  === CLIENT ISBN VALIDATION

	===================================================================================================================*/

function bValidISBN(str, bSendAlert)
{
	if(bSendAlert == null)
	{
		bSendAlert = true;
	}
	
	var cleanStr = str;
	var ISBNArray;
	var ISBNRegex = /^(97(8|9))?\d{9}(\d|X|x)$/g;
	var DashRegex = /-/g;
	var cleanISBNItem = "";
	var i = 0;
	var strMessage = "Something seems to be wrong with the following ISBN(s).\nRemember an ISBN should have 10 or 13 digits and inputting the dashes is optional. \n\n";
	var bValid = true;
	var cleanISBN;

	// replace "/", "\", ";" and newline with the standard delimiter ","
	cleanStr = cleanStr.replace(new RegExp(/\/|\\|;|\n|\f|\r|\s/g),",");

	// get rid of spaces and quotes
	cleanStr = cleanStr.replace(new RegExp(/'|"|\s+|\n+/g),"");

	//' get rid of empty ISBNs (multiple "," entries)
	cleanStr = cleanStr.replace(new RegExp(/,{2,}/g),",");

	var lastCharacterAscii = cleanStr.charCodeAt(eval(cleanStr.length - 1));
	var bDelimiterError = eval(lastCharacterAscii == 44);

	if(bDelimiterError)
	{
		cleanStr = cleanStr.substring(0,eval(cleanStr.length - 1));
	}

	// split by "," and check each item in the list as a regex
	ISBNArray = cleanStr.split(",");

	while (i < ISBNArray.length)
	{
		cleanISBNItem = ISBNArray[i].replace(DashRegex,"");
		if(cleanISBNItem.search(ISBNRegex) == -1)
		{
			strMessage += "  " + ISBNArray[i] + " (" + ISBNArray[i].length + " digits)\n";
			bValid = false;
		}
		i+=1;
	}

	if(bValid)
	{
		//document.getElementById('isbn').value = cleanStr;
		if(document.getElementById('cleanIsbn'))
		{
			document.getElementById('cleanIsbn').value = cleanStr;
		}
		return true;
	}
	else
	{
		if(bSendAlert)
		{
			alert(strMessage);
		}
		return false;
	}
}

//** =================================================================================================================
//** START: process sell
function getTextbookSellQuote(strIsbn, objForm)
{
	if (!bValidISBN(strIsbn))
	{
		return;
	}
	
	if ( document.getElementById("resultsdiv")) 
	{
		document.getElementById("resultsdiv").innerHTML="<table width='100%' border='0'><tr><td width='35px;'>&nbsp;</td><td align=center>Please wait while we look up your ISBN data.</td></tr><tr><td></td><td align=center><img src='images/ajax-loader.gif'></td></tr>";
		document.getElementById("resultsdiv").style.display = 'block';
	}


	objForm.submit();
}
//** END: process sell
//** =================================================================================================================

//** =================================================================================================================
//** LOOKUP ISBN ACTION
function lookupIsbn(str)
{
	if (!bValidISBN(str))
	{
		return;
	}

	xmlHttp=GetXmlHttpObject()

	if (xmlHttp==null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var cleanStr;
	if(document.getElementById('cleanIsbn'))
	{
		cleanStr = document.getElementById('cleanIsbn').value;
	}
	else
	{
		cleanStr = "";
	}
  
	var url="ajax-offer.php";
	url=url+"?cleanIsbn="+cleanStr;
	url=url+"&sid="+Math.random();

	if ( document.getElementById("resultsdiv")) 
	{
		document.getElementById("resultsdiv").innerHTML="<table width='100%' border='0'><tr><td width='35px;'>&nbsp;</td><td align=center>Please wait while we look up your ISBN data.</td></tr><tr><td></td><td align=center><img src='images/ajax-loader.gif'></td></tr>";
		document.getElementById("resultsdiv").style.display = 'block';
	}

	xmlHttp.onreadystatechange=buybackStep;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
} 

function navToSearch(strSearch,strIndexParameter)
{
		if(strIndexParameter == "ISBN")
		{
			if(validateISBN(strSearch,false))
			{
				window.location = "http://www.jitterbook.com/book-details.php?q="+escape(strSearch)+"&query-type="+strIndexParameter;	
			}
			else
			{
				window.location = "http://www.jitterbook.com/book-details.php?q="+escape(strSearch)+"&query-type=Keywords";	
			}
		}
		else
		{
			if(validateISBN(strSearch,false))
			{
				window.location = "http://www.jitterbook.com/book-details.php?q="+escape(strSearch)+"&query-type=ISBN";	
			}
			else
			{
				window.location = "http://www.jitterbook.com/book-details.php?q="+escape(strSearch)+"&query-type="+strIndexParameter;	
			}
		}
}

function validateISBN(str)
{
	
	var cleanStr = str;
	var ISBNArray;
	var ISBNRegex = /^(97(8|9))?\d{9}(\d|X|x)$/g;
	var DashRegex = /-/g;
	var cleanISBNItem = "";
	var i = 0;
	var strMessage = "Something seems to be wrong with the following ISBN(s).\nRemember an ISBN should have 10 or 13 digits and inputting the dashes is optional. \n\n";
	var bValid = true;
	var cleanISBN;

	// replace "/", "\", ";" and newline with the standard delimiter ","
	cleanStr = cleanStr.replace(new RegExp(/\/|\\|;|\n|\f|\r|\s/g),",");

	// get rid of spaces and quotes
	cleanStr = cleanStr.replace(new RegExp(/'|"|\s+|\n+/g),"");

	//' get rid of empty ISBNs (multiple "," entries)
	cleanStr = cleanStr.replace(new RegExp(/,{2,}/g),",");

	var lastCharacterAscii = cleanStr.charCodeAt(eval(cleanStr.length - 1));
	var bDelimiterError = eval(lastCharacterAscii == 44);

	if(bDelimiterError)
	{
		cleanStr = cleanStr.substring(0,eval(cleanStr.length - 1));
	}

	// split by "," and check each item in the list as a regex
	ISBNArray = cleanStr.split(",");

	while (i < ISBNArray.length)
	{
		cleanISBNItem = ISBNArray[i].replace(DashRegex,"");
		if(cleanISBNItem.search(ISBNRegex) == -1)
		{
			bValid = false;
		}
		i+=1;
	}

	return bValid;	
}

function lookupPurchaseIsbn(strSearch,strIndexParameter,intPage)
{
	var intPage = (intPage == null) ? 1 : intPage;
	
	switch(strIndexParameter)
	{
		default:

				xmlHttp=GetXmlHttpObject()
				if (xmlHttp==null)
				{
					alert ("Your browser does not support AJAX!");
					return;
				}

				var url="/ajax-purchase.php";

			
				boolValidIsbn = bValidISBN(strSearch,false);
				
				if(strIndexParameter == "ISBN")
				{
					if(boolValidIsbn)
					{
						url+="?q="+escape(strSearch)+"&query-type="+escape(strIndexParameter)+"&ItemPage="+escape(intPage);
					}
					else
					{
						url+="?q="+escape(strSearch)+"&query-type=Keywords&ItemPage="+escape(intPage);
					}
				}
				else
				{
					if(boolValidIsbn)
					{
						url+="?q="+escape(strSearch)+"&query-type=ISBN&ItemPage="+escape(intPage);
					}
					else
					{
						url+="?q="+escape(strSearch)+"&query-type="+escape(strIndexParameter)+"&ItemPage="+escape(intPage);
					}
				}

				if ( document.getElementById("resultsdiv")) 
				{
					document.getElementById("resultsdiv").innerHTML="<table width='100%' border='0'><tr><td width='35px;'>&nbsp;</td><td align=center>Please wait while we look up this information...</td></tr><tr><td></td><td align=center><img src='/images/ajax-loader.gif'></td></tr></table><br><br>";
					document.getElementById("resultsdiv").style.display = 'block';
				}
			
				xmlHttp.onreadystatechange=buybackStep;
				xmlHttp.open("GET",url,true);
				xmlHttp.send(null);
	
			break;
	}
} 

function buybackStep() 
{ 
	if (xmlHttp.readyState==4)
	{ 

		//document.getElementById("isbnlookupstep").style.display = 'none';
		
		// add response text as new dom div object
		var newDiv = document.createElement("div");
		var strResponseText = xmlHttp.responseText
		newDiv.innerHTML = xmlHttp.responseText;
		
		// clear current container HTML using clone method
		clearContent(document.getElementById("resultsdiv"));

		// insert new content into the container
		document.getElementById("resultsdiv").appendChild(newDiv);
		
		//document.getElementById("resultsdiv").innerHTML=xmlHttp.responseText;

/**
	 	this next part is terrible, this ajax response must be rewritten as XML. the silly characters at the start and end
		of the DIV content are used to do JS string matches in the callback JS function. 
		
		since FF doesn't recognize the DOM objects dynamically inserted using innerHTML we need to get the data back 
		from this file to update a secondary page element (top header area Cart information).
		
		no time to rewrite the ajax component and use XML to get all necessary data back and then update as many DOM 
		elements as needed on the calling page. 
		
		THIS MUST BE REWRITTEN using XML to update multiple DOM elements on the calling page!
**/

		var totalStart = strResponseText.indexOf('{:-');
		var totalEnd = strResponseText.indexOf('-:}');
		var savingsStart = strResponseText.indexOf('{::-');
		var savingsEnd = strResponseText.indexOf('-::}');
		var strQuoteTotal = strResponseText.substring(totalStart+3, totalEnd);
		var strSavings = strResponseText.substring(savingsStart+4, savingsEnd);
		
		if(document.getElementById("cartTotal"))
		{
			document.getElementById("cartTotal").innerHTML = strQuoteTotal;
		}
		
		/**
		if(document.getElementById("cartSavings"))
		{
			document.getElementById("cartSavings").innerHTML = strSavings;
		}
		**/
	}

}

function addItemToCartAjax(strListingId, strTargetDiv)
{
	xmlHttp=GetXmlHttpObject()

	if (xmlHttp==null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}

	oTargetDiv = document.getElementById(strTargetDiv);
	oTargetDiv.innerHTML = "<span style='background-color: #FDFF1F; font-family:Arial, Helvetica, sans-serif; text-align:center; font-weight: bold;'>&nbsp;&nbsp;processing...&nbsp;&nbsp;</span>";
	
	var url="ajax-cart.php?a=add&id="+strListingId;

	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState==4)
		{ 
			// add response text as new dom div object
			var newDiv = document.createElement("div");
			newDiv.innerHTML = xmlHttp.responseText;
			
			// clear current container HTML using clone method
			clearContent(document.getElementById(strTargetDiv));
			
			// insert new content into the container
			document.getElementById(strTargetDiv).appendChild(newDiv);
		}
	}

	xmlHttp.send(null);
}


function clearContent(el) 
{
	// first clone the object, without it’s child elements.
	nEl = el.cloneNode(false);
	
	// Pop the new element in before the old one.
	el.parentNode.insertBefore(nEl,el);
	
	// Now get rid of the one that has all that icky content
	el.parentNode.removeChild(el);
}


function lookupOffers(str)
{
	if (str.length==0)
 	{ 
 		if(document.getElementById("results"))
 		{
 			document.getElementById("results").innerHTML="";
 		}
  		
		return;
	}

	xmlHttp=GetXmlHttpObject()

	if (xmlHttp==null)
	{
		alert ("Your browser does not support AJAX!");
	  	return;
	}
	
	var url ="ajax-offer.php?simple=1&offers="+str;

	if(document.getElementById("resultsdiv")) 
	{
		document.getElementById("resultsdiv").style.display = 'block';
		document.getElementById("resultsdiv").innerHTML="Please wait, looking up ISBN data...";
	}

	xmlHttp.onreadystatechange=buybackStep;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}








/*===================================================================================================================

  === SELECT OFFERS ACTION

	===================================================================================================================*/

function selectBuybackOffers()
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{

  		alert ("Your browser does not support AJAX!");

  		return;

	} 

  	var hidQuoteList = "";
	var hidOfferItemIsbnList = "";
	var quoteForm = document.forms["selectquotesform"];
	var i=0; count=0;

	for ( i=0; i<quoteForm.length; i++ ) 
	{
		if (quoteForm[i].type == 'checkbox' && quoteForm[i].checked) 
		{
			hidQuoteList = hidQuoteList+quoteForm[i].value + ',';
			hidOfferItemIsbnList = hidOfferItemIsbnList+document.getElementById("offerItemIsbn"+quoteForm[i].value).value+',';
			count++;
		}
	}

	if ( count == 0 ) 
	{ 
		alert("Please select offer(s) or search more ISBN's"); return false; 
	}
	
	hidQuoteList = hidQuoteList.substring(0, hidQuoteList.length - 1);
	hidOfferItemIsbnList = hidOfferItemIsbnList.substring(0, hidOfferItemIsbnList.length - 1);
	
	document.forms["selectquotesform"].hidQuoteIDList.value = hidQuoteList;
	document.forms["selectquotesform"].hidSelectedOfferIsbnList.value = hidOfferItemIsbnList;
	document.forms["selectquotesform"].submit();
}



function calcClientQuoteTotal()
{
	var total=0;
	var quoteID;
	var strQuoteValueLookupId
	var i=0; 
	var count=0;
	var quoteForm = document.forms["selectquotesform"];

	for (i = 0; i < quoteForm.length; i++) 
	{
		if (quoteForm[i].type == 'checkbox' && quoteForm[i].checked) 
		{
			quoteID = quoteForm[i].id;
			strQuoteValueLookupId = "amount"+quoteID;
			total+=parseFloat(quoteForm[strQuoteValueLookupId].value);
		}
	}

	if(document.getElementById("selectedTotalTop"))
	{
		document.getElementById("selectedTotalTop").innerHTML = "Total $" + total.toFixed(2) + " ";
	}
	
	if(document.getElementById("selectedTotalBottom"))
	{
		document.getElementById("selectedTotalBottom").innerHTML = "Total $" + total.toFixed(2) + " ";
	}

	if(document.getElementById("cartTotal"))
	{
		document.getElementById("cartTotal").innerHTML = "Cart Total: $" + total.toFixed(2);
	}
	
	if(document.getElementById("hidCartTotal"))
	{
		document.getElementById("hidCartTotal").value = total.toFixed(2);
	}
		
	var savings = total - (total/1.29);
	
	/**
	if(document.getElementById("cartSavings"))
	{
		document.getElementById("cartSavings").innerHTML = "JitterBook Advantage: $" + savings.toFixed(2);
	}
	**/
	
	/**
	if(document.getElementById("hidCartSavings"))
	{
		document.getElementById("hidCartSavings").value = savings .toFixed(2);
	}
	**/
	
}

function loginStep() 

{ 

	if (xmlHttp.readyState==4)

	{ 
	
		if(document.getElementById("isbnform"))
		{
			document.getElementById("isbnform").style.display = 'none';
		}
		
		if(document.getElementById("resultsdiv"))
		{
			document.getElementById("resultsdiv").innerHTML="";
			document.getElementById("resultsdiv").innerHTML=xmlHttp.responseText;
		}
	}
}









/*===================================================================================================================

  === SELECT OFFERS ACTION

	===================================================================================================================*/











function registerAccount()

{

	xmlHttp=GetXmlHttpObject()

	if (xmlHttp==null)

  {

  	alert ("Your browser does not support AJAX!");

  	return;

  } 

	var url="accountlogin.php?register=Y&";

	

	var registerForm = document.forms["register"];

	var i=0; count=0;

	

	for ( i=0; i<registerForm.length; i++ ) {

		url=url+registerForm[i].id + "=" + registerForm[i].value + "&";

		count++;

	}

	

	if ( count == 0 ) { alert("Please select quote or search more ISBN's"); return; }

	

	url = url.substring(0, url.length - 1);

	

	url=url+"&sid="+Math.random();

	//alert (url);

	xmlHttp.onreadystatechange=createAccountCallback;

	xmlHttp.open("GET",url,true);

	xmlHttp.send(null);

} 











function ajaxFunction()

{

	var xmlHttp;

	try {

		// Firefox, Opera 8.0+, Safari

		xmlHttp=new XMLHttpRequest();

	}

	catch (e) {

		// Internet Explorer

		try {

			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

		}

		catch (e) {

			try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }

			catch (e) { 

				alert("Your browser does not support AJAX!");

				return false;

			}

		}

	}

	

	xmlHttp.onreadystatechange=function()	{

		if(xmlHttp.readyState==4) {

			document.myForm.time.value=xmlHttp.responseText;

		}

	}

	xmlHttp.open("GET","isbn.php",true);

	xmlHttp.send(null);

}



//===================================================================================

//=== Div popup / fade effects for "what is isbn"

//===================================================================================

var isDivOpen = false;



function ShowDiv(ID, e)

{

		ShowDivWithOffset(ID,-250,0,e)

}



function ShowDivWithOffset(ID, x_offset, y_offset, e)

{

	var popup = document.getElementById(ID);

	var positionX = 0;
	var positionY = 0;
	var offset = 5;

	if(!isDivOpen)
	{
		if (!e) var e = window.event;
		if (document.all)
		{
			positionX = window.event.clientX + document.body.scrollLeft;
			positionY = window.event.clientY + document.body.scrollTop;
		} 
		else 
		{
			positionX = e.pageX;
			positionY = e.pageY;
		}

		if (positionX < 0){positionX = 0}
		if (positionY < 0){positionY = 0}

		popup.style.top  = (eval(positionY + offset + y_offset)) + 'px';
		popup.style.left = (eval(positionX + x_offset)) + 'px';

		DivFade(ID, 85, 10, 10).show();

		isDivOpen = true;
	}
}


function HideDiv(ID)
{
	if(isDivOpen)
	{
		DivFade(ID, 85, 10, 10).hide();
		//Effect.Shrink(ID);
		//Effect.toggle(ID,'appear');
		isDivOpen = false;
	}
}

function DivFade(DivID, MaxOpacity, FadeInRate, FadeOutRate)
{
	this.maxOpacity = MaxOpacity;
	this.fadeInRate = FadeInRate;
	this.fadeOutRate = FadeOutRate;
	this.opacity = 0;
	this.container = document.getElementById(DivID);
	this.container.changeOpac = function(iOpacity)
	{
		parent.container.style.opacity = (iOpacity / 100);
		parent.container.style.MozOpacity = (iOpacity / 100); 
		parent.container.style.KhtmlOpacity = (iOpacity / 100); 
		parent.container.style.filter = "alpha(opacity=" + iOpacity + ")";

		return; 
	}

	this.container.fadeIn = function()
	{
		parent.opacity += parent.fadeInRate;
		parent.container.changeOpac(parent.opacity);

		if(parent.opacity < parent.maxOpacity) 
		{
			setTimeout("parent.container.fadeIn()", 0);
		}
		else
		{
			parent.opacity = parent.maxOpacity;
		}

		return; 
	}

	this.container.fadeOut = function()
	{
		parent.opacity -= parent.fadeOutRate;
		parent.container.changeOpac(parent.opacity);
		
		if(parent.opacity > 0) 
		{
			setTimeout("parent.container.fadeOut()", 0);
		}
		else 
		{
			parent.container.style.display = "none";
		}

		return; 
	}
	this.show = function()
	{
		parent.opacity = 0;
		parent.container.changeOpac(parent.opacity);
		parent.container.style.display = "";
		setTimeout("parent.container.fadeIn()", 0);

		return; 
	}

	this.hide = function()
	{
		parent.opacity = parent.maxOpacity;
		setTimeout("parent.container.fadeOut()", 0);

		return; 
	}

	return this;
}

function setOpacity(obj, opacity) 
{ 
	opacity = (opacity == 100)?99.999:opacity; 
// IE/Win 
	obj.style.filter = "alpha(opacity:"+opacity+")"; 
// Safari<1.2, Konqueror 
	obj.style.KHTMLOpacity = opacity/100; 
// Older Mozilla and Firefox 
	obj.style.MozOpacity = opacity/100; 
// Safari 1.2, newer Firefox and Mozilla, CSS3 
	obj.style.opacity = opacity/100; 
} 