/**
 * Combined js files into single script for Seconday edDesk dom template
 */

/*
 * Set page title and conditional resource loads
 */

if (document.forms[0].PageType.value == "onixProduct") {
  document.title = "Secondary - " + unescape(document.forms[0].DistinctiveTitle.value);
  
  // Check friendly book URLs and redirect if classification parameters needed
  	if (window.location.toString().indexOf('secondary/book') != -1) 
	  {
	  	var redirectParams = "&cat=" + document.forms[0].Cat.value + "&div=" + document.forms[0].Div.value;
	  	window.location = "/secondary/onix/isbn/" + document.forms[0].ISBN.value + "?open" + redirectParams;
	  }
  else if(window.location.toString().indexOf('&cat=') == -1)
  {
  	var redirectParams = "&cat=" + document.forms[0].Subjects.value + ">" + document.forms[0].Areas.value + "&template=domSecondary";
  	window.location = "/secondary/onix/isbn/" + document.forms[0].ISBN.value + "?open" + redirectParams;
  }
}



/**
 * array.js
 */
// Extend ARRAY class

Array.prototype.hasString = function(str)
{
    for(var i = 0; i < this.length; i++)
    {
        if(this[i] == str)return true;
    }
    return null;
};
Array.prototype.hasArray = function(oArray)
{
    if(this.length < oArray.length)return null;//if current array length is not even equal
    
    var x = 0;
    for(var i = 0; i < oArray.length; i++)
    {
        if(this.hasString(oArray[i]))x++;
    }
    
    if(x == oArray.length)
    {
        return true;
    }
    return null;
};

Array.prototype.areAllTheSame = function()
{
	if(this.length == 0) return true;
	var str = this[0];
	for(var i = 0; i < this.length; i++)
	{
		if(this[i] != str) return false;	
	}
	return true;
};



/**
 * string.js
 */
// Extending the STRING object


String.prototype.toDateFromDDMMYY = function()
{
	//REgular expression to test character '/'
	var oRe = /\//gi;
	
	//If date is not delemited by the character '/'
	//if(!oRe.test(this))
	if(this.indexOf('/') == -1)
	{
		throw new Error('String.toDateFromDDMMYY() expects date \'' + this + '\' delimited with character \'/\'');
	}
	
	//split date string
	var split = this.split(oRe);
	
	//Regular expression to check whether data starts with a '0' character
	var oRe = /^0/gi;
	
	//Get date parts
	//var day = (oRe.test(split[0]) == true) ? split[0].substring(1) : split[0];
	//var month = (oRe.test(split[1]) == true) ? split[1].substring(1) : split[1];
	var day = (split[0].substring(0,1) == '0') ? split[0].substring(1) : split[0];
	var month = (split[1].substring(0,1) == '0') ? split[1].substring(1) : split[1];
	var year = split[2];
	
	//if(Secondary._LOG_ENABLED)LOG.printH1(day + '/' + month + '/' + year);
	
	//Validate date
	if(isNaN(day) || isNaN(month) || isNaN(year))
	{
		throw new Error('String.toDateFromDDMMYY() expect date \'' + this + '\' with numerica values for day(' + day + '), month(' + month + ') and yesr (' + year + ')');
	}
	
	//Set date
	var oDate = new Date();
	oDate.setFullYear(parseInt(year),parseInt(month) - 1, parseInt(day), 0, 0, 0);
	
	return oDate;
};

//Returns date from date string e.g. 'August 28 2008'
String.prototype.toDateFromMonthDDYY = function()
{
	var dateSplit = this.split(/,?\s/gi);
	
	if(dateSplit.length != 3)
	{
		throw new Error('String.toDateFromMonthDDYY() the Date \'' + this + '\' does not match the expected format of \'August 22, 2008\'');
	}
	
	if(isNaN(dateSplit[1]))throw new Error('String.toDateFromMonthDDYY() expects a numeric value for the day');
	if(isNaN(dateSplit[2]))throw new Error('String.toDateFromMonthDDYY() expects a numeric value for the year');
	
	var index = -1;
	var months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
	for(var i = 0; i < months.length; i++)
	{
		if(dateSplit[0].toLowerCase().indexOf(months[i]) != -1)
		{
			index = i;
		}
	}
	
	if(index == -1)
	{
		throw new Error('String.toDateFromMonthDDYY() Month in date does not match any of the months in the year');
	}
	
	var day = (dateSplit[1].substring(0,1) == '0') ? dateSplit[1].substring(1) : dateSplit[1];
	var month = index;
	var year = dateSplit[2];
	
	//Set date
	var oDate = new Date();
	oDate.setFullYear(parseInt(year),month, parseInt(day), 0, 0, 0);	
	return oDate;
	
};

String.prototype.trim = function () 
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


/**
 * date.js
 */

// Extend DATE class

Date.prototype.toDDMMYYYYString = function()
{
	var day = (this.getDate() < 10) ? '0' + this.getDate() : this.getDate();
	var month = (this.getMonth() < 9) ? '0' + (this.getMonth() + 1) : (this.getMonth() + 1);
	var year = this.getFullYear();
	
	return day + '/' + month + '/' + year;
};


/**
 * log.js
 */

(function(){
		  
	//The EDDESK namespace
	if(!window.LOG) { window['LOG'] = {} }

    function createUL(arg)
    {
        var ul = document.createElement('ul');
        ul.setAttribute('id','log');
        return ul;
    }
    window['LOG']['createUL'] = createUL;	

    function createLI(arg)
    {
        var li = document.createElement('li');
        
        if(typeof arg == 'string')
        {
            var p = document.createElement('p');
            p.appendChild(document.createTextNode(arg));
            li.appendChild(p);
        } else {
            li.appendChild(arg);
        }        
        return li;
    }
    window['LOG']['createLI'] = createLI;	
    
    function print(arg)
    {
        //If log window does not exist create it
        if(document.getElementById('log') == null)
        {
            var ul = createUL();
            ul.appendChild(createLI(arg));
            document.getElementById('wrapper').appendChild(ul);
        } else {
            if(!ul)ul = document.getElementById('log');
            document.getElementById('log').appendChild(createLI(arg));
        }  
        
    }
    window['LOG']['print'] = print;
    
    function printH1(arg)
    {
        var h1 = document.createElement('h1');
        
        h1.appendChild(document.createTextNode(arg));
        
        print(h1);
    }
    window['LOG']['printH1'] = printH1;
    
    function printULwithH1(h1,vars)
    {
        //Create heading for LOG window
        var h = document.createElement('h1');
        h.appendChild(document.createTextNode(h1));
        var li = document.createElement('li');
        li.appendChild(h);
        
        //Create element to hold variable list
        var ul = document.createElement('ul');    
        //attach heading
        ul.appendChild(li);
        
        //Loop through variable list and add items    
        for(var i = 0; i < vars.length; i++)
        {
            var li = document.createElement('li');
            li.appendChild(document.createTextNode(vars[i]));
            ul.appendChild(li);
        }
        
        //Print list into LOG window
        
        print(ul);
    }
    window['LOG']['printULwithH1'] = printULwithH1;

})();


/**
 * dh.js
 */

// JavaScript Document


(function(){
		  
	//The DH namespace
	if(!window.DH) { window['DH'] = {} }
	
	
	function isCompatible(other) 
	{ 
		//Use capability detection to check requirements
		if(other===false
		   || !Array.prototype.push
		   || !Object.hasOwnProperty
		   || !document.createElement
		   || !document.getElementsByTagName
		   )
		{ 
			return false;
		}
		return true;
	}
	window['DH']['isCompatible'] = isCompatible;
	
	
	function $() 
	{ 
		var elements = new Array();
		
		//find all elements supplied as arguments
		for(var i = 0 ; i < arguments.length; i++)
		{
			var element = arguments[i];
			
			//if the argument is a string assume it's an id
			if(typeof element == 'string')
			{
				element = document.getElementById(element);	
			}
			
			//if only one argument was supplied, return the element immediately
			if(arguments.length == 1)return element;
			
			//Otherwise add it to the array
			elements.push(element);
		}
		
		//Return the array of multiple requested elements
		return elements;
	}
	window['DH']['$'] = $;
	
	
	function addEvent(node,type,listener)
	{ 
		//Check compatibility using the earlier method to ensure graceful degradation
		if(!isCompatible())return false;
		
		if(!(node = $(node)))return false;
					  
		if(node.addEventListener)
		{
			//W3C method
			node.addEventListener(type,listener,false);
			return true;
		} else if(node.attachEvent){
				//MSIE method
				node['e'+type+listener] = listener;
				node[type+listener] = function(){
					node['e'+type+listener](window.event);
				};
				node.attachEvent('on'+type,node[type+listener]);
				return true;
		}
		
		//Didn't have either so return false
		return false;
	}
	window['DH']['addEvent'] = addEvent;
	
	
	function removeEvent(node,type,listener)
	{ 
		if(!(node = $(node))){return false;}
		
		if(node.removeEventListener)
		{	
			node.removeEventListener(type,listener,false);
			return true;
		} else if(node.detachEvent){
			//MSIE method
			node.detachEvent('on' + type, node[type+listener]);
			node[type+listener] = true;
			return true;
		}
		
		//Didn't have either so return false
		return false;
	}
	window['DH']['removeEvent'] = removeEvent;
	
	
	function getElementsByClassName(className,tag,parent)
	{ 
		parent = parent || document;
		
		if(!(parent = $(parent))){return false;}
		
		//Locate all the matching tags
		var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
		
		var matchingElements = new Array();
		
		//Create a regular expression to determine if the className is correct
		className = className.replace(/\-/g, "\\-");
		var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
		
		var element;
		//Check each element
		for(var i = 0; i < allTags.length; i++)
		{
			element = allTags[i];
			if(regex.test(element.className))
			{
				matchingElements.push(element);	
			}
		}
		
		//Return any matching elements
		return matchingElements;
	}
	window['DH']['getElementsByClassName'] = getElementsByClassName;
	
	function getElementByTagAndNameAttribute(name,tag,parent)
	{
		if(typeof arguments[0] == 'undefined' || (typeof arguments[0] != 'undefined' && typeof arguments[0] != 'string'))
		{
			throw new Error('DH.getElementByTagAndNameAttribute() expects argument 1 of string type');
		}
		
		if(typeof arguments[1] == 'undefined' || (typeof arguments[1] != 'undefined' && typeof arguments[1] != 'string'))
		{
			throw new Error('DH.getElementByTagAndNameAttribute() expects argument 2 of string type');
		}
		
		parent = parent || document;	
		
		var allTags = parent.getElementsByTagName(tag);
		
		for(var i = 0; i < allTags.length; i++)
		{
			if(allTags[i].name && allTags[i].name == name)
			{
				return allTags[i];
			}
		}
		return null;
	}
	window['DH']['getElementByTagAndNameAttribute'] = getElementByTagAndNameAttribute;
	
	function toggleDisplay(node,value)
	{ 
		if(!(node = $(node))){return false;}
		
		if(node.style.display != 'none')
		{
			node.style.display = 'none';
		} else {
			node.style.display = value || '';
		}
		return true;
	}
	window['DH']['toggleDisplay'] = toggleDisplay;
	
	
	function insertAfter(node,referenceNode)
	{ 
		if(!(node = $(node))){return false;}
		
		if(!(referenceNode = $(referenceNode)))return false;
		
		return referenceNode.parentNode.insertBefore(node,referenceNode.nextSibling);
	}
	window['DH']['insertAfter'] = insertAfter;
	
//DH.createXHR - create cross-browser XHR object
	function createXHR()
    {
        if (typeof XMLHttpRequest != "undefined") 
        {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) 
               {
            var aVersions = [ "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0"];
            for (var i = 0; i < aVersions.length; i++) 
            {
                try {
                    var oXHR = new ActiveXObject(aVersions[i]);
                    return oXHR;
                } catch (oError) {
                //Do nothing
                }
            }
        }
        throw new Error("XMLHttp object could not be created.");
    }
    window['DH']['createXHR'] = createXHR;
    
	
//DH.createImg - creates an image tag
// imgSrc - image source (optional)
// imgAlt - image alternate text (optional)
// errorFunction - function to call on load error (option)
	function createImg(imgSrc,imgAlt,errorFunction)
    {
        //If source is passed and not a valid string
        if((typeof arguments[0] != 'undefined') && typeof arguments[0] != 'string')
        {
            throw new Error('DH.createImg() expects argument 1 to be of \'string\' type');
        }
        
        //If imgAlt is not a valid string
        if((typeof arguments[1] != 'undefined') && typeof arguments[1] != 'string')
        {
            throw new Error('DH.createImg() expects argument 2 to be of \'string\' type');
        }
        
        //If errorFunction is not a valid function
        if(typeof arguments[2] != 'undefined' && arguments[2] != null && typeof arguments[2] != 'function')
        {
            throw new Error('DH.createImg() expects argument 3 to be of \'function\' type');
        }
        
        var oImg = document.createElement('img');
        if(imgSrc)oImg.src = imgSrc;
        if(imgAlt)oImg.setAttribute('alt',imgAlt);
        if(errorFunction)oImg.onerror = errorFunction;
        return oImg;
    }
    window['DH']['createImg'] = createImg;

//DH.createDiv - creates a div tag
// divId - sets id attribute (optional)
// divClass - set class attribute (optional)
    function createDiv(divId,divClass)
    {
        //If divId is passed and not a valid string
        if((typeof arguments[0] != 'undefined') && typeof arguments[0] != 'string')
        {
            throw new Error('DH.createImg() expects argument 1 to be of \'string\' type');
        }
        
        //If divClass is not a valid string
        if((typeof arguments[1] != 'undefined') && typeof arguments[1] != 'string')
        {
            throw new Error('DH.createImg() expects argument 2 to be of \'string\' type');
        }
        
        var oDiv = document.createElement('div');
        if(divId)oDiv.setAttribute('id',divId);
        if(divClass)oDiv.className = divClass;
        return oDiv;
    }
    window['DH']['createDiv'] = createDiv;
//DH.createP - creates a P tag
// pId - sets id attribute (optional)
// pClass - set class attribute (optional)
    function createP(pChild,pId,pClass)
    {
        //If id provided does not validate        
        if((typeof arguments[1] != 'undefined') && typeof arguments[1] != 'string')
        {
            throw new Error('DH.createP() expects argument 2 to be of \'string\' type');
        }  
        //If class provided does not validate
        if((typeof arguments[2] != 'undefined') && typeof arguments[2] != 'string')
        {
            throw new Error('DH.createP() expects argument 3 to be of \'string\' type');
        }  
        
        //Crete p tag
        var p = document.createElement('p');
        if(pId)p.setAttribute('id',pId);
        if(pClass)p.className = pClass;
        
        //If inner content has been provided
        if(pChild)
        {  
            //If p child is not an element attach it to text node          
            if(typeof pChild == 'string')
            {
                pChild = document.createTextNode(pChild);
            }
            p.appendChild(pChild);
        }
        return p;
    }
    window['DH']['createP'] = createP;
    
//DH.createLabel = creates a label tag
// inner - sets inner text (required)
// lFor - sets the for attribute (optional)
    function createLabel()
    {
        if(typeof arguments[0] == 'undefined')
        {
            throw new Error('DH.createLabel() expects argument 1 to be of string type');
        }
        
        var label = document.createElement('label');
        label.appendChild(document.createTextNode(arguments[0]));
        
        if(typeof arguments[1] != 'undefined' 
           && arguments[1].length 
           && arguments[1].length > 0)
        {
            label.setAttribute('for',arguments[1]);
        }
        return label;
    }
    window['DH']['createLabel'] = createLabel;

//DH.createInput
// type = type attribute (required)
// name = name attribute (required)
// value = value attribute (optional)
// tabindex = tabindex attribute (optional)
    function createInput()
    {
        //validate type attribute      
        if((typeof arguments[0] == 'undefined') || typeof arguments[0] != 'string' || arguments[0].length < 1)
        {
            throw new Error('DH.createInput() expects argument 1 to be of \'string\' type');
        }
        
        //validate name attribute      
        if((typeof arguments[1] == 'undefined') || typeof arguments[1] != 'string' || arguments[1].length < 1)
        {
            throw new Error('DH.createInput() expects argument 2 to be of \'string\' type');
        }
        
        var oInput = document.createElement('input');
        oInput.setAttribute('type',arguments[0]);
        oInput.setAttribute('name',arguments[1]);
        
        //Attach value
        if((typeof arguments[2] != 'undefined') && typeof arguments[2] == 'string' && arguments[2].length > 0)
        {
            oInput.setAttribute('value',arguments[2]);
        }
        
        //Attach tabindex
        if((typeof arguments[3] != 'undefined') && typeof arguments[3] == 'string' && (!isNaN(arguments[2])))
        {
            oInput.setAttribute('tabindex',arguments[3]);
        }
        return oInput;
    }
    window['DH']['createInput'] = createInput;

//DH.createHiddenInput
// name = name attribute (required)
// value = value attribute (required)
    function createHiddenInput()
    {
        //validate name attribute      
        if((typeof arguments[0] == 'undefined') || typeof arguments[0] != 'string' || arguments[0].length < 1)
        {
            throw new Error('DH.createInput() expects argument 1 to be of \'string\' type');
        }
        
        //validate value attribute      
        //if((typeof arguments[1] == 'undefined') || typeof arguments[1] != 'string' || arguments[1].length < 1)
        if((typeof arguments[1] == 'undefined'))
        {
            throw new Error('DH.createInput() expects argument 2 to be of \'string\' type');
        }
        
        var oInput = document.createElement('input');
        oInput.setAttribute('type','hidden');
        oInput.setAttribute('name',arguments[0]);
        oInput.setAttribute('id',arguments[0]);
        oInput.setAttribute('value',arguments[1]);
        
        return oInput;
    }
    window['DH']['createHiddenInput'] = createHiddenInput;


//DH.createOption
// inner - sets inner text (required)
// value = value attribute (required)
    function createOption()
    {
        //validate inner     
        if((typeof arguments[0] == 'undefined') || typeof arguments[0] != 'string' || arguments[0].length < 1)
        {
            throw new Error('DH.createOption() expects argument 1 to be of \'string\' type');
        }
        
        //validate type attribute      
        if((typeof arguments[1] == 'undefined') || typeof arguments[1] != 'string' || arguments[1].length < 1)
        {
            throw new Error('DH.createOption() expects argument 2 to be of \'string\' type');
        }
        
        var option = document.createElement('option');
        option.setAttribute('value',arguments[1]);
        option.appendChild(document.createTextNode(arguments[0]));
        return option;
    }
    window['DH']['createOption'] = createOption;
    
//DH.createAnchor = creates an anchor tag
// inner - sets inner text (required)
// aHref - sets href attribute (required)
// aId - sets id attribute (optional)
// aClass - sets class attribute (optional)
// aTitle - sets title attribute (optional)
    function createAnchor(inner,aHref,aId,aClass,aTitle)
    {
        //If required inner is not valid
        //if(typeof arguments[0] == 'undefined' || typeof arguments[0] != 'string' || arguments[0].length == 0)
		if(typeof arguments[0] == 'undefined')
        {
            throw new Error('DH.createAnchor() expects argument 1 to be of string type');
        }
        /*
        //If required aHref is not valid
        if(typeof arguments[1] == 'undefined' || typeof arguments[1] != 'string' || arguments[1].length == 0)
        {
            throw new Error('DH.createAnchor() expects argument 2 to be of string type');
        }
        */
        var oAnchor = document.createElement('a');
        if(aHref)oAnchor.setAttribute('href',aHref);
        if(aId)oAnchor.setAttribute('id',aId);
        if(aClass)oAnchor.className = aClass;
        if(aTitle)oAnchor.setAttribute('title',aTitle);
		
		//Check if inner content is an object
		if(typeof inner != 'string')
		{
			oAnchor.appendChild(inner);
		} else {
        	oAnchor.appendChild(document.createTextNode(inner));
		}
		return oAnchor;    
    }
    window['DH']['createAnchor'] = createAnchor;
	
//DH.addWindowLoadEvent
// func - function to be attached to window.onload (required)
	function addWindowLoadEvent(func)
    {
        if(typeof arguments[0] == 'undefined' || typeof arguments[0] != 'function')
        {
            throw new Error('DH.addWindowLoadEvent() expects argument 1 to be of \'function\' type');
        }
        
	    var ondonload = window.onload;
	    //if window.onload does not have any functions attached
	    if(typeof window.onload != 'function')
	    {
		    window.onload = func;
	    } else {
		    window.onload = function()
		    {
			    ondonload();
			    func();
		    };
	    }
    }
    window['DH']['addWindowLoadEvent'] = addWindowLoadEvent;
    
//DH.stopEvent
// oEvent - event reference (required)
    function stopEvent(oEvent)
    {
        if(typeof arguments[0] == 'undefined')
        {
            throw new Error('DH.stopEvent() expects at least one argument');
        }
  
        if(window.event)
        { 
            var target = window.event.srcElement;
            window.event.returnValue = false;
        } else {
            var target = oEvent.target;
            oEvent.preventDefault();
        }
        return target;
    }
	window['DH']['stopEvent'] = stopEvent;
	
	function getURLParam(param)
	{
		var winLoc = window.location.toString().toLowerCase();
		
		if(winLoc.indexOf('?') ==-1) return null;
		
		var winLocParams = (decodeURIComponent(winLoc.split('?')[1])).split('&');
		
		for(var i = 0; i < winLocParams.length; i++)
		{
			if(winLocParams[i].split('=')[0] == param.toLowerCase())
			{
				return (winLocParams[i].split('=')[1]).replace(/\+/gi,' ');
			}
		}
		return null;
	}
	window['DH']['getURLParam'] = getURLParam;

//DH.getCookie
	function getCookie(sName) 
	{
        var sRE = "(?:; )?" + sName + "=([^;]*);?";
        var oRE = new RegExp(sRE);
        if(oRE.test(document.cookie)) 
        {
            return decodeURIComponent(RegExp["$1"]);
        } else {
            return null;
        }
    }
    window['DH']['getCookie'] = getCookie;	

//DH.setCookie		
    function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) 
    {
        var sCookie = sName + "=" + encodeURIComponent(sValue);
        
        if(oExpires) 
        {
            sCookie += "; expires=" + oExpires.toGMTString();
        }
        
        if(sPath) 
        {
            sCookie += "; path=" + sPath;
        }
        
        if(sDomain) 
        {
            sCookie += "; domain=" + sDomain;
        }
        
        if(bSecure) 
        {
            sCookie += "; secure";
        }
        
        document.cookie = sCookie;
    }
	window['DH']['setCookie'] = setCookie;
	
//DH.findPos
    function findPos(obj) 
    {
	    var curleft = curtop = 0;
	    if(obj.offsetParent) 
	    {
	        do
	        {
			    curleft += obj.offsetLeft;
			    curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        }
        return [curleft,curtop];
    }
    window['DH']['findPos'] = findPos;	 
    
    function getEventObject(obj)
    {
        return obj || window.event;
    } 
    window['DH']['getEventObject'] = getEventObject;
    
    function getKeyPressed(eventObject)
    {
        eventObject = eventObject || getEventObject(eventObject);
        
        var code = eventObject.keyCode;
        var value = String.fromCharCode(code);
        return {'code':code,'value':value};
    }  
    window['DH']['getKeyPressed'] = getKeyPressed;  
    
    
})();



/**
 * eddesk.js
 */

// JavaScript Document


(function(){
		  
	//The EDDESK namespace
	if(!window.EDDESK) { window['EDDESK'] = {} }
	
	function isCompatible(other) 
	{ 
		//Use capability detection to check requirements
		if(other===false
		   || !Array.prototype.push
		   || !Object.hasOwnProperty
		   || !document.createElement
		   || !document.getElementsByTagName
		   )
		{ 
			return false;
		}
		return true;
	}
	window['EDDESK']['isCompatible'] = isCompatible;	
	
	
	
	//Checks whether an edDesk form input is valid
	function validFormInput(str)
    {
        var item = null;
        
        //Check whether the input exists and get a reference to it
        try {
                item = eval('document.forms[0].' + str);
        } catch (oError) {return null; }
       
        //if input is invalid return null
        if(typeof item == 'undefined' || typeof item.value == 'undefined' || item.value.length == 0 || item.value == ' ')return null;
        
        //input is valid
        return true;      
    }
    window['EDDESK']['validFormInput'] = validFormInput;
    
    
    //Function which retrieves edDesk Form Input
    function getFormInput(str)
    {
        //Check whether the form input is valid
        if(!validFormInput(str))return null;        
        
        return unescape(eval('document.forms[0].' + str + '.value'));
    }
    window['EDDESK']['getFormInput'] = getFormInput;	
	
	function doHeaderSearch(oEvent)
	{
		
		var target = DH.stopEvent(oEvent);	
		
		var oInput = document.getElementById('searchInput');
		
		var param = (oInput && oInput.value.length > 0) ? oInput.value : null;
		
		if(!param)
		{
			alert('You must enter a valid search argument');
		} else {
			if(window.location.toString().indexOf('macmillan.com.au') != -1) // macmillan server live PA db
		    {
				window.location = 'http://www.macmillan.com.au/secondary31/site/libraries/Search?open&query=' + param;
		    } else { 
				window.location = 'http://secondary3.itechne.com/secondary31/site/libraries/Search?open&query=' + param;
		    }
		}
	
		
	}
	window['EDDESK']['doHeaderSearch'] = doHeaderSearch;
		 
})();



/**
 * function_HeaderLoader.js
 */


/*
    Function which makes a header ajax call - used to check whether a file exists
    
    Creating an object:
        var VAR_NAME = new HeaderLoader(FILE_PATH,FUNCTION_TO_CALL);
            
            FILE_PATH - path to file
            FUNCTION_TO_CALL - reference to function to call if file exists
            
            P.S: The FUNCTION_TO_CALL is optional
    
    Vars used to test the call
    
        VAR_NAME.exist - true if file exist
        VAR_NAME.error - true if there was an error

*/

    
function HeaderLoader(imgPath,funCall)
{
    if(typeof HeaderLoader._initialized == 'undefined')
    {
        HeaderLoader.prototype.load = function()//Make Ajax call to retrieve the header
        {
            this.oXHR = this.createXHR();//reference to ajax object
            
            if(this.oXHR)
            {
                this.oXHR.open('HEAD',this.path,false);
                this.oXHR.send(null); 
                if(this.oXHR.status == 304 || this.oXHR.status == 200)
                {
                    this.exist = true;
                    if(this.funCall)this.funCall();
                }
            } else {
                        this.error = true;
                   }
        };
        HeaderLoader.prototype.createXHR = function()//Create Ajax request object
        {
            if (typeof XMLHttpRequest != "undefined") 
            {
                return  new XMLHttpRequest();
            } else if (window.ActiveXObject) 
                   {
                var aVersions = [ "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0"];
                for (var i = 0; i < aVersions.length; i++) 
                {
                    try {
                        return new ActiveXObject(aVersions[i]);
                    } catch (oError) {
                        //Do nothing
                    }
                }
            }
            return;       
        };
    }
    HeaderLoader._initialized = true;
    
    if(funCall)this.funCall = funCall;
    this.path = imgPath;//path to image file 
    this.load();   
}


/*
 * function_OnixItemSearch
 * 
 */



function OnixItemSearch()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('OnixItemSearch() constructor expects argument 1 to be of \'string\' type');
    }
    
    if(typeof arguments[1] ==  'undefined' || typeof arguments[1] != 'string')
    {
        throw new Error('OnixItemSearch() constructor expects argument 2 to be of \'string\' type');
    }
    
    this.isbn = arguments[0];
    this.searchLabel = arguments[1];
    //Send Ajax request and get response
    this.loaded = this.loadAjax();
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

OnixItemSearch.prototype._SEARCHSTR = '/secondary/onix/onixsearch.js?open&';
//OnixItemSearch.prototype._SEARCH_LABEL =  'TeacherSupportItemSearch';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
OnixItemSearch.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    tempArray.push('query=([ISBN]=' + this.isbn + ')+and+[FORM]=Product');
    tempArray.push('start=1');
    tempArray.push('count=1');
    tempArray.push('label=' + this.searchLabel);    
    return this._SEARCHSTR + tempArray.join('&');
};

OnixItemSearch.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var searchOnixResults = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(searchOnixResults);
        var results = eval('searchOnixResults' + this.searchLabel);
    } catch(oError) {
        throw new Error('OnixItemSearch.loadAjax() error on eval(searchOnixResults) Serries.load()');
    }
        
    //If search results exist
    if(typeof results != 'undefined' && results instanceof Array && results.length > 0)
    {                
        this.tsIndex = new Array();
        for(var i = 1; i < results.length; i++)
        {
            if(typeof results[i] != 'undefined')
            {
                this.tsIndex.push(results[i]);                  
            }
        }
        if(Secondary._LOG_ENABLED)LOG.printH1('OnixItemSearch.loadAjax() - returned ' + this.tsIndex.length + ' results');
            
        //If there are no valid results
        if(this.tsIndex.length == 0)
        {
            return false;
            //If log enabled display message
            if(Secondary._LOG_ENABLED)LOG.printH1('OnixItemSearch.loadAjax() did not return any valid results');
        } else {
            return true;
        } 
            
    } else {
            throw new Error("OnixItemSearch.load() 'results' is undefined");
    }
};



/* 
 * function_cart.js
 */

/*

    CART OBJECT LITERAL
    isbn: string
    title: string
    


*/


Cart = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/
    handlingFee: 10,


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/
    
    add: function()
    {
        //Validate isbn
        if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
        {
            throw new Error('Cart.add() constructor expects argument 1 to be of \'string\' type');
        }
        
        //Validate quantity
        if(typeof arguments[1] ==  'undefined' || isNaN(arguments[1]))
        {
            throw new Error('Cart.add() constructor expects argument 2 to be of \'number\' type');
        }
        
        //Validate purchase type
        if(typeof arguments[2] ==  'undefined' || typeof arguments[2] != 'string')
        {
            throw new Error('Cart.add() constructor expects argument 3 to be of \'string\' type');
        }
        
        var isbn = arguments[0];
        var quantity = arguments[1];
        var purchaseType = arguments[2];
        var inspection = arguments[3];
        
        //Search for item details
        var itemSearch = new OnixItemSearch(isbn,'CartAdd');
		//If item loaded
		if(itemSearch.loaded)
		{
		    var item = new OnixItem('series',itemSearch.tsIndex[0],quantity);
		    if(purchaseType == 'B' && !item.isItemAvailable())purchaseType = 'R';
		    item.purchaseType = purchaseType;	
		    item.inspection = inspection;	    
		    this.items.push(item);
		    this.save();
		}
        
            
    },
    
    load: function()
    {
        //Array used for LOG
        var vars = new Array();
        
        this.items = new Array();
        var oCookie = (DH.getCookie('mac_sec_cart')) ? DH.getCookie('mac_sec_cart').split('|') : null;
        if(oCookie)
        {
            for(var i = 0; i < oCookie.length; i++)
            {
                var isbn = oCookie[i].split('_')[0];
                var purchaseType = oCookie[i].split('_')[1].substring(1);
                var inspection = oCookie[i].split('_')[1].substring(0,1);
                var quantity = parseInt(oCookie[i].split('_')[2]);
                
                vars.push(isbn + '_' + inspection + purchaseType + '_' + quantity);
                
                //Search for item details
                var itemSearch = new OnixItemSearch(isbn,'CartLoad');
                //If item loaded
		        if(itemSearch.loaded)
		        {
		            var item = new OnixItem('series',itemSearch.tsIndex[0],quantity);
		            item.purchaseType = purchaseType;
		            item.inspection = (inspection == 'I') ? true : null;
		            this.items.push(item);
		        }
            }  
        }   
        if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Cart.load() - items in cookie',vars); 
    },
    
    save: function()
    {
        var vars = new Array();
        
        //If there are no items in cart delete cookie
        if(this.items.length == 0)
        {
            var cookieExpires = new Date();
            cookieExpires.setTime(cookieExpires.getTime() - (1 * 60 * 60 * 1000 ));
            DH.setCookie('mac_sec_cart','',cookieExpires,'/');
            if(Secondary._LOG_ENABLED)LOG.printH1('Cart.save() - cookie deleted');
        } else { //If there are items in cart
            for(var i = 0; i < this.items.length; i++)
            {
                var inspection = (this.items[i].inspection) ? 'I' : 'B';
                vars.push(this.items[i].isbn + '_' + inspection + this.items[i].purchaseType + '_' + this.items[i].quantity);
            }
            
            if(vars.length > 0)
            {
                var cookieExpires = new Date();
                cookieExpires.setTime(cookieExpires.getTime() + (1 * 60 * 60 * 1000 ));
                //cookieExpires.setDate(cookieExpires.getDate() + 2);
                DH.setCookie('mac_sec_cart',vars.join('|'),cookieExpires,'/');
                
                if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Cart.save() - items being saved in cookie',vars);
                
            }
        }
    },
    
    remove: function(isbn)
    {
        if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - START - length of items = ' + this.items.length);
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].isbn == isbn)
            {
                //if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - removing ' + isbn);
                var item = this.items[i];
                this.items.splice(i,1);
            }
        } 
        //if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - END - length of items = ' + this.items.length);
        this.save();
        return item;
    },
    
    isItemInCart: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return true;
        }
        return false;
    },
    
    getItemWithISBN: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return this.items[i];
        }
        return null;
    },
    
    getItemCount: function()
    {
        var quantity = 0;
        for(var i = 0; i < this.items.length; i++)
        {
            quantity += this.items[i].quantity;
        }
        return quantity;    
    },
    
    getItemQuantity: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return this.items[i].quantity;
        }
        return 0;
    },
    
    isItemBeingInspected: function(isbn)
    {
        var item = this.getItemWithISBN(isbn);
        if(item && item.purchaseType == 'I')
        {
            return true;
        } else {
            return false;
        }
    },
    
    setPurchaseType: function(isbn,purchaseType)
    {
        var item = this.getItemWithISBN(isbn);
        
        if(item)
        {
            switch(purchaseType)
            {
                case 'I'://Inspect item
                    item.quantity = 1;
                    item.purchaseType = purchaseType;
                    break;
                case 'B'://Buy item
                    item.checkAvailability(item.quantity);
                    item.purchaseType = purchaseType;
                    if(!item.isItemAvailable())item.purchaseType = 'R';
                    break;
                default:
            }                    
        }
        this.save();
    },
    
    setQuantity: function(isbn,quantity)
    {
        var item = this.getItemWithISBN(isbn);
        
        if(item)
        {
            if(quantity > 0)
            {
                item.quantity = quantity;
                item.checkAvailability(quantity);
                item.purchaseType = 'B';
                if(!item.isItemAvailable())item.purchaseType = 'R';
                this.save();
            } else {
                this.remove(isbn);
            }
        }
        
    },
    
    updateItem: function(isbnOrItem,oParent)
    { 
        var item = (typeof isbnOrItem == 'string') ? this.getItemWithISBN(isbnOrItem) : isbnOrItem;
        if(item)
        {
            var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
            if(isOnixProductPage)//If it is a book page
            {
                item.attachOnixProductForm(oParent);
            } else {//If it is an index page
                item.attachSeriesIndex1Item(oParent);
            }    
        }
    },
    
    hasItems: function()
    {
        if(this.items.length > 0)
        {
            return true;
        } else {
            return false;
        }
    },
    
    hasInspectedItems: function()
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType == 'I')return true;
        }
        return false;
    },
    
    hasOnlyItemsInStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType != 'B')return false;
        }
        return true;
    },
    
        hasOnlyItemsOutOfStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType == 'B' || this.items[i].purchaseType == 'I')return false;
        }
        return true;
    },

        removeItemsOutOfStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
        if(this.items[i].purchaseType != 'B') this.remove(this.items[i].isbn);
        }
        return true;
    },
   
 
    getTotal: function()
    {
        var total = 0;
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType != 'I')
            {
                total += (this.items[i].price * this.items[i].quantity);
            }
        }
        
        //Check if handling fee must be added to total
        if(Checkout && (Checkout.step == 3 || Checkout.step == 4) && CheckoutCookie)
        {
            var oCookie = new CheckoutCookie('checkout_step1'); 
            var payType = oCookie.getVarValue('PayType');
            if(payType && payType == '2')//if payment is credit card
            {
                total += this.handlingFee;
            }
        }
        
        return total;
    },
    
    getItemTotal: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].isbn == isbn)
            {
                if(this.items[i].purchaseType != 'I')
                {
                    return (this.items[i].price * this.items[i].quantity);
                }
            }
        }
        return 0;
    },
    
    attachMiniCart: function(oParent)
    {
        var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
        
        var isOnixIndexPage = (Secondary && Secondary.section && Secondary.section == 'Library'
                               && Secondary.subsection && Secondary.subsection == 'Onix') ? true : null;
                               
        var isOnixSearchPage = (Secondary && Secondary.section && Secondary.section == 'Library'
                               && Secondary.subsection && Secondary.subsection == 'Search') ? true : null;
        
        var miniCart = document.getElementById('miniCart');
        if(!miniCart)
        {
            //Create cart holder
            miniCart = document.createElement('div');
            miniCart.setAttribute('id','miniCart');
            //variable to determine whether to attach to parent or not at the end of this
            var parentNecessary = true;
        } else {
            miniCart.innerHTML = '';
        }
        
        var ul = document.createElement('ul');
        
        //Create add button
        var li = document.createElement('li');

//Do not show add to order link if the item is an e-book.  This check only needs to be done on onixProductPages

        if(isOnixProductPage || isOnixIndexPage || isOnixSearchPage)
        {
             //dispConsole("isOnixProductPage || isOnixIndexPage || isOnixSearchPage = TRUE");
             if(isOnixProductPage){
        	//e-book check by passing in the current book object
        	try{
			var isEbook = checkIfEbook(this); 
			this.isEbook = isEbook;        	
        	} catch(e){
        		//dispConsole("error: " + e);
        	}
            }
	    
	    if(this.isEbook){
	    	var tag = document.createElement('span');
	    	tag.className = 'add';
	    	tag.appendChild(document.createTextNode('Add to order'));
	    } else {
            	var tag = document.createElement('a');                          
            	tag.className = 'add';
            	tag.appendChild(document.createTextNode('Add to order'));
            	tag.setAttribute('href','#');
            	//Attach event to element
            	DH.addEvent(tag,'click',OnixItem_AddItems);
            }
        } else {
            var tag = document.createElement('span');
            tag.className = 'add';
            tag.appendChild(document.createTextNode('Add to order'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Create view order button
        var li = document.createElement('li');
        if(this.hasItems())
        {
            var tag = document.createElement('a');
            tag.appendChild(document.createTextNode('View order'));
            tag.setAttribute('href','/secondary31/site/articleIDs/514829CC98A98DA3CA257557001A4C52?open&template=domSecondary');
        } else {
            var tag = document.createElement('span');
            tag.appendChild(document.createTextNode('View order'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Create checkout button
        var li = document.createElement('li');
        if(this.hasItems())
        {
            var tag = document.createElement('a');
            tag.appendChild(document.createTextNode('Checkout'));
            //tag.setAttribute('href','/secondary/site/libraries/checkout');
            tag.setAttribute('href','/secondary31/site/articleIDs/8BBB301D7E16233BCA257555001631ED?open&template=domSecondary');
        } else {
            var tag = document.createElement('span');
            tag.appendChild(document.createTextNode('Checkout'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Attach link list to miniCart
        miniCart.appendChild(ul);
        
        //Attach cart heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Shopping Summary'));
        miniCart.appendChild(h3);
        
        //Attach number of items
        var p = document.createElement('p');
        p.setAttribute('id','miniCartCount');
        p.appendChild(document.createTextNode('No. of items: ' + this.getItemCount()));
        miniCart.appendChild(p);
        
        //Attach total
        var p = document.createElement('p');
        p.setAttribute('id','miniCartTotal');
        p.appendChild(document.createTextNode('Total: AU$' + this.getTotal().toFixed(2)));
        miniCart.appendChild(p);
        
        if(parentNecessary)oParent.appendChild(miniCart);
    },
    
    attachSummaryTableHead: function(oTable)
    {
        var tr = document.createElement('tr');
        //var headings = ['ISBN','Title','RRP','e-Club Price','Quantity','Inspect','Buy','Total','Available',' '];
        var headings = ['ISBN','Title','RRP','Quantity','Inspect','Buy','Total','Available',' '];
        for(var i = 0; i < headings.length; i++)
        {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(headings[i]));
            if(i == (headings.length - 1))th.className = 'last';
            tr.appendChild(th);
        }
        var thead = document.createElement('thead');
        thead.appendChild(tr);
        oTable.appendChild(thead);
    },
    
    attachSummaryTableHeadCheckoutStep3: function(oTable)
    {
        var tr = document.createElement('tr');
        //var headings = ['ISBN','Title','RRP','e-Club Price','Quantity','Inspect','Buy','Total','Available'];
        var headings = ['ISBN','Title','RRP','Quantity','Inspect','Buy','Total','Available'];
        for(var i = 0; i < headings.length; i++)
        {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(headings[i]));
            if(i == (headings.length - 1))th.className = 'last';
            tr.appendChild(th);
        }
        var thead = document.createElement('thead');
        thead.appendChild(tr);
        oTable.appendChild(thead);
    },
    
    attachSummaryTable: function(oParent)
    {
        var oTable = document.createElement('table');
        
        var caption = document.createElement('caption');
        caption.appendChild(document.createTextNode('Summary'));
        oTable.appendChild(caption);
        
        this.attachSummaryTableHead(oTable);
        
        var tbody = document.createElement('tbody');
        
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachSummaryRow(tbody);    
        }
        
        //Attach total
        var tr = document.createElement('tr');
        tr.className = 'last';
        for(var i = 0; i < 9; i++)
        {
            if(i == 8)
            {
                var td =document.createElement('td');
                //td.setAttribute('colspan','2');
                td.className = 'total';
                td.appendChild(document.createTextNode('AU$' + this.getTotal().toFixed(2)));
            } else if(i == 7) {
                var td = document.createElement('td');  
                td.className = 'summaryTitle';
                td.appendChild(document.createTextNode('Total:'));
            } else {
                var td = document.createElement('td');
                if(i == 6)td.style.borderRightWidth = '1px';
                var img = document.createElement('img');
                img.src = 'templates/layout/$file/spacer.gif';
                td.appendChild(img);
                //td.setAttribute('colspan','1'); 
            }
            tr.appendChild(td);  
        }
        tbody.appendChild(tr);
        oTable.appendChild(tbody);
        oParent.appendChild(oTable);
    },
    
    attachSummaryTableCheckoutStep3: function(oParent)
    {
        var oTable = document.createElement('table');
        
        var caption = document.createElement('caption');
        caption.appendChild(document.createTextNode('Summary'));
        oTable.appendChild(caption);
        
        this.attachSummaryTableHeadCheckoutStep3(oTable);
        
        var tbody = document.createElement('tbody');
        
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachSummaryRowCheckoutStep3(tbody);    
        }
        
        //Attach total
        var tr = document.createElement('tr');
        tr.className = 'last';
        for(var i = 0; i < 8; i++)
        {
            if(i == 7)
            {
                var td =document.createElement('td');
                //td.setAttribute('colspan','2');
                td.className = 'total';
                td.appendChild(document.createTextNode('AU$' + this.getTotal().toFixed(2)));
            } else if(i == 6) {
                var td = document.createElement('td');  
                td.className = 'summaryTitle';
                td.appendChild(document.createTextNode('Total:'));
            } else {
                var td = document.createElement('td');
                if(i == 5)td.style.borderRightWidth = '1px';
                var img = document.createElement('img');
                img.src = 'templates/layout/$file/spacer.gif';
                td.appendChild(img);
                //td.setAttribute('colspan','1'); 
            }
            tr.appendChild(td);  
        }
        tbody.appendChild(tr);
        oTable.appendChild(tbody);
        oParent.appendChild(oTable);
    },
    
    attachSummary: function(oParent)
    {   
        oParent.innerHTML = '';
        
        //alert(this.items[0].value);
        
        if(this.items.length > 0)
        {
           this.attachSummaryTable(oParent);
           
           //Attach buttons
           var fieldset = document.createElement('fieldset');
           
           //If it is not check out
           if(!Checkout || Checkout.step != 1)
           {
               //Attach continue shopping button
               var oInput = document.createElement('input');
               oInput.setAttribute('type','button');
               oInput.setAttribute('value','Continue shopping');
               oInput.setAttribute('tabindex','1');
               oInput.className = 'button';
               var ContinueShoppingBtn_onClick = function(oEvent)
               {
                    var target = DH.stopEvent(oEvent);
                    history.go(-1);
               };
               DH.addEvent(oInput,'click',ContinueShoppingBtn_onClick);
               fieldset.appendChild(oInput);
               
               //Attach check out button
               if(this.hasItems())
               {
                   var oInput = document.createElement('input');
                   oInput.setAttribute('type','button');
                   oInput.setAttribute('value','Checkout now');
                   oInput.setAttribute('tabindex','2');
                   oInput.className = 'button';
                   var CheckoutNowBtn_onClick = function()
                   {
                        window.location = '/secondary31/site/articleIDs/8BBB301D7E16233BCA257555001631ED?open&template=domSecondary';
                   };
                   DH.addEvent(oInput,'click',CheckoutNowBtn_onClick);
                   fieldset.appendChild(oInput);
               }
               oParent.appendChild(fieldset);
            }
        } else {
            var p = document.createElement('p');
            p.appendChild(document.createTextNode('There are no items in the cart.'));
            p.className = 'noItems';
            oParent.appendChild(p);
        }
    },
    
    attachSummaryCheckoutStep3: function(oParent)
    {
        oParent.innerHTML = '';
        
        if(this.items.length > 0)
        {
            this.attachSummaryTableCheckoutStep3(oParent);
        } else {
            var p = document.createElement('p');
            p.appendChild(document.createTextNode('There are no items in the cart.'));
            p.className = 'noItems';
            oParent.appendChild(p);
        }
    },
    
    attachCheckoutHiddenInputs: function(oForm)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachCheckoutHiddenInputs(oForm,i);
        };
    },

    init: function()
    {
        this.load();    
    }

}

function dispConsole(dstring){
	try{
		if(window.globalStorage && window.postMessage){    
			console.debug(dstring);
		}
	} catch (e){
		//do nothing
	}
}
function checkIfEbook(tvar){
	//Get isEbook
	    try{
		
	    	var onixProd = document.forms[0].PageType.value;
		var isEbook;		
	    	var dTitle = "";
	    	if (typeof(onixProd) != "undefined"){

			if (onixProd == "onixProduct"){
				dTitle = document.forms[0].DistinctiveTitle.value;
			}
			if (onixProd == "library"){
			    	dTitle = tvar.title;
			}
		}else{
			dTitle = tvar.title;
	   	}
	   	
	   	if (dTitle.match("ebook") != null || dTitle.match("e-book") != null ){
			isEbook = true;
		} else {
			isEbook = false;
		}
	    }catch(e){
	    	isEbook = false
	    }
	    return isEbook;
}



/*
 * function_Checkout
 */

var tmpOS = false;

Checkout = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/





/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/


    attach: function(edDeskBody)
    {
        if(typeof CheckoutAttachCount == 'undefined')CheckoutAttachCount = 0;
		
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(CheckoutAttachCount > 10)
			{
				throw new Error('Checkout.attach() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			CheckoutAttachCount++;
			setTimeout('Checkout.attach()',100);
			return;
		}
		
		//Clear parent
		oParent.innerHTML = '';
		
		//Recreate edDeskBody
		var div = document.createElement('div');
		div.setAttribute('id','edDeskBody');
		
		//Attach heading
		oParent.appendChild(this.attachHeading());
		
        switch(this.step)
        {
            case 1://initial stage
                //Attach introduction
		        this.attachIntroduction_step1(oParent);
                this.attachStep1(div);
                break;
            case 2://invoice form
                this.attachIntroduction_step2(oParent);
                this.attachStep2(div);
                break;
            case 3://final summary step
                this.attachStep3(div);
                break;
            case 4://submit form
                this.attachStep4(div);
                break;
            default:
        }
        oParent.appendChild(div);
        
       //Update mini cart
       Cart.attachMiniCart(document.getElementById('contentRight'));
    },
    
    attachIntroduction_step1: function(oParent)
    {
        var p = document.createElement('p');
        p.className = 'intro';
         
        //p.appendChild(document.createTextNode('Inspection copies can be made by schools only.'));
        p.innerHTML = 'Read our terms and conditions <a href="libraries/Terms+and+Conditions?open">here</a>.<br><br>Inspection copies can be made by schools only.';
        oParent.appendChild(p);
    },
    
    attachIntroduction_step2: function(oParent)
    {
        var p = document.createElement('p');
        p.className = 'intro';
        p.appendChild(document.createTextNode('Please enter your payment details.'));
        p.appendChild(document.createElement('br'));
        var strong = document.createElement('strong');
        strong.appendChild(document.createTextNode('Your total purchase is AU$' + Cart.getTotal().toFixed(2)));
        p.appendChild(strong);
        oParent.appendChild(p);
    },
    
    attachHeading: function()
    {
        switch(this.step)
        {
            case 1://initial stage
                var heading = 'Checkout';
                break;
            case 2://invoice form
                var heading = 'School/University invoice details';
                break;
            case 3://final summary step
                var heading = 'Checkout Purchase confirmation';
                break;
            default:
                var heading = '';
        }
        
        var h2 = document.createElement('h2');
        h2.appendChild(document.createTextNode(heading));
        return h2;
    },
    
    attachStep1: function(oParent)
    {
       //Attach summary
       var div = document.createElement('div');
       div.setAttribute('id','cartSummary');
       if(Cart)Cart.attachSummary(div);
       oParent.appendChild(div);
       
       //Attach form
       this.attachStep1Form(oParent);
       
    },
    
    attachStep2: function(oParent)
    {
       //Attach form
       this.attachStep2Form(oParent);
    },
    
    attachStep3: function(oParent)
    {
       //Attach summary
       var div = document.createElement('div');
       div.setAttribute('id','cartSummary');
       if(Cart)Cart.attachSummaryCheckoutStep3(div);
       oParent.appendChild(div);
       
       //Attach delivery details
       this.attachStep3DeliveryDetails(oParent);
       
       //Attach previous button
        var f = document.createElement('fieldset');
        f.className = 'step3Buttons';
        var oInput = DH.createInput('button','previousStep','Previous','25');
        oInput.className = 'button';
        var PreviousStepBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveBack();
        };
        DH.addEvent(oInput,'click',PreviousStepBtn_onClick);
        f.appendChild(oInput);
        
        //Attach purchase now button
        var oInput = DH.createInput('button','nextStep','Purchase now','26');
        oInput.className = 'button';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        oParent.appendChild(f);  

       //Attach notice
        
        //-----------------------------------------------------------------------------------------------------
	        //Important Notice
		var f = document.createElement('div');
		var p = document.createElement('p');
		var sp = document.createElement('span');
		
		var g = document.createElement('div');
		
		f.style.id='importantNotice';
		f.style.display='inline';
		f.style.fontWeight='bold';
		f.style.color='red';
		f.style.margin='3px';
		f.style.padding='3px';
		f.style.id='importantNotice';
		
		
		sp.style.color='black';
		
		g.style.display='block';
		g.style.width='100%';
		g.style.height='85px';
		g.style.clear='both';
		
		f.appendChild(g);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Important!"));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Dear Customer,"));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you are paying by credit card, submitting your order will take you to a hosted secure page for payment.  Clicking to submit your order multiple times or double-clicking the Process Payment button will result in your credit card being charged multiple times."));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you encounter a problem when making your credit card payment or you do not receive an email confirming your order please contact our "));
		p.appendChild(sp);
		sp.appendChild(document.createTextNode(" Customer Service on 1300 135 113"));
		p.appendChild(document.createTextNode(" before attempting to re-submit your order or re-try your credit card payment."));
		
		//Attach notice
		oParent.appendChild(f);
//-----------------------------------------------------------------------------------------------------          
        
    },
    
    attachStep4: function(oParent)
    {
        
        //create form
        var oForm = this.createForm();  
        
        //Attach website name
        //oForm.appendChild(DH.createHiddenInput('WebSiteName','MEA Secondary'));
        oForm.appendChild(DH.createHiddenInput('WebSiteName','MEA Secondary')); // interim form before secure pay goes live
        
        //Attach eClub
        var oInput = DH.createHiddenInput('eClub','eClub');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach ISBNBundleCode
        var oInput = DH.createHiddenInput('ISBNBundleCode','ISBNBundleCode');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach OrgName
        var oInput = DH.createHiddenInput('OrgName','OrgName');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach DiscountCode
        var oInput = DH.createHiddenInput('DiscountCode','DiscountCode');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Get step 1 vars
        var oCookie = new CheckoutCookie('checkout_step1');
        var payType = oCookie.getVarValue('PayType');
        
        oCookie.getHiddenInputs_personalDetails(oForm);
        oCookie.getHiddenInputs_information(oForm);
        
        if(payType != '2' && payType != '3')
        {
            //Get step 2 vars
            var oCookie = new CheckoutCookie('checkout_step2');
            oCookie.getHiddenInputs_invoice(oForm);
        }
        
        //Attach items
        Cart.attachCheckoutHiddenInputs(oForm);
        
        //Attach Total
        oForm.appendChild(DH.createHiddenInput('Total',Cart.getTotal().toFixed(2)));
        
        //Attach handling fee
        if(this.isPersonalOrder())
        {
            oForm.appendChild(DH.createHiddenInput('Handling',Cart.handlingFee.toFixed(2)));
        } else {
            var oInput = DH.createHiddenInput('Handling','0');
            
        }
        //Attach freight
        var oInput = DH.createHiddenInput('Freight','0');
        
        oForm.appendChild(DH.createHiddenInput('ST','F'));
        
        //Attach form to parent
        oParent.appendChild(oForm);
        
//Attach notice
        
        //-----------------------------------------------------------------------------------------------------
	        //Important Notice
		var f = document.createElement('div');
		var p = document.createElement('p');
		var sp = document.createElement('span');
		
		var g = document.createElement('div');
		
		f.style.id='importantNotice';
		f.style.display='inline';
		f.style.fontWeight='bold';
		f.style.color='red';
		f.style.margin='3px';
		f.style.padding='3px';
		f.style.id='importantNotice';
		
		
		sp.style.color='black';
		
		g.style.display='block';
		g.style.width='100%';
		g.style.height='85px';
		g.style.clear='both';
		
		f.appendChild(g);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Important!"));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Dear Customer,"));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you are paying by credit card, submitting your order will take you to a hosted secure page for payment.  Clicking to submit your order multiple times or double-clicking the Process Payment button will result in your credit card being charged multiple times."));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you encounter a problem when making your credit card payment or you do not receive an email confirming your order please contact our "));
		p.appendChild(sp);
		sp.appendChild(document.createTextNode(" Customer Service on 1300 135 113"));
		p.appendChild(document.createTextNode(" before attempting to re-submit your order or re-try your credit card payment."));
		
		//Attach notice
		oParent.appendChild(f);
//-----------------------------------------------------------------------------------------------------               

        setTimeout('document.getElementById(\'secondary_checkout_form\').submit()',1000);
        
    },
    
    isPersonalOrder: function()
    {
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');
        if(payType && payType == '2')//if payment is credit card
        {
            return true;
        } else {
            return false;
        }
    },
    
    attachStep3DeliveryDetails: function(oParent)
    {
    
      if(this.isPersonalOrder()) {
      var p1 = document.createElement('p');
      var text = "A handling fee of $10.00 applies for private customers.";
      p1.appendChild(document.createTextNode(text));
        oParent.appendChild(p1);
     }
    
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Your delivery details:'));
        h3.style.marginTop = '0';
        oParent.appendChild(h3);
    
        var p = document.createElement('p');
        p.setAttribute('id','deliveryDetails');
        
        var oCookie = new CheckoutCookie('checkout_step1');
        
        //Atach first and last name
        var text = oCookie.getVarValue('Firstname') + ' ' + oCookie.getVarValue('Lastname'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach organisation
        var text = oCookie.getVarValue('Organisation'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach address and city
        var text = oCookie.getVarValue('PostalAddress'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach state and post code
        var text = oCookie.getVarValue('PostalCity') + '   ' + oCookie.getVarValue('PostalState') + '   ' + oCookie.getVarValue('PostalCode'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach to parent
        oParent.appendChild(p);
    },
    
    attachStep1Form: function(oParent)
    {
        var oCookie = new CheckoutCookie('checkout_step1');
        
        var oForm = this.createForm();
        
        // Payment method
        var div = document.createElement('div');        
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Payment method'));
        div.appendChild(h3);

        var f = document.createElement('fieldset');
        f.className = 'payType';
        //f.appendChild(DH.createLabel('Payment','PayType'));
        //var sValue = (oCookie.getVarValue('PayType')) ? oCookie.getVarValue('PayType') : '2';
        //Attach radios
        var ul = document.createElement('ul');
        var names = ['School/University invoice','School/University credit card','Personal credit card'];
        var values = ['4','3','2'];
        
        /*var checkPurchases_onClick = function(oEvent)
        {
        //alert(this.value);
            if(this.value && (this.value == '2' || this.value == '3') && !Cart.hasOnlyItemsInStock()) {
              alert('Items not available cannot be purchased by credit card. Select payment by invoice or else the unavailable item(s) will not be added to your order');
             }
        }*/
            
        for(var i = 0; i < names.length; i++)
        {
            try{
                var checked = "";
                //if(sValue == values[i])checked = "checked='checked'";
                var oInput = document.createElement("<input type='radio' name='PayType' value='" + values[i] + "' " + checked + " tabindex='7' />");
                //DH.addEvent(oInput,'click',checkPurchases_onClick);
            } catch(oError) {
                var oInput = DH.createInput('radio','PayType',values[i],'7');
                //DH.addEvent(oInput,'click',checkPurchases_onClick);                
                //if(sValue == values[i])oInput.checked = true;
            }
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode(names[i]));
            //Attach handling fee message to last item
            if(i == (names.length - 1))
            {
                var p = document.createElement('p');
                p.appendChild(document.createTextNode('(A handling fee of $' + Cart.handlingFee.toFixed(2) + ' applies for private customers.)'));
                li.appendChild(p);
            }
            ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
		oForm.appendChild(div);
        
        //Personal details
        var div = document.createElement('div');
        div.setAttribute('id','personalDetails');
        
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Personal details'));
        div.appendChild(h3);
        
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('First name*','Firstname'));
        var sValue = (oCookie.getVarValue('Firstname')) ? oCookie.getVarValue('Firstname') : '';
        var oInput = DH.createInput('text','Firstname',sValue,'1');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Last name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Last name*','Lastname'));
        var sValue = (oCookie.getVarValue('Lastname')) ? oCookie.getVarValue('Lastname') : '';
        var oInput = DH.createInput('text','Lastname',sValue,'2');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Position
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Position*','Position'));
        var sValue = (oCookie.getVarValue('Position')) ? oCookie.getVarValue('Position') : '';
        var oInput = DH.createInput('text','Position',sValue,'3');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Organisation
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('School name (if applicable)','Organisation'));
        var sValue = (oCookie.getVarValue('Organisation')) ? oCookie.getVarValue('Organisation') : '';
        var oInput = DH.createInput('text','Organisation',sValue,'4');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach ContactType
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Preferred contact','ContactType'));
        var sValue = (oCookie.getVarValue('ContactType')) ? oCookie.getVarValue('ContactType') : 'Email';
        var select = document.createElement('select');
        select.setAttribute('name','ContactType');
        //select.setAttribute('tabindex','5');
        var values = ['Email','Phone','Postal'];
        for(var i = 0; i < values.length; i++)
        {
            var option = document.createElement('option');
            option.appendChild(document.createTextNode(values[i]));
            option.setAttribute('value',values[i]);
            select.appendChild(option);
        }
        switch(oCookie.getVarValue('ContactType'))
        {
            case 'Email': var sValue = 0; break;
            case 'Phone': var sValue = 1; break;
            case 'Postal': var sValue = 2; break;
            default: var sValue = '';
        }
        select.selectedIndex = sValue;
        //select.value = sValue;
        f.appendChild(select);
        div.appendChild(f);

        //Attach Comments
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Comments','Comments'));
        var sValue = (oCookie.getVarValue('Comments')) ? oCookie.getVarValue('Comments') : '';
        var oTextArea = document.createElement('textarea');
        oTextArea.setAttribute('name','Comments');
        oTextArea.setAttribute('tabindex','6');
        oTextArea.setAttribute('cols','25');
        oTextArea.appendChild(document.createTextNode(sValue));
        f.appendChild(oTextArea);
        div.appendChild(f);
        
        //-----------------------------------------------------------------------------------------------------
	        //Important Notice
		var f = document.createElement('div');
		var p = document.createElement('p');
		var sp = document.createElement('span');
		
		var g = document.createElement('div');
		
		f.style.id='importantNotice';
		f.style.display='inline';
		f.style.fontWeight='bold';
		f.style.color='red';
		f.style.margin='3px';
		f.style.padding='3px';
		f.style.id='importantNotice';
		
		
		sp.style.color='black';
		
		g.style.display='block';
		g.style.width='100%';
		g.style.height='85px';
		g.style.clear='both';
		
		f.appendChild(g);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Important!"));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Dear Customer,"));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you are paying by credit card, submitting your order will take you to a hosted secure page for payment.  Clicking to submit your order multiple times or double-clicking the Process Payment button will result in your credit card being charged multiple times."));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you encounter a problem when making your credit card payment or you do not receive an email confirming your order please contact our "));
		p.appendChild(sp);
		sp.appendChild(document.createTextNode(" Customer Service on 1300 135 113"));
		p.appendChild(document.createTextNode(" before attempting to re-submit your order or re-try your credit card payment."));
		
		//Attach notice
		div.appendChild(f);
//-----------------------------------------------------------------------------------------------------     
        
        //Attach PayType
        
        //Attach SalesRepCode
        var f = document.createElement('fieldset');
        //f.appendChild(DH.createLabel('Sales rep code','SalesRepCode'));
        var sValue = (oCookie.getVarValue('SalesRepCode')) ? oCookie.getVarValue('SalesRepCode') : 'website';
        var oInput = DH.createInput('hidden','SalesRepCode',sValue,'8');
        oInput.setAttribute('tabindex','8');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach personal details to form       
        oForm.appendChild(div);
        
		//Information
        var div = document.createElement('div');
        div.setAttribute('id','information');
        
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Information'));
        div.appendChild(h3);

		// attach delivery type
		//alert(oCookie.getVarValue('AddressType'))
		
        var f = document.createElement('fieldset');
        f.className = 'AddressType';
        var ul = document.createElement('ul');   
       try{
        var oInput = document.createElement("<input type='radio' name='AddressType' value='1' />");
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('Private address'));
        ul.appendChild(li);
        var oInput = document.createElement("<input type='radio' name='AddressType' value='2' />");
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('School / Institution'));
        ul.appendChild(li);
               
        } catch(oError) {
        var oInput = DH.createInput('radio','AddressType','1','');
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('Private address'));
        ul.appendChild(li);
        var oInput = DH.createInput('radio','AddressType','2','');
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('School / Institution'));
        ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
           
        
        var p = document.createElement('p');
        p.appendChild(document.createTextNode('Note: we do not deliver to post office boxes.'));
        div.appendChild(p);
        
        //Attach postal address
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Street address*','PostalAddress'));
        var sValue = (oCookie.getVarValue('PostalAddress')) ? oCookie.getVarValue('PostalAddress') : '';
        var oInput = DH.createInput('text','PostalAddress',sValue,'9');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach postal city
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Suburb*','PostalCity'));
        var sValue = (oCookie.getVarValue('PostalCity')) ? oCookie.getVarValue('PostalCity') : '';
        var oInput = DH.createInput('text','PostalCity',sValue,'10');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Postal state
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('State*','PostalState'));
        var select = document.createElement('select');
        select.setAttribute('name','PostalState');
        select.setAttribute('tabindex','11');
        select.appendChild(DH.createOption('Select a state','Select a state'));
        select.appendChild(DH.createOption('ACT','Australian Capital Territory'));
        select.appendChild(DH.createOption('NSW','New South Wales'));
        select.appendChild(DH.createOption('NT','Northern Territory'));
        select.appendChild(DH.createOption('QLD','Queensland'));
        select.appendChild(DH.createOption('SA','South Australia'));
        select.appendChild(DH.createOption('TAS','Tasmania'));
        select.appendChild(DH.createOption('VIC','Victoria'));
        select.appendChild(DH.createOption('WA','Western Australia'));
        switch(oCookie.getVarValue('PostalState'))
        {
            case 'Australian Capital Territory': var sValue = 1; break;
            case 'New South Wales': var sValue = 2; break;
            case 'Northern Territory': var sValue = 3; break;
            case 'Queensland': var sValue = 4; break;
            case 'South Australia': var sValue = 5; break;
            case 'Tasmania': var sValue = 6; break;
            case 'Victoria': var sValue = 7; break;
            case 'Western Australia': var sValue = 8; break;
            default: var sValue = 0;
        }
        select.selectedIndex = sValue;
        f.appendChild(select);
        div.appendChild(f);
        
        //Attach postal code
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Postcode*','PostalCode'));
        var sValue = (oCookie.getVarValue('PostalCode')) ? oCookie.getVarValue('PostalCode') : '';
        var oInput = DH.createInput('text','PostalCode',sValue,'12');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach overseas order
        var f = document.createElement('fieldset');
        f.className = 'overseasOrder';
        f.appendChild(DH.createLabel('Is your order to be delivered outside Australia?','overseasOrder'));
        var sValue = (oCookie.getVarValue('overseasOrder')) ? oCookie.getVarValue('overseasOrder') : '0';
        

        var overseasOrder_onClick = function(oEvent)
        {
            if(this.value && this.value == '1')
            {
                tmpOS = true;
                var isInternational = confirm('If your order is for delivery outside Australia then please ensure you have provided an email address and click OK, your order will be sent to our Sales Department and we will contact you shortly. If you do not wish to proceed with this order then click Cancel.');
                if(!isInternational)
                {
                    var oInputs = document.getElementById('secondary_checkout_form').getElementsByTagName('input');
                    var radioButtons = new Array();
                    for(var i = 0; i < oInputs.length; i++)
                    {
                        if(oInputs[i].type
                           && oInputs[i].type.toLowerCase() == 'radio'
                           && oInputs[i].name
                           && oInputs[i].name == 'overseasOrder')
                        {
                            radioButtons.push(oInputs[i]);
                        }  
                    }
                    if(radioButtons.length == 2)
                    {
                        radioButtons[1].checked = true;
                    }
                }
            }
        };
        
        //Attach radios
        var ul = document.createElement('ul');
        try{
                //attach yes
                var checked = "";
                if(sValue == '1')checked = "checked='checked'";
                tmpOS = false;
                var oInput = document.createElement("<input type='radio' name='overseasOrder' value='1' " + checked + " tabindex='13' />");
                DH.addEvent(oInput,'click',overseasOrder_onClick);
                var li = document.createElement('li');
                li.appendChild(oInput);
                li.appendChild(document.createTextNode('Yes'));
                ul.appendChild(li);
                //attach no
                var checked = "";
                if(sValue == '0')checked = "checked='checked'";
                var oInput = document.createElement("<input type='radio' name='overseasOrder' value='0' " + checked + " tabindex='13' />");
                DH.addEvent(oInput,'click',overseasOrder_onClick);
                var li = document.createElement('li');
                li.appendChild(oInput);
                li.appendChild(document.createTextNode('No'));
                ul.appendChild(li);
                
        } catch(oError) {
            //Attach yes
            var oInput = DH.createInput('radio','overseasOrder','1','13');
            DH.addEvent(oInput,'click',overseasOrder_onClick);
            if(sValue == '1')oInput.checked = true;
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode('Yes'));
            ul.appendChild(li);
            //Attach no
            var oInput = DH.createInput('radio','overseasOrder','0','13');
            DH.addEvent(oInput,'click',overseasOrder_onClick);
            if(sValue == '0')oInput.checked = true;
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode('No'));
            ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
        
        //Attach phone number
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Phone*','PhoneNumber'));
        var sValue = (oCookie.getVarValue('PhoneNumber')) ? oCookie.getVarValue('PhoneNumber') : '';
        var oInput = DH.createInput('text','PhoneNumber',sValue,'14');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);   
        
        //Attach fax
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Fax','FaxNumber'));
        var sValue = (oCookie.getVarValue('FaxNumber')) ? oCookie.getVarValue('FaxNumber') : '';
        var oInput = DH.createInput('text','FaxNumber',sValue,'15');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f); 
        
        //Attach email address
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Email*','EmailAddress'));
        var sValue = (oCookie.getVarValue('EmailAddress')) ? oCookie.getVarValue('EmailAddress') : '';
        var oInput = DH.createInput('text','EmailAddress',sValue,'16');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f); 
        
        //Attach remember checkbox
        var f = document.createElement('fieldset');
        f.className = 'rememberDetails';
        var sValue = (oCookie.getVarValue('EmailAddress')) ? oCookie.getVarValue('EmailAddress') : '';
        var oInput = DH.createInput('checkbox','Remember','Yes','17');
        var Remember_onClick = function()
        {
            var oCookie = new CheckoutCookie('checkout_step1');
            oCookie.save();
        };
        DH.addEvent(oInput,'click',Remember_onClick);
        if(sValue)
        {
            oInput.checked = true;
        }
        f.appendChild(oInput);
        f.appendChild(DH.createLabel('Remember my details','Remember'));
        div.appendChild(f);
        
        //Attach receive info checkbox
        var f = document.createElement('fieldset');
        f.className = 'receiveInfo';
        var sValue = (oCookie.getVarValue('ReceiveInfo')) ? oCookie.getVarValue('ReceiveInfo') : '';
        var oInput = DH.createInput('checkbox','ReceiveInfo','Yes','18');
        if(sValue)
        {
            oInput.checked = true;
        }
        f.appendChild(oInput);
        f.appendChild(DH.createLabel('Please send me further info on Macmillan products','ReceiveInfo'));
        div.appendChild(f);
        
        //Attach required fields message
        var p = document.createElement('p');
        p.className = 'requiredInfo';
        p.appendChild(document.createTextNode('* = required fields.'));
        div.appendChild(p); 
        
        //Attach buttons
        var f = document.createElement('fieldset');
        f.className = 'buttons';
        var oInput = DH.createInput('button','continueShopping','Continue shopping','19');
        oInput.className = 'continueShopping';
        var ContinueShoppingBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            history.go(-1);
        };
        DH.addEvent(oInput,'click',ContinueShoppingBtn_onClick);
        f.appendChild(oInput);
        var oInput = DH.createInput('button','nextStep','Next step','20');
        oInput.className = 'nextStep';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        div.appendChild(f);   
                

        //Attach information form       
        oForm.appendChild(div);
        
        oParent.appendChild(oForm);
        
    },
    
    attachStep2Form: function(oParent)
    {
        var oCookie = new CheckoutCookie('checkout_step2');
        
        var oForm = this.createForm();
        
        //Personal details
        var div = document.createElement('div');
        div.setAttribute('id','invoiceInfo');
        /*
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('School/University invoice details'));
        div.appendChild(h3);
        */
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Customer order number*','Inv_Order_Number'));
        var sValue = (oCookie.getVarValue('Inv_Order_Number')) ? oCookie.getVarValue('Inv_Order_Number') : '';
        var oInput = DH.createInput('text','Inv_Order_Number',sValue,'21');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Macmillan Account code (if known)','Inv_Order_Number'));
        var sValue = (oCookie.getVarValue('Inv_Order_AccountCode')) ? oCookie.getVarValue('Inv_Order_AccountCode') : '';
        var oInput = DH.createInput('text','Inv_Order_AccountCode',sValue,'22');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach required fields message
        var p = document.createElement('p');
        p.className = 'requiredInfo';
        p.appendChild(document.createTextNode('* = required fields.'));
        div.appendChild(p);
        
        //Attach p.text
        var p = document.createElement('p');
        p.className = 'text';
        //p.appendChild(document.createTextNode('All Customer Order Numbers will be checked and verified by the Customer Service Department.'));
       // p.appendChild(document.createElement('br'));
       // p.appendChild(document.createTextNode('Proceeding with the Next Step button below will issue a request for an invoice.<br><br><a href="libraries/Terms+and+Conditions">Click here for terms and conditions</a>.'));
        div.appendChild(p);
        p.innerHTML = '<br>Proceeding with the Next Step button below will issue a request for an invoice.<br><br><a href="libraries/Terms+and+Conditions">Click here for terms and conditions</a>.';
        
        //Attach buttons
        var f = document.createElement('fieldset');
        var oInput = DH.createInput('button','previousStep','Previous','23');
        oInput.className = 'button';
        var PreviousStepBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveBack();
        };
        DH.addEvent(oInput,'click',PreviousStepBtn_onClick);
        f.appendChild(oInput);
        var oInput = DH.createInput('button','nextStep','Next step','24');
        oInput.className = 'button';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        div.appendChild(f);  
         
        //Attach information form       
        oForm.appendChild(div);
        oParent.appendChild(oForm);   
        
        //-----------------------------------------------------------------------------------------------------
	        //Important Notice
		var f = document.createElement('div');
		var p = document.createElement('p');
		var sp = document.createElement('span');
		
		var g = document.createElement('div');
		
		f.style.id='importantNotice';
		f.style.display='inline';
		f.style.fontWeight='bold';
		f.style.color='red';
		f.style.margin='3px';
		f.style.padding='3px';
		f.style.id='importantNotice';
		
		
		sp.style.color='black';
		
		g.style.display='block';
		g.style.width='100%';
		g.style.height='85px';
		g.style.clear='both';
		
		f.appendChild(g);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Important!"));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("Dear Customer,"));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you are paying by credit card, submitting your order will take you to a hosted secure page for payment.  Clicking to submit your order multiple times or double-clicking the Process Payment button will result in your credit card being charged multiple times."));
		p.appendChild(document.createElement('br'));
		p.appendChild(document.createElement('br'));
		f.appendChild(p);
		p.appendChild(document.createTextNode("If you encounter a problem when making your credit card payment or you do not receive an email confirming your order please contact our "));
		p.appendChild(sp);
		sp.appendChild(document.createTextNode(" Customer Service on 1300 135 113"));
		p.appendChild(document.createTextNode(" before attempting to re-submit your order or re-try your credit card payment."));
				
		//Attach notice
		oParent.appendChild(f);
//-----------------------------------------------------------------------------------------------------           
    },
    
    createForm: function()
    {
        var oForm = document.createElement('form');
        oForm.setAttribute('enctype','multipart/form-data');
        oForm.setAttribute('method','post');
        oForm.setAttribute('action','http://macmillan.itechne.com/');
        oForm.setAttribute('id','secondary_checkout_form');
        return oForm;
    },
    
    validate_step1: function()
    {
        //check if there are items in cart
        if(!Cart || !Cart.hasItems())
        {
            alert('Please add items to cart before proceeding.');
            return false;
        }

      
        var vars = new Array();
        var oCookie = new CheckoutCookie('checkout_step1');

    	// check not PO box
    	var regExpPOBox = /(\b)(po|p o|pb|p.o|box|bag|locked|private|locked bag|ms|rmd|private bag)(\b)/;
    	var inputValue = oCookie.getFormTextInputValue('PostalAddress');
    	if (inputValue && regExpPOBox.test(inputValue.toLowerCase())) {
 			alert('Sorry, we do not deliver to post office/private boxes.');
        	return false;
		}

        
        //Validate fields
        var message = oCookie.validate_step1(vars);
        if(vars.length > 0)
        {
            alert(message + vars.join('\n'));
            return false;
        }
        
        //validate cart items against paytype
        var payType = oCookie.getFormRadioInputValue('PayType');
        if (payType==undefined || payType=='undefined') 
        {
            alert('Please select a payment type.');
            return false;
        
        }
        if(payType == '2' && Cart.hasInspectedItems())
        {
            alert('Inspection copies may only be requested by schools.');
            return false;
        }
        if(payType == '3' && Cart.hasInspectedItems())
        {
            alert('Inspect on Approval items cannot be ordered using credit card for payment. Please select payment by invoice or remove these items.');
            return false;
        }

        /*if((payType == '2' || payType == '3') && Cart.hasOnlyItemsOutOfStock())
        {
            alert('Items not available cannot be purchased by credit card. Please select payment by invoice.');
            return false;
        }
        if((payType == '2' || payType == '3') && !Cart.hasOnlyItemsInStock())
        {
            Cart.removeItemsOutOfStock();
        }*/
        
        return true;
    },
    
    validate_step2: function()
    {
        var vars = new Array();
        var oCookie = new CheckoutCookie('checkout_step2');
        //Validate fields
        var message = oCookie.validate_step2(vars);
        if(vars.length > 0)
        {
            alert(message + vars.join('\n'));
            return false;
        }
        
        return true;
    },
    
    moveFrom: function()
    {
        switch(this.step)
        {
            case 1:
                this.moveFrom_step1();
                break;
            case 2:
                this.moveFrom_step2();
                break;
            case 3:
                this.moveFrom_step3();
                break;
            default:
        }
    },
    
    moveBack: function()
    {
        switch(this.step)
        {
            case 3://summary
                this.moveBack_step3();    
                break;
            case 2://invoice
                this.step = 1;
                break;   
            default:
        }
        this.attach();
    },
    
    moveBack_step3: function()
    {
        //Get paytype
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');  
        if(payType == '2' || payType == '3')//credit card
        {
            this.step = 1;
        } else {//invoice
            this.step = 2;
        }
    },
    
    moveFrom_step1: function()
    {
        var step1Valid = this.validate_step1();
        if(step1Valid)
        {
            //Save cookie
            var oCookie = new CheckoutCookie('checkout_step1');
            oCookie.save();
            
            var payType = oCookie.getFormRadioInputValue('PayType');
            if(payType == '2' || payType == '3')//credit card
            {
                this.step = 3;
            } else {
                this.step = 2;
            }
            this.attach();
        } 
    },
    
    moveFrom_step2: function()
    {
        var step2Valid = this.validate_step2();
        if(step2Valid)
        {
            //Save cookie
            var oCookie = new CheckoutCookie('checkout_step2');
            oCookie.save();
            
            this.step = 3;
            
            this.attach();
        } 
    },
    
    moveFrom_step3: function()
    {
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');
        //if(payType == '2' && Cart.hasOnlyItemsInStock())
        if((payType == '2' || payType == '3') && oCookie.getVarValue('overseasOrder')!='1')
        {
            var confirmPurchase = confirm('Please be advised when you confirm your order your credit card will be debited and your order will not be refundable unless we are notified within 14 days that an item is faulty or incorrectly supplied.');
            if(confirmPurchase)
            {
                this.step = 4;
                this.attach();
            }
        }  else {
            this.step = 4;
            this.attach();
        }     
    },
    
    moveTo_step2: function()
    {
    
    },

    init: function()
    {
    
        //Set checkout step
        this.step = 1;
    }

}


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    cookie manager
    
*/

function CheckoutCookie(cookieName)
{
    if(!cookieName || typeof cookieName != 'string' || cookieName.length < 1)
    {
        throw new Error('CheckoutCookieManager constructor expects at least one argument of \'string\' type');
    }
    
    this.name = cookieName;
    this.vars = new Array();
    this.load();
}

CheckoutCookie.prototype.load = function()
{
    var oCookie = DH.getCookie(this.name);
    
    var vars = new Array();
    
    if(oCookie)
    {
        var tempArray = oCookie.split('||');
        for(var i = 0; i < tempArray.length; i++)
        {
            var cookieVar = tempArray[i].split('=');
            if(cookieVar.length != 2)
            {
                throw new Error('CheckoutCookie.load() - cookie is corrupt');
            }
            var item = {name: cookieVar[0],value: decodeURIComponent(cookieVar[1])};
            this.vars.push(item);
            vars.push(item.name + '=' + item.value);
        }
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('CheckoutCookie.load() - cookie loaded',vars);
    }
};

CheckoutCookie.prototype.getVarValue = function(name)
{
    for(var i = 0; i < this.vars.length; i++)
    {
        if(this.vars[i].name == name 
           && typeof this.vars[i].value == 'string' 
           && this.vars[i].value.length > 0)
        {
            return this.vars[i].value;
        }
    }
    return null;
};

CheckoutCookie.prototype.save = function()
{
    var vars = new Array();
    switch(this.name)
    {
        case 'checkout_step1':
            this.get_personalDetails(vars);
            this.get_information(vars);
            break;
        case 'checkout_step2':
            this.get_invoice(vars);
            break;
        default:
    }
    
    if(vars.length > 0)
    {
        var cookieExpires = new Date();
        cookieExpires.setTime(cookieExpires.getTime() + (1 * 60 * 60 * 1000 ));
        DH.setCookie(this.name,vars.join('||'),cookieExpires,'/');
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('CheckoutCookie.save() - cookie saved',vars);
    }
};

CheckoutCookie.prototype.getFormTextInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var oInputs = oForm.getElementsByTagName('input');
    
    if(oInputs.length < 1)return null;
    
    for(var i = 0; i < oInputs.length; i++)
    {
        if(oInputs[i].name 
           && oInputs[i].name == name 
           && typeof oInputs[i].value == 'string' 
           && oInputs[i].value.length > 0)
        {
            return encodeURIComponent(oInputs[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormTextAreaValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var textAreas = oForm.getElementsByTagName('textarea');
    
    if(textAreas.length < 1)return null;
    
    for(var i = 0; i < textAreas.length; i++)
    {
        if(textAreas[i].name 
           && textAreas[i].name == name 
           && textAreas[i].value
           && textAreas[i].value.length > 0)
        {
            return encodeURIComponent(textAreas[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormCheckboxInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var oInputs = oForm.getElementsByTagName('input');
    
    if(oInputs.length < 1)return null;
    
    for(var i = 0; i < oInputs.length; i++)
    {
        if(oInputs[i].name 
           && oInputs[i].name == name 
           && oInputs[i].checked
           && typeof oInputs[i].value == 'string' 
           && oInputs[i].value.length > 0)
        {
            return encodeURIComponent(oInputs[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormSelectValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var selects = oForm.getElementsByTagName('select');
    for(var i = 0; i < selects.length; i++)
    {
        if(selects[i].name && selects[i].name == name)
        {
            var select = selects[i];
        }
    }
    
    //If no select found
    if(!select)return null;
    
    var options = select.getElementsByTagName('option');
    //If no option tags found
    if(options.length < 1)return null;
    return options[select.selectedIndex].value;
};

CheckoutCookie.prototype.getFormRadioInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var inputs = oForm.getElementsByTagName('input');
    var radios = new Array();
    for(var i = 0; i < inputs.length; i++)
    {
        if(inputs[i].type && inputs[i].type.toLowerCase() == 'radio'
           && inputs[i].name && inputs[i].name == name)
        {
            radios.push(inputs[i]);
        }
    }
    
    //If no select found
    if(radios.length < 1)return null;
    
    for(var i = 0; i < radios.length; i++)
    {
        if(radios[i].checked)return radios[i].value;
    }
    
    return null;
};

CheckoutCookie.prototype.get_personalDetails = function(vars)
{

    //Get firstname
    var inputValue = this.getFormTextInputValue('Firstname');
    if(inputValue)vars.push('Firstname=' + inputValue);
    
    //Get lastname
    var inputValue = this.getFormTextInputValue('Lastname');
    if(inputValue)vars.push('Lastname=' + inputValue);
    
    //Get position
    var inputValue = this.getFormTextInputValue('Position');
    if(inputValue)vars.push('Position=' + inputValue);
    
    //Get Organisation
    if (this.getFormRadioInputValue('AddressType') == '1') {  // private address
      var inputValue = "";
    }
    else {
      var inputValue = this.getFormTextInputValue('Organisation');
      if(inputValue)vars.push('Organisation=' + inputValue);
	} 
  
   
    //Get ContactType
    var inputValue = this.getFormSelectValue('ContactType');
    if(inputValue)vars.push('ContactType=' + inputValue);
    
    //Get comments
    var inputValue = this.getFormTextAreaValue('Comments');
    if(inputValue)vars.push('Comments=' + inputValue);
    
    //Get PayType
    var inputValue = this.getFormRadioInputValue('PayType');
    if(inputValue)vars.push('PayType=' + inputValue);
    
    //Get SalesRepCode
    var inputValue = this.getFormTextInputValue('SalesRepCode');
    if(inputValue)vars.push('SalesRepCode=' + inputValue);
};

CheckoutCookie.prototype.getHiddenInputs_personalDetails = function(oForm)
{
    //Get firstname
    oForm.appendChild(DH.createHiddenInput('FirstName',this.getVarValue('Firstname')));
    
    //Get lastname
    oForm.appendChild(DH.createHiddenInput('LastName',this.getVarValue('Lastname')));
    
    //Get position
    oForm.appendChild(DH.createHiddenInput('Position',this.getVarValue('Position')));
    
    //Get Organisation
    /*** bug?
    var inputValue = (this.getVarValue('Organisation').toLowerCase().indexOf('school') == -1)
                      ? ('School ' + this.getVarValue('Organisation')) : this.getVarValue('Organisation') ;
    oForm.appendChild(DH.createHiddenInput('SchoolName',inputValue));
    */
     oForm.appendChild(DH.createHiddenInput('SchoolName',this.getVarValue('Organisation')));    
        
    //Get ContactType
    switch(this.getVarValue('ContactType'))
    {
        case 'Email': var sValue = '1'; break;
        case 'Phone': var sValue = '2'; break;
        case 'Postal': var sValue = '3'; break;
        default: var sValue = '';
    }
    oForm.appendChild(DH.createHiddenInput('PreferredContactType',sValue));
    
    //Attach comments
    if(this.getVarValue('Comments'))
    {
        var textArea = document.createElement('textarea');
        textArea.style.display = 'none';
        textArea.setAttribute('name','Comments');
        textArea.appendChild(document.createTextNode(this.getVarValue('Comments')));
        oForm.appendChild(textArea);
    }
        
    //Get PayType
    oForm.appendChild(DH.createHiddenInput('PaymentType',this.getVarValue('PayType')));
    
    //Get SalesRepCode
    oForm.appendChild(DH.createHiddenInput('SalesRepCode',this.getVarValue('SalesRepCode')));
};

CheckoutCookie.prototype.getHiddenInputs_information = function(oForm)
{
    //Get PostalAddress
    oForm.appendChild(DH.createHiddenInput('PostalAddress',this.getVarValue('PostalAddress')));
    
    //Get PostalCity
    oForm.appendChild(DH.createHiddenInput('PostalCity',this.getVarValue('PostalCity')));
    
    //Get PostalState
    var isOverseasOrder = (this.getVarValue('overseasOrder') == '1') ? true : null;
    if(isOverseasOrder)
    {
        oForm.appendChild(DH.createHiddenInput('PostalState','International'));
    } else {
        oForm.appendChild(DH.createHiddenInput('PostalState',this.getVarValue('PostalState')));
    }
    
    //Get PostalCode
    oForm.appendChild(DH.createHiddenInput('PostalCode',this.getVarValue('PostalCode')));
    
    //Get PhoneNumber
    oForm.appendChild(DH.createHiddenInput('PhoneNumber',this.getVarValue('PhoneNumber')));
    
    //Get FaxNumber
    oForm.appendChild(DH.createHiddenInput('FaxNumber',this.getVarValue('FaxNumber')));
    
    //Get EmailAddress
    oForm.appendChild(DH.createHiddenInput('EmailAddress',this.getVarValue('EmailAddress')));
    
    //Get ReceiveInfo
    var moreInfo = (this.getVarValue('ReceiveInfo') == 'Yes') ? 'True' : 'False';
    oForm.appendChild(DH.createHiddenInput('FurtherInfo',moreInfo));
};

CheckoutCookie.prototype.getHiddenInputs_invoice = function(oForm)
{
    //Get customer order number
    oForm.appendChild(DH.createHiddenInput('Inv_Order_Number',this.getVarValue('Inv_Order_Number')));
    
    //macmillan account code
    oForm.appendChild(DH.createHiddenInput('Inv_Order_AccountCode',this.getVarValue('Inv_Order_AccountCode')));
};

CheckoutCookie.prototype.get_information = function(vars)
{
    //Get PostalAddress
    var inputValue = this.getFormTextInputValue('PostalAddress');
    if(inputValue)vars.push('PostalAddress=' + inputValue);
    
    //Get PostalCity
    var inputValue = this.getFormTextInputValue('PostalCity');
    if(inputValue)vars.push('PostalCity=' + inputValue);
    
    //Get PostalState
    var inputValue = this.getFormSelectValue('PostalState');
    if(inputValue)vars.push('PostalState=' + inputValue);
    
    //Get PostalCode
    var inputValue = this.getFormTextInputValue('PostalCode');
    if(inputValue)vars.push('PostalCode=' + inputValue);
    
    //Get overseasOrder
    var inputValue = this.getFormRadioInputValue('overseasOrder');
    if(inputValue)vars.push('overseasOrder=' + inputValue);
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(inputValue)vars.push('PhoneNumber=' + inputValue);
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    if(inputValue)vars.push('FaxNumber=' + inputValue);
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    if(inputValue)vars.push('EmailAddress=' + inputValue);
    
    //Get Remember
    var inputValue = this.getFormCheckboxInputValue('Remember');
    if(inputValue)vars.push('Remember=' + inputValue);
    
    //Get ReceiveInfo
    var inputValue = this.getFormCheckboxInputValue('ReceiveInfo');
    if(inputValue)vars.push('ReceiveInfo=' + inputValue);
};

CheckoutCookie.prototype.get_invoice = function(vars)
{
    //Get customer order number
    var inputValue = this.getFormTextInputValue('Inv_Order_Number');
    if(inputValue)vars.push('Inv_Order_Number=' + inputValue);
    
    //macmillan account code
    var inputValue = this.getFormTextInputValue('Inv_Order_AccountCode');
    if(inputValue)vars.push('Inv_Order_AccountCode=' + inputValue);
};

CheckoutCookie.prototype.validate_step1 = function(vars)
{
    //Get firstname
    var inputValue = this.getFormTextInputValue('Firstname');
    if(!inputValue)vars.push('-Firstname');
    
    //Get lastname
    var inputValue = this.getFormTextInputValue('Lastname');
    if(!inputValue)vars.push('-Lastname');
    
    //Get position
    var inputValue = this.getFormTextInputValue('Position');
    if(!inputValue)vars.push('-Position');
    
    // Address Type
    var inputValue = this.getFormRadioInputValue('AddressType');
    if(!inputValue)vars.push('-Address type (private or school/institution)');  
    
    //Get PostalAddress
    var inputValue = this.getFormTextInputValue('PostalAddress');
    if(!inputValue)vars.push('-PostalAddress');
    
    //Get PostalCity
    var inputValue = this.getFormTextInputValue('PostalCity');
    if(!inputValue)vars.push('-Suburb');
    
    //Get PostalState
    if (!tmpOS) {
    var inputValue = this.getFormSelectValue('PostalState');
    if(!inputValue || inputValue == 'Select a state')vars.push('-State');
    }
    
    //Get PostalCode
    var inputValue = this.getFormTextInputValue('PostalCode');
    if(!inputValue)vars.push('-Postcode (numbers only)');
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(!inputValue)vars.push('-Phone (numbers only)');
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    //if(!inputValue)vars.push('-Fax (numbers only)');
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    if(!inputValue)vars.push('-Email');
    
    if(vars.length > 0)return 'You must fill out the following field(s):\n\n';
    
    //second step of validation
    var reNumbersOnly = /^[0-9]+$/;
    var reEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    
    //Get PostalCode
    var isoverseasOrder = this.getFormRadioInputValue('overseasOrder');
    var inputValue = this.getFormTextInputValue('PostalCode');
    var reNumbersOnly = /^[0-9]+$/;
    if (!inputValue || !reNumbersOnly.test(inputValue) || (isoverseasOrder == "0" && inputValue.length > 4)) vars.push('-Postcode (numbers only)');
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(!inputValue || !reNumbersOnly.test(inputValue))vars.push('-Phone (numbers only)');
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    //if(!inputValue || !reNumbersOnly.test(inputValue))vars.push('-Fax (numbers only)');
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    var reEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    if(!inputValue || !reEmail.test(decodeURIComponent(inputValue)))vars.push('-Email');
    
    if(vars.length > 0)return 'Please verify the following field(s):\n\n';
    
    return true;    
};

CheckoutCookie.prototype.validate_step2 = function(vars)
{
    //Get firstname
    var inputValue = this.getFormTextInputValue('Inv_Order_Number');
    if(!inputValue)vars.push('-Customer order number');
   
    if(vars.length > 0)return 'You must fill out the following field(s):\n\n';
    
    return true;    
};


/*
 * function_HomePageFeatures
 */


HomePageFeatures = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/ 


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/ 


//function to set the z-indexes of the images
    resetZIndexes: function()
    {
        var li = this.module.getElementsByTagName('li');
        for(var i = 0; i < li.length; i++)
        {
            if(i == 0)
            {
                var zIndex = '2';
            } else {
                var zIndex = '1';
            }
            li[i].style.zIndex = zIndex;
        }     
    },
    
//Function to validate tiles
    validate: function()
    {
        var count = 0;
        var li = this.module.getElementsByTagName('li');
        for(var i = 0; i < li.length; i++)
        {
            var a = li[i].getElementsByTagName('a');
            var img = li[i].getElementsByTagName('img');
            if(a.length == 1 && img.length == 1)
            {
                count++;
            }
        }  
        
        if(count == li.length)
        {
            return true;
        } else {
            return null;
        }
    },
    
//Function to get number of tiles
    getTilesCount: function()
    {
        var li = this.module.getElementsByTagName('li');
        return li.length;
    },

//Function to get current tile
    getCurrentTileNum: function()
    {
        var li = this.module.getElementsByTagName('li');
        for(var i = 0; i < li.length; i++)
        {
            if(li[i].style.zIndex == '2')
            {
                return i;
            }
        }  
        return -1;
    },

//Function which returns next tile
    getNext: function()
    {
        var current = this.getCurrentTileNum();
        if((current + 1) >= this.getTilesCount())
        {
            return 0;
        } else {
            return (current + 1);
        }
    },
    
//Function which returns previous tile
    getPrevious: function()
    {
        var current = this.getCurrentTileNum();
        if(current == 0)
        {
            return (this.getTilesCount() - 1);
        } else {
            return (current - 1);
        }
    },

//Function to set current tile
    setCurrent: function(x)
    {
        var li = this.module.getElementsByTagName('li');
        for(var i = 0; i < li.length; i++)
        {
            if(i == x)
            {
                var zIndex = '2';
            } else {
                var zIndex = '1';
            }
            li[i].style.zIndex = zIndex;
        }   
    },
    
//Function to set counter
    setCounter: function(x)
    {
        var counter = document.getElementById('featuresCounter');
        counter.innerHTML = '';
        counter.appendChild(document.createTextNode((x+1) + '/' + this.getTilesCount()));
    },    
        
//Function to attach navigation buttons    
    attachNavigation: function()
    {
        if(this.getTilesCount() < 2)return;
        
        var div = document.createElement('div');
        
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Features'));
        div.appendChild(h3);
        
        var a = document.createElement('a');
        a.className = 'previous';
        a.setAttribute('href','#');
        a.setAttribute('title','previous');
        a.appendChild(document.createTextNode('previous'));
        DH.addEvent(a,'click',HomePageFeatures.move);
        div.appendChild(a);
        
        var a = document.createElement('a');
        a.className = 'next';
        a.setAttribute('href','#');
        a.setAttribute('title','next');
        a.appendChild(document.createTextNode('next'));
        DH.addEvent(a,'click',HomePageFeatures.move);
        div.appendChild(a);
        
        var span = document.createElement('span');
        span.setAttribute('id','featuresCounter');
        span.appendChild(document.createTextNode('1/' + this.getTilesCount()));
        div.appendChild(span);
        
        this.module.appendChild(div);
    },
    
    move: function(oEvent)
    {
        var target = DH.stopEvent(oEvent);
        
        switch(target.className)
        {
            case 'previous':
                var num = HomePageFeatures.getPrevious();
                break;
            case 'next':
                var num = HomePageFeatures.getNext();
                break;   
            default:          
        }
        HomePageFeatures.setCurrent(num);
        HomePageFeatures.setCounter(num);
    },


    init: function()
    {
        if(!HomePageFeaturesCount)var HomePageFeaturesCount = 0;
		
		//Get reference to holder element
		this.module = document.getElementById('features');
		if(!this.module)
		{
			//If exceeded the number of determined iterations
			if(HomePageFeaturesCount > 10)
			{
				throw new Error('HomePageFeatures.init() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			HomePageFeaturesCount++;
			setTimeout('HomePageFeatures.init()',100);
			return;
		}
		
		//If structure is valid
		if(this.validate())
		{
            this.resetZIndexes();
            
            this.attachNavigation();
        }
    }


}



/*
 * function_TeacherSupport
 */



function TeacherSupport()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('Series.init() expects argument 1 to be of \'string\' type');
    }
        
    this.isbn = arguments[0]; 
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

TeacherSupport.prototype._SEARCHSTR = '/secondary31/site/search.js?open&';
TeacherSupport.prototype._SEARCH_LABEL =  'TeacherSupport';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
TeacherSupport.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    tempArray.push('start=1');
    tempArray.push('count=1');
    tempArray.push('query=[SectionPath]=Teacher+Support+and+[MetaKeywords]=' + this.isbn);
    tempArray.push('label=' + this._SEARCH_LABEL);
    return this._SEARCHSTR + tempArray.join('&');
};

TeacherSupport.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var teacherSupportStr = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(teacherSupportStr);
        var results = eval('searchResults' + this._SEARCH_LABEL);
    } catch(oError) {
        throw new Error('TeacherSupport.loadAjax() error on eval(teacherSupportStr) TeacherSupport.load()');
    } 
        
    //If search results exist
    if(typeof results != 'undefined' && results instanceof Array && typeof results[1] != 'undefined' && this.isResultValid(results[1]))
    {                
        this.index = results[1];
        this.loaded = true;
    } /* else {
        throw new Error("TeacherSupport.load() 'viewResultsTeacherSupport(results)' is undefined");
    }
    */
};

//Function which validates a 'viewResults' entry
TeacherSupport.prototype.isResultValid =  function(result)
{
    //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
        
    //Variable used to detect invalid properties
    var valid = true;
        
    //Array to store invalid properties
    var tempArray = new Array();
        
    //check DocID    
    if(typeof result.viewDocID != 'string' || result.viewDocID.length == 0)
    {
        valid = false;
        tempArray.push('DocID');
    } 
    
        
    //if there are invalid entries and log is enabled
    if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('TeacherSupport.isResultValid() - invalid result : ' + tempArray.join(', '));
        
    return valid;
};



/*
 * function_TeacherSupportFilter
 */


function TeacherSupportFilter()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('TeacherSupportFilter contructor expects argument 1 to be of \'string\' type');
    }
        
    this.subject = arguments[0];
    this.category = (typeof arguments[1] != 'undefined' && typeof arguments[1] == 'string') ? arguments[1] : null;
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

TeacherSupportFilter.prototype._SEARCHSTR = '/secondary31/site/filter.js?readform&';
//TeacherSupportFilter.prototype._SEARCH_LABEL =  'TeacherSupportFilter';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
TeacherSupportFilter.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    tempArray.push('type=Multi');
    var subcat = (this.category) ? (this.subject + '>' + this.category) : this.subject;
    
      
    tempArray.push('cat=Teacher Support>Stories:Teacher+Support>' + subcat);    
    tempArray.push('start=1');
    tempArray.push('count=100');
    //alert(this._SEARCHSTR + tempArray.join('&'));
    return this._SEARCHSTR + tempArray.join('&');
};

TeacherSupportFilter.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var TeacherSupportFilterStr = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(TeacherSupportFilterStr);
    } catch(oError) {
        throw new Error('TeacherSupportFilter.loadAjax() error on eval(TeacherSupportFilterStr) TeacherSupportFilter.load()');
    } 
        
    //If teacher support filter results exist
    if(typeof viewResults != 'undefined' && viewResults instanceof Array && viewResults.length > 0)
    {                
        this.index = new Array();
        for(var i = 1; i < viewResults.length; i++)
        {
            if(typeof viewResults[i] != 'undefined' && this.isResultValid(i))
            {
            
                this.index.push(viewResults[i]);                  
            }
        }
        if(Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportFilterloadAjax() - returned ' + this.index.length + ' results');
            
        //If there are no valid results
        if(this.index.length == 0)
        {
            //If log enabled display message
            if(Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportFilterloadAjax() did not return any valid results');
        } else {
            this.loaded = true;
        } 
            
    } else {
        throw new Error("TeacherSupportFilterloadAjax() 'viewResults' is undefined");
    }
};

//Function which validates a 'viewResults' entry
TeacherSupportFilter.prototype.isResultValid =  function(i)
{
    var result = viewResults[i];
    
    //Variable used to detect invalid properties
    var valid = true;
    
    //Check DocID
    if(!result.viewDocID || result.viewDocID.length != 32)valid = false;
    
    //Check Title
    if(!result.viewTitle || result.viewTitle.length < 1)valid = false;
    
    //Check Categories
    if(!result.viewCategories || result.viewCategories.length < 1)valid = false;
    if(!valid && Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportFilter.isResultValid() result [' + i + '] is NOT valid');
       
    return valid;
};

TeacherSupportFilter.prototype.getCategoriesFromSubject = function()
{
    var tempArray = new Array();
    
    for(var i = 0; i < this.index.length; i++)
    {
        var cat = (decodeURIComponent(this.index[i].viewCategories)).split('>')[1];
        
        if(i == 0)
        {
            tempArray.push(cat);
        } else {
            if(!tempArray.hasString(cat))
            {
                tempArray.push(cat);
            }   
        }
    }
    return tempArray.sort();
};

TeacherSupportFilter.prototype.getItemsFromCategory = function(category)
{
    var tempArray = new Array();
    
    for(var i = 0; i < this.index.length; i++)
    {
        var cat = (decodeURIComponent(this.index[i].viewCategories)).split('>')[1];
        
        if(cat.toLowerCase() == category.toLowerCase())
        {
            tempArray.push(this.index[i]);
        }
    }
    return tempArray;
};

//Function which attaches all results from subject grouped according to categories
TeacherSupportFilter.prototype.attachIndex1 = function(oParent)
{
    var categories = this.getCategoriesFromSubject();
    
    //Attach heading
    var h3 = document.createElement('h3');
    h3.appendChild(document.createTextNode(this.subject));
    h3.className = 'teacherSupportIndex';
    oParent.appendChild(h3);
    
    //Create main div
    var mainDiv = document.createElement('div');
    mainDiv.setAttribute('id','teacherSupportIndex');
    
    //Attach index
    for(var i = 0; i < categories.length; i++)
    {
        var h4 = document.createElement('h4');
        h4.appendChild(document.createTextNode(categories[i]));
        mainDiv.appendChild(h4);
        
        var items = this.getItemsFromCategory(categories[i]).sort(sortByViewTitle);
        
        for(var x = 0; x < items.length; x++)
        {
            var title = '- ' + decodeURIComponent(items[x].viewTitle);
            var docID = decodeURIComponent(items[x].viewDocID);
            
            var a = document.createElement('a');
            a.appendChild(document.createTextNode(title));
            a.setAttribute('title',title);
            a.setAttribute('href','/secondary31/site/articleIDs/' + docID + '?open&template=domSecondary');
            mainDiv.appendChild(a);    
        }
    }
    oParent.appendChild(mainDiv);
};

//Function which attaches results from a category
TeacherSupportFilter.prototype.attachIndex2 = function(oParent)
{ 
    //Attach heading
    var h3 = document.createElement('h3');
    h3.appendChild(document.createTextNode(this.subject));
    h3.className = 'teacherSupportIndex';
    oParent.appendChild(h3);
    
    //Create main div
    var mainDiv = document.createElement('div');
    mainDiv.setAttribute('id','teacherSupportIndex');
    
    //Attach index
    var items = this.index.sort(sortByViewTitle);
    for(var x = 0; x < items.length; x++)
    {
        var title = '- ' + decodeURIComponent(items[x].viewTitle);
        var docID = decodeURIComponent(items[x].viewDocID);
            
        var a = document.createElement('a');
        a.appendChild(document.createTextNode(title));
        a.setAttribute('title',title);
        a.setAttribute('href','/secondary31/site/articleIDs/' + docID + '?open&template=domSecondary');
        mainDiv.appendChild(a);    
    }
    oParent.appendChild(mainDiv);
};

//Function which attaches results from a category in a subject
TeacherSupportFilter.prototype.attachIndex3 = function(oParent)
{
    if(!this.category)return;
    
    //Attach heading
    var h3 = document.createElement('h3');
    h3.appendChild(document.createTextNode(this.subject));
    h3.className = 'teacherSupportIndex';
    oParent.appendChild(h3);
    
    //Create main div
    var mainDiv = document.createElement('div');
    mainDiv.setAttribute('id','teacherSupportIndex');
    
    var h4 = document.createElement('h4');
    h4.appendChild(document.createTextNode(this.category));
    mainDiv.appendChild(h4);
        
    var items = this.getItemsFromCategory(this.category).sort(sortByViewTitle);
        
    for(var x = 0; x < items.length; x++)
    {
        var title = '- ' + decodeURIComponent(items[x].viewTitle);
        var docID = decodeURIComponent(items[x].viewDocID);
            
        var a = document.createElement('a');
        a.appendChild(document.createTextNode(title));
        a.setAttribute('title',title);
        a.setAttribute('href','/secondary31/site/articleIDs/' + docID + '?open&template=domSecondary');
        mainDiv.appendChild(a);    
    }
    
    oParent.appendChild(mainDiv);
};

TeacherSupportFilter.prototype.attachNoRecordsMessage = function(oParent,message)
{
    //Attach heading
    var h3 = document.createElement('h3');
    h3.appendChild(document.createTextNode(this.subject));
    h3.className = 'teacherSupportIndex';
    oParent.appendChild(h3);
    
    //Create main div
    var mainDiv = document.createElement('div');
    mainDiv.setAttribute('id','teacherSupportIndex');
    
    var p = document.createElement('p');
    p.style.margin = '0';
    p.style.padding = '20px 0 0 0';
    p.style.fontWeight = 'bold';
    p.appendChild(document.createTextNode(message));
    mainDiv.appendChild(p);
    oParent.appendChild(mainDiv);
};


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/

function sortByViewTitle(a, b)
{
    atitle = decodeURIComponent(a.viewTitle);
    btitle = decodeURIComponent(b.viewTitle);

    if (atitle < btitle)
    {
        return -1;
    } else if (atitle > btitle) {
        return 1;
    } else {
        return 0;
    }
}




/*
 * function_TeacherSupportTable
 */



TeacherSupportTable = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/ 
    table: null,
    
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/ 

    reset: function()
    {
        var trs = this.table.getElementsByTagName('tr');
        for(var i = 0; i < trs.length; i ++)
        {
            var tds = trs[i].getElementsByTagName('td');
            for(var x = 0; x < tds.length; x++)
            {
                switch(x)
                {
                    case 0://title
                        tds[x].setAttribute('width','40%');
                        break;
                    case 1://pdf
                        tds[x].setAttribute('width','20%');
                    case 2://word
                        tds[x].setAttribute('width','20%');
                    case 3://other
                        tds[x].setAttribute('width','20%'); 
                        break;
                    default:    
                }
            }
        }   
    },
    
    attachHead: function()
    {
        var tr = document.createElement('tr');
        for(var i = 0; i < 4; i++)
        {
            var td = document.createElement('td');
            switch(i)
            {
                case 0:
                    var title = 'Title';
                    break;
                case 1:
                    var title = 'Download PDF';
                    break;
                case 2:
                    var title = 'Download Word';
                    break;
                case 3:
                    var title = 'Download Other';
                    break;
            }   
            td.appendChild(document.createTextNode(title));
            tr.appendChild(td);
        }
        
        var thead = document.createElement('thead');
        thead.appendChild(tr);
        this.table.insertBefore(thead,this.table.getElementsByTagName('tbody')[0]);
    },
    
    parseFiles: function()
    {
        var tr = this.table.getElementsByTagName('tr');
        for(var i = 1; i < tr.length; i++)
        {
            var td = tr[i].getElementsByTagName('td');
            for(var x = 0; x < td.length; x++)
            {
                switch(x)
                {
                    case 1:
                    case 2:
                    case 3:
                        var fileName = this.getFileName(td[x]);
                        var readOnly = this.isLocked(td[x]);
                        var displayName = this.getDisplayFileName(td[x]);
                        
                        if(fileName)
                        {
                            var filePath = '/secondary31/site/articleIDs/' + this.DocID + '/$file/' + fileName;
                            var fileLoad = new HeaderLoader(filePath);
                            if(fileLoad.exist)
                            {  
                                td[x].innerHTML = '';
                                
                                if(readOnly)
                                {
                                    var img = document.createElement('img');
                                    img.setAttribute('alt','read only');
                                    img.src = '/secondary31/site/templates/layout/$file/padlockIcon.jpg';
                                    td[x].appendChild(img);
                                }
                                
                                var a = document.createElement('a');
                                
                                var classArray = new Array();
                                if(fileName.toLowerCase().indexOf('.pdf') != -1)
                                {
                                    classArray.push('pdf');
                                } else if(fileName.toLowerCase().indexOf('.xls') != -1) {
                                    classArray.push('excel');
                                } else if(fileName.toLowerCase().indexOf('.doc') != -1) { 
                                    classArray.push('word');  
								} else if(fileName.toLowerCase().indexOf('.zip') != -1) { 
                                    classArray.push('zip');                                    
                                } else if(fileName.toLowerCase().indexOf('.mp3') != -1) { 
                                    classArray.push('mp3');                                    
                                } else { 
                                    classArray.push('other');  
				}                                    
                                a.className = classArray.join(' ');
                                a.setAttribute('href',filePath);
                                if(readOnly)
                                {
                                a.setAttribute('title','locked');
                                }
                                a.appendChild(document.createTextNode(displayName));
                                DH.addEvent(a,'click',tsAnchorClick);
                                td[x].appendChild(a);
                            } else {
                                this.resetTD(td[x]);
                            }  
                        } else {
                            this.resetTD(td[x]);
                        }
                        break;
                    default:    
                } 
            }
        }
    },
    
    getFileName: function(td)
    {
        var children = td.childNodes;
        for(var i = 0; i < children.length; i++)
        {
            if((children[i].nodeType == 3)
                && ((children[i].nodeValue.toLowerCase().indexOf('.pdf') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.xls') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.zip') != -1)
		    || (children[i].nodeValue.toLowerCase().indexOf('.mp3') != -1)	
		    || (children[i].nodeValue.toLowerCase().indexOf('.wma') != -1)

		    || (children[i].nodeValue.toLowerCase().indexOf('.swf') != -1)
	
                    || (children[i].nodeValue.toLowerCase().indexOf('.doc') != -1)))
            {
                var fileStr = (children[i].nodeValue.trim()).split('|');
                for(var x = 0; x < fileStr.length; x++)
                {
                    if(fileStr[x].toLowerCase().indexOf('.pdf') != -1
                       || fileStr[x].toLowerCase().indexOf('.xls') != -1
                       || fileStr[x].toLowerCase().indexOf('.zip') != -1
                       || fileStr[x].toLowerCase().indexOf('.mp3') != -1
                       || fileStr[x].toLowerCase().indexOf('.wma') != -1

		       || fileStr[x].toLowerCase().indexOf('.swf') != -1

                       || fileStr[x].toLowerCase().indexOf('.doc') != -1)
                    {
                        return fileStr[x];
                    }
                }
            }        
        }
        return null;
    },
    
    isLocked: function(td)
    {
        var children = td.childNodes;
        if(Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportTable.isLocked() children length - ' + children.length);
        for(var i = 0; i < children.length; i++)
        {
            if(Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportTable.isLocked() - loop =  ' + i);
            if((children[i].nodeType == 3)
                && ((children[i].nodeValue.toLowerCase().indexOf('.pdf') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.xls') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.zip') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.mp3') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.wma') != -1)

		    || (children[i].nodeValue.toLowerCase().indexOf('.swf') != -1)

                    || (children[i].nodeValue.toLowerCase().indexOf('.doc') != -1)))
            {
                var fileStr = (children[i].nodeValue.trim()).split('|');
                if(Secondary._LOG_ENABLED)LOG.printH1('TeacherSupportTable.isLocked() - array =  ' + fileStr);
                for(var x = 0; x < fileStr.length; x++)
                {
                    if(fileStr[x].toLowerCase() == 'l')
                    {
                        return true;
                    }
                }
            }        
        }
        return null;
    },
    
    getDisplayFileName: function(td)
    {
        var children = td.childNodes;
        for(var i = 0; i < children.length; i++)
        {
            if((children[i].nodeType == 3)
                && ((children[i].nodeValue.toLowerCase().indexOf('.pdf') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.xls') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.zip') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.mp3') != -1)
                    || (children[i].nodeValue.toLowerCase().indexOf('.wma') != -1)

		    || (children[i].nodeValue.toLowerCase().indexOf('.swf') != -1)

                    || (children[i].nodeValue.toLowerCase().indexOf('.doc') != -1)))
            {
                var fileStr = (children[i].nodeValue.trim()).split('|');
                if(typeof fileStr[1] != 'undefined' && fileStr[1].toLowerCase() != 'l')
                {
                    return fileStr[1];
                }
            }        
        }
        return 'View';
    },
    
    resetTD: function(td)
    {
        td.innerHTML = '';
        td.className = 'blank';
        td.appendChild(document.createTextNode('--'));
    },
    
/*----------------------------------------------------------------------------------------------------------

    init
    
*/   
    init: function (edDeskBody)
    { 
        this.tables = (edDeskBody.getElementsByTagName('table').length > 0) ? edDeskBody.getElementsByTagName('table') : null;
        this.DocID = (EDDESK.getFormInput('DocID')) ? EDDESK.getFormInput('DocID') : null;
        
        if(this.tables && this.DocID)
        {
            for(var i = 0; i < this.tables.length; i++)
            {
                this.table = this.tables[i];
                this.attachHead();
                this.reset();   
                this.parseFiles();
            }
        }        
        	//this.attachPopup();
    }
}

function tsAnchorClick(oEvent)
{

    // if popup already exists remove it first
	removePopup();
	
    attachPopup(this.href, this.title);
    
	var dims = getWindowDims();

   
    var popup = document.getElementById('popup');
    popup.style.height = document.getElementById('wrapper').offsetHeight+20;

    var popupText = document.getElementById('popupText');
    popupText.style.left = (document.body.offsetWidth - 660) / 2;
    popupText.style.top = ((dims['height'] / 2) - (popupText.offsetHeight / 2)) + dims['scrollTop'];
    var target = DH.stopEvent(oEvent);

    return;
}


function tsAnchorClickBAK(oEvent)
{
    var prompted = null;
    if(!(prompted = DH.getCookie('tsDownload')))
    {
        var confirmDownload = confirm('Terms and Conditions: \n\n The terms are....');
        if(confirmDownload)
        {
            DH.setCookie('tsDownload','true');
            return;
        } else {
            var target = DH.stopEvent(oEvent);
        }
    } else {
        return;
    }
}

function attachPopup(url,title) 
{
        var div =  document.createElement('div');
        div.className = "popup";
        div.id = "popup";
        var textdiv =  document.createElement('div');
        textdiv.className = "popupText";
        textdiv.id = "popupText";
        
        textdiv.innerHTML = "<img src='/secondary/images/category_straps/teacher_support.jpg'><br>";
        textdiv.innerHTML += "<p><b>Licence terms and conditions</b></p>";
        if (title=="locked") { 
	        textdiv.innerHTML += "<p>This is a password protected file. If you do not have a password click <a href='libraries/Password+protected+documents'>here</a>.</p>";
        }
        textdiv.innerHTML += "<p><input type='checkbox' id='TCs' onClick='if (this.checked==true) {document.getElementById(\"download\").disabled=false;} else { document.getElementById(\"download\").disabled=true;};'>&nbsp;Yes, I understand and accept the <a href='libraries/Licence+Agreement' target='_blank'>Licence agreement</a> for use of this material.</p>";        
        textdiv.innerHTML += "<p><input type='button' id='download' value='Download file' onclick='document.getElementById(\"popup\").style.display=\"none\";document.getElementById(\"popupText\").style.zIndex=-10;document.location=\""+ url + "\";' disabled>&nbsp;<input type='button' id='cancel' value='Cancel' onClick='removePopup()'></p>";        
        
        document.body.appendChild(div);
        document.body.appendChild(textdiv);
}
function removePopup() {
		var div = document.getElementById('popup');
		var textdiv = document.getElementById('popupText');
		
		if (div!=null && textdiv!=null) {
		document.body.removeChild(div);
		document.body.removeChild(textdiv);
		}
}

function getWindowDims() {
  return {
  'width' : window.innerWidth ?
            window.innerWidth : //firefox
            ((document.documentElement.clientWidth == 0) ? // are we in quirks mode?
              document.body.clientWidth :  // yes we are, so this is width
              document.documentElement.clientWidth ), // no, so this is width

  'height': window.innerHeight ?
            window.innerHeight : //firefox
            ((document.documentElement.clientHeight == 0) ? // are we in quirks mode?
              document.body.clientHeight:  // yes we are, so this is width
              document.documentElement.clientHeight ), // no, so this is width

  'scrollTop' : window.pageYOffset ?
                window.pageYOffset : // ff
                (document.body.scrollTop != 0 ? //ie
                  document.body.scrollTop :  // quirks mode ie
                  (document.documentElement.scrollTop) ), // strict mode ie

  'scrollLeft': window.pageXOffset ?
                window.pageXOffset :
                (document.body.scrollLeft != 0 ? //ie
                          document.body.scrollLeft : // quirks mode ie
                          document.documentElement.scrollLeft ) // strict mode ie

  } ;
}
      


/*
 * function_MoreInfo
 */



function MoreInfo()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 1 to be of \'string\' type');
    }
    
    //If  series has not been sent or is not set
    if(typeof arguments[1] ==  'undefined' || typeof arguments[1] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 2 to be of \'string\' type');
    }
    
    //If  isbn has not been sent or is not set
    if(typeof arguments[2] ==  'undefined' || typeof arguments[2] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 3 to be of \'string\' type');
    }
    
    this.subject = arguments[0];    
    this.area = arguments[1];
    this.isbn = arguments[2];
    
    //Send Ajax request and get response
    this.loaded = this.loadAjax();
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

MoreInfo.prototype._SEARCHSTR = '/secondary/onix/onixsearch.js?open&';
MoreInfo.prototype._SEARCH_LABEL =  'MoreInfo';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
MoreInfo.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    //tempArray.push('query=[Division]=Secondary+and+[EAN13]=' + this.isbn + '+and+![ed_TextType]=Table of contents+and+[Form]=Related');
    tempArray.push('query=[Division]=Secondary+and+[ISBN]=' + this.isbn + '+and+[ed_TextType]=Long description+and+[Form]=Related');
    tempArray.push('start=1');
    tempArray.push('count=1');
    tempArray.push('label=' + this._SEARCH_LABEL);    
    return this._SEARCHSTR + tempArray.join('&');
};

MoreInfo.prototype.getLinkHref = function()
{
    var tempArray = new Array();
    tempArray.push('div=Secondary');
    tempArray.push('cat=' + this.subject + '>' + this.area);
    tempArray.push('template=domSecondary');
    tempArray.push('onixtype=more_info');
    tempArray.push('ed=site/seced31.nsf');
    return '/secondary/onix/all/' + decodeURIComponent(this.moreInfoIndex[0].viewCol1) + '?open&' + decodeURIComponent(tempArray.join('&'));
};

MoreInfo.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var searchOnixResults = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(searchOnixResults);
        var results = eval('searchOnixResultsMoreInfo');
    } catch(oError) {
        throw new Error('MoreInfo.loadAjax() error on eval(searchOnixResults) Serries.load()');
    }
        
    //If search results exist
    if(typeof results != 'undefined' && results instanceof Array && results.length > 0)
    {                
        this.moreInfoIndex = new Array();
        for(var i = 1; i < results.length; i++)
        {
            if(typeof results[i] != 'undefined' && this.isResultValid(results[i]))
            {
                this.moreInfoIndex.push(results[i]);                  
            }
        }
        if(Secondary._LOG_ENABLED)LOG.printH1('MoreInfo.loadAjax() - returned ' + this.moreInfoIndex.length + ' results');
            
        //If there are no valid results
        if(this.moreInfoIndex.length == 0)
        {
            return false;
            //If log enabled display message
            if(Secondary._LOG_ENABLED)LOG.printH1('MoreInfo.loadAjax() did not return any valid results');
        } else {
            return true;
        } 
            
    } else {
            throw new Error("MoreInfo.load() 'results' is undefined");
    }
};

//Function which validates a 'viewResults' entry
MoreInfo.prototype.isResultValid =  function(result, i)
{
    //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
        
    //Variable used to detect invalid properties
    var valid = true;
        
    //Array to store invalid properties
    var tempArray = new Array();
        
    //check DocID
    if(typeof result.viewCol1 != 'string' || result.viewCol1.length < 1)
    {
        valid = false;
        tempArray.push('DocID');
    }
      
    //if there are invalid entries and log is enabled
    if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('MoreInfo.isResultValid()[' + i + '] - invalid result : ' + tempArray.join(', '));
        
    return valid;
};


MoreInfo.prototype.attach =  function(oParent)
{
    if(!this.loaded)return;  
    var a = document.createElement('a');
    a.setAttribute('href',this.getLinkHref());
    a.setAttribute('title','More');    
    if(DH.getURLParam('onixtype') && DH.getURLParam('onixtype') == 'more_info')
    {
        a.className = 'current';
    }
    var span = document.createElement('span');
    span.appendChild(document.createTextNode('More'));
    a.appendChild(span);
    var li = document.createElement('li');
    li.appendChild(a);
    oParent.appendChild(li);    
};



/*
 * function_Contents
 */



function Contents()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 1 to be of \'string\' type');
    }
    
    //If  series has not been sent or is not set
    if(typeof arguments[1] ==  'undefined' || typeof arguments[1] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 2 to be of \'string\' type');
    }
    
    //If  isbn has not been sent or is not set
    if(typeof arguments[2] ==  'undefined' || typeof arguments[2] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 3 to be of \'string\' type');
    }
    
    this.subject = arguments[0];    
    this.area = arguments[1];
    this.isbn = arguments[2];
    
    //Send Ajax request and get response
    this.loaded = this.loadAjax();
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

Contents.prototype._SEARCHSTR = '/secondary/onix/onixsearch.js?open&';
Contents.prototype._SEARCH_LABEL =  'Contents';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
Contents.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    tempArray.push('query=[Division]=Secondary+and+[ISBN]=' + this.isbn + '+and+[ed_TextType]=Table of contents+and+[Form]=Related');
    tempArray.push('start=1');
    tempArray.push('count=1');    
    tempArray.push('label=' + this._SEARCH_LABEL);
    return this._SEARCHSTR + tempArray.join('&');
};

Contents.prototype.getLinkHref = function()
{
    var tempArray = new Array();
    tempArray.push('div=Secondary');
    tempArray.push('cat=' + this.subject + '>' + this.area);
    tempArray.push('template=domSecondary');
    tempArray.push('onixtype=contents');
    tempArray.push('ed=site/seced31.nsf');
    return '/secondary/onix/all/' + decodeURIComponent(this.ContentsIndex[0].viewCol1) + '?open&' + decodeURIComponent(tempArray.join('&'));
};

Contents.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var searchOnixResults = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(searchOnixResults);
        var results = eval('searchOnixResultsContents');
    } catch(oError) {
        throw new Error('Contents.loadAjax() error on eval(searchOnixResults) Serries.load()');
    }
        
    //If search results exist
    if(typeof results != 'undefined' && results instanceof Array && results.length > 0)
    {                
        this.ContentsIndex = new Array();
        for(var i = 1; i < results.length; i++)
        {
            if(typeof results[i] != 'undefined' && this.isResultValid(results[i]))
            {
                this.ContentsIndex.push(results[i]);                  
            }
        }
        if(Secondary._LOG_ENABLED)LOG.printH1('Contents.loadAjax() - returned ' + this.ContentsIndex.length + ' results');
            
        //If there are no valid results
        if(this.ContentsIndex.length == 0)
        {
            return false;
            //If log enabled display message
            if(Secondary._LOG_ENABLED)LOG.printH1('Contents.loadAjax() did not return any valid results');
        } else {
            return true;
        } 
            
    } else {
            throw new Error("Contents.load() 'results' is undefined");
    }
};

//Function which validates a 'viewResults' entry
Contents.prototype.isResultValid =  function(result, i)
{
    //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
        
    //Variable used to detect invalid properties
    var valid = true;
        
    //Array to store invalid properties
    var tempArray = new Array();
        
    //check DocID
    if(typeof result.viewCol1 != 'string' || result.viewCol1.length < 1)
    {
        valid = false;
        tempArray.push('DocID');
    }
      
    //if there are invalid entries and log is enabled
    if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('Contents.isResultValid()[' + i + '] - invalid result : ' + tempArray.join(', '));
        
    return valid;
};


Contents.prototype.attach =  function(oParent)
{
    if(!this.loaded)return;  
    
    var a = document.createElement('a');
    a.setAttribute('href',this.getLinkHref());
    a.setAttribute('title','More info');
    if(DH.getURLParam('onixtype') && DH.getURLParam('onixtype') == 'contents')
    {
        a.className = 'current';
    }
    var span = document.createElement('span');
    span.appendChild(document.createTextNode('Contents'));
    a.appendChild(span);
    
    var li = document.createElement('li');
    li.appendChild(a);
    oParent.appendChild(li);    
};



/*
 * function_RelatedTitles
 */



function RelatedTitles()
{
    //If subject has not been sent or is not set
    if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 1 to be of \'string\' type');
    }
    
    //If  series has not been sent or is not set
    if(typeof arguments[1] ==  'undefined' || typeof arguments[1] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 2 to be of \'string\' type');
    }
    
    //If  area has not been sent or is not set
    if(typeof arguments[2] ==  'undefined' || typeof arguments[2] != 'string')
    {
        throw new Error('RelatedTitles.init() expects argument 3 to be of \'string\' type');
    }
    
    this.subject = arguments[0];    
    this.series = arguments[1]; 
    this.area = arguments[2];
    
    //Send Ajax request and get response
    this.loaded = this.loadAjax();
    if(this.loaded)
    {
        //this.removeDuplicateISBN();
        //this.filterByArea();
        this.relatedIndex.sort(RelatedTitlesSortIndexByTitle);
    }
}


//STATIC PROPERTIES------------------------------------------------------------------------------------------------------------------------------------------------------

RelatedTitles.prototype._SEARCHSTR = '/secondary/onix/onixsearch.js?open&';
RelatedTitles.prototype._SEARCH_LABEL =  'RelatedTitles';


//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 
RelatedTitles.prototype.getSearchURL = function()
{
    var tempArray = new Array();
    tempArray.push('query=[Division]=Secondary+and+[ed_SeriesList]=' + this.series + '+and+[Subject]=' + this.subject + '+and+[Area]=' + this.area + '+and+[Form]=Product');
//    tempArray.push('query=[Division]=Secondary+and+[ed_SeriesList]=' + this.series + '+and+[Form]=Product');
    tempArray.push('start=1');
    tempArray.push('count=20');
    tempArray.push('label=' + this._SEARCH_LABEL);
    return this._SEARCHSTR + tempArray.join('&');
};

RelatedTitles.prototype.getLinkHref = function(id,isbn,subject,area)
{
    var tempArray = new Array();
    tempArray.push('div=Secondary');
    //tempArray.push('cat=' + this.subject + '>' + this.series);
    tempArray.push('cat=' + subject + '>' + area);
    tempArray.push('template=domSecondary');
    tempArray.push('ed=site/seced31.nsf');
    //return '/secondary/onix/isbn/' + isbn + '?open&' + decodeURIComponent(tempArray.join('&'));
    return '/secondary/onix/all/' + id  + '?open&' + decodeURIComponent(tempArray.join('&'));
};

RelatedTitles.prototype.loadAjax = function()
{          
    var oXHR = DH.createXHR();
    oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
    oXHR.send(null);  
		
    //If request error
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
    var searchOnixResults = oXHR.responseText;
        
    //Check wheter request was successfull
    try{
        eval(searchOnixResults);
        var results = eval('searchOnixResultsRelatedTitles');
    } catch(oError) {
        throw new Error('RelatedTitles.loadAjax() error on eval(searchOnixResults) Serries.load()');
    }
        
    //If search results exist
    if(typeof results != 'undefined' && results instanceof Array && results.length > 0)
    {                
        this.relatedIndex = new Array();
        for(var i = 1; i < results.length; i++)
        {
            if(typeof results[i] != 'undefined' && this.isResultValid(results[i]))
            {
                this.relatedIndex.push(results[i]);                  
            }
        }
        if(Secondary._LOG_ENABLED)LOG.printH1('RelatedTitles.loadAjax() - returned ' + this.relatedIndex.length + ' results');
            
        //If there are no valid results
        if(this.relatedIndex.length == 0)
        {
            return false;
            //If log enabled display message
            if(Secondary._LOG_ENABLED)LOG.printH1('RelatedTitles.loadAjax() did not return any valid results');
        } else {
            return true;
        } 
            
    } else {
            throw new Error("RelatedTitles.load() 'results' is undefined");
    }
};

//Function which validates a 'viewResults' entry
RelatedTitles.prototype.isResultValid =  function(result, i)
{
    //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
        
    //Variable used to detect invalid properties
    var valid = true;
        
    //Array to store invalid properties
    var tempArray = new Array();
        
    //check isbn
	var oRe = /\s|\D/gi;
    if(typeof result.viewCol6 != 'string' || result.viewCol6.length != 13 || oRe.test(decodeURIComponent(result.viewCol6)))
    {
        valid = false;
        tempArray.push('isbn');
    }
        
    //check title
    if(typeof result.viewCol2 != 'string' || result.viewCol2.length == 0)
    {
        valid = false;
        tempArray.push('title');
    }
    
    //check subject
    if(typeof result.viewCol13 != 'string' || result.viewCol13.length == 0)
    {
        valid = false;
        tempArray.push('subject');
    }
    
    //check area
    if(typeof result.viewCol14 != 'string' || result.viewCol14.length == 0)
    {
        valid = false;
        tempArray.push('area');
    }
        
    //if there are invalid entries and log is enabled
    if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('RelatedTitles.isResultValid()[' + i + '] - invalid result : ' + tempArray.join(', '));
        
    return valid;
};


RelatedTitles.prototype.attach =  function(oParent)
{
    if(this.relatedIndex.length < 1)return;
    
    oParent.style.borderLeft = '1px solid #DDDEDF';
    oParent.paddingLeft = '20px';
    
    var div = document.createElement('div');
    div.className = 'relatedTitles';
    
    var h4 = document.createElement('h4');
    h4.appendChild(document.createTextNode('Related Titles'));
    div.appendChild(h4);
    
    var ul = document.createElement('ul');
    
    for(var i = 0; i < this.relatedIndex.length; i++)
    {
        var id = decodeURIComponent(this.relatedIndex[i].viewCol1);
        var isbn = decodeURIComponent(this.relatedIndex[i].viewCol6);
        var title = decodeURIComponent(this.relatedIndex[i].viewCol2);   
        var subject = decodeURIComponent(this.relatedIndex[i].viewCol13);
        var area = decodeURIComponent(this.relatedIndex[i].viewCol14);
        
        var a = document.createElement('a');
        a.setAttribute('href',this.getLinkHref(id,isbn,subject,area));
        a.setAttribute('title',title);
        a.appendChild(document.createTextNode(title));
        var li = document.createElement('li');
        li.appendChild(a);
        ul.appendChild(li);
    }
    div.appendChild(ul);
    oParent.appendChild(div);
};

RelatedTitles.prototype.removeDuplicateISBN =  function()
{
    var isbns = new Array();
    isbns.push(decodeURIComponent(this.relatedIndex[0].viewCol6));
    
    var tempArray = new Array();
    tempArray.push(this.relatedIndex[0]);
    
    for(var i = 1; i < this.relatedIndex.length; i++)
    {
        if(!isbns.hasString(decodeURIComponent(this.relatedIndex[i].viewCol6)))
        {
            tempArray.push(this.relatedIndex[i]);
            isbns.push(decodeURIComponent(this.relatedIndex[i].viewCol6));
        } else {
            if(Secondary._LOG_ENABLED)LOG.printH1('RelatedTitles.removeDuplicateISBN() duplicate isbn[' + decodeURIComponent(this.relatedIndex[i].viewCol6) + '] removed');
        }
    }
    this.relatedIndex = null;
    this.relatedIndex = tempArray;
};

RelatedTitles.prototype.filterByArea =  function()
{
    
    var tempArray = new Array();
    
    for(var i = 0; i < this.relatedIndex.length; i++)
    {   
        var sameArea = ((decodeURIComponent(this.relatedIndex[i].viewCol14)).toLowerCase() == this.area.toLowerCase()) ? true : null;
   
        var notSameBook = (EDDESK.getFormInput('DistinctiveTitle') 
                           && this.relatedIndex[i].viewCol2
                           && (EDDESK.getFormInput('DistinctiveTitle').toLowerCase() != (decodeURIComponent(this.relatedIndex[i].viewCol2)).toLowerCase()))
                           ? true : null;
                       
        if(sameArea && notSameBook)
        {
            tempArray.push(this.relatedIndex[i]);
        }
      
        
    }
    this.relatedIndex = null;
    this.relatedIndex = tempArray;
};

/*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/

function RelatedTitlesSortIndexByTitle(a,b)
{
    a = decodeURIComponent(a.viewCol2);
    b = decodeURIComponent(b.viewCol2);   
    
    if(b > a)
    {
        return -1;
    } else if(b < a) {
        return 1;
    } else {
        return 0;
    }
}


/*
 * function_PagesNav
 */



function PagesNav()
{
    if(arguments.length != 4)
    {
        throw new Error('Constructor of PagesNav expects 4 arguments');
    }
	
	var vars = new Array();
    
    this.linkURL = arguments[0];
	vars.push('linkURL: ' + this.linkURL);
    this.start = arguments[1];
	vars.push('start: ' + this.start);
    this.count = arguments[2];
	vars.push('count: ' + this.count);
    this.searchCount = parseInt(arguments[3]);
	vars.push('searchCount: ' + this.searchCount);
    this.pageCount = Math.ceil(this.searchCount / this.count);
	vars.push('pageCount: ' + this.pageCount);
    this.currentPage = this.getCurrentPageNum();
	vars.push('currentPage: ' + this.currentPage);
    this.navPages = this.getPageNums();
	vars.push('navPages[type]: ' + typeof this.navPages);
	
	if(Secondary._LOG_ENABLED)LOG.printULwithH1('PagesNav variables',vars);	
}

PagesNav.prototype.getCurrentPageNum = function()
{
    for(var i = 1; i <= this.searchCount; i = i + this.count)
    {
        if(!nCount)var nCount = 0;
        ++nCount;
        if(i == this.start)
        {
            if(Secondary._LOG_ENABLED)LOG.printH1('Search current page: ' + nCount);
            return nCount;
        }
    }
    throw new Error('PagesNav.getCurrentPageNum() - current page is undefined');
};

PagesNav.prototype.getPageNums = function()
{
    var smallNav = (this.pageCount <= 10) ? true : null;
    var bottomNav = (!smallNav && this.currentPage <= 10) ? true : null;
    var topNav = (!smallNav && this.currentPage > (this.pageCount - 9)) ? true : null;
    var middleNav = (!smallNav && !bottomNav && !topNav) ? true : null;
										  
    if(smallNav)
    {
        var navPages = this.getPageNumsSmallNav();
		if(Secondary._LOG_ENABLED)LOG.printH1('Search Page Nav: smallNav');
    } else if(bottomNav) {
        var navPages = this.getPageNumsBottomNav();
		if(Secondary._LOG_ENABLED)LOG.printH1('Search Page Nav: bottomNav');
    } else if(topNav){
        var navPages = this.getPageNumsTopNav();
		if(Secondary._LOG_ENABLED)LOG.printH1('Search Page Nav: topNav');
    } else {
        var navPages = this.getPageNumsMiddleNav();
		if(Secondary._LOG_ENABLED)LOG.printH1('Search Page Nav: middleNav');
    }
    return navPages;
};


PagesNav.prototype.getPageNumsSmallNav = function()
{
    var pages = new Array();
    for(var i = 0; i < this.pageCount; i++)
    {
        pages.push(i + 1);
    }
    return pages;
};

PagesNav.prototype.getPageNumsBottomNav = function()
{
    var pages = new Array();
    for(var i = 0; i < 10; i++)
    {
        pages.push(i + 1);
    }
    pages.push(-1);
    if((this.pageCount - 1) > 10)pages.push(this.pageCount - 1);
    pages.push(this.pageCount);
    return pages;
};

PagesNav.prototype.getPageNumsTopNav = function()
{
    var pages = new Array();
    pages.push(1);
    pages.push(2);
    pages.push(-1);
    
    for(var i = (this.pageCount - 9); i <= this.pageCount; i++)
    {
        pages.push(i);
    }
    return pages;
};

PagesNav.prototype.getPageNumsMiddleNav = function()
{
    var pages = new Array();
    pages.push(1);
    pages.push(2);
    pages.push(-1);
	
    var startPage = this.currentPage.toString().split('');
    startPage[startPage.length - 1] = '0';
    startPage = parseInt(startPage.join(''));
    
    for(var i = startPage; i < (startPage + 10); i++)
    {
        pages.push(i);
    }
    
    pages.push(-1);
    
    if((this.pageCount - 1) > (startPage + 9))pages.push(this.pageCount - 1);
    pages.push(this.pageCount);
    return pages;
};


PagesNav.prototype.attach = function(oHolder)
{
    if(this.pageCount < 2)return;
    
    var ul = document.createElement('ul');
    //ul.setAttribute('id','searchNav');
	ul.className = 'searchNav';
    
	//Attach previous button
    if(this.currentPage != 1)
    {
        var sHref = this.linkURL + '&start=' + (this.start - this.count) + '&count=' + this.count;
        var anchor = document.createElement('a');
        anchor.setAttribute('href',sHref);
        anchor.appendChild(document.createTextNode('<< previous'));
        var li = document.createElement('li');
        li.appendChild(anchor);
        ul.appendChild(li);
    } else {
        var span = document.createElement('span');
        span.appendChild(document.createTextNode('<< previous'));
        var li = document.createElement('li');
        li.appendChild(span);
        ul.appendChild(li);
    }   
     
	//Attach pages
    for(var i = 0; i < this.navPages.length; i++)
    {
    	if(this.navPages[i] == -1)
		{
			var element = document.createElement('span');
			element.className = 'dots';
		} else {
			var start = (this.navPages[i] * this.count) - (this.count - 1);
			var sHref = this.linkURL + '&start=' + (start) + '&count=' + this.count;
			var element = document.createElement('a');
			if(this.navPages[i] == this.currentPage)element.className = 'current';
			element.setAttribute('href',sHref);
			element.appendChild(document.createTextNode(this.navPages[i]));
		}
		var li = document.createElement('li');
		li.appendChild(element);
		ul.appendChild(li);
    }
	
	//Attach next button
	if(this.currentPage != this.pageCount)
	{
		var sHref = this.linkURL + '&start=' + (this.start + this.count) + '&count=' + this.count;
        var anchor = document.createElement('a');
        anchor.setAttribute('href',sHref);
        anchor.appendChild(document.createTextNode('next >>'));
        var li = document.createElement('li');
        li.appendChild(anchor);
        ul.appendChild(li);
	} else {
        var span = document.createElement('span');
        span.appendChild(document.createTextNode('next >>'));
        var li = document.createElement('li');
        li.appendChild(span);
        ul.appendChild(li);
    }  
	
	oHolder.appendChild(ul);
};





/*
 * function_Search
 */



Search = {
	
//PROPERTIES---------------------------------------------------------------------------
	
	//Used for onix search
	_SEARCHSTR: '/secondary/onix/onixsearch.js?open&query=',
	_COUNT_SEARCHSTR: '/secondary/onix/countsearch.js?open&query=',
	
	
//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
 	
	loadAjaxSearchCount: function()
    {           
        var oXHR = DH.createXHR();
        oXHR.open('GET',(this._COUNT_SEARCHSTR + this.query + '+and+[Form]=Product'),false);
        oXHR.send(null);  
		
		//If request error
		if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
		var searchElementsStr = oXHR.responseText;
        
        //Check wheter request was successfull
        try{
            eval(searchElementsStr);
        } catch(oError) {
            throw new Error('Search.loadAjaxSearchCount() error on eval(searchElementsStr) Serries.load()');
        }
		 
        //If search results exist
        if(typeof searchElements != 'undefined' && typeof searchElements == 'number')
        { 
           this.searchElements = parseInt(searchElements);
		   if(Secondary._LOG_ENABLED)LOG.printH1('Search.loadAjaxSearchCount() - returned ' + this.searchElements + ' as a count');
        } else {
            throw new Error("Search.loadAjaxSearchCount() 'searchElements' is undefined");
        }
    },
	
	getSearchStr: function()
	{
		
	},
	
	loadAjax: function()
    {  
		if(typeof this.searchElements == 'undefined')return false;
		
        var oXHR = DH.createXHR();
        oXHR.open('GET',this._SEARCHSTR + this.query + '+and+[Form]=Product&start=' + this.start + '&count=' + this.count,false);
        oXHR.send(null);  
		
		//If request error
		if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
		var viewResultsStr = oXHR.responseText;
        
        //Check wheter request was successfull
        try{
            eval(viewResultsStr);
        } catch(oError) {
            throw new Error('Search.loadAjax() error on eval(viewResultsStr) Serries.load()');
        }
        
        //If search results exist
        if(typeof searchOnixResults != 'undefined' && searchOnixResults instanceof Array && searchOnixResults.length > 0)
        {                
            this.searchIndex = new Array();
            for(var i = 1; i < searchOnixResults.length; i++)
            {
                if(typeof searchOnixResults[i] != 'undefined' && this.isResultValid(i))
                {
                    this.searchIndex.push(searchOnixResults[i]);                  
                }
            }
			
			
			if(this.searchIndex.length > 0)
			{
				this.loaded = true;	
			}
			
            if(Secondary._LOG_ENABLED)LOG.printH1('Search.loadAjax() - returned ' + this.searchIndex.length + ' results');
            
            //If there are no valid results
            if(this.searchIndex.length == 0)
            {
                return false;
                //If log enabled display message
                if(Secondary._LOG_ENABLED)LOG.printH1('Search.loadAjax() did not return any valid results');
            } else {
                return true;
            } 
        } else {
            throw new Error("Search.loadAjax() 'searchOnixResults' is undefined");
        }
    },
	
	//Function which validates a 'viewResults' entry
    isResultValid: function(x)
    {
        //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
        
        //Variable used to detect invalid properties
        var valid = true;
        
        //Array to store invalid properties
        var tempArray = new Array();
        
        //check isbn
		var oRe = /\s|\D/gi;
        if(typeof searchOnixResults[x].viewCol6 != 'string' || searchOnixResults[x].viewCol6.length != 13 || oRe.test(decodeURIComponent(searchOnixResults[x].viewCol6)))
        {
            valid = false;
            tempArray.push('isbn' + decodeURIComponent(searchOnixResults[x].viewCol6.toString()));
        }
        
        //check title
        if(typeof searchOnixResults[x].viewCol2 != 'string' || searchOnixResults[x].viewCol2.length == 0)
        {
            valid = false;
            tempArray.push('title');
        }
        
        //check isbn
        if(typeof searchOnixResults[x].viewCol15 != 'string' || searchOnixResults[x].viewCol15.length == 0)
        {
            valid = false;
            tempArray.push('series');
        }
        
        //if there are invalid entries and log is enabled
        if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('searchOnixResults[' + x + '] invalid ' + tempArray.join(', '));
        
        return valid;
    },
	
	attachResults: function()
	{
		if(typeof attachResultsCount == 'undefined')attachResultsCount = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('index2');
		if(!oHolder)
		{
			//If exceeded the number of determined iterations
			if(attachResultsCount > 10)
			{
				throw new Error('Search.attachResults() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachResultsCount++;
			setTimeout('Search.attachResults()',100);
			return;
		}
		
		this.attachResultsHeader(oHolder);	
		
		this.attachPageNav(oHolder);
		
		if(!this.loaded)return;
		
		//var arrayLength = ((this.count + this.start) < this.searchElements) ? (this.count + this.start) : this.searchElements;
		
		for(var i = 0; i < this.searchIndex.length; i = i + 3)
		{
			var start = i;
			var count = i + 3;
			if(this.searchIndex.length < count) count = this.searchIndex.length;
			
			//Create ul to hold row for series items
			var ul = document.createElement('ul');
			var ulClass = new Array();
			ulClass.push('second');
			ul.className = ulClass.join(' ');
				
			//Loop through items and attach series items
			for(var x = start; x < count; x++)
			{
				//Crate list item
				var li = document.createElement('li');
					
				var item = new OnixItem('series',this.searchIndex[x]);
					
				item.attachSeriesIndex1Item(li);
					
				ul.appendChild(li);
			}	
				
			oHolder.appendChild(ul);
		}
		
		this.attachPageNav(oHolder);
	},
	
	attachResultsHeader: function(parent)
	{
		var div = DH.createDiv('','searchResultsHeader');
		
		var oh2 = document.createElement('h2');
		oh2.appendChild(document.createTextNode('Search results'));
		div.appendChild(oh2);	
		
		var start = this.start;
		var count = this.start + (this.searchIndex.length - 1);
		if(this.loaded)
		{
			var str = 'Viewing results ' + start + ' to ' + count + ' of ' + this.searchElements + ' from the catalogue:';
		} else {
			var str = 'There are no results.';	
		}
		var p = DH.createP(str);
		div.appendChild(p);
		
		parent.appendChild(div);
	},
	
	attachPageNav: function(oHolder)
	{
	    if(!this.pageNav)
	    {
	        this.pageNav = new PagesNav('libraries/Search?open&query=' + this.query,this.start,this.count,this.searchElements);
	    }
	    this.pageNav.attach(oHolder);   
	},
	
	
	init: function()
	{
		//Get search parameters
		this.start = (DH.getURLParam('start')) ? parseInt(decodeURIComponent(DH.getURLParam('start'))) : 1;
		this.count = (DH.getURLParam('count')) ? parseInt(decodeURIComponent(DH.getURLParam('count'))) : 20;
		this.query = (DH.getURLParam('query')) ? decodeURIComponent(DH.getURLParam('query')) : '';
		
		this.loadAjaxSearchCount();		
		this.loadAjax();
	}
}



/*
 * function_Navigation
 */



Navigation = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/ 
    //Variable which identifies nav type to load
    // Onix - 
    navType: null,
    
    //Variable used to count the numbers of attempts to retrieve reference to subnav holder
    loadCount: 0,
    
    //Variable to store current item
    item: null,
    
    //Variable to store nav items
    items: new Array(),
    
    //Variable to store current subitem
    subitem: null,
    
    //Variable to store nav items
    subitems: new Array(),
    


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/ 

    isCompatible: function()
    {
        //If Dom Helper is not defined
        if(!DH
            || !DH.createAnchor){        
            return false;
        }
        
        if(!LOG
            || !LOG.printULwithH1){
            return false;
        }
        return true;    
    },

/*----------------------------------------------------------------------------------------------------------

    load
    
*/
    //Load main items
    loadMainNavItems: function()
    {
		this.items.push(new NavigationItem('/secondary/site/divisions?open&cat=The Arts%3EArt&template=domSecondary','Arts','Art'));
		this.items.push(new NavigationItem('/secondary/site/divisions?open&cat=The Arts%3EDrama&template=domSecondary','Drama','Drama'));
        this.items.push(new NavigationItem('homepages/Commerce+and+Business?open&template=domSecondary','Business & Commerce','Commerce and Business'));
        this.items.push(new NavigationItem('homepages/English?open&template=domSecondary','English','English'));
        this.items.push(new NavigationItem('homepages/ELT?open&template=domSecondary','ELT','ELT'));
        this.items.push(new NavigationItem('/secondary/site/divisions/?open&label=onix&view=subjects&type=cat&div=Secondary&cat=Food%20Technology&start=1&count=500','Food Technology','Food Technology'));
        this.items.push(new NavigationItem('homepages/Geography?open&template=domSecondary','Geography','Geography'));
        this.items.push(new NavigationItem('homepages/Health+and+PE?open&template=domSecondary','Health and PE','Health and PE'));
        this.items.push(new NavigationItem('homepages/History?open&template=domSecondary','History','History'));
        this.items.push(new NavigationItem('homepages/LOTE?open&template=domSecondary','LOTE','LOTE'));
        this.items.push(new NavigationItem('homepages/Mathematics?open&template=domSecondary','Mathematics','Mathematics'));
        this.items.push(new NavigationItem('homepages/Science?open&template=domSecondary','Science','Science'));
        this.items.push(new NavigationItem('/secondary/site/divisions/?open&label=onix&view=areas&type=cat&div=Secondary&cat=Study+Guides>General&start=1&count=500','Study Guides','Study Guides'));
        this.items.push(new NavigationItem('/secondary/site/divisions/?open&label=onix&view=areas&type=cat&div=Secondary&cat=VCE>General&start=1&count=500','VCE','VCE'));
		this.items.push(new NavigationItem('homepages/Macmillan+Library?open&template=domSecondary','Macmillan Library','Macmillan Library'));
    },
    
    //Load sub nav items
    loadSubNavItems: function()
    {
        switch(this.subject)
        {
            case 'commerce and business':				
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>Accounting&template=domSecondary&start=1&count=20','Accounting','Accounting'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>business+studies?open&template=domSecondary','Business Studies','Business Studies'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>commerce?open&template=domSecondary','Commerce','Commerce'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>economics?open&template=domSecondary','Economics','Economics'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>industry+work+studies?open&template=domSecondary','Industry / Work Studies','Industry Work Studies'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>legal+studies?open&template=domSecondary','Legal Studies','Legal Studies'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Commerce+and+Business>study+guides?open&template=domSecondary','Study Guides','Study Guides'));
				break;
			case 'english':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Australian%20Curriculum&template=domSecondary','Australian Curriculum','Australian Curriculum'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>NSW&template=domSecondary','NSW','NSW'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Queensland&template=domSecondary','Queensland','Queensland'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Victoria&template=domSecondary','Victoria','Victoria'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>National&template=domSecondary','National','National'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Dictionaries&template=domSecondary','Dictionary','Dictionaries'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Drama&template=domSecondary','Drama','Drama'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Language and Grammar&template=domSecondary','Language / Grammar','Language and Grammar'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Poetry&template=domSecondary','Poetry','Poetry'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Shakespeare&template=domSecondary','Shakespeare','Shakespeare'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Short Stories&template=domSecondary','Short Stories','Short Stories'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=English>Study Guides&template=domSecondary','Study Guides','Study Guides'));
				break;
			case 'elt':
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=ELT%3EGeneral&template=domSecondary','Macmillan ELT','General'));
			    break;
			case 'geography':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>Atlas&template=domSecondary','Atlases','Atlas'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>NSW&template=domSecondary','NSW','NSW'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>Queensland&template=domSecondary','Queensland','Queensland'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>Victoria&template=domSecondary','Victoria','Victoria'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>National&template=domSecondary','National','National'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Geography>Study Guides&template=domSecondary','Study Guides','Study Guides'));
				break;
			case 'health and pe':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Health and PE>Queensland&template=domSecondary','Queensland','Queensland'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Health and PE>NSW&template=domSecondary','NSW','NSW'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Health and PE>Victoria&template=domSecondary','Victoria','Victoria'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Health and PE>National&template=domSecondary','National','National'));
				break;
			case 'history':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=History>Australian%20Curriculum&template=domSecondary','Australian Curriculum','Australian Curriculum'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=History>NSW&template=domSecondary','NSW','NSW'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=History>Victoria&template=domSecondary','VIC','Victoria'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=History>National&template=domSecondary','National','National'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=History>Study Guides&template=domSecondary','Study Guides','Study Guides'));
				break;
			case 'mathematics':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>Australian%20Curriculum&template=domSecondary','Australian Curriculum','Australian Curriculum'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>CAS&template=domSecondary','CAS','CAS'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>NSW&template=domSecondary','NSW','NSW'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>Queensland&template=domSecondary','Queensland','Queensland'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>Victoria&template=domSecondary','Victoria','Victoria'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>National&template=domSecondary','National','National'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>Study Guides&template=domSecondary','Study Guides','Study Guides'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Mathematics>Homework&template=domSecondary','Homework','Homework'));	
				break;
			case 'lote':
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=LOTE>Japanese&template=domSecondary','Japanese','Japanese'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=LOTE>Indonesian&template=domSecondary','Indonesian','Indonesian'));
				break;
			case 'science':
				//this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Senior General Science&template=domSecondary','Senior General Science'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Australian%20Curriculum&template=domSecondary','Australian Curriculum','Australian Curriculum'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Queensland&template=domSecondary','Queensland','Queensland'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>NSW&template=domSecondary','NSW','NSW'));
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Victoria&template=domSecondary','Victoria','Victoria'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Biology&template=domSecondary','Biology','Biology'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Psychology&template=domSecondary','Psychology','Psychology'));	
				this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Science>Study Guides&template=domSecondary','Study Guides','Study Guides'));	
				break;
			case 'macmillan library':
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>Humanities&template=domSecondary','Humanities','Humanities'));
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>Science&template=domSecondary','Science','Science'));
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>Health&template=domSecondary','Health','Health'));
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>General Hardback Library&template=domSecondary','General Hardback Library','General Hardback Library'));
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>Fiction&template=domSecondary','Fiction','Fiction'));
			    this.subitems.push(new NavigationItem('/secondary/site/divisions?open&cat=Macmillan Library>Reference&template=domSecondary','Reference','Reference'));
			    break;	
            default:
        }
    },

/*----------------------------------------------------------------------------------------------------------

    attach
    
*/

    attach: function()
    {
    
        try{//attempt to get reference to subnavigation module
            var oHolder = document.getElementById('subNavModule');
        } catch(oError){//if navigation module has not loaded
                            if(this.loadCount < 10)//if there have been less than 10 attempts
                            {
                                this.loadCount++;
                                setTimeout('Navigation.attach()',100);
                                return;
                            } else {//if attempts have been exceeded   
                                        throw new Error('Navigation.attach() - element \'subNavModule\' not defined');
                                   }
                       }
       
        //create UL element to hold list of links              
        var oUl = document.createElement('ul');
        oUl.setAttribute('id','subNav');
        
        //Loop through nav items and attach them to ul Holder
        for(var i = 0; i < this.items.length; i++)
        {
            var oLi = document.createElement('li');
            
            //Array to store class for list item
            var classArray = new Array();
            classArray.push('main');
            if(i == this.items.length - 1)classArray.push('last');
            oLi.className = classArray.join(' ');
            
            //create anchor tag and attach it to list item
            var oAnchor = this.items[i].attach();
            //if current attach class name
            if(this.isMainItemSubCatCurrent(this.items[i].subcat))oAnchor.className = 'current';
            
            oLi.appendChild(oAnchor);
            
            //If it is the current link attach subitems
            //if(this.subject && this.subject == this.items[i].title.toLowerCase())
            if(this.isMainItemSubCatCurrent(this.items[i].subcat))
            {
                this.attachSubitems(oLi);
            }
            
            //Check if there are categories and add them
            oUl.appendChild(oLi);
        }  
        
        oHolder.appendChild(oUl); 
    }, 
    
    isMainItemSubCatCurrent: function(subcat)
    {
        switch(this.subject)
        {
            case 'the arts':
            case 'reference':
                if(this.category)
                {
                    if(this.category == subcat.toLowerCase())
                    {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
                break;
            case null:
                break;
            default:
                if(this.subject == subcat.toLowerCase())
                {
                    return true;
                } else {
                    return false;
                }
        }
    },
    
    attachSubitems: function(obj)
    {
		if(this.subitems.length == 0) return;
	
        var ul = document.createElement('ul');
        
        for(var i = 0 ; i < this.subitems.length; i++)
        {
            
           
            //create li tag
            var li = document.createElement('li');
            
            //Create anchor tag and attach it to list item
            var oAnchor = this.subitems[i].attach();
            //If it is the current link attach class name
            if(this.category && this.category == this.subitems[i].subcat.toLowerCase())
            {
                oAnchor.className = 'current';
            }
                
            li.appendChild(oAnchor);
            
            //attach li to ul
            ul.appendChild(li);
        }
        obj.appendChild(ul);        
    },  
    
    printVariables: function()
    {
        var vars = new Array();
        
        //Add variables to array
        if(this.navType)vars.push('navType: ' + this.navType);
        if(this.subject)vars.push('subject: ' + this.subject);
        if(this.category)vars.push('category: ' + this.category);
        
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('Secondary Navigation Variables',vars);
    },
    

/*----------------------------------------------------------------------------------------------------------

    init
    
*/   
    init: function ()
    {  
        //Check whether Navigation is compatible
        if(!this.isCompatible) throw new Error('Navigation is not compatible');
        
        //If there are no arguments
        if(arguments.length == 0)throw new Error('Navigation.init() expects at least on argument');
        
        //Set navigation type
        this.navType = arguments[0];
        
        
        //If item exists make sure it's valid
        if(typeof arguments[1] != 'undefined' && typeof arguments[1] != 'string')
        {
            throw new Error('Navigation.init() expects argument \'item\' to be of \'string\' type');
        }
        
        //If subitem exists make sure it's valid
        if(typeof arguments[2] != 'undefined' && typeof arguments[2] != 'string')
        {
            throw new Error('Navigation.init() expects argument \'subitem\' to be of \'string\' type');
        }
        
       
        
        switch(this.navType)
        {
            case 'main'://main pages
            case 'onix'://book index page
             
                //Get subject - to be compared to item later
                this.subject = (typeof arguments[1] != 'undefined') ? arguments[1].replace(/\+/gi,' ').toLowerCase() : null;
                //Get category - to be compared to subitem later
                this.category = (typeof arguments[2] != 'undefined') ? arguments[2].replace(/\+/gi,' ').toLowerCase() : null;
                
                //Load main nav items into 'items' array
                this.loadMainNavItems();
                
                //load 'subitems'                
                if(this.subject)this.loadSubNavItems();                     
                       
                break;                
            default:
              
        }
        
        this.printVariables();
        
    }


}

function NavigationItem(href,title,subcat)
{
    this.title = title;
    this.href = href;
    this.subcat = subcat;
    
    if(typeof NavigationItem._initialized == 'undefined')
    {
        NavigationItem.prototype.attach = function()
        {
            return DH.createAnchor(this.title,this.href,'','',this.title);
        };
    }
    NavigationItem._initialized = true;
}




/*
 * function_PriceAvailability
 */



function PriceAvailability(isbn,quantity)
{


	if(typeof isbn != 'string' || isbn.length != 13)
	{
		//throw new Error('Constructor of Price and Availability expects a valid isbn argument: [' + isbn + ']')
	}
	
    this.isbn = isbn;
    //this.isbn = "9780732958749";
    this.quantity = 1;
    if(quantity)this.quantity = quantity;
    
    // GET request variables
    this.searchVars = new Array();
    this.searchVars['ClientID'] = 'PAL';
    //this.searchVars['ClientPassword'] = 'xxxx';
    this.searchVars['ProductIDType'] = '15';
    if(isbn)this.searchVars['ProductIDValue'] = isbn;    
    this.searchVars['SupplyQuantity'] = this.quantity;
    this.searchVars['CurrencyCode'] = 'AUD';
    
	this.load();    
}


PriceAvailability.prototype.load = function()
{
	this.loadAjax();
	this.getPrice();
	this.getAvailability();
	this.getShipDate();
};

        
PriceAvailability.prototype.loadAjax = function()
{
	//var sUrl = 'http://secondary3.itechne.com/site/OnixPA02.nsf/PAService?readform&' + this.getSearchVars();
	//var sUrl = 'http://secondary3.itechne.com/site/OnixPA02_test.nsf/PAService?readform&' + this.getSearchVars();
	//document.write(sUrl);

	if(window.location.toString().indexOf('macmillan.com.au') != -1) // macmillan server live PA db
	{
		// var sUrl = '/site/OnixPA02.nsf/PAService?readform&' + this.getSearchVars();
		var sUrl = '/PriceAvailabilityService?readform&' + this.getSearchVars();
	} else { 
		var sUrl = 'http://macmillan.test.itechne.com/macmillan/OnixPA02_test.nsf/PAService?readform&' + this.getSearchVars();    
	}
	
	
	    	this.xml = null;

    var oXHR = DH.createXHR();
    oXHR.open('GET',sUrl,false);
    oXHR.send(null); 
    if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;

	try 
        {
		var responseType = oXHR.responseXML.getElementsByTagName('ResponseType')[0].hasChildren;
	}
	catch (err) {}

	if(!responseType)
	{
		this.xml = oXHR.responseXML;
	} else {
	  	this.xml = null;
	}
 
};
        
PriceAvailability.prototype.getSearchVars = function()
{
	var tempArray = new Array();
	for(i in this.searchVars)
    {
		if(typeof this.searchVars[i] != 'undefined' && typeof this.searchVars[i] != 'function')
		{
    		tempArray.push(i + '=' + this.searchVars[i]);
		}
	}
    return (tempArray.join('&'));
};
        
PriceAvailability.prototype.parseXML = function(text)
{
	// code for IE
	if (window.ActiveXObject)
	{
		var doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(text);
    } else { // code for Mozilla, Firefox, Opera, etc.
    	var parser=new DOMParser();
    	var doc=parser.parseFromString(text,"text/xml");
    }
    return doc;
};
        
PriceAvailability.prototype.getPrice = function()
{
	if(!this.xml)return;

		// New xml walk to work in IE6
                var getLevel1 = XMLWalk(this.xml.childNodes, "PriceAvailabilityResponse");
                var getLevel2 = XMLWalk(getLevel1, "ProductPriceAvailability");
                var getLevel3 = XMLWalk(getLevel2, "SupplierPriceAvailability");
                var getLevel4 = XMLWalk(getLevel3, "RetailPrice");
                var getLevel5 = XMLWalk(getLevel4, "PriceAmount");

		var oPrice = getLevel5[0].nodeValue;

	// var oPrice = this.xml.getElementsByTagName('SupplierPriceAvailability')[0].getElementsByTagName('PriceAmount')[0].firstChild.nodeValue;
            
    //if book not found
    if(oPrice == 'Entry not found in index')return;
            
    if(oPrice.indexOf('$') != -1)
    {
    	this.price = oPrice;
    } else {
    	this.price = '$' + oPrice;
    }
};
        
PriceAvailability.prototype.getAvailability = function()
{
	if(!this.xml)return;

                // XMLWalk for Instock
                var getLevel1 = XMLWalk(this.xml.childNodes, "PriceAvailabilityResponse");
                var getLevel2 = XMLWalk(getLevel1, "ProductPriceAvailability");
                var getLevel3 = XMLWalk(getLevel2, "SupplierPriceAvailability");
                var getLevel4 = XMLWalk(getLevel3, "InStock");
                if (!getLevel4[0]) return;
                var oAvailability = getLevel4[0].nodeValue;
		// var oAvailability = this.xml.getElementsByTagName('SupplierPriceAvailability')[0].getElementsByTagName('InStock')[0].firstChild;

    if(!oAvailability)return;
    		//oAvailability = oAvailability.nodeValue;
    if(oAvailability.toLowerCase().indexOf('true') != -1)
    {
    	this.available = true;
    }
};


        
PriceAvailability.prototype.getShipDate = function()
{
	if(!this.xml || this.available)return;

                var getLevel1 = XMLWalk(this.xml.childNodes, "PriceAvailabilityResponse");
                var getLevel2 = XMLWalk(getLevel1, "ProductPriceAvailability");
                var getLevel3 = XMLWalk(getLevel2, "SupplierPriceAvailability");
                var getLevel4 = XMLWalk(getLevel3, "ExpectedShipDate");
                //var shipDate = getLevel4[0].nodeValue;
		if (getLevel4[0] == null) return;
		var shipDate = getLevel4[0].nodeValue;
          
	//var shipDate = this.xml.getElementsByTagName('SupplierPriceAvailability')[0].getElementsByTagName('ExpectedShipDate')[0].firstChild;
	//if(!shipDate || shipDate.nodeValue.length != 8)return;         

		if (!shipDate)return;
		if (shipDate.length != 8)return;

    //var tempDate = shipDate.nodeValue;
            
            var year = parseInt(shipDate.substring(0,4));
            // strip leading zeros
            if  (shipDate.substring(4,5)=="0") {
            var month = parseInt(shipDate.substring(5,6));
            }
            else {
            var month = parseInt(shipDate.substring(4,6));    
            }  
            if  (shipDate.substring(6,7)=="0") {
            var day = parseInt(shipDate.substring(7,8));
            }
            else {
            var day = parseInt(shipDate.substring(6));
            }   

    
    var todayDate = new Date();
    var tmpShipDate = new Date();
    tmpShipDate.setDate(day);
    tmpShipDate.setMonth(month-1);
    tmpShipDate.setYear(year);
    
    if (tmpShipDate < todayDate) {
	    this.shipDate = "";
    }
    else {
        this.shipDate = day + '/' + month + '/' + year; 
    }

};




function XMLWalk(nodesToWalk, FindByName)
{
    for (var i=0; i < nodesToWalk.length; i++) { if (nodesToWalk[i].nodeType == 1 && nodesToWalk[i].nodeName == FindByName) { return nodesToWalk[i].childNodes; } }
}



/*
 * function_OnixItem
 */

// 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));

/*	
	//Get summary (to check for an e-book).  May need to do this if the digital packages which include an e-book are to be included
	this.summary = (typeof obj.viewCol10 == 'string' && obj.viewCol10.length != 0) ? decodeURIComponent(obj.viewCol10) : null;
	vars.push('summary': + this.summary);
*/

	/*check here for e-books and set the flag */
	var isEbook = checkIfEbook(this); 
	this.isEbook = isEbook;
	
	//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));

	/*check here for e-books and set the flag */
	var isEbook = checkIfEbook(this); 
	this.isEbook = isEbook;
	
	//dispConsole("parseOnixProductItem isEbook = " + isEbook);
	//dispConsole("parseOnixProductItem this.isEbook = " + this.isEbook);
	
	//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());
	    
	    //build an href for the image that uses oAnchor's href
	    try{
	    	var thisHref = this.getItemLink();
	    	oAnchor.setAttribute('href', thisHref);
	    }catch (e){
	    	//dispConsole(e);
	    }
	    
	    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 (changed to use the variable we have already obtained instead of calling getItemLink() twice
	//var oAnchor = DH.createAnchor(this.title,this.getItemLink(),'','',this.title);
	var oAnchor = DH.createAnchor(this.title,thisHref,'','',this.title);
	var p = DH.createP(oAnchor,'','');
	obj.appendChild(p);
	
	//Attach price and isbn
	var p = DH.createP('AU' + 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
	    
if (!this.isEbook){
	    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);  
        }
    }
};

function dispConsole(dstring){
	try{
		if(window.globalStorage && window.postMessage){    
			console.debug(dstring);
		}
	} catch (e){
		//do nothing
	}
}

function checkIfEbook(tvar){
	//Get isEbook
	    try{
		
	    	var onixProd = document.forms[0].PageType.value;
		var isEbook;		
	    	var dTitle = "";
	    	if (typeof(onixProd) != "undefined"){

			if (onixProd == "onixProduct"){
				dTitle = document.forms[0].DistinctiveTitle.value;
			}
			if (onixProd == "library"){
			    	dTitle = tvar.title;
			}
		}else{
			dTitle = tvar.title;
	   	}
	   	
		//dispConsole("dTtile: " + dTitle);
	   	
	   	if (dTitle.match("ebook") != null || dTitle.match("e-book") != null ){
			isEbook = true;
		} else {
			isEbook = false;
		}
	    }catch(e){
	    	isEbook = false
	    }
	    return isEbook;
}

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('AU' + this.getPriceStr()));
	div.appendChild(p);
	
	//If item not published yet or not in stock display availability
	if(!this.available)
	{
		if(this.shipDate)
		{
			//show the ship date for the coming date
			var availability = 'Coming ' + this.shipDate.toDDMMYYYYString();
		} else if(this.publicationDate && !this.published()){
			//has a publicationDate and is NOT published.  Write out the publication Date
			var availability = 'Coming ' + ((this.publicationDate) ? this.publicationDate.toDDMMYYYYString() : '- no date available');
		} else {
			//does NOT have a publication date
		    var availability = 'Coming - no date available';
		}
	}
	
	if(availability)
	{
		//This actually appends the paragraph about availability to the div
		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))
	{
	//dispConsole("this.isEbook in attachOnixProductForm = " + this.isEbook);
	if (!this.isEbook){  //the inline add.
        //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 {
		try{
			var textSpan = document.createElement("span");
			textSpan.style.fontWeight = "bold";
			textSpan.style.color = "616D7E";
			var textLabel = document.createTextNode("Use the link below to order this product.");
		
			textSpan.appendChild(textLabel);
			div.appendChild(textSpan);
		} catch (e) {}
	}
    } 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('AU' + 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('AU$' + 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('AU$' + 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('AU$' + 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('AU$' + 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'));
}



/*
 * function_Series
 */




Series = {

//PROPERTIES---------------------------------------------------------------------------
	
	//Used for onix search
	_SEARCHSTR: '/secondary/onix/viewfilter.js?readform&',
	/*
	//Variable used to switch the LOG on and off
	_LOG_ENABLED: true,
	*/
	
//METHODS-----------------------------------------------------------------------------------------------------------------------------------------------------------------	
    
//function used to print Series variable to LOG
	printVariables: function()
    {
        //print series list
        var vars = new Array();
    	
		if(!this.series)return;
		
        for(var i = 0; i < this.series.length; i++)
        {
            var tempArray = new Array();
            tempArray.push(this.series[i].title);
            if(this.series[i].description)tempArray.push(this.series[i].description.substring(0,5) + '...');
            if(this.series[i].audience)tempArray.push(this.series[i].audience.substring(0,5) + '...');
            vars.push(tempArray.join('||'));
        }   
          
        if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Secondary Series(' + vars.length + ')',vars);
    },
    
//Function which builds the URL for Onix search
    getSearchURL: function()
    {
        var tempArray = new Array();
        tempArray.push('view=' + this.searchParams.view);
        tempArray.push('type=' + this.searchParams.type);
        tempArray.push('div=' + this.searchParams.div);
        tempArray.push('cat=' + this.searchParams.cat);
        tempArray.push('start=' + this.searchParams.start);
        tempArray.push('count=' + this.searchParams.count);
        //alert(this._SEARCHSTR + tempArray.join('&'));
        return this._SEARCHSTR + tempArray.join('&');
    },


//Function used to make the ajax call and load results into 'this.seriesIndex'
    loadAjax: function()
    {           
        var oXHR = DH.createXHR();
        oXHR.open('GET',decodeURIComponent(this.getSearchURL()),false);
        oXHR.send(null);  
		
		//If request error
		if(!(oXHR.readyState == 4 && (oXHR.status == 200 || oXHR.status == 304))) return false;
        
		var viewResultsStr = oXHR.responseText;
        
                //alert(viewResultsStr);
        
        //Check wheter request was successfull
        try{
            eval(viewResultsStr);
        } catch(oError) {
            //throw new Error('Series.loadAjax() error on eval(viewResultsStr) Serries.load()');
            return false;
        }
        
        //alert(viewResults.length);
        
        //If search results exist
        if(typeof viewResults != 'undefined' && viewResults instanceof Array && viewResults.length > 0)
        {                
            this.seriesIndex = new Array();
            for(var i = 1; i < viewResults.length; i++)
            {
                if(typeof viewResults[i] != 'undefined' && this.isResultValid(i))
                {
                    this.seriesIndex.push(viewResults[i]);                  
                }
            }
            if(Secondary._LOG_ENABLED)LOG.printH1('Series.loadAjax() - returned ' + this.seriesIndex.length + ' results');
            
            //If there are no valid results
            if(this.seriesIndex.length == 0)
            {
                return false;
                //If log enabled display message
                if(Secondary._LOG_ENABLED)LOG.printH1('Series.loadAjax() did not return any valid results');
            } else {
                return true;
            } 
            
        } else {
            throw new Error("Series.load() 'viewResults' is undefined");
        }
    },
    
//Function which validates a 'viewResults' entry
    isResultValid: function(x)
    {
        //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
        
        //Variable used to detect invalid properties
        var valid = true;
        
        //Array to store invalid properties
        var tempArray = new Array();
        
        //check isbn
		var oRe = /\s|\D/gi;
        if(typeof viewResults[x].viewCol6 != 'string' || viewResults[x].viewCol6.length != 13 || oRe.test(decodeURIComponent(viewResults[x].viewCol6)))
        {
            valid = false;
            tempArray.push('isbn');
        }
        
        //check title
        if(typeof viewResults[x].viewCol2 != 'string' || viewResults[x].viewCol2.length == 0)
        {
            valid = false;
            tempArray.push('title');
        }
        
        //check isbn
        if(typeof viewResults[x].viewCol15 != 'string' || viewResults[x].viewCol15.length == 0)
        {
            valid = false;
            tempArray.push('series');
        }
        
        //check subject
        if(typeof viewResults[x].viewCol13 != 'string' || viewResults[x].viewCol13.length == 0)
        {
            valid = false;
            tempArray.push('subject');
        }
        
        //check area
        if(typeof viewResults[x].viewCol14 != 'string' || viewResults[x].viewCol14.length == 0)
        {
            valid = false;
            tempArray.push('area');
        }
        
        //if there are invalid entries and log is enabled
        if(valid == false && Secondary._LOG_ENABLED)LOG.printH1('viewResults[' + x + '] invalid ' + tempArray.join(', '));
        
        return valid;
    },
	
//Function which extracts and store the series into an array
// INPUT: -
// OUTPUT : Array
// 			Series {}
// 			.title
//			.authors
//			.description
//			.audience
    getSeries: function()
    {
        //Array to store series object literals        
        var tempArray = new Array();
        
        //Loop through search results
        for(var m = 0; m < this.seriesIndex.length; m++) 
        {
            //If item is not undefined and has not been added 
            if(!this.hasBeenAdded(unescape(this.seriesIndex[m].viewCol15),tempArray))
            {
                //Set the series
                var sTitle = unescape(this.seriesIndex[m].viewCol15);
                //Set the authors
                var sAuthors = unescape(this.seriesIndex[m].viewCol4);
                    
                //If description and audience have been retrieved
                if(!(DA = this.getDescriptionAndAudience(m,unescape(this.seriesIndex[m].viewCol15))))
                {
                    var sDescription = null;
                    var sAudience = null; 
                } else {
                    var sDescription = DA[0];
                    var sAudience = DA[1]; 
                }   
                
                tempArray.push({
                    title: decodeURIComponent(sTitle),    
                    authors: decodeURIComponent(sAuthors),
                    description: decodeURIComponent(sDescription),
                    audience: decodeURIComponent(sAudience)
                });
            }
        }
        return tempArray;
    },
	
//Function to sort series by title
	sortSeriesByTitle: function()
	{
		//function to be passed as argument for sort algorythm
		function sortByTitle(a,b)
		{
			if(b.title > a.title)
			{
				return -1;
			} else if(b.title < a.title) {
				return 1;
			} else {
				return 0;
			}
		}
		
		this.series.sort(sortByTitle);
		
		var vars = new Array();
		for(var i = 0; i < this.series.length; i++)
		{
			vars.push(this.series[i].title);	
		}
		if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Secondary Series sorted by title',vars);
	},
	
//Function to group series index items according to the series
	groupSeriesIndexBySeriesTitle: function()
	{
	 	var tempArray = new Array();
		for(var i = 0; i < this.series.length; i++)
		{
			for(var x = 0; x < this.seriesIndex.length; x++)
			{
				if((decodeURIComponent(this.seriesIndex[x].viewCol15)) == this.series[i].title)
				{
					tempArray.push(this.seriesIndex[x]);
				}
			}
		}
		this.seriesIndex = null;
		this.seriesIndex = tempArray;
		
		//if LOG is enabled
		 if(Secondary._LOG_ENABLED)
		 {
			 var vars = new Array();
			 for(var i = 0; i < this.seriesIndex.length; i++)
			 {
				 vars.push(decodeURIComponent(this.seriesIndex[i].viewCol15));
			 }
			 LOG.printH1('Secondary.groupSeriesIndexBySeriesTitle() - ' + vars.length + ' - ' + vars.join('|'));
		 }
	},

//Function which loops through series titles in order to attach items to page
//INPUT:
//		obj - DOM element to attach series index to
    attachSeries: function(obj)// obj
    {
        if(this.series.length == 0) return false;
    	
	    //Attach series nav bar	  
        this.attachNav(obj);
        
        //Loop through series and print book indexes
        for(var i=0; i < this.series.length; i++)
        {
            var title = this.series[i].title;        
            
            //Create tag to hold level details
            var levelDetails = DH.createDiv('','levelDetails');
            
            //Create anchor tag for level
            var oAnchor = DH.createAnchor(title,'','','heading',title,(title.toLowerCase()).replace(/\s/gi,""));
            levelDetails.appendChild(oAnchor);
            
            //If audiences is set
            
            if(this.series[i].audience)
            {
                var oP = DH.createP(this.series[i].audience,'','audience');
                levelDetails.appendChild(oP);
            }
            
            //Attach authors paragraph
            var oP = DH.createP(this.series[i].authors,'','authors');
            levelDetails.appendChild(oP);
            
          
            //If description is set
            if(this.series[i].description)
            {
                var oP = DH.createP(this.series[i].description,'','description');
                levelDetails.appendChild(oP);
            }  
          
            
            //Create level container
            var levelContainer = DH.createDiv('','levelContainer');
            
            //Attach level details to level container
            levelContainer.appendChild(levelDetails);
            
			/*
			//Get packs for series
            var packs = this.getPacks(title);
			//Get books for series
            var books = this.getBooks(title);
            if(Secondary._LOG_ENABLED)LOG.printH1(this.series[i].title + ' -  p: ' + packs.length + ' - b: ' + books.length);
            */
			
			var items = this.getItems(title);
            if(Secondary._LOG_ENABLED)LOG.printH1(this.series[i].title + ' -  items: ' + items.length);
			
			this.attachItems(items);
			
            //this.printPack(obj);
            //this.printBooks(obj);	   
                   
            obj.appendChild(levelContainer);
            
            var loc = document.location.toString();
            var oEnd = loc.indexOf('#');
            if(oEnd != -1)loc =  loc.substring(0,oEnd);
          
            var sLink = window.location.toString().split('#')[0] + '#pageTop';
            var oAnchor = DH.createAnchor('Back to top',sLink,'','backToTop','Back to top','');
            DH.addEvent(oAnchor,'click',BackToTop_onClick);
            obj.appendChild(oAnchor);
        }
    },
	
//Function which loops through series titles in order to attach items to page
//INPUT:
//		obj - DOM element to attach series index to
    attachSeriesIndex1: function(obj)// obj
    {
        if(typeof attachSeriesIndex1Count == 'undefined')attachSeriesIndex1Count = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('contentLeft');
		if(!oHolder)
		{
			//If exceeded the number of determined iterations
			if(attachSeriesIndex1Count > 10)
			{
				throw new Error('Series.attachSeriesIndex1() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSeriesIndex1Count++;
			setTimeout('Series.attachSeriesIndex1()',100);
			return;
		}
    	
		//Sort series by title
		this.sortSeriesByTitle();
		
	    //Attach series nav bar	  
        this.attachSeriesIndex1Nav(oHolder);
		
		this.attachSeriesIndex1Items();
       
    },
	
//Function which loops through series titles in order to attach items to page
//INPUT:
//		obj - DOM element to attach series index to
    attachSeriesIndex2: function(obj)// obj
    {
        if(typeof attachSeriesIndex2Count == 'undefined')attachSeriesIndex2Count = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('contentLeft');
		if(!oHolder)
		{
			//If exceeded the number of determined iterations
			if(attachSeriesIndex2Count > 10)
			{
				throw new Error('Series.attachSeriesIndex2() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSeriesIndex2Count++;
			setTimeout('Series.attachSeriesIndex2()',100);
			return;
		}
    	
		//Sort series by title
		this.sortSeriesByTitle();
		
	    //Attach series nav bar	  
        this.attachSeriesIndex1Nav(oHolder);
		
		this.attachSeriesIndex2Items();
       
    },
	
//Function to attach series items to index1 template
	attachSeriesIndex1Items: function()
	{
	 	if(typeof attachSeriesIndex1ItemsCount == 'undefined')attachSeriesIndex1ItemsCount = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('index1');
		if(!oHolder)
		{
			//If it is first time ul must be attached to the page
			if(attachSeriesIndex1ItemsCount == 0)
			{
				//Create ul to hold category nav
				var div = DH.createDiv('index1','');
				document.getElementById('contentLeft').appendChild(div);
			}
			//If exceeded the number of determined iterations
			if(attachSeriesIndex1ItemsCount > 10)
			{
				throw new Error('Series.attachSeriesIndex1Items() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSeriesIndex1ItemsCount++;
			setTimeout('Series.attachSeriesIndex1Items()',100);
			return;
		}
		
		//Group items in series index by title
		this.groupSeriesIndexBySeriesTitle();
		
		//Loop through items by 3
		for(var i = 0; i < this.seriesIndex.length; i = i + 3)
		{
			var start = i;
			var count = i + 3;
			if(this.seriesIndex.length < count)count = this.seriesIndex.length;
			
			if(Secondary._LOG_ENABLED)LOG.printH1('start:  ' + start + ' count:  ' + count);
			
			var series1 = decodeURIComponent(this.seriesIndex[start].viewCol15);
			var series2 = ((start + 1) < this.seriesIndex.length) ? decodeURIComponent(this.seriesIndex[start + 1].viewCol15) : null;
			var series3 = ((start + 2) < this.seriesIndex.length) ? decodeURIComponent(this.seriesIndex[start + 2].viewCol15) : null;
			var linesClass = this.defineIndex1BkgLines(series1,series2,series3);
			//Print to log
			if(Secondary._LOG_ENABLED)LOG.printH1('Series.attachSeriesIndex1Items() - linesClass: ' + linesClass);
			
			//If there are series details to display
			if(this.haveSeriesDetailsToDisplay(start))
			{
				//Create ul to hold row for series details
				var ul = document.createElement('ul');
				//Add margin if it is not the very first row
				if(start != 0)ul.style.marginTop = '50px';
				//If there is a class attach it
				if(linesClass)ul.className = linesClass;
					
				//Loop through items and attach series details
				for(var x = start; x < count; x++)
				{
					//Crate list item
					var li = document.createElement('li');
					//Check if next in line is same series. If so, add class to adjust the width
					if((x != (count - 1)) && this.isNextSameSeries(x,count))
					{
						var liClass = new Array();
						liClass.push('doubleWidth');
						//if there is no list item before the one in the middle add extra padding
						//if((x == (start + 1)) && (decodeURIComponent(this.seriesIndex[x].viewCol15)!= decodeURIComponent(this.seriesIndex[x-1].viewCol15)))
						if((x == (start + 1)) && ul.getElementsByTagName('li').length == 0)
						{
							liClass.push('doublePadding');
						}
						li.className = liClass.join(' ');;	
					}
					
					if((x == (count - 1)) && ul.getElementsByTagName('li').length == 0)
					{
						li.className = 'tripplePadding';	
					}
					
					//Check if it s a new series
					var newSeries = (x == 0 || 	decodeURIComponent(this.seriesIndex[x].viewCol15) != decodeURIComponent(this.seriesIndex[x-1].viewCol15)) ? true : false;
					
					//If a new series is starting
					if(newSeries)
					{
						this.attachSeriesIndex1Series(this.seriesIndex[x],li);	
						//Attach list to ul
						ul.appendChild(li);	
					} else {
						//var img = document.createElement('img');
						//img.src = 'templates/layout/$file/spacerWhite.gif';
						//li.appendChild(img);
					}
					
								
				}
				
				oHolder.appendChild(ul);
			}
			
			//Create ul to hold row for series items
			var ul = document.createElement('ul');
			var ulClass = new Array();
			ulClass.push('second');
			if(linesClass)ulClass.push(linesClass);
			ul.className = ulClass.join(' ');
			
			//Loop through items and attach series items
			for(var x = start; x < count; x++)
			{
				//Crate list item
				var li = document.createElement('li');
				
				var item = new OnixItem('series',this.seriesIndex[x]);
				
				item.attachSeriesIndex1Item(li);
				
				ul.appendChild(li);
			}			
			oHolder.appendChild(ul);
		}
		
		//Attach back to top button
			var oAnchor = DH.createAnchor('Back to top',(window.location.toString().split('#')[0] + '#pageTop'),'','','Back to top');
			DH.addEvent(oAnchor,'click',BackToTop_onClick);
			var p = DH.createP(oAnchor,'','backToTop');			
			oHolder.appendChild(p);
	},
	
//Function to attach series items to index1 template
	attachSeriesIndex2Items: function()
	{
	 	if(typeof attachSeriesIndex2ItemsCount == 'undefined')attachSeriesIndex2ItemsCount = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('index2');
		if(!oHolder)
		{
			//If it is first time ul must be attached to the page
			if(attachSeriesIndex2ItemsCount == 0)
			{
				//Create ul to hold category nav
				var div = DH.createDiv('index2','');
				document.getElementById('contentLeft').appendChild(div);
			}
			//If exceeded the number of determined iterations
			if(attachSeriesIndex2ItemsCount > 10)
			{
				throw new Error('Series.attachSeriesIndex2Items() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSeriesIndex2ItemsCount++;
			setTimeout('Series.attachSeriesIndex2Items()',100);
			return;
		}
		
		//Loop through series and print items
		for(var i = 0; i < this.series.length; i++)
		{
			oHolder.appendChild(this.attachSeriesIndex2Series(this.series[i],i));
			
			//Get items
			var items = this.getItems(this.series[i].title);
			
			for(var m = 0; m < items.length; m = m + 3)
			{
				var start = m;
				var count = m + 3;
				if(items.length < count)count = items.length;
				
				//Create ul to hold row for series items
				var ul = document.createElement('ul');
				var ulClass = new Array();
				ulClass.push('second');
				ul.className = ulClass.join(' ');
				
				//Loop through items and attach series items
				for(var x = start; x < count; x++)
				{
					//Crate list item
					var li = document.createElement('li');
					
					var item = new OnixItem('series',items[x]);
					
					item.attachSeriesIndex1Item(li);
					
					ul.appendChild(li);
				}	
				
				oHolder.appendChild(ul);
			}
			
			//Attach back to top button
			var oAnchor = DH.createAnchor('Back to top',(window.location.toString().split('#')[0] + '#pageTop'),'','','Back to top');
			DH.addEvent(oAnchor,'click',BackToTop_onClick);
			var p = DH.createP(oAnchor,'','backToTop');
			oHolder.appendChild(p);
		}
	},
	
//Function to attach series details above item
	attachSeriesIndex1Series: function(obj,oHolder)
	{
		var oSeries = this.getSeriesDetails(decodeURIComponent(obj.viewCol15));	
		
		//Attach title
		var oAnchor = DH.createAnchor(oSeries.title,'','','',oSeries.title,'');
		oAnchor.setAttribute('name',oSeries.title.replace(/\s/gi,'_'));
		var h3 = document.createElement('h3');
		h3.appendChild(oAnchor);
		oHolder.appendChild(h3);
		
		//Attach audience
		if(oSeries.audience)
		{
			var p = DH.createP(oSeries.audience,'','audienceAuthors');
		}
		
		//Attach authors
		if(oSeries.authors)
		{
			if(p)
			{
				p.appendChild(document.createElement('br'));
				p.appendChild(document.createTextNode(oSeries.authors))
			} else {
				var p = DH.createP(oSeries.authors,'','audienceAuthors');
			}
		}
		
		//Attach audience authors paragraph
		if(p)oHolder.appendChild(p);
		
		//Attach description
		if(oSeries.description)
		{
			var p = DH.createP(oSeries.description,'','description');
			oHolder.appendChild(p);
		}
		
	},
	
//Function to attach series details above item
	attachSeriesIndex2Series: function(obj,i)
	{
		var oSeries = obj;
		
		var oHolder = DH.createDiv('',((i == 0) ? 'first' : ''));
		
		//Attach title
		var oAnchor = DH.createAnchor(oSeries.title,'','','',oSeries.title,'');
		oAnchor.setAttribute('name',oSeries.title.replace(/\s/gi,'_'));
		var h3 = document.createElement('h3');
		h3.appendChild(oAnchor);
		oHolder.appendChild(h3);
		
		//Attach audience
		if(oSeries.audience)
		{
			var p = DH.createP(oSeries.audience,'','audienceAuthors');
		}
		
		//Attach authors
		if(oSeries.authors)
		{
			if(p)
			{
				p.appendChild(document.createElement('br'));
				p.appendChild(document.createTextNode(oSeries.authors))
			} else {
				var p = DH.createP(oSeries.authors,'','audienceAuthors');
			}
		}
		
		//Attach audience authors paragraph
		if(p)oHolder.appendChild(p);
		
		//Attach description
		if(oSeries.description)
		{
			var p = DH.createP(oSeries.description,'','description');
			oHolder.appendChild(p);
		}
		return oHolder;
	},
	
//Function to determine if group of three items belong to the same category
	haveSeriesDetailsToDisplay: function(start)
	{
		//If it is the beginning
		if(start == 0)return true;
		
		var series = decodeURIComponent(this.seriesIndex[start - 1].viewCol15);
		//If they don't match
		if(decodeURIComponent(this.seriesIndex[start].viewCol15) != series)return true;
		if(typeof this.seriesIndex[start + 1] != 'undefined' && decodeURIComponent(this.seriesIndex[start + 1].viewCol15) != series)return true;
		if(typeof this.seriesIndex[start + 2] != 'undefined' && decodeURIComponent(this.seriesIndex[start + 2].viewCol15) != series)return true;
		
		return false;
	},
	
//Function which checks if the next item in line is in the same Series
	isNextSameSeries: function(x,count)
	{
		var series = decodeURIComponent(this.seriesIndex[x].viewCol15);	
		
		if((x + 1) == count) return false;
		
		if(decodeURIComponent(this.seriesIndex[x + 1].viewCol15) == series)
		{
			return true;
		} else {
			return false;
		}
	},
	
//Function which checks if the whole line is in the same Series
	isWholeLineSameSeries: function(start,count)
	{
		var series = decodeURIComponent(this.seriesIndex[start].viewCol15);	
		
		for(var i = start; i < count; i++)
		{
			if(decodeURIComponent(this.seriesIndex[1].viewCol15) != series)
			{
				return false;
			}
		}
		return true;
	},	
	
	isSameSeries: function(start,count,obj)
	{
		var series = decodeURIComponent(obj[start]);	
		
		for(var i = start; i < count; i++)
		{
			if(decodeURIComponent(obj[i]) != series)
			{
				return false;
			}
		}
		return true;
	},	
	
	
	
//Function to define dividers for indexes an returns className for ul element
	defineIndex1BkgLines: function()
	{
		//Count number of valid arguments
		var argsNum = 1;
		if(arguments[2])argsNum++;
		if(arguments[1])argsNum++;
		
		//If there's only one argument
		if(argsNum == 1)return null;
		
		//If whole line is the same		
		if(argsNum == 3 && (arguments[2] == arguments[1] == arguments[0]))return null;
		
		//If there are three items and the third is not equal the second
		var right = (argsNum == 3 && arguments[2] != arguments[1]) ? true : false;
		//If the second item is not equal the first
		var left = (arguments[1] != arguments[0]) ? true : false;
		
		if(Secondary._LOG_ENABLED)LOG.printH1('Series.defineIndex1BkgLines() - left: ' + left.toString() + ' right: ' + right.toString());
		
		//if both right and left are different
		if(right && left)
		{
			return 'leftright';
		} else if(right && !left) {
			return 'right';
		} else if(!right && left) {
			return 'left';
		} else {
			return null;
		}
	},
	
//Function to attach books and packs to page
//INPUT:
//		items - array of items
	attachItems: function(items)
	{
		for(var i = 0; i < items.length; i++)
		{	
			//Create new OnixItem object
			var item = new OnixItem('series',items[i]);	
		}
	},
//Function which attaches category nav to body of page
//INPUT:
//		obj - DOM element to attach the nav to
// OUTPUT: --
    attachNav: function(obj)
    {
        var loc = document.location;   
    	
	    var oDiv = DH.createDiv('','areasLinks');        
    	        
	    var sLength = 0;
	    var lineMax = 1;
    	
	    for(var i=0; i < this.series.length; i++)
	    {	
	        sLength +=  this.series[i].length;
	        if(sLength > 120 || lineMax == 5)
            {   
                sLength = 0;
                lineMax = 1;
                oDiv.appendChild(document.createElement('br'));
            }
    	    
	        var linkStr = loc + '#' + (this.series[i].title.toLowerCase()).replace(/\s/gi,"");        
            var oAnchor = DH.createAnchor(this.series[i].title,(loc + '#'),'','',this.series[i].title,'');
            oDiv.appendChild(oAnchor);        
            lineMax++;
        } 	        
	    obj.appendChild(oDiv);	        
    },
	
//Function which attaches category nav to body of page
//INPUT:
//		obj - DOM element to attach the nav to
// OUTPUT: --
    attachSeriesIndex1Nav: function()
    {
        if(typeof attachSeriesIndex1NavCount == 'undefined')attachSeriesIndex1NavCount = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('categoryNav');
		if(!oHolder)
		{
			//If it is first time ul must be attached to the page
			if(attachSeriesIndex1NavCount == 0)
			{
				//Create div to hold category nav
				var div = document.createElement('div');
				div.setAttribute('id','categoryNav');
				document.getElementById('contentLeft').appendChild(div);
			}
			//If exceeded the number of determined iterations
			if(attachSeriesIndex1NavCount > 10)
			{
				throw new Error('Series.attachSeriesIndex1Nav() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSeriesIndex1NavCount++;
			setTimeout('Series.attachSeriesIndex1Nav()',100);
			return;
		}
		
		//Loop thour series and attach them
		for(var i = 0; i < this.series.length; i++)
		{
			var winLoc = window.location.toString().split('#')[0];
			//var seriesLink = winLoc + '#' + this.series[i].title.replace(/\s/gi,'_');
			var seriesLink = '#' + this.series[i].title.replace(/\s/gi,'_');
			var anchor = DH.createAnchor(this.series[i].title,seriesLink,'','',this.series[i].title)
		    DH.addEvent(anchor,'click',SeriesIndex1Nav_onClick);
			//Attach anchor item to page
			oHolder.appendChild(anchor);
			
		}
		
    },

//Function which returns the packs of a specified series title
// INPUT:
//			title - series title (required)
// OUTPUT:
//			Array with packs
    getPacks: function(title)
    {
        var tempArray = new Array();
        for (var m = 0; m < this.seriesIndex.length; m++) 
        {
            if((unescape(this.seriesIndex[m].viewCol2).toLowerCase().indexOf("pack")!=-1) 
                && (title == unescape(this.seriesIndex[m].viewCol15))) {                
                tempArray.push(this.seriesIndex[m]);
            }
        }
	    return tempArray;
    },

//Function which returns the books of a specified series title
// INPUT:
//			title - series title (required)
// OUTPUT:
//			Array with books
    getBooks: function(title)
    {
        var tempArray = new Array();
        for(var m = 0; m < this.seriesIndex.length; m++) 
        {
            if((unescape(this.seriesIndex[m].viewCol2).toLowerCase().indexOf("pack")==-1) 
                && (title == unescape(this.seriesIndex[m].viewCol15))) {
                tempArray.push(this.seriesIndex[m]);
            }
        }        
        return tempArray;
    },
	
//Function which returns the books and packs of a specified series title
// INPUT:
//			title - series title (required)
// OUTPUT:
//			Array with books and packs
    getItems: function(title)
    {
        var tempArray = new Array();
        for(var m = 0; m < this.seriesIndex.length; m++) 
        {
            if(title == unescape(this.seriesIndex[m].viewCol15)) {
                tempArray.push(this.seriesIndex[m]);
            }
        }        
        return tempArray;
    },
	
//function to return series details
	getSeriesDetails: function(title)
	{
		for(var i = 0; i < this.series.length; i++)
		{
			if(this.series[i].title == title)return this.series[i];
		}
	},

	
/*
    printPack: function(obj)
    {
    
        if(this.lPacks.length == 0) return false;
        
        //this.getLevelIconClass();  
        
        var oPacks = DH.createDiv('','packs');
    	
	    for(var i=0; i < this.lPacks.length; i+=3)
	    {
            var rowEnd = i + 3;
    		    
            if(this.lPacks.length < rowEnd) rowEnd = this.lPacks.length;
    		
		    var oLevelRow = DH.createDiv('','levelRow');
    		
		    for(var n=i; n < rowEnd; n++)
            {	
     
                //var oPack = new Pack(this.lPacks[n]);
                //oPack.printPack(oCart);
            }
        }
    		  
        var oLevel = DH.createDiv('','level');
        oLevel.appendChild(oPacks);
        obj.appendChild(oLevel);
        
    },

    printBooks: function()
    {
    
        if(this.lBooks.length == 0) return false;
    	       
        if(this.searchDisplay == true)
        {
            var bookCount = 4;
            if(typeof args['div'] == "undefined") args['div'] = viewResults[0].viewCol17;
        } else {
            var bookCount = 3;
            var reAt = /literacy/i;
            if(args['div'] && reAt.test(unescape(args['div']))) bookCount = 4;
        }
    	       
        document.write('<div class="books">');
        
        for(var i=0; i < this.lBooks.length; i+=bookCount)
        {
            if(this.searchDisplay == true)
            {	            
                if(typeof args['div'] == "undefined") args['div'] = viewResults[this.lBooks[i]].viewCol17;
                if(typeof args['cat'] == "undefined")
                {
                    if(typeof viewResults[this.lBooks[i]].viewCol14=="undefined" || viewResults[this.lBooks[i]].viewCol14 == "")
  	                {
  	                    args['cat'] = viewResults[this.lBooks[i]].viewCol13;
  	                } else {
  	                    args['cat'] = viewResults[this.lBooks[i]].viewCol13 + ">" + viewResults[this.lBooks[i]].viewCol14;
  	                }
                }
            }
    	          
            var rowEnd = i + bookCount;
            if(this.lBooks.length < rowEnd) rowEnd = this.lBooks.length;
            document.write('<div class="bookRow">');
            for(var n=i; n < rowEnd; n++)
            {
                var oBook = new Book(this.lBooks[n]);
                oBook.printBook(oCart);
            }
            document.write('</div>');
        }
        document.write('</div>');
    
    },
*/

//Function which checks whether a series has already been added to the an Array
//INPUT:
//		sItem - new series title
//      sArray - array to be checked
//OUTPUT:
//		boolean
    hasBeenAdded: function(sItem, sArray)
    {
        for(var i=0; i < sArray.length; i++)
        {
            if(sItem == sArray[i].title) return true;
        }
        return false;
    },

//Function which sends HTTP request to server in order to retrieve series description and audience
//INPUT:
//		i - viewResults index used to label the results 
//		series - title of series to sent in search
//OUTPUT: Array
//		[0] - description
//		[1] - audience
    getDescriptionAndAudience: function(i,series)
    {
        var url = '/secondary/onix/seriesDescArray.js?readform&label=' + i + '&cat=' + encodeURIComponent(series);
        var oXHR = DH.createXHR();
        oXHR.open('GET',url,false);
        oXHR.send(null);  
        
        var seriesDescriptionArray = new Array();
        var seriesAudienceArray = new Array();
        
        //evaluate response
        try{
            var response = oXHR.responseText;
            eval(response);
        } catch(oError) {return null;}
        
        
        if(typeof seriesDescriptionArray[i] != 'undefined' && typeof seriesAudienceArray[i] != 'undefined')
        {
            var tempArray = new Array();
            tempArray.push(decodeURI(seriesDescriptionArray[i]));
            tempArray.push(decodeURI(seriesAudienceArray[i]));
            
            return tempArray;
        } else {
        
            return null;
        }
    },
//Function which validates parameters used on onix search
    validateSearchParams: function(obj)
    {
        if(!obj.view || typeof obj.view != 'string')
        {
            throw new Error('Series.init() expects valid \'view\' parameter');
        }
        
        if(!obj.type || typeof obj.type != 'string')
        {
            throw new Error('Series.init() expects valid \'type\' parameter');
        }
        
        if(!obj.cat || typeof obj.cat != 'string')
        {
            throw new Error('Series.init() expects valid \'cat\' parameter');
        }
        
        if(!obj.div)obj.div = 'secondary';
        if(!obj.start)obj.start = 1;
        if(!obj.count)obj.count = 200;        
        this.searchParams = obj;   
        
        return true;
    },
    
//Function which initiates the Series object     
    init: function()//expects 'subject' and 'category'
    { 
        //If subject has not been sent or is not set
        if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
        {
            throw new Error('Series.init() expects argument 1 to be of \'string\' type');
        }
        
        //If category has not been sent or is not set
        if(typeof arguments[1] !=  'undefined' && typeof arguments[1] != 'string')
        {
            throw new Error('Series.init() expects argument 2 to be of \'string\' type');
        }
        
        //Expects 3rd argument as object literal with search variables
        // .view
        // .type
        // .cat  
        if(typeof arguments[2] == 'undefined')
        {
            throw new Error('Series.init() expects argument 3 to be of \'object literal\' type');
        }
        
        
        
        if(!this.validateSearchParams(arguments[2]))
        {
            throw new Error('Series.init() expects valid search arguments');
        } 
        
        //Send Ajax request and get response
        this.loaded = this.loadAjax();
        
        if(this.loaded)
        {
            //Variable to store reference to 'Series' literal object
            //---Series-----------------
            //   .title
            //   .authors
            //   .description
            //   .audience
            this.series = this.getSeries();
           
        }          
        this.printVariables();       
    }
}



//---------------------------------------------------------------------------------------------------------------------------------------------------------------------	

function SeriesIndex1Nav_onClick(oEvent)
{
    var target = DH.stopEvent(oEvent);
    var sHash = target.getAttribute('href');
    
    if(sHash)
    {
        sHash = (sHash.indexOf('#') != -1) ? sHash.substring(1) : sHash;
        
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++)
        {
            if(anchors[i].getAttribute('name') && (anchors[i].getAttribute('name').toLowerCase() == sHash.toLowerCase()))
            {
                var anchor = anchors[i];
                break;
            } 
        }
        
        if(anchor)
        {
            var pos = DH.findPos(anchor);
            window.scrollTo((pos[0] - 10),pos[1]);
        }
    }
}

function BackToTop_onClick(oEvent)
{
    var target = DH.stopEvent(oEvent);
    window.scrollTo(0,0);
}



/*
 * function_Secondary
 */



Secondary = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/ 
    section: null,
    subsection: null,
    pageType: null,
    subject: null,
    category: null,
    
	//Variable which enables the log
	
    //_LOG_ENABLED: (EDDESK.getFormInput('DocID') && (EDDESK.getFormInput('DocID') == '8CC36E685372FC4CCA25754D0013A6E3')) ? true : null,
    _LOG_ENABLED: (DH.getURLParam('log')) ? true : null,
    

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/ 

    isCompatible: function()
    {
        if(!DH){
            return false;
        }
        
        if(!EDDESK
            || !EDDESK.getFormInput){
            return false;    
        }
        
        if(!LOG
            || !LOG.print
            || !LOG.printH1){
            return false;
        }
        
        return true; 
    },  
/*----------------------------------------------------------------------------------------------------------

    functions for edDesk form
    
 
    validFormInput: function(str)//function which checks whether an edDesk form input is valid
    {
        var item = null;
        
        try {//check whether the input exists and get a reference to it
                item = eval('document.forms[0].' + str);
        } catch (oError) {return null; }
       
        //if input is valid
        if(!item || item.value.length == 0 || item.value == ' ')return null;
        
        return true;      
    },
    
    getFormInput: function(str)//function which retrieces edDesk Form Input
    {
        //NOTE: use function validFormInput() to validate input first
        return unescape(eval('document.forms[0].' + str + '.value'));
    },
*/       
    printFormVariables: function()
    {
        var vars = new Array();
        
        //Add variables to array
        if(this.section)vars.push('section: ' + this.section);
        if(this.subsection)vars.push('subsection: ' + this.subsection);
        if(this.pageType)vars.push('pageType: ' + this.pageType);
        if(this.subject)vars.push('subject: ' + this.subject);
        if(this.category)vars.push('category: ' + this.category);
		if(this.DocID)vars.push('DocID: ' + this.DocID);
        
        //Create heading for LOG window
        var h = document.createElement('h1');
        h.appendChild(document.createTextNode('Secondary DOM Form variables'));
        var li = document.createElement('li');
        li.appendChild(h);
        
        //Create element to hold variable list
        var ul = document.createElement('ul');    
        //attach heading
        ul.appendChild(li);
        
        //Loop through variable list and add items    
        for(var i = 0; i < vars.length; i++)
        {
            var li = document.createElement('li');
            li.appendChild(document.createTextNode(vars[i]));
            ul.appendChild(li);
        }
        
        //Print list into LOG window        
        if(this._LOG_ENABLED)LOG.print(ul);
        
    },

/*----------------------------------------------------------------------------------------------------------

    urlvars
    
*/

    getSubjectAndCategory: function()
    {
		/*
        var winLoc = (window.location.toString()).split('?')[0];
        
        winLoc = winLoc.split('/');
        
        var index = 0;
        for(var i = 0; i < winLoc.length; i++)
        {
            if(winLoc[i] == 'divisions')index = i;
        }
        
        if(index == 0)throw new Error('Secondary.getSubjectAndCategory() expects the string \'divisions\' in url string');
        
        var oRe = /_/gi;
        this.subject = winLoc[index + 1].replace(oRe,' ');
        this.category = winLoc[index + 2].replace(oRe,' ');
		*/
		
		var params = (DH.getURLParam('cat')) ? DH.getURLParam('cat').split('>') : null;
		
		if(params instanceof Array)
		{
			this.subject = params[0];
			if(params.length == 2)
			{
				this.category = params[1];
			}
			
			
			/*
			//Check if it is the Study Guide section
			if((this.subject && this.category)
			    && (this.subject == 'reference' && this.category == 'study guides'))
			{
			    this.subject = 'Study Guides';
			    this.category = null;
			}
			*/
		}
		
		//if there is no &cat= parameter and the page is an Onix book record, then get the Subject>Area from the book metadata
		else if (document.forms[0].PageType.value == 'onixProduct')
		{
			this.subject=document.forms[0].Subjects.value.toLowerCase();
			this.category=document.forms[0].Areas.value.toLowerCase();
		}
    },

 
/*----------------------------------------------------------------------------------------------------------

    page
    
*/

    loadPage: function()
    {
        switch(this.pageType)
        {
            case 'home':
                this.loadPageHome();
                break;
            case 'article':
                this.loadPageArticle();
                break;
            case 'library':
                this.loadPageLibrary();
                break;    
            case 'Error'://for 404 pages
                this.loadPageError();
                break;
			case 'onixProduct':
				this.loadPageOnixProduct();
				break;
            case null:
                throw new Error('Secondary.loadPage() - pageType is not set');
                break;
            default:
            	this.loadPageLibrary();       
            	 }
        
        //If not site's main home page parse contentRight
        if(!this.section || this.section != 'Home')
        {
            this.loadPageContentRight();
        }
    },
    
    loadPageContentRight: function()
    {
        if(!loadPageContentRightCount)var loadPageContentRightCount = 0;
		
		//Get reference to holder element
		var oParent = document.getElementById('contentRight');
		if(!oParent)
		{
			//If exceeded the number of determined iterations
			if(loadPageContentRightCount > 10)
			{
				throw new Error('Secondary.loadPageContentRight() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageContentRightCount++;
			setTimeout('Secondary.loadPageContentRight()',100);
			return;
		}	
		
		if(Cart)Cart.attachMiniCart(oParent);
    },
    
    loadPageHome: function()
    {
		switch(this.section)
		{
			case 'Home':
        		this.loadSiteHomePage();
				break;
			default:
				this.loadPageHomeSubjects();
		}
	},
	
//Function to attach home page elements for subjects	
	loadPageHomeSubjects: function()
	{
		if(!loadPageHomeSubjectsCount)var loadPageHomeSubjectsCount = 0;
		
		//Get reference to holder element
		var oParent = document.getElementById('contentLeft');
		var oSibling = document.getElementById('edDeskBody');
		if(!oParent || ! oSibling)
		{
			//If exceeded the number of determined iterations
			if(loadPageHomeSubjectsCount > 10)
			{
				throw new Error('Secondary.loadPageHomeSubjects() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageHomeSubjectsCount++;
			setTimeout('Secondary.loadPageHomeSubjects()',100);
			return;
		}	
		
		
        Navigation.init('main',this.section);
        Navigation.attach();
		
		//Attach strap
		oParent.insertBefore(this.attachSubjectStrap(),oSibling);
		
	},

//Function to attach body of main home page	
	loadSiteHomePage: function()
	{
	    //START - Code to get HTML element reference
	    if(typeof loadSiteHomePageCount == 'undefined')loadSiteHomePageCount = 0;
		
		var oHolder = document.getElementById('wrapper');
		var  mainNavModule = document.getElementById('mainNavModule');
		if(!oHolder || !mainNavModule)
		{
			//If exceeded the number of determined iterations
			if(loadSiteHomePageCount > 10)
			{
				throw new Error('Secondary.loadSiteHomePage() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadSiteHomePageCount++;
			setTimeout('Secondary.loadSiteHomePage()',100);
			return;
		}
		//END - Code to get HTML element reference
		
		//Set class of wrapper tag to siteHome
		oHolder.className = 'siteHome';
		
		//Attach class to body tag
		//document.getElementsByTagName('body')[0].style.backgroundImage = 'url(templates/site_home/$file/siteHomeBodyBkg.jpg)';
		document.getElementsByTagName('body')[0].className = 'bodySiteHome';
		
		//Attach spacing element to mainNavModule
		var oDiv = DH.createDiv('','spacingDiv');
		mainNavModule.insertBefore(oDiv,mainNavModule.firstChild);
		
		//Attach navigation
        Navigation.init('main',this.section);
        Navigation.attach();
        
        //Initialize features
        HomePageFeatures.init();
	},
	
	loadPageArticle: function()
	{
	    switch(this.section)
	    {
	        case 'Teacher Support':
	            this.loadPageArticleTeacherSupport();
	            break;   
	        default:
	            this.loadPageArticleDefault();    
	    }
	},
	
	loadPageArticleDefault: function()
	{
		if(typeof loadPageArticleCount == 'undefined')loadPageArticleCount = 0;
		
		//Get reference to holder element
		var oParent = document.getElementById('contentLeft');
		
		if(!oParent)
		{
			//If exceeded the number of determined iterations
			if(loadPageArticleCount > 10)
			{
				throw new Error('Secondary.loadPageArticle() exceeded its limit of iterations');
			}
			 
			//Try again in 100 miliseconds
			loadPageArticleCount++;
			setTimeout('Secondary.loadPageArticle()',100);
			return;
		}	
		
    	//Attach introduction heading
		var oChild = document.getElementById('edDeskBody');
		if (this.DocID && this.DocID == '951725866ADC945FCA2575830018EFA5'){
		oChild.style.width = '664px';	
		}
		else {
		oChild.style.width = '601px';
	  	oChild.style.marginLeft = '45px';
		oChild.style.paddingTop = '20px';
		}
		//alert(oChild.offsetWidth);
		var h3 = document.createElement('h3');
		h3.setAttribute('class','article');
		h3.style.margin = '0';
		h3.appendChild(document.createTextNode(unescape(document.forms[0].Headline.value)));
		oChild.insertBefore(h3,oChild.firstChild);

		
		//this.attachSubjectCategoryStrap();	
		if (this.pageType == 'message') {
	   		Navigation.init('main','home');
	   	}
	   	else {
	   		Navigation.init('main',this.section);	   	
		}	
		Navigation.attach();		
		
	},
	
	loadPageArticleTeacherSupport: function()
	{
	    if(typeof loadPageArticleTeacherSupportCount == 'undefined')loadPageArticleTeacherSupportCount = 0;
		
		//Get reference to holder element
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(loadPageArticleTeacherSupportCount > 10)
			{
				throw new Error('Secondary.loadPageArticleTeacherSupport() exceeded its limit of iterations');
			}
			
			 
			//Try again in 100 miliseconds
			loadPageArticleTeacherSupportCount++;
			setTimeout('Secondary.loadPageArticleTeacherSupport()',100);
			return;
		}			
		
		oChild.className = 'teacherSupportTemplate';
		oChild.style.paddingLeft = '45px';
		oChild.style.paddingTop = '20px';
		oChild.style.marginTop = '20px';
		oChild.style.borderTop = '1px solid #DDDEDF';
		
		//Attach introduction heading
		var h3 = document.createElement('h3');
		h3.style.margin = '0';
		h3.appendChild(document.createTextNode('Introduction'));
		oChild.insertBefore(h3,oChild.firstChild);
		
		//Attach strap
		this.attachSubjectCategoryStrap();
		
		//Attach navigation
		Navigation.init('main',this.subject);
		Navigation.attach();
		
		//Get isbn
		if((EDDESK.getFormInput('MetaKeywords')) 
		    && (EDDESK.getFormInput('MetaKeywords').length == 13))
		{
		    var isbn = EDDESK.getFormInput('MetaKeywords');
		    if(this._LOG_ENABLED)LOG.printH1('Secondary.loadPageArticleTeacherSupport() - isbn from EDDESK FORM:  [' + isbn + ']');
		}
		
		//If isbn exists
		if(isbn)
		{
		    //Search for item details
		    var itemSearch = new OnixItemSearch(isbn,'TeacherSupportItemSearch');
		    //If item loaded
		    if(itemSearch.loaded)
		    {
		        var item = new OnixItem('series',itemSearch.tsIndex[0]);
		        item.attachOnixProductTeacherSupport(oParent,oChild);
		    }
        }
        
        TeacherSupportTable.init(oChild);
	},
    
    loadPageLibrary: function()
    {
        switch(this.subsection)
        {
            case 'Onix':
                this.loadPageLibraryOnix();    
                break;
		    case 'Forms':
		         this.loadPageArticleDefault();
		        break;               
   		    case 'Info':
		         this.loadPageArticleDefault();
		        break;               
			case 'Search':
				this.loadPageLibrarySearch();
				break;
		    case 'Teacher Support':
		        this.loadPageLibraryTeacherSupport();
		        break;
		    case 'Checkout':
		        var isOverviewPage = (this.DocID && this.DocID == '514829CC98A98DA3CA257557001A4C52') ? true : null;
		        if(isOverviewPage)
		        {
		            this.loadPageLibraryCheckoutOverview();
		        } else {
		            this.loadPageLibraryCheckout();
		        }
		        break;
            default:
	            this.loadPageArticleDefault();
        }
    },
    
    loadPageLibraryCheckoutOverview: function()
	{
		if(typeof loadPageLibraryCheckoutOverviewCount == 'undefined')loadPageLibraryCheckoutOverviewCount = 0;
		
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(loadPageLibraryCheckoutOverviewCount > 10)
			{
				throw new Error('Secondary.loadPageLibraryCheckout() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageLibraryCheckoutOverviewCount++;
			setTimeout('Secondary.loadPageLibraryCheckout()',100);
			return;
		}
		
		oParent.className = 'checkout';
		
		if(this.articleTitle)
		{
		    var h2 = document.createElement('h2');
		    h2.appendChild(document.createTextNode(this.articleTitle));
		    oParent.insertBefore(h2,oChild);
		}
		
		//Attach navigation
		Navigation.init('main',this.section);
        Navigation.attach();
        
       //Create summary tag
       var div = document.createElement('div');
       div.setAttribute('id','cartSummary');
       
       //Attach summary
       if(Cart)Cart.attachSummary(div);
       
       /*
       //Attach buttons
       var fieldset = document.createElement('fieldset');
       
       //Attach continue shopping button
       var oInput = document.createElement('input');
       oInput.setAttribute('type','button');
       oInput.setAttribute('value','Continue shopping');
       oInput.setAttribute('tabindex','1');
       oInput.className = 'button';
       var ContinueShoppingBtn_onClick = function(oEvent)
       {
            var target = DH.stopEvent(oEvent);
            history.go(-1);
       };
       DH.addEvent(oInput,'click',ContinueShoppingBtn_onClick);
       fieldset.appendChild(oInput);
       
       //Attach check out button
       if(Cart.hasItems())
       {
           var oInput = document.createElement('input');
           oInput.setAttribute('type','button');
           oInput.setAttribute('value','Checkout now');
           oInput.setAttribute('tabindex','2');
           oInput.className = 'button';
           var CheckoutNowBtn_onClick = function()
           {
                window.location = '/secondary31/site/articleIDs/8BBB301D7E16233BCA257555001631ED?open&template=domSecondary';
           };
           DH.addEvent(oInput,'click',CheckoutNowBtn_onClick);
           fieldset.appendChild(oInput);
       }
       
       //Attach fieldset
       div.appendChild(fieldset);
       */
       oChild.appendChild(div);
		
	},
	
	loadPageLibraryCheckout: function()
	{
		if(typeof loadPageLibraryCheckoutCount == 'undefined')loadPageLibraryCheckoutCount = 0;
		
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(loadPageLibraryCheckoutCount > 10)
			{
				throw new Error('Secondary.loadPageLibraryCheckout() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageLibraryCheckoutCount++;
			setTimeout('Secondary.loadPageLibraryCheckout()',100);
			return;
		}
		
		oParent.className = 'checkout';
		/*
		if(this.articleTitle)
		{
		    var h2 = document.createElement('h2');
		    h2.appendChild(document.createTextNode(this.articleTitle));
		    oParent.insertBefore(h2,oChild);
		}
		*/
		//Attach navigation
		Navigation.init('main',this.section);
        Navigation.attach();
       /*
       //Attach step holder
       var div = document.createElement('div');
       div.setAttribute('id','checkoutStep');
       oChild.appendChild(div);
       */
       if(Checkout)
       {
            Checkout.init();
            Checkout.attach();
       }
	   
	},
	
	
    
    loadPageLibraryTeacherSupport: function()
	{
		if(typeof loadPageLibraryTeacherSupportCount == 'undefined')loadPageLibraryTeacherSupportCount = 0;
		
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(loadPageLibraryTeacherSupportCount > 10)
			{
				throw new Error('Secondary.loadPageLibraryTeacherSupport() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageLibraryTeacherSupportCount++;
			setTimeout('Secondary.loadPageLibraryTeacherSupport()',100);
			return;
		}
		
		var imgPath = '/secondary/images/category_straps/teacher_support.jpg';
		var oTitle = 'Teacher Support';
		
		//Attach strap
		oParent.insertBefore(DH.createImg(imgPath,oTitle,null),oChild);
		
		//Attach navigation
		Navigation.init('main',this.section);
        Navigation.attach();
        
        switch(this.subject)
        {
            case 'business and commerce':
                var tsFilter = new TeacherSupportFilter(this.subject,this.category);
                tsFilter.loadAjax();
                if(tsFilter.loaded)
                {
                    tsFilter.attachIndex3(oChild);
                } else {
                    tsFilter.attachNoRecordsMessage(oChild,'There are no entries for this division.');
                }
            break;
            default:
                var tsFilter = new TeacherSupportFilter(this.subject,null);
                tsFilter.loadAjax();
                if(tsFilter.loaded)
                {
                    tsFilter.attachIndex2(oChild);
                } else {
                    tsFilter.attachNoRecordsMessage(oChild,'There are no entries for this subject.');
                }
		}
		
	},
	
	loadPageLibrarySearch: function()
	{
		if(typeof loadPageLibrarySearchCount == 'undefined')loadPageLibrarySearchCount = 0;
		
		var oHolder = document.getElementById('contentLeft');
		if(!oHolder)
		{
			//If exceeded the number of determined iterations
			if(loadPageLibrarySearchCount > 10)
			{
				throw new Error('Secondary.loadPageLibrarySearch() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageLibrarySearchCount++;
			setTimeout('Secondary.loadPageLibrarySearch()',100);
			return;
		}
		
		Navigation.init('main',this.section);
        Navigation.attach();
		
		//Create div to hold index
		var div = DH.createDiv('index2','');
		oHolder.appendChild(div);
				
		Search.init();
		Search.attachResults();
	},
	
	loadPageOnixProduct: function()
	{
		if(typeof loadPageOnixProductCount == 'undefined')loadPageOnixProductCount = 0;
		
		//Get reference to holder element
		var oParent = document.getElementById('contentLeft');
		
		if(!oParent)
		{
			//If exceeded the number of determined iterations
			if(loadPageOnixProductCount > 10)
			{
				throw new Error('Secondary.loadPageOnixProduct() exceeded its limit of iterations');
			}
			
			 
			//Try again in 100 miliseconds
			loadPageOnixProductCount++;
			setTimeout('Secondary.loadPageOnixProduct()',100);
			return;
		}	
		
		var oChild = document.getElementById('edDeskBody');
		//Add padding to edDeskBody
		//oChild.style.paddingLeft = '45px';
		
		//Get onix type
		var onixType = DH.getURLParam('onixtype');
		
		var detailsTable = document.getElementById('edDeskBody').getElementsByTagName('table')[0];
		detailsTable.setAttribute('id','onixProductTable');
		if(onixType)detailsTable.className = 'noDividerBorder';
		var detailsHolder0 = detailsTable.getElementsByTagName('td')[0];
		detailsHolder0.className = 'bookCover'; 
		var detailsHolder1 = detailsTable.getElementsByTagName('td')[1];
		detailsHolder1.className = 'divider'; 
		var detailsHolder2 = detailsTable.getElementsByTagName('td')[2];
		detailsHolder2.className = 'bookDetails';
		
		this.attachSubjectCategoryStrap();	
		
		if(!this.category)
		{
        	Navigation.init('onix',this.subject);
		} else {
			Navigation.init('onix',this.subject,this.category);
		}
		Navigation.attach();
		
		var item = new OnixItem('onixProduct');
		item.attachOnixProduct(oParent,oChild);	
		
		
		if(!onixType)
		{
		    item.attachOnixProductLinks();
		    item.attachOnixProductRelatedTitles(detailsHolder2);
		}
	},
    
	
	
    loadPageLibraryOnix: function()
    {
        if(!this.subject)throw new Error('Secondary.loadPageLibraryOnix() expects a subject type');
        //if(!this.category)throw new Error('Secondary.loadPageLibraryOnix() expects a category type');
        
		if(!this.category)
		{
        	Navigation.init('onix',this.subject);
		} else {
			Navigation.init('onix',this.subject,this.category);
		}
		Navigation.attach();
		
		//Attach strap
		this.attachSubjectCategoryStrap();		
		
		var subcat = (this.category) ? this.subject + '>' + this.category  : this.subject;
		
        var search = {
            view: (DH.getURLParam('view')) ? DH.getURLParam('view') : 'areas',
            start: (DH.getURLParam('start')) ? DH.getURLParam('start') : null,
            count: (DH.getURLParam('count')) ? DH.getURLParam('count') : null,
            type: 'cat',
            cat: subcat   
        }
        
		if(this.category)
		{
        	//Series.init(this.subject,this.category,search);
			Series.init(this.subject,this.category,search);
		} else {
			Series.init(this.subject,'',search);	
		}
		
        //If loaded successfully
        if(Series.loaded == true)
        {
			switch(this.subject)
			{
			/*
				case 'commerce and business':					
					Series.attachSeriesIndex2(document.getElementById('content'));
					break;
				case 'the arts':
					Series.attachSeriesIndex1(document.getElementById('content'));
					break;
				case 'english':
					switch(this.category)
					{
						case 'dictionaries':
						case 'drama':
						case 'language grammar':
							Series.attachSeriesIndex2(document.getElementById('content'));
							break;
						default:
							Series.attachSeriesIndex1(document.getElementById('content'));
					}
					break;
				case 'geography':
					switch(this.category)
					{
						case 'atlas':
							Series.attachSeriesIndex1(document.getElementById('content'));
							break;
						default:
							Series.attachSeriesIndex2(document.getElementById('content'));
					}
					break;
				case 'food technology':
					Series.attachSeriesIndex1(document.getElementById('content'));
					break;
			*/
				default:
					Series.attachSeriesIndex2(document.getElementById('content'));
			}
        } else {
			
			//Attach message to page
			this.loadPageMessage('There are 0 results for ' + this.category + ' - ' + this.subject);
			
            if(this._LOG_ENABLED)LOG.printH1('Secondary.loadPageLibraryOnix() - No results for ' + this.subject + '>' + this.category);
        }
    },
    
    loadPageError: function()
    {
        if(typeof pageErrorCount == 'undefined')pageErrorCount = 0;
        
        try{
            var oBody = document.getElementById('body');
        } catch(oError){
                            if(pageErrorCount < 10)
                            {
                                pageErrorCount++;
                                setTimeout('Secondary.loadPageError()',100);
                                return;
                            } else {
                                        throw new Error('Secondary.loadPageError() has exceeded its number of iterations');
                                   }
                       }
        oBody.style.paddingLeft = '159px';
    },
	
//Function which prints message on body of page
    loadPageMessage: function(message)// obj
    {
        if(typeof loadPageMessageCount == 'undefined')loadPageMessageCount = 0;
		
		//Get reference to holder element
		var oHolder = document.getElementById('contentLeft');
		if(!oHolder)
		{
			//If exceeded the number of determined iterations
			if(loadPageMessageCount > 10)
			{
				throw new Error('Secondary.loadPageMessage() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			loadPageMessageCount++;
			setTimeout('Secondary.loadPageMessage()',100);
			return;
		}
    	
		//Create message holder
		var div = DH.createDiv('','message');
		
		var p = DH.createP(message,'','');
		div.appendChild(p);
		oHolder.appendChild(div);
       
    },
//function to attach strap for subject>category pages
	attachSubjectCategoryStrap: function()
	{
	
		if(typeof attachSubjectCategoryStrapCount == 'undefined')attachSubjectCategoryStrapCount = 0;

		//Get reference to holder element
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(attachSubjectCategoryStrapCount > 10)
			{
				throw new Error('Secondary.attachSubjectCategoryStrap() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			attachSubjectCategoryStrapCount++;
			setTimeout('Secondary.attachSubjectCategoryStrap()',100);
			return;
		}
			
	
		//Get image's file name	
		if(this.category)
		{
			var imgPath = '/secondary/images/category_straps/' + this.subject.replace(/\s|\+/gi,'_') + '___' + this.category.replace(/\s|\+/gi,'_') + '.jpg';
			var oTitle = this.subject + ' - ' + this.category;
			
		} else {
			var imgPath = '/secondary/images/category_straps/' + this.subject.replace(/\s|\+/gi,'_') + '.jpg';
			var oTitle = this.subject;
		}
		//Attach image
		oParent.insertBefore(DH.createImg(imgPath,oTitle,SubjectCategoryStrapError),oChild);
		
		
	},
	
	//function to attach strap for subject>category pages
	attachSubjectStrap: function()
	{
		//Get image's file name	
		var imgPath = 'homepages/' + this.section.replace(/\s/gi,'+') + '/$file/strap.jpg';
		//Attach image
		return DH.createImg(imgPath,this.section,null);		
	},
	
	getSubjectAndCategoryFromURL: function()
	{
	    var cat = DH.getURLParam('cat');
	    if(cat)
	    {
	        cat = cat.split('>');
	        this.subject = cat[0];
	        if(typeof cat[1] != 'undefined')
	        {
	            this.category = cat[1];
	        } else {
	            this.category = null;
	        }
	    } else {
	        this.subject = null;
	    }
	},
    
    
/*----------------------------------------------------------------------------------------------------------

    init
    
*/   
    init: function ()
    { 
        //check whether Secondary is compatible
        if(!this.isCompatible) throw new Error('Secondary is not compatible');
        
        //Load edDesk variables  
        if(EDDESK.getFormInput('Section'))this.section = EDDESK.getFormInput('Section');
        if(EDDESK.getFormInput('Subsection'))this.subsection = EDDESK.getFormInput('Subsection');
        if(EDDESK.getFormInput('PageType'))this.pageType = EDDESK.getFormInput('PageType');
		if(EDDESK.getFormInput('DocID'))this.DocID = EDDESK.getFormInput('DocID');
		if(EDDESK.getFormInput('Title'))this.articleTitle = EDDESK.getFormInput('Title');
        
        //If it is an Onix index page
        if((this.pageType && this.pageType == 'onixProduct') 
			|| (this.section && this.subsection && this.section == 'Library' && this.subsection == 'Onix'))
        {
            //Get subject and category
            this.getSubjectAndCategory();
        }
        
        //If it is a Teacher Support article page
        if((this.pageType && this.pageType == 'article')
            && (this.section && this.section == 'Teacher Support'))
        {
            this.subject = 'teacher support';
        }
        
       
        //If it is a teacher support index page
        if((this.section && this.section == 'Library')
            && (this.subsection && this.subsection == 'Teacher Support'))
        {
            this.getSubjectAndCategoryFromURL();
        }
        
        
    }
}

/*---------------------------------------------------------------------------------------------------------------------------------------------------------------
*/

//Initiate cart
if(Cart)Cart.init();

Secondary.init();
Secondary.printFormVariables();
Secondary.loadPage();


/*---------------------------------------------------------------------------------------------------------------------------------------------------------------
*/


function SubjectCategoryStrapError()
{
	var originalPath = this.getAttribute('src');
	
	var pathSplit = this.getAttribute('src').split('/');
	var imgName = pathSplit[pathSplit.length - 1];
	
	if(imgName.indexOf('jpg') != -1)
	{
		var newName = imgName.split('___');
		this.src = (originalPath.replace(imgName,newName[0] + '.jpg'));
	}
}






