/** 
 * When the checkbox is set to true on the HTML page, this functions triggers and add/remove the product id to the compare array
 */
var items = new Array();

function setItemtoCompare(event){
	event = event || window.event; 
	var chk = event.target || event.srcElement; 	
	
	if (chk.checked == true)								/* ADD the product to the compare array */
		items[items.length]=chk.name;			
	else													/* the product was already in the compare array: find and REMOVE */
		for(i in items)								
			if (items[i]==chk.name) 			
		    	items.splice(i,1);
}


/** 
 * Start the compare popup:
 *		- see if any items have been added to the compare array
 *		- create a wireframe to display data
 *		- replenish the wireframe with the compare data
 *		- display the compare
 */
var displayed = 0; 
var wireframe = null;
function startCompare(){
	if (items.length > 1){
		displayed = items.length;
		wireframe = createWireframe();				/* very IMPORTANT: set global variable with referred wireframe */
		loadCompareData();
		
		//document.getElementsByTagName("body")[0].appendChild(wireframe);	
		
		displayCompare(wireframe);
	}
	else 
		alert('Please select 2 or more items to compare');
}


/**
 * 	Creates a Wireframe with the following format:
 *	<div id="comparewrapper">
 *		<div id="comparewireframe">
 *			<div id="comparetop"><a href="javascript:Page(1)" class="compareexit" title="exit compare">Exit</a></div>
 *			<div id="comparedata">
 *				<table class="comparetabledata" align="center" border="0" cellspacing="0" cellpadding="0">
 *					<!-- first COLUMN of labels for each row of data -->
 *				<table>
 *			</div>
 *		</div>x
 *	</div>
 */
var compareRowsClass = 'firstRowColumn';
var numRows = 0;
function createWireframe(){

	var cwrapp = document.createElement('div');										
	cwrapp.id = 'comparewrapper';
	
		var cpwf = document.createElement('div');									/* create the wireframe div object */
		cpwf.id = 'comparewireframe';
	
			var cptop = document.createElement('div');
			cptop.id = 'comparetop';
			cptop.innerHTML = '<span class="comparetoptitle">Product Comparison</span><a href="javascript:removeCompare()" class="compareexit" title="exit compare">Exit</a>';
	
			var cpdata = document.createElement('div');
			cpdata.id = 'comparebottom';
	
				var tbl = document.createElement('table');
				tbl.id = 'comparetabledata';
	
					var tblBody = document.createElement("tbody");		
	
						appendRow(tblBody, compareRowsClass, 'removeitem', '');		/* first row will be used for the remove button */
						numRows++;
	
						/* get first item to compare and create first column of labels */ 
						var firstitem = document.getElementById('comparedata_'+items[0]);
						if(firstitem){
							var comparedivs = firstitem.getElementsByTagName('div');
							for (var d in comparedivs){
								if (comparedivs[d].className == 'cdata' || comparedivs[d].className == 'clabel'){
									appendRow(tblBody, compareRowsClass, 'cfirstcol', ((comparedivs[d].className == 'clabel')?comparedivs[d].title:''));
									numRows++;								
								}
							}	
						}				
	
					tbl.appendChild(tblBody);
		   
				tbl.setAttribute("border", "0");									/* set attributes for table */
				tbl.setAttribute("cellspacing", "0");
				tbl.setAttribute("cellpadding", "0");		
			
			cpdata.appendChild(tbl);
				
		cpwf.appendChild(cptop);
		cpwf.appendChild(cpdata);
			
	cwrapp.appendChild(cpwf);
	return (cwrapp);
}


/**
 *	helper function to create rows
 */
function appendRow(tableBody, rowClass, cellClass, cellinnerHTML){
	var row = document.createElement('tr');
	if (rowClass != 'undefined')
		row.className = rowClass;
	var cell = document.createElement('td');
	if (cellClass != 'undefined')
		cell.className = cellClass;
	if (cellinnerHTML != 'undefined')
		cell.innerHTML = cellinnerHTML;
	cell.setAttribute('vAlign','top');	
	row.appendChild(cell);
	tableBody.appendChild(row);
}


/**
 *	LOADS the data of the items to compare into the wireframe
 */
function loadCompareData() {
	
	if(!wireframe) return;
	var auxRows = wireframe.getElementsByTagName("table")[0].getElementsByTagName("tr");	/* get all the rows in wireframe */

	/* 	Filter rows that are not part of the Compare Wireframe. 
		This is specifically for solving problem with quantity pricing tables has appeared in Bamboo F. */
	var rows = [];
	for (var r=0; r < auxRows.length; r++)
		if (auxRows[r].className == compareRowsClass)
			rows[rows.length] = auxRows[r];
			

	for(var i=0; i < items.length; i++){													/* while there are items to display */
		var comparedata = document.getElementById('comparedata_'+items[i]);					/* retrieve divs from DOM with data */
		if(comparedata){
			
			var row_count = 0;		/* data is entered in each row by position, so we need a varible to keep track of the rows fulfilled */
	
			/* first remove button */
			var removeButton = '<a href="javascript:removeItem(\'td_'+i.toString()+'\')" title="remove item" class="compareremove">remove</a>';
			insertData(rows, removeButton, row_count++, i);

			var comparedivs = comparedata.getElementsByTagName('div');
			for (var d in comparedivs){
				if (comparedivs[d].className == 'cdata' || comparedivs[d].className == 'clabel'){
					insertData(rows, comparedivs[d].innerHTML, row_count++, i);
				}				
			}
		}	
	}
	hideEmptyRows(rows);
}


/**
 *	helper function to insert data 
 */
function insertData(rows, html, rownum, i) {
	var td = document.createElement("td");													// create a new TD
	td.setAttribute('vAlign','top');
	td.id="tr"+rownum.toString()+"_td_"+i.toString();										// assign ID, allows to remove it later 
	td.className = "compareValues";															// assign a class for CSS styles
	td.innerHTML = html;																	// write the HTML  inside the TD
	rows[rownum].appendChild(td);															// put the new td in the cell array
}


/**
 * remove an item from the compare wireframe
 */
function removeItem(td_id) {
	for (var r = 0; r < numRows; r++) {
		var cell = document.getElementById("tr" + r.toString() + "_" + td_id);
		if (cell) {
			cell.innerHTML = ' ';
			removeObject(cell);
		}
	}
	displayed--;
	document.getElementById('comparewireframe').style.width = (110 + 160*displayed)+'px';		/* set width of the wireframe */

	if (displayed < 2) 											/* NO sense in showing the compare if there is only one product */
 		removeCompare();						
}


/**
 * Hide every row that didn't load actual values 
 */
function hideEmptyRows(rows){
	var count = 0, cells, empty;

	for (var r=2; r < rows.length; r++) {
		
		cells = rows[r].getElementsByTagName("td");
		empty = true;
		
		for (var c=1; c < cells.length; c++)
			if (!(/^\s*$/.test(cells[c].innerHTML)))										// check if empty
				empty = false;																// cell needs to have some child and not blank
		
		/* only if it is a row of the wireframe (not of inner tables) */
		if(rows[r].className.indexOf(compareRowsClass) > -1){
			if (empty)
				removeObject(rows[r]);
			else
		    	rows[r].className += (count++%2==0)?" even":" odd";							// assign a class for CSS styles			
		} 
	}
}


/**
 * 	Remove the compare from the DOM
 */ 
function removeCompare(){

	visibilitySelectsIE(true);

	if(document.getElementById('blur'))
	 	removeObject(document.getElementById('blur'));
	if(wireframe){
		wireframe.innerHTML = '';
	 	removeObject(wireframe);
	}
}
	
 
/**
 * 	Show blur screen and display compare wireframe
 */ 
function displayCompare(){

	visibilitySelectsIE(false);
	
	div = document.createElement("div");
	div.id = "blur";
	div.onclick = function(){removeCompare();};

	var h=document.body.offsetHeight;															/* calculate the size of the blur */
	var h_a=document.body.scrollHeight;
	h = ( h > h_a)?h:h_a;									
	var w=document.body.offsetWidth;

/*	div.style.width = w+'px';	*/		/* better to set the width by styles */
	div.style.height = h+'px';

	window.scroll(0,0);
	document.getElementsByTagName("body")[0].appendChild(wireframe);	
	document.getElementsByTagName("body")[0].appendChild(div);

	wireWidth = 110 + 160*displayed;															/* set width of the wireframe */
	document.getElementById('comparewireframe').style.width = wireWidth+'px';					
	
	var leftDif = w-wireWidth;
	var left = (leftDif > 0)?(leftDif/2):1;
	if (/MSIE/.test(navigator.userAgent))	
		document.getElementById('comparewrapper').style.left = left+'px';						/* align problem on IE */
	else		
		document.getElementById('comparewireframe').style.marginLeft = left+'px';
}


/* hide selects on IE */
function visibilitySelectsIE(flag){
	var n = navigator.userAgent;
	if (/MSIE/.test(n)){
		selects = document.getElementsByTagName("select");	
		for (var i=0;i < selects.length;i++)
			selects[i].style.visibility = (flag)?"visible":"hidden";
	}
}

/* remove an object from the DOM */
function removeObject(obj){
	if (obj)
		obj.parentNode.removeChild(obj);
}




//---- Cross-browser add/remove event functions --------------------------
function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    return (obj.attachEvent("on"+evType, fn));
  } else 
	return false;
}
function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    return (obj.detachEvent("on"+evType, fn));
  } else 
	return false;
} 
//------------------------------------------------------------------------

