var items = [];
function setItem(item) {
	item.realPrice = item.price;
	item.price = formatPrice(item.price);
	items[items.length] = item;
	
}
function updatePagination() {
	try {
		if (currentPaginationPage < paginationAs.length) {
		
			callPage(paginationAs[currentPaginationPage]);
			currentPaginationPage++;
		
		}
	} catch (e) { }
}
function ajaxResponse() {
	try{
		if(xmlHttp.readyState == 4) {
			if(xmlHttp.status == 200) {
				var rStr = xmlHttp.responseText;
				
				try {
					parserPaginationAjaxResponse(rStr);
				
					updatePagination();
					updateItemTable();
					
				} catch (e) { alert(e); }
			}
		}
	} catch (e) { }
}
function parserPaginationAjaxResponse(rStr) {
	
	var names = rStr.split('START_' + 'NAME');
	var ids = rStr.split('START_' + 'ID');
	var prices = rStr.split('START_' + 'PRICE');
	var htmls = rStr.split('START_' + 'HTML');
	var categories = rStr.split('START_' + 'CATEGORIES');
	
	for (var i=1; i < names.length; i++) {
		var itemId = ids[i].substring(0, ids[i].indexOf('END_' + 'ID'));
		var itemName = names[i].substring(0, names[i].indexOf('END_' + 'NAME'));
		var itemPrice = prices[i].substring(0, prices[i].indexOf('END_' + 'PRICE'));
		var itemCategories = categories[i].substring(0, categories[i].indexOf('END_' + 'CATEGORIES'));
		
		var itemHTML = htmls[i].substring(0, htmls[i].indexOf('END_' + 'HTML'));
		itemHTML = itemHTML.substring('</span>'.length, itemHTML.lastIndexOf('<span'));
		
		var item = new Object(); 

		item.id = itemId;
		item.name = itemName;
		item.price = itemPrice;
		item.categories = itemCategories;

		item.htmlItem = itemHTML;

		setItem(item);
		
	}
}
function callPage(pageLink) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Your browser does not support AJAX!");
		return;
	}
	xmlHttp.onreadystatechange=ajaxResponse;
	xmlHttp.open("GET", pageLink, true);
	xmlHttp.send(null);			
}
function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}
function getPaginationAs() {
	try {
		var tds = document.getElementsByTagName("td");
                var tr = null;
		for (var i=0; i<tds.length; i++) {
			if (tds[i].innerHTML.indexOf("Results 1-") == 0) {
				tr = tds[i].parentNode;
			}
		}
                if (tr != null) {
                    tr.parentNode.style.display = 'none';
                    var as = [];
                    for (var i=0; i < tr.getElementsByTagName('a').length-1; i++) {
                        as[i] = tr.getElementsByTagName('a')[i];
                    }
                    return as;
                }
	} catch (e) { }
}
function sortItems(itemsToSort) {
	var itemsToShow = [];
	
	var sortOptions = document.getElementById('sortBySelectButton').value;
	
	if (sortOptions == 'bestSellers') {
		for (var i=0; i < itemsToSort.length; i++) {
			itemsToShow[i] = itemsToSort[i];
		}
		return itemsToShow;
	}
	
	var itemsToSortAux = [];
	for (var i=0; i < itemsToSort.length; i++) {
		itemsToSortAux[i] = [];
		if ((sortOptions == 'alphabeticalAtoZ') || (sortOptions == 'alphabeticalZtoA')) {
			itemsToSortAux[i][0] = itemsToSort[i].name;
			
		} else if ((sortOptions == 'priceHighToLow') || (sortOptions == 'priceLowToHigh')) {
			itemsToSortAux[i][0] = itemsToSort[i].price;
			
		}
		
		itemsToSortAux[i][1] = itemsToSort[i].id;
	}
	
	itemsToSortAux = itemsToSortAux.sort();
	
	if ((sortOptions == 'alphabeticalZtoA') || (sortOptions == 'priceHighToLow')) {
		var itemsToSortAux2 = [];
		for (var i=itemsToSortAux.length-1; 0 <= i; i--) {
			itemsToSortAux2[itemsToSortAux2.length] = itemsToSortAux[i];
		}
		itemsToSortAux = itemsToSortAux2;
	}
	
	for (var i=0; i < itemsToSortAux.length; i++) {
		itemsToShow[i] = getItem(itemsToSort, itemsToSortAux[i][1]);
	}			
	
	return itemsToShow;
}
function getItem(itemsSource, itemId) {
	for (var i=0; i < itemsSource.length; i++) {
		if (itemsSource[i].id == itemId) {
			return itemsSource[i];
		}
	}
	return new Object();			
}
function filterItems(items) {
	var priceNarrowSelect = document.getElementById('priceNarrow');
	var narrowcatSelect = document.getElementById('categoryNarrow');
	
	var itemsValidated = [];
	
	for (var i=0; i < items.length; i++) {
		try {
			if ((narrowcatSelect.value == 'ALL') || (items[i].categories.indexOf(narrowcatSelect.value) != -1)) {
				if (priceNarrowSelect.value == 'ALL') {
					itemsValidated[itemsValidated.length] = items[i];
				} else {
					var minPrice = parseInt(priceNarrowSelect.value.split('-')[0]);
					var maxPrice = parseInt(priceNarrowSelect.value.split('-')[1]);
					var itemValue = Math.floor(items[i].price);
					//alert(minPrice+'\n'+maxPrice+'\n'+itemValue+'\n')
					if ((minPrice <= itemValue) && (itemValue <= maxPrice)) 
						itemsValidated[itemsValidated.length] = items[i];
				}
			}
				
		} catch (e) { }
	}
	
	return itemsValidated;
}
function updateItemTable() {
	var table = document.getElementById('item_list');

	emptyTable(table);

	var itemsToShow = filterItems(items);
	itemsToShow = sortItems(itemsToShow);
	
	for (var i=(currentTable*ROWS_QTY); i < itemsToShow.length && i < ((currentTable+1)*ROWS_QTY); i++) {
		var tr = table.insertRow(table.rows.length);
		var td = tr.insertCell(tr.cells.length);
		td.className = "item_cell";
		td.innerHTML = itemsToShow[i].htmlItem;
	}


	pageCount = Math.floor(itemsToShow.length / ROWS_QTY); 
	pageCount = pageCount + ((itemsToShow.length % ROWS_QTY > 0)? 1: 0);

	var paginationHTML = '<span id="showing">Showing ' + ((currentTable*ROWS_QTY+1));
	var topQtyItems = Math.min(((currentTable+1)*ROWS_QTY), itemsToShow.length);
	paginationHTML += ' to ' + topQtyItems + ' of: ' + itemsToShow.length + '</span><span><a href="javascript:previousPage();">< Prev</a></span>';
	
	for (var i=0; i < pageCount; i++) {
		if (i == currentTable) {
			selectedClass = ' class="selectedPage" ';
		} else {
			selectedClass = ' class="unselectedPage" ';
		}
		paginationHTML += '<span><a ' + selectedClass + ' href="javascript:movePage(' + i + ');">' + (i+1) + '</a></span>';
	}
	paginationHTML += '<span><a href="javascript:nextPage();">Next ></a></span>';
	
	if (1 < pageCount) {
		document.getElementById('pageResultsTop').innerHTML = paginationHTML;
		document.getElementById('pageResultsButton').innerHTML = paginationHTML;			
		
		document.getElementById('typeAllTop').style.display = 'inline';
		document.getElementById('typeAllButton').style.display = 'inline';
		
	} else {
		document.getElementById('pageResultsTop').innerHTML = '';
		document.getElementById('typeAllTop').style.display = 'none';
		
		document.getElementById('pageResultsButton').innerHTML = '';			
		document.getElementById('typeAllButton').style.display = 'none';
	}
}
function previousPage() {
	if (currentTable > 0) {
		currentTable--;
		updateItemTable();			
	}
}
function nextPage() {
	if (currentTable < (pageCount-1)) {
		currentTable++;
		updateItemTable();			
	}
}
function movePage(newPage) { 
	currentTable = newPage;
	updateItemTable();
}
function sortByTopChange() {
	var sortBySelectTop = document.getElementById('sortBySelectTop');
	var sortBySelectButton = document.getElementById('sortBySelectButton');
	
	sortBySelectButton.value = sortBySelectTop.value;
	
	currentTable = 0; 
	updateItemTable();
}
function sortByButtonChange() {
	var sortBySelectTop = document.getElementById('sortBySelectTop');
	var sortBySelectButton = document.getElementById('sortBySelectButton');
	
	sortBySelectTop.value = sortBySelectButton.value;
	
	currentTable = 0;
	updateItemTable();
}	function formatPrice(priceToFormat) {
    var priceFormatted = priceToFormat.substring(1, priceToFormat.length);
    var ceroToAdd = 5;
    if (priceFormatted.indexOf('.') != -1) {
        ceroToAdd -= priceFormatted.indexOf('.');
    } else {
        ceroToAdd -= priceFormatted.length;
    }
    for (var i=0; i < ceroToAdd; i++) {
        priceFormatted = '0' + priceFormatted;
    }
    return priceFormatted;
}
function emptyTable(table) {
	for (;table.rows.length > 0;) {
		table.deleteRow(0);
	}
}
function updateNarrowing() {
	var categoriesValues = [];
	
	for (var i=0; i < items.length; i++) {
		try {
			var categories = items[i].categories.split(',');
			for (var c=0; c < categories.length; c++) {
				if (notExist(categoriesValues, categories[c])) {
					categoriesValues[categoriesValues.length] = categories[c];
				}
			}
		} catch (e) { }
	}
	var narrowcatSelect = document.getElementById('categoryNarrow');
	for (var i=0; i < categoriesValues.length; i++) {
		try {
			var catLabel = categoriesValues[i].substring(categoriesValues[i].lastIndexOf(':')+2, categoriesValues[i].length);
			if (catLabel.length > 3)
				narrowcatSelect.options[narrowcatSelect.options.length] = new Option(catLabel, categoriesValues[i]);
		} catch (e) { }
	}
	
	var priceJumpQty = 4;
	
	var minPrice = 999;
	var maxPrice = 0;
	
	for (var i=0; i < items.length; i++) {
		var currentPrice = parseFloat(items[i].price);
		if (currentPrice < minPrice) {
			minPrice = currentPrice;
		}
		if (maxPrice < currentPrice) {
			maxPrice = currentPrice;
		}
	}
	
	var priceNarrowSelect = document.getElementById('priceNarrow');
	
	minPrice = Math.floor(minPrice);
	maxPrice = Math.ceil(maxPrice);
	
	try {
		var jump = Math.ceil((maxPrice - minPrice)/priceJumpQty);
		for (var i=0; i < priceJumpQty; i++) {
			var startJump = minPrice + (jump * i);
			var jumpLabel = '$'+startJump+' - '+'$'+(startJump+jump-1) + ' (' + getItemQty(items, startJump, (startJump+jump-1)) + ')';
			var jumpValue = startJump+'-'+(startJump+jump-1);
			priceNarrowSelect.options[priceNarrowSelect.options.length] = new Option(jumpLabel, jumpValue);
		}
	} catch (e) { }
}
function getItemQty(items, minPrice, maxPrice) {
	var itemsFound = 0;
	
	for (var i=0; i < items.length; i++) {
		try {
			var itemValue = Math.floor(items[i].price);
			if ((minPrice <= itemValue) && (itemValue <= maxPrice)) 
				itemsFound++;
				
		} catch (e) { }
	}
	
	return itemsFound;
}

function notExist(vector, value) {
	for (var i=0; i < vector.length; i++) { 
		if (vector[i] == value) {
			return false;
		}
	}
	return true;
}
function viewTypePage() {
	document.getElementById('typePageTop').className = 'selectedPage';
	document.getElementById('typeAllTop').className = 'unselectedPage';		
	document.getElementById('typePageButton').className = 'selectedPage';
	document.getElementById('typeAllButton').className = 'unselectedPage';		
	
	ROWS_QTY = DEFAULT_ROWS_QTY;

	updateItemTable();
}
function viewTypeAll() {
	document.getElementById('typePageTop').className = 'unselectedPage';
	document.getElementById('typeAllTop').className = 'selectedPage';		
	document.getElementById('typePageButton').className = 'unselectedPage';
	document.getElementById('typeAllButton').className = 'selectedPage';		
	
	ROWS_QTY = 999;
	
	currentTable = 0;
	
	updateItemTable();
}
function getValueFromUrlSearch2(){
	//Capture  URL
	var callingURL =document.URL;

	//separate parameters
	var idx = callingURL.indexOf('?');
	if (idx!=-1){
		var cgiString = callingURL.substring(idx+1,callingURL.length);
		
		//Eliminate # if exists
		if (cgiString.indexOf('#')!=-1){
			cgiString=cgiString.slice(0,cgiString.indexOf('#'));
		}
		//separate cgiString 
		var arrayParams=cgiString.split("&");
		
		//search the array, 				
		var searchFound = false;
		for (var j=0; j<arrayParams.length && !searchFound; j++){
			var itemValue = arrayParams[j].split("="); 
			// check if the parameter is from the url 
			if (itemValue[0].toLowerCase()=="search"){
				//check the search value
				var plus = itemValue[1].indexOf("+");
				if (plus!=-1){
					var aux=itemValue[1].split("+");
					var auxValue = aux[0];
					for (var i=1;i<aux.length;i++){
						auxValue = auxValue + "&#160;" + aux[i] ;			
					}
				}
				else{
					auxValue=itemValue[1];
				}					
				var spn = document.getElementById("spnUrlItem2") ;
				spn.innerHTML = auxValue;
				// en the cycle with the flag searchFound in true
				searchFound = true;
			}
		}
	}	
}