// Function OnixItem

//OnixItem CONSTRUCTOR------------------------------------------------------------------------------------------------------------------------------------------------------
//INPUT:
//		[0] - object
//		[1] type - 'onix' if coming from Series
//      [2] quantity - used for items created from cart
function OnixItem()
{
	var onixProduct = (typeof arguments[0] != 'undefined' && typeof arguments[0] == 'string' && arguments[0] == 'onixProduct') ? true : null;
	
	//Check if at leat one argument has been passed
	if((!onixProduct) && typeof arguments[1] == 'undefined')
	{
		throw new Error('Constructor of OnixItem expects at least one argument');
	}
	
	//Check if 'type' property has been set
	if(typeof arguments[0] == 'undefined' || typeof arguments[0] != 'string' || arguments[0].length == 0)
	{
		throw new Error('Constructor of OnixItem expects argument 2 of string type');
	}
	
	//Parse series item
	if(arguments[0] === 'series')
	{
	    var quantity = (typeof arguments[2] != 'undefined') ? arguments[2] : null;
	    this.parseSeriesItem(arguments[1],quantity);
	}
	//Parse Onix Product Item
	if(arguments[0] === 'onixProduct')this.parseOnixProductItem();
	
}

//OnixItem PROTOTYPE------------------------------------------------------------------------------------------------------------------------------------------------------

//Variables used for building the book links
OnixItem.prototype._DIVISION = 'Secondary';
OnixItem.prototype._ED = 'site/seced31.nsf';
OnixItem.prototype._TEMPLATE = 'domSecondary';

//OnixItem CONSTANTS--------------------------------------------------------------------------------------------



//OnixItem FUNCTIONS--------------------------------------------------------------------------------------------


//Function which validates Series Item and sets Item object
OnixItem.prototype.parseSeriesItem = function(obj,quantity)
{
	//1 - docID
	//2 - Distinctive Title
    //3 - Edition Statement
    //4 - Lead Author
    //5 - Publication Date
    //6 - ISBN
    //7 - Price
    //8 - Publisher Name
    //9 - Imprint or Binding
    //10 - Summary (Abstract if it exists otherwise first 300 chars of Main Description)
    //11 - parentID
    //12 - BIC Main Subject Code
    //13 - Subject
    //14 - Area
    //15 - Series	
	
	//17 Inpec col
	
	//Array for log
	var vars = new Array();

	//Get ID
	this.ID = this.getISBN13(decodeURIComponent(obj.viewCol1));
	
	//Get isbn
	this.isbn = this.getISBN13(decodeURIComponent(obj.viewCol6));
	//Get heading for log
	var heading = 'Item: ' + this.isbn + '(from isbn' + (decodeURI(obj.viewCol6)).length + ')';
	
	//Get title
	this.title = decodeURIComponent(obj.viewCol2);
	vars.push('title: ' + this.title);
	
	//Get publisher
	this.publisher = (typeof obj.viewCol8 == 'string' && obj.viewCol8.length != 0) ? decodeURIComponent(obj.viewCol8) : null;
	vars.push('publisher: ' + this.publisher);
	
	//Get authors
	this.authors = (typeof obj.viewCol4 == 'string' && obj.viewCol4.length != 0) ? this.parseSeriesAuthors((decodeURIComponent(obj.viewCol4))) : null;
	vars.push('authors (array): ' + this.authors);
	
	//Get edition statement
	this.edtitionStatement = (typeof obj.viewCol3 == 'string' && obj.viewCol3.length != 0) ? decodeURIComponent(obj.viewCol3) : null;
	vars.push('edition statement: ' + this.edtitionStatement);
	
	//Get publication date
	this.publicationDate = (typeof obj.viewCol5 == 'string' && obj.viewCol5.length != 0) ? (decodeURIComponent(obj.viewCol5)).toDateFromDDMMYY() : null;
	vars.push('publication date: ' + (this.publicationDate ? this.publicationDate.toGMTString() : null));
	vars.push('publication date (unparsed): ' + decodeURIComponent(obj.viewCol5));
	
	//Get BIC
	this.bic = (typeof obj.viewCol12 == 'string' && obj.viewCol12.length != 0) ? decodeURIComponent(obj.viewCol12) : null;
	vars.push('bic: ' + this.bic);
	
	//Get subject
	this.subject = (typeof obj.viewCol13 == 'string' && obj.viewCol13.length != 0) ? decodeURIComponent(obj.viewCol13) : null;
	vars.push('subject: ' + this.subject);
	
	//Get area
	this.area = (typeof obj.viewCol14 == 'string' && obj.viewCol14.length != 0) ? decodeURIComponent(obj.viewCol14) : null;
	vars.push('area: ' + this.area);
	
	//Get series
	this.series = (typeof obj.viewCol15 == 'string' && obj.viewCol15.length != 0) ? decodeURIComponent(obj.viewCol15) : null;
	vars.push('series: ' + this.series);
	
	//Get inspection
	this.inspection = (typeof obj.viewCol17 == 'string' && obj.viewCol17.length != 0) ? decodeURIComponent(obj.viewCol17) : null;
	vars.push('inspection: ' + this.inspection);
	
	//If quantity has been passed (from the cart) set quantity
	if(quantity)
	{
	    this.quantity = quantity;
	    vars.push('quantity: ' + this.quantity);
	}
	
	//Get new price and availability	
	var priceAvailability = new PriceAvailability(this.isbn,quantity);
	
	//Get old price
	this.price = this.parseSeriesPrice(decodeURIComponent(obj.viewCol7));
	//Get new price
	this.price = (priceAvailability.price) ? this.parseSeriesPrice(priceAvailability.price) : this.price;	
	vars.push('price: ' + this.getPriceStr());
	
	//Get availability
	this.available = (priceAvailability.available) ? true : false;
	vars.push('available: ' + this.available);
	
	//Get ship date
	this.shipDate = (typeof priceAvailability.shipDate == 'string' && priceAvailability.shipDate.length != 0) ? (decodeURIComponent(priceAvailability.shipDate)).toDateFromDDMMYY() : null;
	vars.push('ship date: ' + (this.shipDate ? this.shipDate.toGMTString() : null));
	vars.push('ship date (unparsed): ' + decodeURIComponent(priceAvailability.shipDate));
	
	//Print vars to LOG
	if(Secondary._LOG_ENABLED)LOG.printULwithH1(heading,vars);
};

OnixItem.prototype.checkAvailability = function(quantity)
{
    var priceAvailability = new PriceAvailability(this.isbn,quantity);
    //Get availability
	this.available = (priceAvailability.available) ? true : false;
};

OnixItem.prototype.hasSameISBN = function(isbn)
{
    if(this.isbn && this.isbn == isbn)
    {
        return true;
    } else {
        return false;
    }
};

OnixItem.prototype.isItemAvailable = function()
{
    return this.available;
};



//Function which validates Series Item and sets Item object
OnixItem.prototype.parseOnixProductItem = function()
{
	//1 - docID
	//2 - Distinctive Title
    //3 - Edition Statement
    //4 - Lead Author
    //5 - Publication Date
    //6 - ISBN
    //7 - Price
    //8 - Publisher Name
    //9 - Imprint or Binding
    //10 - Summary (Abstract if it exists otherwise first 300 chars of Main Description)
    //11 - parentID
    //12 - BIC Main Subject Code
    //13 - Subject
    //14 - Area
    //15 - Series	
	
	//17 Inpec col
	
	//Array for log
	var vars = new Array();
	
	//Get isbn
	this.isbn =  this.getISBN13(decodeURIComponent(EDDESK.getFormInput('ISBN')));
	//Get heading for log
	var heading = 'Item: ' + this.isbn + '(from isbn' + (decodeURIComponent(EDDESK.getFormInput('ISBN'))).length + ')';
	
	//Get title
	this.title = (EDDESK.getFormInput('DistinctiveTitle')) ? decodeURIComponent(EDDESK.getFormInput('DistinctiveTitle')) : null;
	vars.push('title: ' + this.title);
	
	//Get title
	this.subTitle = (EDDESK.getFormInput('SubTitle')) ? decodeURIComponent(EDDESK.getFormInput('SubTitle')) : null;
	vars.push('subTitle: ' + this.subTitle);
	
	//Get authors
	this.contributors = (EDDESK.getFormInput('Contributors')) ? decodeURIComponent(EDDESK.getFormInput('Contributors')) : null;
	vars.push('contributors : ' + this.contributors);
	
	//Get publication date
	this.publicationDate = (DH.getElementByTagAndNameAttribute('PublicationDate','input')) 
							? (decodeURIComponent(DH.getElementByTagAndNameAttribute('PublicationDate','input').value)).toDateFromMonthDDYY() 
							: null;
	vars.push('publication date: ' + (this.publicationDate ? this.publicationDate.toGMTString() : null));
	//vars.push('publication date: ' + (this.publicationDate ? this.publicationDate : null));
	vars.push('publication date (unparsed): ' + decodeURIComponent(DH.getElementByTagAndNameAttribute('PublicationDate','input').value));
	
	//Get subject
	this.subject = (EDDESK.getFormInput('Subjects')) ? decodeURIComponent(EDDESK.getFormInput('Subjects')) : null;
	//if subject is not set in EDESK form get it from url parameter
	if(!this.subject)
	{
	    this.subject = (DH.getURLParam('cat')) ? (decodeURIComponent(DH.getURLParam('cat'))).split('>')[0] : null;
	}
	vars.push('subject: ' + this.subject);
	
	//Get area
	this.area = (DH.getURLParam('cat')) ? (decodeURIComponent(DH.getURLParam('cat'))).split('>')[1] : null;
	vars.push('area: ' + this.area);
	
	//Get subject
	this.series = (EDDESK.getFormInput('TitleOfSeries')) ? decodeURIComponent(EDDESK.getFormInput('TitleOfSeries')) : null;
	vars.push('series: ' + this.series);
	
	//Get inspection
	this.inspection = (EDDESK.getFormInput('InspectionStatus') 
						&& EDDESK.getFormInput('InspectionStatus') == '1') ? decodeURIComponent(EDDESK.getFormInput('InspectionStatus')) : null;
	vars.push('inspection: ' + this.inspection);
	
	//Get new price and availability	
	var priceAvailability = new PriceAvailability(this.isbn);
	
	//Get old price
	this.price = this.parseSeriesPrice(decodeURIComponent(EDDESK.getFormInput('Price')));
	//Get new price
	this.price = (priceAvailability.price) ? this.parseSeriesPrice(priceAvailability.price) : this.price;	
	vars.push('price: ' + this.getPriceStr());
	
	//Get availability
	this.available = (priceAvailability.available) ? true : false;
	vars.push('available: ' + this.available);
	
	//Get ship date
	this.shipDate = (typeof priceAvailability.shipDate == 'string' && priceAvailability.shipDate.length != 0) ? (decodeURIComponent(priceAvailability.shipDate)).toDateFromDDMMYY() : null;
	vars.push('ship date: ' + (this.shipDate ? this.shipDate.toGMTString() : null));
	vars.push('ship date (unparsed): ' + decodeURIComponent(priceAvailability.shipDate));
	
	//Print vars to LOG
	if(Secondary._LOG_ENABLED)LOG.printULwithH1(heading,vars);
};

OnixItem.prototype.parseSeriesAuthors = function(str)
{
	//Regular expression used to split string
	var oRe = /,|;\s*/gi;
	return str.split(oRe);
};

//Function to convert string price to float
OnixItem.prototype.parseSeriesPrice = function(price)
{
	//If price is not valid without the dollar sign return null
	if(isNaN(parseFloat(price)) && price.indexOf('$') == -1)return null;
	
	//If price is valid
	if((!isNaN(parseFloat(price))) && price.indexOf('$') == -1)return parseFloat(price);
	
	//Remove dollar sign from string
	price = price.substring(1);
	
	//If price is number return it, otherwise set price to null
	return (isNaN(price)) ? null : parseFloat(price);
};

//Return price of item as string
OnixItem.prototype.getPriceStr = function()
{
    if(this.price)
    {
	    return '$' + this.price.toFixed(2);
	} else {
	    return '--';
	}	
};

//Function to convert isbn10 to isbn13
OnixItem.prototype.getISBN13 = function(isbn)
{
	if(isbn.length == 10)
    {
		//preEditIsbn
		var len = isbn.length;
		var c;
		var s;
	
		if((isbn.substring(0,4) == 'ISBN') || (isbn.substring(0,4) == 'isbn')) 
		{
			isbn = isbn.substring(4, len);
        	len = isbn.length;
		}
		s = "";
		for(var i = 0; i < len; i++) 
		{
        	c = isbn.charAt(i);
        	if((c == '-') || (c == ' '))
            continue;
        	s += c;
    	}		
    	isbn = s;		
		
		//convISBN10toISBN13
		var c;
		var checkDigit = 0;
		var result = "";

		c = '9';
		result += c;
		checkDigit += (c - 0) * 1;

		c = '7';
		result += c;
		checkDigit += (c - 0) * 3;

		c = '8';
		result += c;
		checkDigit += (c - 0) * 1;

		for(var i = 0; i < 9; i++) 
		{  
        	c = isbn.charAt(i);
        	if(i % 2 == 0)
			{
            	checkDigit += (c - 0) * 3;
			} else {
            	checkDigit += (c - 0) * 1;
			}
			result += c;
    	}
    	checkDigit = (10 - (checkDigit % 10)) % 10;
    	result += (checkDigit + "");

    	isbn = result;
    }	
	return isbn;	
};

OnixItem.prototype.getItemLink = function()
{
	// http://wheelsstaging.itechne.com/secondary/onix/isbn/9781420228656?open&div=Secondary&cat=Commerce+and+Business%3EAccounting
	// &template=domSecondary&ed=site/seced3.nsf
	var vars = new Array();
	vars.push('div=' + this._DIVISION);
	if(this.subject && this.area)
	{
		vars.push('cat=' + encodeURIComponent(this.subject.replace(/\s/gi,'+') + '>' + this.area.replace(/\s/gi,'+')));
	} else if(this.subject){
		vars.push('cat=' + encodeURIComponent(this.subject.replace(/\s/gi,'+')));	
	}
	vars.push('template=' + this._TEMPLATE);
	vars.push('ed=' + this._ED);
	
	//return '/secondary/onix/isbn/' + this.isbn + '?open&' + vars.join('&');
	return '/secondary/onix/all/' + this.ID + '?open&' + vars.join('&');
};

OnixItem.prototype.getItemImgSrc = function()
{
	//return 'http://www.macmillan.com.au/mea/covers/thumbnails/' + this.isbn + '.jpg';
    return 'http://www.macmillan.com.au/mea/covers/' + this.isbn + '.jpg';
	//return 'http://secondary3.itechne.com/files/covers/thumbnailsNEW/' + this.isbn + '.jpg';
	//return 'http://www.macmillan.com.au/site/maconixexch.nsf/ea07417a56ce417fca256f9400142125/' + this.ID + '/ed_CoverImageAttachment/0.84?OpenElement&FieldElemFormat=jpg';	
	//return 'http://www.macmillan.com.au/mea/covers/' + this.isbn + '.jpg';
	
};

OnixItem.prototype.published = function()
{
	if(!this.publicationDate)return false;
	
	var today = new Date();
	if(today > this.publicationDate)return true;
	
	return false;
};

OnixItem.prototype.isNewBook = function()
{
	if(!this.publicationDate)return false;
	
	var today = new Date();	
	var one_day = 1000*60*60*24;
    var days = Math.floor((today - this.publicationDate) / one_day);
    if(days <= 180)
	{
	    return true;
    } else {
        return false;
    }
};

OnixItem.prototype.attachSeriesIndex1Item = function(obj)
{
    //Check if tag has already got an image module
    var hasImgModule = OnixItem_ParentHasImgModule(obj);
	if(!hasImgModule)//If there is no image module create it
	{
	    //Create book cover module	
	    var p = document.createElement('p');
	    p.className = 'image';
	    var oAnchor = document.createElement('a');
	    oAnchor.setAttribute('title',this.title);
	    p.appendChild(oAnchor);
	    var img = document.createElement('img');
	    img.setAttribute('alt',this.title);
	    img.onload = optimizeImg;
	    img.onerror = loadNoCoverThumb;
	    img.setAttribute('src',this.getItemImgSrc());
	    oAnchor.appendChild(img);
    	
	    var imgClass = new Array();
	    imgClass.push('ts_' + this.isbn);
	    if(this.isNewBook())
	    {
	        imgClass.push('new');	    
	    }
        if(imgClass.length > 0)
        {
            img.className = imgClass.join(' ');
        }
	    obj.appendChild(p);
	
	} else {//If it has image module remove remaining children
	    OnixItem_ClearParent(obj);
	}
	
	//Attach title
	var oAnchor = DH.createAnchor(this.title,this.getItemLink(),'','',this.title);
	var p = DH.createP(oAnchor,'','');
	obj.appendChild(p);
	
	//Attach price and isbn
	var p = DH.createP(this.getPriceStr(),'','');
	var span = document.createElement('span');
	span.appendChild(document.createTextNode('|'));
	p.appendChild(span);
	p.appendChild(document.createTextNode(this.isbn));
	obj.appendChild(p);
	
	//If item not published yet or not in stock display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			var availability = 'Coming ' + this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			var availability = 'Coming ' + ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : '- no date available');
		} else {
		    var availability = 'Coming - no date available';
		}
	}
	
	if(availability)
	{
		var p = DH.createP(availability,'','available');
		obj.appendChild(p);
	}
	
	//If item is not in cart
	if(Cart && !Cart.isItemInCart(this.isbn))
	{
	    //Create quantity field
	    var oInput = document.createElement('input');
	    oInput.className = 'quantity';
	    oInput.setAttribute('type','text');
	    oInput.setAttribute('name','quantity');
	    var p = DH.createP(oInput,'','addForm');
    	
	    //Create label for quantity field
	    var label = document.createElement('label');
	    label.setAttribute('for','quantity');
	    label.appendChild(document.createTextNode('Units'));
	    p.appendChild(label);
    	
	    //Create add button
	    var oInput = document.createElement('input');
	    oInput.setAttribute('type','image');
	    oInput.setAttribute('src','templates/layout/$file/addToOrder.gif');
	    oInput.setAttribute('value','add to order');
	    oInput.className = 'add';
	    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'B',this.inspection);
	    p.appendChild(oInput);
    	
	    //Attach addForm
	    obj.appendChild(p);
	    if(this.inspection)
	    {
		    //Create inspect button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/inspectItem.gif');
		    oInput.setAttribute('value','inspect item');
		    oInput.className = 'inspect';
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'I',this.inspection);
		    obj.appendChild(oInput);
	    }
    } else {//If item is in cart
        //If item is being inspected
        if(Cart && Cart.isItemBeingInspected(this.isbn))
        {
            //Create inspected button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/removeItemForInspection.gif');
		    oInput.setAttribute('value','inspected item');
		    oInput.className = 'inspect';
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'D');
		    obj.appendChild(oInput);   
        } else {//Display the item as added to cart as purchase or request
            
            var quantity = (Cart && Cart.getItemQuantity(this.isbn) != 0) ? Cart.getItemQuantity(this.isbn) : '';
            
            var p = document.createElement('p');
            p.className = 'added';
            //Attach quantity
            p.appendChild(document.createTextNode(quantity));
            obj.appendChild(p);
            
            //Create remove button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/removeFromOrder.gif');
		    oInput.setAttribute('value','added');
		    oInput.className = 'added';
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'D');
		    obj.appendChild(oInput);  
        }
    }
};


OnixItem.prototype.attachOnixProduct = function(oParent,oChild)
{
	//Create element to hold the item details
	var div = DH.createDiv('onixProduct');
	
	var h3 = document.createElement('h3');
	h3.appendChild(document.createTextNode(this.title));
	div.appendChild(h3);
	
	
	//If there is a subject
	if(this.series)
	{
	    var span = document.createElement('span');
	    span.appendChild(document.createTextNode('Series: '));
	    var p = document.createElement('p');
	    p.appendChild(span);
	    p.appendChild(document.createTextNode(this.series));
		div.appendChild(p);
	}
	
	//If there are contributors
	if(this.contributors)
	{
	    var span = document.createElement('span');
	    span.appendChild(document.createTextNode('Authors: '));
	    var p = document.createElement('p');
	    p.appendChild(span);
	    p.appendChild(document.createTextNode(this.contributors));
		div.appendChild(p);
	}
	
	//Attach ISBN
	var span = document.createElement('span');
	span.appendChild(document.createTextNode('ISBN: '));
	var p = document.createElement('p');
	p.appendChild(span);
	p.appendChild(document.createTextNode(this.isbn));
	div.appendChild(p);
	
	//Attach Price
	var span = document.createElement('span');
	span.appendChild(document.createTextNode('RRP: '));
	var p = document.createElement('p');
	p.appendChild(span);
	p.appendChild(document.createTextNode(this.getPriceStr()));
	div.appendChild(p);
	
	//If item not published yet or not in stock display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			var availability = 'Coming ' + this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			var availability = 'Coming ' + ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : '- no date available');
		} else {
		    var availability = 'Coming - no date available';
		}
		
	}
	
	if(availability)
	{
		var p = DH.createP(availability,'','available');
		div.appendChild(p);
	}
	
	if(this.series && this.subject)
	{
	    //Attach tabs
	    var ulTabs = document.createElement('ul');
    	ulTabs.className = 'tabs';
    	
    	//if there are table of contents
	    var contents = new Contents(this.subject,this.area,this.isbn);
    	contents.attach(ulTabs);
	    //If there is more info
	    var moreInfo = new MoreInfo(this.subject,this.area,this.isbn);
	    moreInfo.attach(ulTabs);
	    
	    //If there are any of the tabs create a Summary tab
	    if(contents.loaded || moreInfo.loaded)
	    {
	        var tempArray = new Array();
            tempArray.push('div=Secondary');
            tempArray.push('cat=' + this.subject + '>' + this.area);
            tempArray.push('template=domSecondary');
            tempArray.push('ed=site/seced31.nsf');
            var aHref = '/secondary/onix/isbn/' + this.isbn + '?open&' + decodeURIComponent(tempArray.join('&'));
            
            var a = document.createElement('a');
            a.setAttribute('href',aHref);
            a.setAttribute('title','Summary');
            if(!DH.getURLParam('onixtype'))a.className = 'current';
            var span = document.createElement('span');
            span.appendChild(document.createTextNode('Summary'));
            a.appendChild(span);
    
            var li = document.createElement('li');
            li.appendChild(a);
            ulTabs.appendChild(li); 
	    }
	    
	    if(moreInfo.loaded || contents.loaded)
	    {
	        if(Secondary._LOG_ENABLED)LOG.printH1('ulTabs.hasChildren');
	        div.appendChild(ulTabs);   
	    }
    }
	
	//Attach onixProduct details to page
	oParent.insertBefore(div,oChild);
	
	//Create element to hold the item form
	var div = DH.createDiv('onixProductForm');
	/*
	//Attach quantity input
	var oInput = document.createElement('input');
	oInput.setAttribute('type','text');
	oInput.setAttribute('name','quantity');
	oInput.setAttribute('id','quantity');
	div.appendChild(oInput);
	
	//Attach label
	var oLabel = document.createElement('label');
	oLabel.setAttribute('for','quantity');
	oLabel.appendChild(document.createTextNode('Units'));
	div.appendChild(oLabel);
	
	//Attach add to order input
	var oInput = document.createElement('input');
	oInput.setAttribute('type','image');
	oInput.setAttribute('src','templates/layout/$file/addToOrder.gif');
	oInput.setAttribute('value','add to order');
	oInput.className = 'add';
	OnixItem_AddIndexEvent(oInput,'click',this.isbn,'B', this.inspection);
	div.appendChild(oInput);

	if(this.inspection)
	{
		//Create inspect button
		var oInput = document.createElement('input');
		oInput.setAttribute('type','image');
		oInput.setAttribute('src','templates/layout/$file/inspectItem.gif');
		oInput.setAttribute('value','inspect item');
		oInput.className = 'inspect';
		OnixItem_AddIndexEvent(oInput,'click',this.isbn,'I', this.inspection);
		div.appendChild(oInput);
	}
    */
    
    this.attachOnixProductForm(div);
    
	//Attach onixProduct details to page
	oParent.insertBefore(div,oChild);
};

OnixItem.prototype.attachOnixProductForm = function(div)
{
    //Clear parent
    OnixItem_ClearParent(div);
    
    //If item is not in cart
	if(Cart && !Cart.isItemInCart(this.isbn))
	{
        //Attach quantity input
	    var oInput = document.createElement('input');
	    oInput.setAttribute('type','text');
	    oInput.setAttribute('name','quantity');
	    oInput.setAttribute('id','quantity');
	    div.appendChild(oInput);
    	
	    //Attach label
	    var oLabel = document.createElement('label');
	    oLabel.setAttribute('for','quantity');
	    oLabel.appendChild(document.createTextNode('Units'));
	    div.appendChild(oLabel);
    	
	    //Attach add to order input
	    var oInput = document.createElement('input');
	    oInput.setAttribute('type','image');
	    oInput.setAttribute('src','templates/layout/$file/addToOrder.gif');
	    oInput.setAttribute('value','add to order');
	    oInput.className = 'add';
	    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'B', this.inspection);
	    div.appendChild(oInput);

	    if(this.inspection)
	    {
		    //Create inspect button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/inspectItem.gif');
		    oInput.setAttribute('value','inspect item');
		    oInput.className = 'inspect';
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'I', this.inspection);
		    div.appendChild(oInput);
	    }
    } else {
        //If item is being inspected
        if(Cart && Cart.isItemBeingInspected(this.isbn))
        {
            //Create inspected button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/removeItemForInspection.gif');
		    oInput.setAttribute('value','inspected item');
		    oInput.className = 'inspect';
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'D');
		    div.appendChild(oInput);   
		    
        } else {
            var quantity = (Cart && Cart.getItemQuantity(this.isbn) != 0) ? Cart.getItemQuantity(this.isbn) : '';
            
            //Attach added graphic
            var span = document.createElement('span');
            span.className = 'added';
            span.appendChild(document.createTextNode(quantity));  
            div.appendChild(span); 
            
            //Create remove button
		    var oInput = document.createElement('input');
		    oInput.setAttribute('type','image');
		    oInput.setAttribute('src','templates/layout/$file/removeFromOrder.gif');
		    oInput.setAttribute('value','added');
		    OnixItem_AddIndexEvent(oInput,'click',this.isbn,'D');
		    div.appendChild(oInput);  
        }
    }
};

OnixItem.prototype.attachOnixProductTeacherSupport = function(oParent,oChild)
{
	//Create element to hold the item details
	var div = DH.createDiv('onixProduct');
	
	var h3 = document.createElement('h3');
	
	if(typeof this.isbn != 'string' || this.isbn.length != 13)
	{
		this.title = unescape(document.forms[0].Headline.value);
	}
	var back = document.createElement('div');
	back.setAttribute('align','right');
	
	var url = document.referrer;
	
	back.innerHTML = "<a href='"+ url +"'>Go back</a>";

	h3.appendChild(document.createTextNode(this.title));
	div.appendChild(back);
	div.appendChild(h3);
	
	/*
	//If there is a subtitle
	if(this.subTitle)
	{
		var h4 = document.createElement('h4');
		h4.appendChild(document.createTextNode(this.subTitle));
		div.appendChild(h4);
	}
	*/
	
	//If there is a subject
	if(this.series)
	{
	    var span = document.createElement('span');
	    span.appendChild(document.createTextNode('Series: '));
	    var p = document.createElement('p');
	    p.appendChild(span);
	    p.appendChild(document.createTextNode(this.series));
		div.appendChild(p);
	}
	
	//If there are contributors
	if(this.contributors)
	{
	    var span = document.createElement('span');
	    span.appendChild(document.createTextNode('Authors: '));
	    var p = document.createElement('p');
	    p.appendChild(span);
	    p.appendChild(document.createTextNode(this.contributors));
		div.appendChild(p);
	}
	
	//Attach ISBN
	var span = document.createElement('span');
	span.appendChild(document.createTextNode('ISBN: '));
	var p = document.createElement('p');
	p.appendChild(span);
	
	if(typeof this.isbn != 'string' || this.isbn.length != 13)
	{
		this.isbn = unescape(document.forms[0].MetaKeywords.value).replace(/\s/ig, '');
	}

	p.appendChild(document.createTextNode(this.isbn));
	div.appendChild(p);
	
	//Attach Price
	var span = document.createElement('span');
	span.appendChild(document.createTextNode('RRP: '));
	var p = document.createElement('p');
	p.appendChild(span);
	p.appendChild(document.createTextNode(this.getPriceStr()));
	div.appendChild(p);
	
	//If item not published yet or not in sotck display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			var availability = 'Coming ' + this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			var availability = 'Coming ' + ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : '- no date available');
		} else {}
	}
	
	if(availability)
	{
		var p = DH.createP(availability,'','available');
		div.appendChild(p);
	}
	
	//Attach onixProduct details to page
	oParent.insertBefore(div,oChild);
};

OnixItem.prototype.attachOnixProductRelatedTitles = function(oParent)
{
    if(!this.series || !this.subject)return;
    var relatedTitles = new RelatedTitles(this.subject,this.series,this.area);
    relatedTitles.attach(oParent);
};

OnixItem.prototype.attachOnixProductLinks = function()
{
    var oParent = document.getElementById('edDeskBody').getElementsByTagName('table')[0].getElementsByTagName('td')[0];
    //oParent.className = 'OnixDeskBookHolder';
    
    var ul = document.createElement('ul');
    
    this.attachOnixProductLinks_IMG(ul);
    
    this.attachOnixProductLinks_PDF(ul);
    
    this.attachOnixProductLinks_TS(ul);
    
    oParent.appendChild(ul);
};

OnixItem.prototype.attachOnixProductLinks_IMG = function(ul)
{
    var winLoc = window.location.toString();
    if(winLoc.indexOf('macmillan.com.au') != -1)//Is it the test site
    {
        var imgPath = 'http://www.macmillan.com.au/mea/downloadcovers/' + this.isbn + '.jpg';
    } else {
                var imgPath = '/mea/downloadcovers/' + this.isbn + '.jpg';
           }
    
    var imgLoad = new HeaderLoader(imgPath);
    if(imgLoad.exist)
    {
        var a = document.createElement('a');
        a.appendChild(document.createTextNode('Download cover'));
        a.setAttribute('href',imgPath);
        a.setAttribute('title',this.title);
        var li = document.createElement('li');    
        li.appendChild(a);
        ul.appendChild(li);
    }
};

OnixItem.prototype.attachOnixProductLinks_PDF = function(ul)
{
    var winLoc = window.location.toString();
    if(winLoc.indexOf('macmillan.com.au') != -1)//Is it the test site
    {
        var pdfPath = 'http://www.macmillan.com.au/mea/downloadpdfs/' + this.isbn + '.pdf';
    } else {
                var pdfPath = '/mea/downloadpdfs/' + this.isbn + '.pdf';
           }
    
    var pdfLoad = new HeaderLoader(pdfPath);
    if(pdfLoad.exist)
    {
        var a = document.createElement('a');
        a.appendChild(document.createTextNode('Sample pages'));
        a.setAttribute('href',pdfPath);
        a.setAttribute('title',this.title);
        var li = document.createElement('li');    
        li.appendChild(a);
        ul.appendChild(li);
    }
};

OnixItem.prototype.attachOnixProductLinks_TS = function(ul)
{
    var ts = new TeacherSupport(this.isbn);
    ts.loadAjax();
    if(ts.loaded)
    {
        var a = document.createElement('a');
        a.className = 'teacherSupport';
        a.setAttribute('href','/secondary31/site/articleIDs/' + decodeURIComponent(ts.index.viewDocID) + '?open&template=domSecondary');
        a.appendChild(document.createTextNode('Teacher Support'));        
        
        var aTS = document.createElement('a');
        aTS.className = 'ts';
        aTS.appendChild(document.createTextNode('Teacher Support'));
        
        var li = document.createElement('li');
        li.className = 'ts';
        
        li.appendChild(a);
        li.appendChild(aTS);
        ul.appendChild(li);
    }
};

OnixItem.prototype.attachSummaryRow = function(tbody)
{
    var tr = document.createElement('tr');
    
    //Attach isbn
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(this.isbn));
    tr.appendChild(td);
    
    //Attach title field
    var a = document.createElement('a');
    a.setAttribute('href',this.getItemLink());
    a.setAttribute('title',this.title);
    a.appendChild(document.createTextNode(this.title));
    var td = document.createElement('td');
    td.className = 'title';
    td.appendChild(a);
    tr.appendChild(td);
    
    //Attach price
    var td = document.createElement('td');
    td.appendChild(document.createTextNode('$' + this.price.toFixed(2)));
    tr.appendChild(td);
    
    //Attach eClub Price
    /*var td = document.createElement('td');
    td.appendChild(document.createTextNode('-'));
    tr.appendChild(td);*/
    
    //Attach quantity
    var oInput = document.createElement('input');
    oInput.setAttribute('type','text');
    oInput.className = 'quantity';
    //If item is being inspected
    if(Cart.isItemBeingInspected(this.isbn))
    {
        oInput.disabled = true;
    }
    oInput.setAttribute('value',this.quantity);
    OnixItem_AddCartSummaryEvent(oInput,'keyup',this.isbn,'quantity');
    var td = document.createElement('td');
    td.appendChild(oInput);
    tr.appendChild(td);
    
    var radioName = 'inspect_buy_' + this.isbn;
    
    //Attach inspect radio button
    try {
        var inspection = "";
        if(!this.inspection)inspection = "disabled='disabled'";
        var checked = "";
        if(Cart.isItemBeingInspected(this.isbn))checked = "checked='checked'";
        var oInput = document.createElement("<input type='radio' name='" + radioName + "' " + inspection + " " + checked + " />");
    } catch(oError) {
        var oInput = document.createElement('input');
        oInput.setAttribute('type','radio');
        oInput.setAttribute('name',radioName);
        //If item can be inspected
        if(!this.inspection)
        {
            oInput.disabled = true;
        }
        if(Cart.isItemBeingInspected(this.isbn))
        {
            oInput.checked = true;
        }
    }
    oInput.setAttribute('value','inspect');
    oInput.className = 'inspect';
    OnixItem_AddCartSummaryEvent(oInput,'click',this.isbn,'inspect');
    var td = document.createElement('td');
    td.appendChild(oInput);
    tr.appendChild(td);
    
    //Attach buy radio button
    try {
        if(!Cart.isItemBeingInspected(this.isbn))
        {
            var oInput = document.createElement("<input type='radio' name='" + radioName + "' checked='checked' />");
        } else {
            var oInput = document.createElement("<input type='radio' name='inspect_buy' />");
        }
    } catch(oError) {
        var oInput = document.createElement('input');
        oInput.setAttribute('type','radio');
        oInput.setAttribute('name',radioName);
        if(!Cart.isItemBeingInspected(this.isbn))
        {
            oInput.checked = true;
        }
    }
    OnixItem_AddCartSummaryEvent(oInput,'click',this.isbn,'buy');
    oInput.setAttribute('value','buy');
    oInput.className = 'buy';
    
    var td = document.createElement('td');
    td.appendChild(oInput);
    tr.appendChild(td);
    
    //Attach total
    var td = document.createElement('td');
    td.appendChild(document.createTextNode('$' + Cart.getItemTotal(this.isbn).toFixed(2)));
    tr.appendChild(td);
    
    //Attach availability
    //If item not published yet or not in stock display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			var availability = this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			var availability = ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : 'no date available');
		} else {
		    var availability = 'no date available';
   		    //var availability = '';
		}
	} else {
	    var availability = document.createElement('img');
	    availability.src = 'templates/layout/$file/buyInspectOn.jpg';
	    availability.setAttribute('alt','available');
	}
	var td = document.createElement('td');
	if(typeof availability == 'string')
	{
	    td.appendChild(document.createTextNode(availability));
	} else {
	    td.appendChild(availability);
	}
	tr.appendChild(td);
	
	//Attach remove button
	var oInput = document.createElement('input');
    oInput.setAttribute('type','button');
    oInput.setAttribute('value','remove');
    oInput.className = 'remove';
    OnixItem_AddCartSummaryEvent(oInput,'click',this.isbn,'remove');
	var td = document.createElement('td');
	td.className = 'last';
	td.appendChild(oInput);
	tr.appendChild(td);
	
	tbody.appendChild(tr);
};


OnixItem.prototype.attachSummaryRowCheckoutStep3 = function(tbody)
{
    var tr = document.createElement('tr');
    
    //Attach isbn
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(this.isbn));
    tr.appendChild(td);
    
    //Attach title field
    var a = document.createElement('a');
    a.setAttribute('href',this.getItemLink());
    a.setAttribute('title',this.title);
    a.appendChild(document.createTextNode(this.title));
    var td = document.createElement('td');
    td.className = 'title';
    td.appendChild(a);
    tr.appendChild(td);
    
    //Attach price
    var td = document.createElement('td');
    td.appendChild(document.createTextNode('$' + this.price.toFixed(2)));
    tr.appendChild(td);
    
    //Attach eClub Price
    /*var td = document.createElement('td');
    td.appendChild(document.createTextNode('-'));
    tr.appendChild(td);
    */
    
    //Attach quantity
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(this.quantity));
    tr.appendChild(td);
    
    //Attach inspection
    var td = document.createElement('td');
    var img = document.createElement('img');
    if(Cart.isItemBeingInspected(this.isbn))
    {
	    img.src = 'templates/layout/$file/buyInspectOn.jpg';
	    img.setAttribute('alt','inspected');
    } else {
        img.src = 'templates/layout/$file/spacer.gif';
	    img.setAttribute('alt','not inspected');
    }
    td.appendChild(img);
    tr.appendChild(td);
    
    //Attach buy
    var td = document.createElement('td');
    var img = document.createElement('img');
    if(!Cart.isItemBeingInspected(this.isbn))
    {
	    img.src = 'templates/layout/$file/buyInspectOn.jpg';
	    img.setAttribute('alt','inspected');
    } else {
        img.src = 'templates/layout/$file/spacer.gif';
	    img.setAttribute('alt','not purchased');
    }
    td.appendChild(img);
    tr.appendChild(td);
    
    //Attach total
    var td = document.createElement('td');
    td.appendChild(document.createTextNode('$' + Cart.getItemTotal(this.isbn).toFixed(2)));
    tr.appendChild(td);
    
    //Attach availability
    //If item not published yet or not in stock display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			var availability = this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			var availability = ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : 'no date available');
		} else {
		    var availability = 'no date available';
   		    //var availability = '';
		}
	} else {
	    var availability = document.createElement('img');
	    availability.src = 'templates/layout/$file/buyInspectOn.jpg';
	    availability.setAttribute('alt','available');
	}
	var td = document.createElement('td');
	if(typeof availability == 'string')
	{
	    td.appendChild(document.createTextNode(availability));
	} else {
	    td.appendChild(availability);
	}
	td.className = 'last';
	tr.appendChild(td);
	/*
	//Attach remove button
	var oInput = document.createElement('input');
    oInput.setAttribute('type','button');
    oInput.setAttribute('value','remove');
    oInput.className = 'remove';
    OnixItem_AddCartSummaryEvent(oInput,'click',this.isbn,'remove');
	var td = document.createElement('td');
	td.className = 'last';
	td.appendChild(oInput);
	tr.appendChild(td);
	*/
	tbody.appendChild(tr);
};

OnixItem.prototype.attachCheckoutHiddenInputs = function(oForm,i)
{
    i += 1;
    oForm.appendChild(DH.createHiddenInput('book' + i + '_ProdId',this.isbn));
    oForm.appendChild(DH.createHiddenInput('book' + i + '_Desc',this.title));
    switch(this.purchaseType)
    {
        case 'B': var sValue = '1'; break;
        case 'I': var sValue = '2'; break;
        case 'R': var sValue = '3'; break;
        default: throw new Error('OnixItem.attachCheckoutHiddenInputs() expected item\'s purchaseType to be set.');
    }
    
    oForm.appendChild(DH.createHiddenInput('book' + i + '_OrderType',sValue));
    oForm.appendChild(DH.createHiddenInput('book' + i + '_RRP',this.price));
    oForm.appendChild(DH.createHiddenInput('book' + i + '_QTY',this.quantity));
};



/*----------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/

function loadNoCoverThumb()
{
    this.src = 'templates/layout/$file/noCover.gif';
}

function optimizeImg()
{
    var width = parseInt(this.width);
    var height = parseInt(this.height);
    var wh = (width > height) ? 'w' : 'h';
    /*
    if(Secondary._LOG_ENABLED)
    {
            LOG.printH1('BEFORE RESIZED:\n'
                        + this.src.split('/')[this.src.split('/').length - 1]
                        + '\nw: ' + width
                        + '\nh: ' + height
                        );
    }
    */
    //Does it need resizing?    
    var needsResizing = (wh == 'h' && height > 131) || (wh == 'w' && width > 110);
        
    if(needsResizing && this.src.indexOf('noCover') == -1)
    {
        var dimensions = resizeImg.call(this);   
        width = dimensions[0];
        height = dimensions[1];        
    }
        
    if(this.className)
    {
        var parent = this.parentNode;
        while(parent.nodeName.toLowerCase() != 'p')
        {
            parent = parent.parentNode;
        }
        
        if(this.className.indexOf('new') != -1)
        {
            var span = document.createElement('span');
            span.className = 'new';
            span.style.left = (width - 20) + 'px';
            span.style.top = ((131 - height) + 10) + 'px';
            span.appendChild(document.createTextNode('new'));
            parent.appendChild(span);
        }
        
        if(this.className.indexOf('ts') != -1)
        {
            var isbn = this.className.split(' ')[0].split('_')[1];
            var ts = new TeacherSupport(isbn);
            ts.loadAjax();
            if(ts.loaded)
            {
                var a = document.createElement('a');
                a.className = 'ts';
                a.setAttribute('href','/secondary31/site/articleIDs/' + decodeURIComponent(ts.index.viewDocID) + '?open&template=domSecondary');
                a.setAttribute('title','Teacher Support');
                a.style.left = (width + 10) + 'px';
                //a.style.top = ((131 - height) + 10) + 'px';
                //a.style.top = (height - 10) + 'px';
                a.style.top =  '101px';
                a.appendChild(document.createTextNode('Teacher Support'));
                parent.appendChild(a);
            }   
        }
    }
    
    
    
}

function resizeImg()
{
    var width = parseInt(this.width);
    var height = parseInt(this.height);
    
    if(height > width)
    {
        var percentage = ((131*100)/height)/100;
    } else {
        var percentage = ((110*100)/width)/100;
    }   
    
    this.style.height = Math.floor(height * percentage) + 'px';
    this.style.width = Math.floor(width * percentage) + 'px';
    
    /*
    if(Secondary._LOG_ENABLED)
    {
        LOG.printH1('IMAGE RESIZED:\n'
                    + this.src.split('/')[this.src.split('/').length - 1]
                    + '\nw: ' + Math.floor(width * percentage)
                    + '\nh: ' + Math.floor(height * percentage)
                    );
    }
    */
    return [Math.floor(width * percentage),Math.floor(height * percentage)];
    
    
}


/*------------------------------------------------------------------------------------------------------------------
*/

//Function to attach click events to cart items
// eElement - element to attach the event to
// eType - type of event
// isbn - item's isbn
// eActionType - type of action to be executed (add,delete,inspect, etc..)
function OnixItem_AddIndexEvent(eElement,eType,isbn,eActionType,eInspection)
{
    var eventISBN = isbn;
    var eventActionType = eActionType;
    var inspection = eInspection;
    
    var OnixItem_onClick = function(event)
    {
        var vars = new Array();
        vars.push('ISBN: ' + eventISBN);
        vars.push('action: ' + eventActionType);
        vars.push('inspection: ' + inspection);
        
        var target = DH.stopEvent(event);
        
        switch(eventActionType)
        {
            case 'B':
                var quantity = OnixItem_GetQuantity.call(this);
                break;
            case 'I':
                var quantity = 1;
                break;
            case 'D':
                var quantity = -1;
                break;
            default:
        }
        
        vars.push('quantity: ' + quantity);
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('OnixItem_onClick() - values to passed to Cart.add():',vars);
        
        if(Cart && Cart.add)
        {
            switch(eventActionType)
            {
                case 'B':
                case 'I':
                    Cart.add(eventISBN,quantity,eventActionType,inspection);
                    //Get reference to parent element
                    var oParent = OnixItem_GetItemHolder.call(this);
                    if(oParent)Cart.updateItem(eventISBN,oParent);
                    break;
                case 'D':
                    var item = Cart.remove(eventISBN);
                    //Get reference to parent element
                    var oParent = OnixItem_GetItemHolder.call(this);
                    if(oParent)Cart.updateItem(item,oParent);
                    break;
                default:
            }
            Cart.attachMiniCart(document.getElementById('contentRight'));
        }
    };
    
    //Attach event to element
    DH.addEvent(eElement,eType,OnixItem_onClick);
}

//Function which returns quantity for an index item
function OnixItem_GetQuantity()
{
    var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
    
    if(isOnixProductPage)
    {
        var quantity = document.getElementById('quantity');
        if(quantity)quantity = quantity.value;
    } else {
        var parent = this.parentNode;
        do{
            if(parent.tagName && parent.tagName.toLowerCase() == 'li')
            {
                var parentFound = true;
            } else {
                parent = parent.parentNode;
            }
        } while(!parentFound)
        var inputs = DH.getElementsByClassName('quantity','input',parent);
        if(inputs.length == 1)
        {
            var quantity = inputs[0].value
        }
    }
    
    if(quantity)
    {
        quantity = (quantity.length > 0 && (!isNaN(quantity.trim()))) ? parseInt(quantity.trim()) : 1;
        return quantity;
    } else {
        return 1;
    }
}

//Function which returns parent of item
function OnixItem_GetItemHolder()
{
    var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
    
    if(isOnixProductPage)
    {
        var oParent = document.getElementById('onixProductForm');
    } else {
        var parent = this.parentNode;
        do{
            if(parent.tagName && parent.tagName.toLowerCase() == 'li')
            {
                var oParent = parent;
                var parentFound = true;
            } else {
                parent = parent.parentNode;
            }
        } while(!parentFound)
    }
    if(oParent)
    {
        return oParent;
    } else {
        return null;
    }
}

function OnixItem_ParentHasImgModule(obj)
{
    var p = obj.getElementsByTagName('*');
    for(var i = 0; i < p.length; i++)
    {
        if(p[i].tagName 
           && p[i].tagName.toLowerCase() == 'p'
           && p[i].className
           && p[i].className == 'image')
        {
            return true;
        }
    }   
    return false;
}

function OnixItem_ClearParent(obj)
{
    if(!obj.hasChildNodes())return;
    
    var children = obj.childNodes;    
    for(var i = (children.length - 1); i >= 0; i--)
    {
        if(children[i].nodeType != 1 
           || !children[i].className 
           || children[i].className != 'image')
        {
            var vars = new Array();
            vars.push('nodeType: ' + children[i].nodeType);
            vars.push('tagName: ' + ((children[i].tagName) ? children[i].tagName : ''));
            //if(Secondary._LOG_ENABLED)LOG.printULwithH1('OnixItem_ClearParent() - removing ',vars);
            obj.removeChild(children[i]);
        }
    }   
    
}

function OnixItem_AddItems(oEvent)
{
    var target = DH.stopEvent(oEvent);
    
    var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
    //If it is not a book page
    if(!isOnixProductPage)
    {
        var fields = DH.getElementsByClassName('quantity','input',null);
        if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_AddItems() - quantity fields num '+ fields.length);
        for(var i = 0; i < fields.length; i++)
        {
            if(fields[i].value && typeof fields[i].value == 'string' && fields[i].value.length > 0)
            {
                if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_AddItems() - field ['+ i + '] = ' + fields[i].value);
                var oParent = OnixItem_GetItemHolder.call(fields[i]);
                var addBtn = DH.getElementsByClassName('add','input',oParent);
                addBtn[0].click();
            }
        }
    } else {
        var addBtn = DH.getElementsByClassName('add','input',document.getElementById('onixProductForm'));
        addBtn[0].click();
    }
}


/*------------------------------------------------------------------------------------------------------------------
*/

//Function to attach click events to cart items
// eElement - element to attach the event to
// eType - type of event
// isbn - item's isbn
// eActionType - type of action to be executed (quantity,inspect, buy, remove etc..)
function OnixItem_AddCartSummaryEvent(eElement,eType,isbn,eActionType)
{
    var eventISBN = isbn;
    var eventActionType = eActionType;
    
    var OnixItem_summaryEvent = function(event)
    {
        var vars = new Array();
        vars.push('ISBN: ' + eventISBN);
        vars.push('action: ' + eventActionType);
        
        var target = DH.stopEvent(event);
        
        switch(eventActionType)
        {
            case 'quantity':
                var keyValue = (DH.getKeyPressed(event)).value;
                var keyCode = (DH.getKeyPressed(event)).code;
                if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_summaryEvent() - key pressed = ' + keyCode);
                //var keyValues = ['0','1','2','3','4','5','6','7','8','9','0'];
                //if(!keyValues.hasString(keyValue))return;
                if((keyCode < 48 || keyCode > 57) && (keyCode < 96 || keyCode > 105) && keyCode != 8)return;
                
                target.setAttribute('id','QuantityKeyUp');
                if(typeof QuantityKeyUpInterval == 'undefined' || !QuantityKeyUpInterval)
                {
                    QuantityKeyUpInterval = setTimeout('OnixItem_QuantityKeyUpIntervalListener("' + eventISBN + '")',600);
                    if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_summaryEvent() - setting QuantityKeyUpInterval for first time');
                } else {
                    clearInterval(QuantityKeyUpInterval);                        
                    QuantityKeyUpInterval = setTimeout('OnixItem_QuantityKeyUpIntervalListener("' + eventISBN + '")',600);
                    if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_summaryEvent() - clearing QuantityKeyUpInterval and setting again');
                } 
                return;   
                //if(Secondary._LOG_ENABLED)LOG.printULwithH1('summaryEvent() - values to passed to Cart.setQuantity():',vars);
                break;
            case 'inspect':
                Cart.setPurchaseType(eventISBN,'I');
                if(Secondary._LOG_ENABLED)LOG.printULwithH1('summaryEvent() - values to passed to Cart.setPurchaseType():',vars);
                break;
            case 'buy':
                Cart.setPurchaseType(eventISBN,'B'); 
                if(Secondary._LOG_ENABLED)LOG.printULwithH1('summaryEvent() - values to passed to Cart.setPurchaseType():',vars);      
                break;
            case 'remove':
                var item = Cart.remove(eventISBN);
                if(Secondary._LOG_ENABLED)LOG.printULwithH1('summaryEvent() - values to passed to Cart.remove():',vars);
                break;
            default:
        }
        
        Cart.attachMiniCart(document.getElementById('contentRight'));
        Cart.attachSummary(document.getElementById('cartSummary'));
    };
    
    //Attach event to element
    DH.addEvent(eElement,eType,OnixItem_summaryEvent);
}

function OnixItem_QuantityKeyUpIntervalListener(isbn)
{
    if(Secondary._LOG_ENABLED)LOG.printH1('OnixItem_summaryEvent() - timeout processed');  
    var quantity = document.getElementById('QuantityKeyUp').value;
    quantity = (quantity.length > 0 && (!isNaN(quantity.trim()))) ? parseInt(quantity.trim()) : 1;    
    
    Cart.setQuantity(isbn,quantity);
                    
    OnixItem_QuantityKeyUpCeased = null;
    QuantityKeyUpInterval = null;
                    
    Cart.attachMiniCart(document.getElementById('contentRight'));
    Cart.attachSummary(document.getElementById('cartSummary'));
}























