﻿


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);
}














