function reloadImage(source){
	var target = source;
	var isbn = target.id.substring(6);
	var images = [("http://www.macmillan.com.au/mea/covers/" + isbn + ".jpg"),("templates/layout/$file/noCover.gif")];
	var index = 1;if(target.src.indexOf(convISBN10toISBN13(preEditISBN(isbn))) != -1) index = 0;target.src = images[index];
}

function resizeImg(source){       
	if(source.width > 108){
      		var percentage = ((108*100)/source.width)/100;var nHeight = Math.floor(source.height * percentage);var nWidth = Math.floor(source.width * percentage);
      		if(nHeight > 131){
       			percentage = ((131*100)/nHeight)/100;
        		nHeight = Math.floor(nHeight * percentage);
        		nWidth = Math.floor(nWidth * percentage);
      		}
      		source.width = nWidth;source.height = nHeight;
	}else if(source.height > 131){
      		var percentage = ((131*100)/source.height)/100;var nHeight = Math.floor(source.height * percentage);var nWidth = Math.floor(source.width * percentage);
      		if(nWidth > 108){
        		percentage = ((108*100)/nWidth)/100;nHeight = Math.floor(nHeight * percentage);nWidth = Math.floor(nWidth * percentage)
      		}
      		source.width = nWidth;source.height = nHeight;
	}
    	checkNew(source, source.width, source.height);   
}

function checkNew(source, nWidth, nHeight){
    var oParent = source.parentNode;
    var oBookContainer = oParent.parentNode; //this will be the link, if there is a link, else it will be the div.

//Mod code here to handle wrapping the image in an a tag
/*
    try{
    	dispConsole("oBookContainer.tagName is:  " + oBookContainer.tagName);
    
    	dispConsole("source.tagName is:  " + source.tagName);
    } catch(e){}
*/
/*
    if(oBookContainer.nodeType == 1){
    	//element of type html-object/tag
      	if(oBookContainer.tagName=="a"){
      		dispConsole("oBookContainer.tagName is (a)");
        	//this is an a-element.  get the parent
        	oBookContainer = oBookContainer.parentNode; //go up one level to get the div that has an imgContainer class
        	oBookContainer = oBookContainer.parentNode; //go up another level to get the div that has an id
      	} else {
       		
       		if (oBookContainer.id == null){
       			oBookContainer = oBookContainer.parentNode; //go up one level to get the div that has an id
       		}
       		try{
        		dispConsole("oBookContainer.tagName is: " + oBookContainer.tagName);
        		dispConsole("oBookContainer.id is: " + oBookContainer.id);
        	} catch(e){}
	}
    }
    
    try{
    	dispConsole(oBookContainer.tagName);
    	dispconsole("oBookContainer.id is: " + oBookContainer.id);
    } catch(e){}

*/    
    var pNum = oBookContainer.getAttribute('id').substr(4);    
    if(getPubDate(unescape(viewResults[pNum].viewCol5)) != "undefined")
    {
      var oDate = new Date(Date.parse(getPubDate(unescape(viewResults[pNum].viewCol5))));
      var dToday = new Date();     
      var one_day = 1000*60*60*24;
      var days = Math.floor((dToday - oDate) / one_day);                  
      if(days <= 180)
      {
         var oDiv = document.createElement('div');
         oDiv.className = "labelNew";
         oDiv.style.bottom = (nHeight - 45) + "px";
         oDiv.style.left = (nWidth - 28) +"px";
         oParent.appendChild(oDiv);
      }
    }
  }
function getPubDate(pubDate){var oSplitDate = pubDate.split("/");if(oSplitDate.length > 1){var oTemp = oSplitDate[1];oSplitDate[1] = oSplitDate[0];oSplitDate[0] = oTemp;return oSplitDate.join('/');} else {return "undefined";}
}
function Book(pNum){
    this.pNum = pNum;
    this.pubDate = getPubDate(unescape(viewResults[pNum].viewCol5));
    this.isbn = unescape(viewResults[pNum].viewCol6);
    this.title = unescape(viewResults[pNum].viewCol2);
    this.price = unescape(viewResults[pNum].viewCol7);
    this.series = unescape(viewResults[pNum].viewCol15);
    this.subject = unescape(viewResults[pNum].viewCol13);
    this.area = unescape(viewResults[pNum].viewCol14);
    this.author = unescape(viewResults[pNum].viewCol4).replace(/,/ig,", ");
    this.summary = unescape(viewResults[pNum].viewCol10);
    this.buyInspect = "";
    this.isAvail = checkIsAvailable(unescape(viewResults[pNum].viewCol5)); 
    this.inspectionCopies = ((viewResults[pNum].viewCol17 == 1)||(viewResults[pNum].viewCol17 == "1"));   
    this.imgSrc = "/files/" + convISBN10toISBN13(preEditISBN(this.isbn)) + ".jpg"; 
    this.inspectVar = "&bi=0";
    if(this.inspectionCopies)this.inspectVar = "&bi=1";
    this.titleLink = "/primary/onix/domisbn/" + this.isbn + "?open&div=" + args['div'].replace(/\s/ig,"+") + "&cat=" + args['cat'].replace(/\s/ig, "+") + this.inspectVar + "&ed=site/primed31.nsf";
    //load availability and price from new database
    this.priceAvailability = new PriceAvailability(this.isbn);
    
    // set isEbook in the constructor.  Should be able to remove it from the function below and use the property that is set here
    // the value is being set on the product page, but not on the series load page, since dTitle will have no value and PageType is "library"
    // Will need to use values from the cart object items here, or possibly the book object.
    
    try{

    	var onixProd = document.forms[0].PageType;
    	var dTitle = "";
    	this.isEbook = false; 
    	if (typeof(onixProd) != "undefined"){
		if (onixProd.value == "onixProduct"){
		    	dTitle = document.forms[0].DistinctiveTitle.value;		   	
		}
		if (onixProd.value == "library"){
		    	dTitle = this.title;
		}
	}else{
		dTitle = this.title;
   	}
   	
   	if (dTitle.match("ebook") != null || dTitle.match("e-book") != null ){
		this.isEbook = true
	}  	
    }catch(e){
	if(window.globalStorage && window.postMessage){    
	    	console.debug("error in the constrctor: " + e);
	}
    	this.isEbook = false
    }
    
    if(this.priceAvailability.price) 
    {
        this.price = this.priceAvailability.price;
    }
    
    if(typeof Book._initialized == "undefined")
    {
        Book.prototype.isEClub = function()
        {          
          if(typeof division == "undefined")
          {
            var division = "";
            if(args['div'])division = unescape(args['div']);
          }         
          var discounted = eClub.isDiscounted(division + ">" + this.subject + ">" + this.area);          
          return discounted;
        };
        Book.prototype.printBookDetailPage = function(oCart)
        {
            document.write('<div id="titleContainer">');
            document.write('<p class="title"><span>',this.title,'</span></p>');
            document.write('<p>Series: ',this.series,'</p>');
            document.write('<p class="author"><span>Author: ',this.author,'</span></p>');
            document.write('<p>ISBN: <span>',isbn10to13(this.isbn),'</span></p>');
                if(this.price.toString().indexOf('$') == -1)
                {
                    this.price = parseFloat(this.price).toFixed(2);
                    document.write('<p>Price: <span>AU$',this.price,'</span></p>');
                } else {
                            document.write('<p>Price: <span>AU',this.price,'</span></p>');
                       }
                if(this.isEClub())
                {
                      document.write('<p>eClub Price: <span>AU$',this.eClubPrice(),'</span></p>');
                }
            if(!this.priceAvailability.available)
            {
                document.write('<p class="notAvailable">',this.priceAvailability.getShipDateStringBookDetail(),'</p>');      
            }
            document.write('<div id="cartControls">');
	    try{var dTitle = document.forms[0].DistinctiveTitle.value;var onixProd = document.forms[0].PageType;var isEbook = false;this.isEbook = false; if (typeof(onixProd) != "undefined"){
	    if (onixProd.value == "onixProduct"){  if (dTitle.match("ebook") != null || dTitle.match("e-book") != null ){isEbook = true;}}}}catch(e){isEbook = false;}

if(oCart.isIsbnInCart(this.isbn)){
 if(!oCart.isItemInspect(this.isbn)){
  document.write('<span class="addedToOrder">',oCart.getItemQuantity(this.isbn),'<span>added to order</span></span>');
  document.write('<a href="#" class="removeFromOrder" onclick="removeItemFromCart(event)">remove from order</a>');
 }else{
  document.write('<a href="#" class="inspected" onclick="removeItemFromCart(event)">inspected on approval</a>');
 }
}else{
	if(isEbook){
		document.write('<span style="font-weight:bold; color:#616d7e;">Use the link below to order this product.</span>');
	}else{
		document.write('<div id="bUnitsContainer"><input type="text" class="bUnits" name="bUnits" value="" /></div><label for="bUnits">Units</label><a href="#" class="addToOrder" onclick="addItemToCart(event)">add to order</a>');
 		if(this.inspectionCopies){
 			document.write('<a href="#" class="inspect" onclick="addItemToCart(event)">inspect on approval</a>');
 		}
	}
}
document.write('</div>');         
document.write('</div>');
}
Book.prototype.getExtraClass = function(){
var locSearch = document.location.toString();
if(locSearch.indexOf("Search+results") != -1)return "";
var reAt = /literacy/i;
if(args['div'] && reAt.test(unescape(args['div']))) return "";
  return " bookMargin";
};
Book.prototype.eClubPrice = function(){
  if(this.price.indexOf('$') == -1){
   var nPrice = Number(this.price);
  } else {
   var nPrice = Number(this.price.substring(1));
  }
  return (nPrice * 0.9).toFixed(2);
};

Book.prototype.printBook = function(oCart){

	//build an href for the image that uses this.titleLink
	try{
		var hRef = this.titleLink;
	}catch (e){
		dispConsole(e); 
	}
	
	document.write('<div class="bookContainer',this.getExtraClass(),'" id="book',this.pNum,'">');        
	document.write('<div class="imgContainer">');
	try{
		var aLinkStart = '<a href="'+ hRef + '">';
		var aLinkImg = '<img src="' + this.imgSrc + '" alt="' + this.title + '" id="cover_' + this.isbn + '" onerror="reloadImage(this)" onload="resizeImg(this)" />';
		var aLinkEnd = '</a>';
	} catch (e){
		dispConsole(e)
	}
	
	//dispConsole(aLinkStart);
	//dispConsole(aLinkImg);
	//dispConsole(aLinkEnd);
	
	//document.write(aLinkStart + aLinkImg + aLinkEnd);
	//Wrapping in a link causes an error oBookContainer.getAttribute("id") is null in function_book.js line 28 (that line is below)
	//var oParent = source.parentNode;var oBookContainer = oParent.parentNode;var pNum = oBookContainer.getAttribute('id').substr(4);
					
	document.write(aLinkImg);				
					
	
	
	//document.write('<img src="',this.imgSrc,'" alt="',this.title,'" id="cover_',this.isbn,'" onerror="reloadImage(this)" onload="resizeImg(this)" />');
	
	//this.checkNewLabel();
		
	document.write('</div>');
	document.write('<p class="bTitle"><a href="',this.titleLink,'">',this.title,'</a></p>');
	var priceIsbnString = "";
	if(this.price.toString().indexOf('$') == -1){
		this.price = parseFloat(this.price).toFixed(2);
		priceIsbnString = 'AU$' + this.price + ' | ';
	} else {
		priceIsbnString = 'AU' + this.price + ' | ';
	}
	priceIsbnString += isbn10to13(this.isbn);
	if(this.published() == false){
		// priceIsbnString += '<br /><b>Coming ' + this.pubDate + '</b>'; 
	}
	document.write('<p>',priceIsbnString,'</p>');
	
	try{
		if (!this.isEbook){
			//Do not print the form for e-books
        		this.printBookForm(oCart);
        	}
        }catch (e){
        	//default to a not e-book status
        	this.printBookForm(oCart);
        }
        document.write('</div>');
};

Book.prototype.printBookForm = function(oCart){
	
              if(this.isEClub())
              {
                  document.write('<p class="eClubPrice">eClub Price: $',this.eClubPrice(),'</p>');
              }
              if(!this.priceAvailability.available)//if book is not available
              {
                    document.write('<p class="notAvailable">',this.priceAvailability.getShipDateString(),'</p>');
              }
              if(oCart.isIsbnInCart(this.isbn))
	          {
	                if(!oCart.isItemInspect(this.isbn))
                    {
		                document.write('<p class="addedToOrder">',oCart.getItemQuantity(this.isbn),'<span>added to order</span></p>');
		                var classArray = new Array();
                        var anchorClass = "";
                        classArray.push('removeFromOrder');
                        if(!this.priceAvailability.available)classArray.push('bookRequest');
                        if(classArray.length != 0)anchorClass = 'class="' + classArray.join(' ') + '"';
                        document.write('<a ',anchorClass,' onclick="removeItemFromCart(event)" href="#">remove from order</a>');    
	                } else {
	                            document.write('<a class="removeInspect" onclick="removeItemFromCart(event)" href="#">remove inspected item from order</a>'); 
	                       }
              } else {
                document.write('<p class="buyBook"><span>');
                //if(this.priceAvailability.available)//if book is not available
                //{
                    document.write('<input type="text" class="bUnits" name="Num_',this.isbn,'" onChange="thisVal=this.value;" value="" />');
                    document.write('<label for="bUnits">Units</label>');
                //}
                var classArray = new Array();
                var anchorClass = "";
                if(!this.priceAvailability.available)classArray.push('bookRequest');
                if(classArray.length != 0)anchorClass = 'class="' + classArray.join(' ') + '"';
                document.write('<a href="#" onclick="addItemToCart(event)" ',anchorClass,'>add to cart</a>');
                document.write('</span></p>');
                // inspect
                if (this.inspectionCopies) { // inspection copies only allowed if col17 = 1
                  var classArray = new Array();
                  var anchorClass = "";
                  classArray.push('inspectApproval');
                  if(!this.priceAvailability.available)classArray.push('bookRequest');
                  if(classArray.length != 0)anchorClass = 'class="' + classArray.join(' ') + '"';
                  document.write('<a href="#" ',anchorClass,' onclick="addItemToCart(event)">Inspect on Approval</a>');
                } 
              }
        };

        Book.prototype.updateBookDetail = function(cartContainer,oCart)
        {
          cartContainer.innerHTML = "";
          
          this.priceAvailability = new PriceAvailability(this.isbn);  
          /*
          if(!this.priceAvailability.available)
          {  
            cartContainer.innerHTML = '<p class="notAvailable">Not in stock</p>';
            return;
          }
           */      
          if(oCart.isIsbnInCart(this.isbn))
	      {
	              if(!oCart.isItemInspect(this.isbn))
                {
                      var addedToOrder = document.createElement('span');                      
                      addedToOrder.className = "addedToOrder";
                      addedToOrder.innerHTML = oCart.getItemQuantity(this.isbn) + '<span>added to order</span>';
                      cartContainer.appendChild(addedToOrder);
          		        
		        var aremoveFromOrder = document.createElement('a');
		        var classArray = new Array();
                      var anchorClass = "";
                      classArray.push('removeFromOrder');
                      if(!this.priceAvailability.available)classArray.push('bookRequest');
                      if(classArray.length != 0)aremoveFromOrder.className = classArray.join(' ');
		              aremoveFromOrder.setAttribute('href','#');
		              aremoveFromOrder.innerHTML = "remove from order";		        
                      if(document.attachEvent)
                      {
                        aremoveFromOrder.onclick = function(oEvent){removeItemFromCart();}; 
                      } else {
                        aremoveFromOrder.setAttribute('onclick','removeItemFromCart(event)'); 
                      }  
                      cartContainer.appendChild(aremoveFromOrder);
	              } else {
	                    var removeInspect = document.createElement('a');
	                    removeInspect.className = "inspected";
	                    removeInspect.setAttribute('href','#');
	                    removeInspect.innerHTML = "remove inspected item from order";
	                    if(document.attachEvent)
                      {
                        removeInspect.onclick = function(oEvent){removeItemFromCart();}; 
                      } else {
                        removeInspect.setAttribute('onclick','removeItemFromCart(event)'); 
                      }
	                    cartContainer.appendChild(removeInspect);
	              }	        
          } else {
              var units = document.createElement('input');
              units.setAttribute('type','text');
              units.setAttribute('name','bUnits');
              units.className = "bUnits";
              var unitsContainer = document.createElement('div');
              unitsContainer.setAttribute('id','bUnitsContainer');        
              unitsContainer.appendChild(units);
              cartContainer.appendChild(unitsContainer);
              var unitsLabel = document.createElement('label');
              unitsLabel.setAttribute('for','bUnits');
              cartContainer.appendChild(unitsLabel);
              var aaddToOrder = document.createElement('a');
              var classArray = new Array();
              var anchorClass = "";
              classArray.push('addToOrder');
              if(!this.priceAvailability.available)classArray.push('bookRequest');
              if(classArray.length != 0)aaddToOrder.className = classArray.join(' ');
              aaddToOrder.setAttribute('href','#');
              aaddToOrder.innerHTML = "add to order";
              if(document.attachEvent)
              {
                 aaddToOrder.onclick = function(oEvent){addItemToCart();}; 
              } else {
                 aaddToOrder.setAttribute('onclick','addItemToCart(event)'); 
              }
              cartContainer.appendChild(aaddToOrder);
              if (this.inspectionCopies) 
              {
                 var inspect = document.createElement('a');
                 inspect.className = "inspect";
                 inspect.setAttribute('href','#');
                 inspect.innerHTML = "inspect on approval";             
                 if(document.attachEvent)
                 {
                    inspect.onclick = function(oEvent){addItemToCart();}; 
                 } else {
                    inspect.setAttribute('onclick','addItemToCart(event)'); 
                 }
                 cartContainer.appendChild(inspect);
              }             
          }     
          /*
          if(!this.priceAvailability.available)
          {  
            var oP = document.createElement('p');
            oP.className = 'notAvailable';
            oP.appendChild(document.createTextNode(this.priceAvailability.getShipDateString()));
            cartContainer.appendChild(oP);
          } 
          */    
        };
        Book.prototype.updateBook = function(bookContainer,oCart)
        {
            var oImgContainer = document.getInnerElementByClassName(bookContainer,'div','imgContainer');
            var oImg = oImgContainer.getElementsByTagName('img')[0];  
            var oImgSrc = oImg.src;
            var oImgWidth = oImg.width;
            var oImgHeight = oImg.height;        
            bookContainer.innerHTML = "";            
            this.attachBook(bookContainer, oCart, oImgSrc, oImgWidth, oImgHeight);
        };   
        Book.prototype.published = function()
        {
            if(!this.pubDate)return false;
            var pubDate = new Date(Date.parse(this.pubDate));
            var today = new Date(); 
            if(pubDate > today)return false;
            return true;                       
        };  
    }
    Book._initialized = true;   
  }

function dispConsole(dstring){
 	if(window.globalStorage && window.postMessage){    
 		try{
 		    	console.debug(dstring);
 		} catch (e){
 			console.debug("Error in dispConsole:" + dstring);
 		}
 	}
}
