//__________________________________________________________________________
// Declare global variables
var datafile = "/data/pp_catalog.xml"; // xml data file
var table = 0; // table of xml data
var col_list = new Array(); // array of column data types
var npages = 0; // total number of pages
var page_index = 0; // index of current page
var ordered_ind = new Array(); // array of first item indices
var itemsperpage = 6; // max number of items displayed per page
var itemsthispage = 0; // number of items to display on current page

//__________________________________________________________________________
// Initialize global variables
function globalInit(){
    table = get_table(datafile);
    col_list = get_col_list();
    npages = get_npages();
    ordered_ind = sort_by_date();
    return 0;
}

//__________________________________________________________________________
// Make xmlHttpRequest object
function loadxml(xmlfile){
    var xmldoc;
    if(window.XMLHttpRequest){
	xmldoc = new window.XMLHttpRequest();
    }
    else if(window.ActiveXObject){
	xmldoc = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else
	xmldoc = false;
    if (xmldoc){
	xmldoc.open("GET",xmlfile,false);
	xmldoc.send(null);
	return xmldoc.responseXML;    
    }
    else{
	alert("XML loading not supported.");
	return null;
    }   
}

//__________________________________________________________________________
// Get global table element
function get_table(xmlfile){
    var xmldocument = loadxml(xmlfile);
    var a_table = xmldocument.getElementsByTagName("Table")[0];
    return a_table;
}

//__________________________________________________________________________
// Get global array of column data types
function get_col_list(){
    var row0 = table.getElementsByTagName("Row")[0];
    var cells = new Array();
    cells = row0.getElementsByTagName("Cell");
    var a_col_list = new Array(cells.length);
    for (var i=0;i<cells.length;i++){
	if (cells[i].getElementsByTagName("Data").length>0){
	    var data = cells[i].getElementsByTagName("Data")[0].childNodes[0];
	    a_col_list[i] = data.nodeValue;
	}
	else
	    a_col_list[i] = '';
    }
    return a_col_list;
}

//__________________________________________________________________________
// Calculate number of pages
function get_npages(){
    var rows = table.getElementsByTagName("Row");
    var np = parseInt((rows.length-1)/itemsperpage);
    if ((rows.length-1)%itemsperpage != 0)
	np += 1;
    return np;
}

//__________________________________________________________________________
// Get column index of a particular data type (e.g. 'release date')
function get_col_ind(data_type){
    var ind = -1;
    for (var i=0;i<col_list.length;i++){
	if (col_list[i]==data_type){
	    ind = i;
	    break;
	}
    }
    return ind;
}

//__________________________________________________________________________
// Get full column of a particular data type (e.g. 'release date')
function get_full_col(data_type){
    var col = get_col_ind(data_type);
    var rows = new Array();
    rows = table.getElementsByTagName("Row");
    var full_col = new Array(rows.length);
    for (var i=0;i<rows.length;i++){
	var cell = rows[i].getElementsByTagName("Cell")[col];	
	if (cell.getElementsByTagName("Data").length>0){
	    var data = cell.getElementsByTagName("Data")[0].childNodes[0];
	    full_col[i] = data.nodeValue;
	}
	else
	    full_col[i] = '';
    }
    return full_col;
}

//__________________________________________________________________________
// Get a list of dates
function get_dates(){
    var all_dates = new Array();
    all_dates = get_full_col('release date');
    var fake = 0;
    for (var i=0;i<all_dates.length;i++){
	var tmp = all_dates[i].split('T');
	var tmp2 = tmp[0].split('-');
	var thisdate = Date.UTC(tmp2[0],tmp2[1]-1,tmp2[2]);
	if (isNaN(thisdate)==true)
	    all_dates[i] = fake++;
	else
	    all_dates[i] = thisdate;
    }
    return all_dates;
}

//__________________________________________________________________________
// sort arrays of numbers
function sortNumber(a, b){
    return a - b;
}	     

//__________________________________________________________________________
// Sort row indices by date
function sort_by_date(){
    var dates = get_dates();
    var sorted = get_dates();
    sorted.sort(sortNumber);
    var indices = new Array(dates.length);
    var nfound = 0;
    var skip = 0;
    for (var i=sorted.length-1;i>=0;i--){
	for (var j=0;j<dates.length;j++){
	    if (dates[j] == sorted[i]){
		skip = 0;
		for (var k=0;k<nfound;k++){
		    if (j == indices[k])
			skip = 1;
		}
		if (skip == 1)
		    continue;
		else {
		    indices[nfound] = j;
		    nfound++;
		    break;
		}
	    }
	}
    }
    return indices;
}

//__________________________________________________________________________
// Get the number of items displayed on this page
function get_itemsthispage(){
    var itemsthis = itemsperpage;
    var rows = table.getElementsByTagName("Row");
    if (page_index == npages-1)	    
	itemsthis = (rows.length-1)%itemsperpage;
    if (itemsthis == 0)
	itemsthis = itemsperpage;
    return itemsthis;
}

//__________________________________________________________________________
// Get a single column's data for a particular row
function get_data(row_ind,data_type){
    var data = '';
    var row = table.getElementsByTagName("Row")[row_ind];
    var cell = row.getElementsByTagName("Cell")[get_col_ind(data_type)];
    if (cell.getElementsByTagName("Data").length>0)
	data = cell.getElementsByTagName("Data")[0].childNodes[0].nodeValue;
    return data;
}

//__________________________________________________________________________
// Fill item values
function fill_item(row_ind){
    var item = {
	sku        : get_data(row_ind,'SKU'),
	title      : get_data(row_ind,'title'),
	author     : get_data(row_ind,'author'),
	style      : get_data(row_ind,'style'),
	status     : get_data(row_ind,'status'),
	short_desc : get_data(row_ind,'short description'),
	price      : get_data(row_ind,'price'),
	weight     : get_data(row_ind,'ounces')/16.0,
	full_desc  : get_data(row_ind,'description'),
	guts       : get_data(row_ind,'spilling its guts'),
	said       : get_data(row_ind,'he said, she said'),
	date       : get_data(row_ind,'release date'),
	publisher  : get_data(row_ind,'Publisher'),
	paper      : get_data(row_ind,'Paper/binding'),
	dimensions : get_data(row_ind,'Dimensions'),
	pages      : get_data(row_ind,'Pages'),
	language   : get_data(row_ind,'Language'),
	isbn       : get_data(row_ind,'ISBN'),
	copyright  : get_data(row_ind,'Copyright Ownership'),
	barcode    : get_data(row_ind,'Barcode'),
	outofprint : get_data(row_ind,'Out Of Print'),
	also_avail : get_data(row_ind,'also available at:'),
	as_seen_in : get_data(row_ind,'as seen in:'),
       	sneak_peek : get_data(row_ind,'sneak peek:')
    }
    return item;
}

//__________________________________________________________________________
// Get item array
function get_items(){
    var items = new Array(itemsthispage);
    var first_item = page_index*itemsperpage;
    for (var i=0;i<itemsthispage;i++){
	var row_ind = ordered_ind[first_item+i];
	items[i] = new Array();
	items[i] = fill_item(row_ind);
    }
    return items;
}

//__________________________________________________________________________
// Get "add to cart" button divs
function get_buttons(){
    var buttons = new Array();
    for (var i=0;i<itemsperpage;i++){
	var prod_i = "prod_" + parseInt(i + 1);
	var iprod = document.getElementById(prod_i);
	buttons[i] = getElementsByClassName("add2cart",'div',iprod)[0];
    }
    return buttons;
}

//__________________________________________________________________________
// Place buttons on page
function place_buttons(){
    var buttons = get_buttons();
    for (var i=0;i<itemsthispage;i++){
	buttons[i].innerHTML = "<form target='paypal' action='https://www.paypal.com/cgi-bin/webscr' method='post'><input type='image' src='/images/btn_cart_LG.gif' border='0' name='submit' /><img alt='' border='0' src='/images/blank_1px.gif' width='1' height='1' /><input type='hidden' name='add' value='1' /><input type='hidden' name='cmd' value='_cart' /><input type='hidden' name='business' value='alt.current@gmail.com' /><input type='hidden' name='item_name' class='button_title' value='' /><input type='hidden' name='item_number' class='button_sku' value='' /><input type='hidden' name='amount' class='button_price' value='' /><input type='hidden' name='weight' class='button_weight' value='' /><input type='hidden' name='no_shipping' value='0' /><input type='hidden' name='no_note' value='1' /><input type='hidden' name='currency_code' value='USD' /><input type='hidden' name='lc' value='US' /><input type='hidden' name='bn' value='Alt-Current_AddToCart_WPS_US' /></form>";
    }
    return 0;
}

//__________________________________________________________________________
// Fill in the purchase button information
function fill_buttons(items){
    var buttons = get_buttons();
    for (var i=0;i<itemsthispage;i++){
	var button_title = getElementsByClassName("button_title",'input',buttons[i])[0];
	button_title.value = items[i]['title']+" by "+items[i]['author'];
	var button_sku = getElementsByClassName("button_sku",'input',buttons[i])[0];
	button_sku.value = items[i]['sku'];
	var button_price = getElementsByClassName("button_price",'input',buttons[i])[0];
	button_price.value = parseFloat(items[i]['price']).toFixed(2);
	var button_weight = getElementsByClassName("button_weight",'input',buttons[i])[0];
	button_weight.value = parseFloat(items[i]['weight']).toFixed(2);
    }
    return 0;
}

//__________________________________________________________________________
// get document product nodes
function get_prods(){
	 var prods = new Array();
	 for (var i=0;i<itemsperpage;i++){
	     prods[i] = new Array(5);
	     var prod_i = "prod_" + parseInt(i + 1);
	     var iprod = document.getElementById(prod_i);
	     prods[i]['title'] = getElementsByClassName("title",'div',iprod)[0];
	     prods[i]['author'] = getElementsByClassName("author",'div',iprod)[0];
	     prods[i]['desc'] = getElementsByClassName("desc",'div',iprod)[0];
	     prods[i]['price'] = getElementsByClassName("price",'div',iprod)[0];
	     prods[i]['thumb'] = getElementsByClassName("thumbnail",'img',iprod)[0];
	 }
	 return prods;
}

//__________________________________________________________________________
// Print a nicely formatted date
function get_nice_date(ugly_date){
    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";
    var tmp = ugly_date.split('T');
    var tmp2 = tmp[0].split('-');
    var nice_date = month[tmp2[1]-1]+" "+tmp2[0];
    return nice_date;
}

//__________________________________________________________________________
// Simplify a string (e.g. a title)
function simplify_string(orig_string){
    return orig_string.toLowerCase().replace(/ /g,"_").replace(/\'/g,"").replace("...","").replace(/\,/g,"").replace(/\:/g,"").replace(/\[/g,"").replace(/\]/g,"").replace(/\(/g,"").replace(/\)/g,"").replace("#","issue_").replace("&","and").replace(/\//g,"_").replace(/\./g,"");
}

//__________________________________________________________________________
// Fill in the page
function fill_page(){
    // get the array of item information
    var items = new Array(itemsthispage);
    items = get_items();
    // place and fill the purchase buttons
    place_buttons();
    fill_buttons(items);
    // get array of products in the document
    var prods = new Array(itemsthispage);
    prods = get_prods();
    // fill the products' information
    for (var i=0;i<itemsthispage;i++){
	// title
	prods[i]['title'].innerHTML = items[i]['title'];
	// author
	prods[i]['author'].innerHTML = "by";
	var auth1 = items[i]['author'].split(';');
	for (var j=0;j<auth1.length;j++){
	    if (j>0){ // for multiple authors
		if (j==auth1.length-1)
		    prods[i]['author'].innerHTML += " and ";
		else
		    prods[i]['author'].innerHTML += ", ";
	    }
	    var auth2 = auth1[j].split(',');
	    for (var k=auth2.length-1;k>=0;k--)
		prods[i]['author'].innerHTML += " " + auth2[k];
	}
	// short description
	prods[i]['desc'].innerHTML = items[i]['short_desc'];
	// price
	if (items[i]['outofprint'] != 'Yes' && items[i]['price'] != ''){ // if NOT out of print and price is listed
	    prods[i]['price'].innerHTML = "$" + 
		parseFloat(items[i]['price']).toFixed(2);
	}
	else if (items[i]['outofprint'] == 'Yes' || items[i]['price'] == ''){ // if out of print or price is not listed
	    prods[i]['price'].innerHTML = "Out Of Print";
	    var buttons = get_buttons();
	    buttons[i].innerHTML = ''; // clear purchase button
	}
	// picture
	var picture = simplify_string(items[i]['title']) + ".jpg";
	prods[i]['thumb'].setAttribute("src","/images/book_thumbs/thumb_" + picture);
	// page counter
	var current_page = document.getElementById("page_current");
	current_page.innerHTML = "| page " + 
	    parseInt(page_index+1) + " (of " + npages + ") |";
    }
    return 0;
}

//__________________________________________________________________________
// Clean up page
function clean_page(){
    var titles  = getElementsByClassName('title','div',document);
    var authors = getElementsByClassName('author','div',document);
    var descs   = getElementsByClassName('desc','div',document);
    var prices  = getElementsByClassName('price','div',document);
    var thumbs  = getElementsByClassName('thumbnail','img',document);
    var buttons = getElementsByClassName('add2cart','div',document);
    for (var i=0;i<itemsperpage;i++){
	titles[i].innerHTML  = '';
	authors[i].innerHTML = '';
	descs[i].innerHTML   = '';
	prices[i].innerHTML  = '';
	thumbs[i].setAttribute("src","/images/blank_1px.gif");
	buttons[i].innerHTML = '';
    }
    return 0;
}

//__________________________________________________________________________
// Check that the page index is in bounds
function check_index(){
	 if (page_index>npages-1)
	    page_index = page_index%npages;
	 if (page_index<0)
	    page_index = (npages+page_index);
	 return 0;
}

//__________________________________________________________________________
// Display the given page
function display(){
	 check_index();
	 clean_page();
	 itemsthispage = get_itemsthispage();
      	 fill_page();
	 return 0;
}

//__________________________________________________________________________
// Display functions
function initDisplay(){page_index=0; globalInit(); display();}
function displayNext(){page_index++; display();}
function displayLast(){page_index--; display();}

//__________________________________________________________________________
// go to the clicked product's page
function gotoprod(node){
    var grandparent = node.parentNode.parentNode;
    var title = getElementsByClassName("title",'div',grandparent)[0].innerHTML.replace("amp;","");
    var new_url = "http://alt-current.com/pp/pp_item.html#"+simplify_string(title);
    window.open(new_url);
    return 0;
}
