//onload functions
function onloads() {
	//setFocus();
	//RequestTrCode();
	
	new Ajax.Autocompleter("searchInput", "autocomplete_choices", "drop_search.php", {
		//paramName: "value", 
		//updateElement: addItemToList, 
		//indicator: 'indicator1',
		minChars: 3
	});
	
	preLoadImages();
}


function preLoadImages() {
	//search button
	searchButtonOnHover = new Image();
	searchButtonOnHover.src = 'images/template/searchOnHover.jpg';
	
	//view bag
	viewBagOnHover = new Image();
	viewBagOnHover.src = 'images/template/viewCartButtonHover.jpg';
	
	//checkout
	checkOutOnHover = new Image();
	checkOutOnHover.src = 'images/template/checkoutButtonHover.jpg';
	
	//compare
	compareOnHover = new Image();
	compareOnHover.src = 'images/template/compareButtonHover.jpg';
	
}

function DoSubmission() {
	document.cart_quantity.submit();
}	



function SetFocus(TargetFormName) {
  var target = 0;
  if (TargetFormName != "") {
    for (i=0; i<document.forms.length; i++) {
      if (document.forms[i].name == TargetFormName) {
        target = i;
        break;
      }
    }
  }

  var TargetForm = document.forms[target];
    
  for (i=0; i<TargetForm.length; i++) {
    if ( (TargetForm.elements[i].type != "image") && (TargetForm.elements[i].type != "hidden") && (TargetForm.elements[i].type != "reset") && (TargetForm.elements[i].type != "submit") ) {
      TargetForm.elements[i].focus();

      if ( (TargetForm.elements[i].type == "text") || (TargetForm.elements[i].type == "password") ) {
        TargetForm.elements[i].select();
      }

      break;
    }
  }
}


/*
brand description on the index_products.tpl.php page. 
*/
function toggleBrandDescription(brandName) {
	//display
	if($('brandDescription').style.height == '130px') {
		$('brandDescription').style.height='';
		$('brandDescription').style.overflow='';
		$('brandReadMore').innerHTML='<<< Read less about '+brandName;
	//minimize
	} else {
		$('brandDescription').style.height='130px';
		$('brandDescription').style.overflow='hidden';
		$('brandReadMore').innerHTML='Read more about '+brandName+' >>>';
	}
}


//make sure there is atleast one product with a quantity of 1 or greater being added to the bag.
function validateAddToBagQuantity() {
	var selects = $$('select.productQuantity');
	var numberOfSelects = selects.length;
	for(i=0; i<numberOfSelects; i++) {
		if(selects[i].options[selects[i].selectedIndex].value > 0) {
			return true;
		}
	}
	alert('Please select a quantity');
	return false;
}

//open the product compare page
function compareProducts() {
	window.open('productCompare.php','Compare_Products','scrollbars=1, height=700, width=840');
}


//add product to compare 
//make ajax request to php page that will save product id in session and will return the product name
//returns - product name. 
function addProductToCompare(productId) {
	
	new Ajax.Request('productCompare.php?action=add&productId='+productId, {
			method: 'get',
			onSuccess: function(compareAddResponse) {
			
				//check for response
			if (compareAddResponse.responseText) {
				//add product name to compare box
				if($('productCompareList')) {
					
					//decode json string returned
					var productInfo = compareAddResponse.responseText.evalJSON();
					
					//insert the html on the page
					$('productCompareList').insert({ bottom: '<div style="display:none;" class="productCompareItem" id="productCompare_'+productInfo.productId+'"><div class="productCompareItemRow"><div class="productCompareItemCell-ProductName">'+productInfo.productNameLink+'</div><div class="productCompareItemCell-Remove"><img src="images/template/productCompareRemove.gif" onclick="removeCompareProduct('+productInfo.productId+')"></div></div>'});
										
					//must have a function like this before the highlight so the highlight works in IE
					new Effect.Appear('productCompare_'+productInfo.productId);
					
					//highlight the new product
					new Effect.Highlight('productCompare_'+productInfo.productId, { startcolor: '#faba5a', endcolor: '#ffffff' });	
										
					//hide "no compare items" message if necessary
					toggleNoCompareItemsMessage();
					
					//show or hide the compare button if necessary
					toggleCompareButton();
				}
			}
		}
	});	
}

//remove a product from the compare box and make ajax request to remove it from the php session.
function removeCompareProduct(productId) {
	if(productId) {
		//both of these here so something looks decent in both ie and ff. slideup doesn't work in ff... probably b/c of the nested divs.
		new Effect.Fade('productCompare_'+productId);
		new Effect.SlideUp('productCompare_'+productId, {duration: 1.5});
		
		//ajax request will return 1 for success or 0 for failure
		new Ajax.Request('productCompare.php?action=remove&productId='+productId, {
				method: 'get',
				onSuccess: function(compareRemoveResponse) {
				//do nothing
			}
		});	
		
		//remove div container
		removeProductCompareDiv(productId);
		
		//display "no compare items" message if necessary
		toggleNoCompareItemsMessage();
		
		//show or hide the compare button if necessary
		toggleCompareButton();
	}
}

//remove product div after it has been removed by user
function removeProductCompareDiv(productId) {
	//get the parent element
	var parentContainer = document.getElementById('productCompareList');
	
	//find element to remove
	var productDiv = document.getElementById('productCompare_'+productId);
	
	//remove
	parentContainer.removeChild(productDiv);
}

//return number of productCompareItem divs in the compare box
function countProductCompareItems() {
	return $('productCompareList').getElementsByClassName('productCompareItem').length;
}

//toggle visibility of the compare button
function toggleCompareButton() {
	//count number of products in the compare box
	var numProducts = countProductCompareItems();
	
	//if there are two or more products to compare, display the button.
	if(numProducts >= 2) {
		new Effect.Appear('compareButton');
		//$('compareButton').style.display = '';
	} else {
		new Effect.Fade('compareButton');
		//$('compareButton').style.display = 'none';
	}
}


//toggle visibility of the noCompareItems message
function toggleNoCompareItemsMessage() {
	
	//count number of products in the compare box
	var numProducts = countProductCompareItems();
	
	//if there are no products to compare, display message.  otherwise, hide it.
	if(numProducts >= 1) {
		new Effect.BlindUp('noCompareItems');
	} else {
		new Effect.BlindDown('noCompareItems');
	}
}

//display modal box verify delivery address overlay box
function verifyDeliveryAddress() {
	Modalbox.show($('verifyDeliveryAddress'), {title: 'Terms and Conditions', width: 540});;
	return false;
}

function submitCheckoutConfirmationAfterAddressVerification() {
	//submit confirmation form
	document.checkout_confirmation.submit(); 
	
	//deactivate modal box so they can't change things. 
	Modalbox.deactivate();
}

//display modal box contact form submission overlay box
function displayFaqPopup() {
	Modalbox.show($('faqPopup'), {title: 'Is your question an FAQ?', width: 450});;
	return false;
}

//used on product compare page.  found at http://codingforums.com/showthread.php?t=83993
document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
	var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
	return $A(children).inject([], function(elements, child) {
		var attributeValue = child.getAttribute(attribute);
		if(attributeValue != null) {
			if(!value || attributeValue == value) {
				elements.push(child);
			}
		}
		return elements;
	});
}


//used by select boxes for brand and category on top sellers page. redirects using selected params
function redirectTopSellerSelection() {
	//get value of days
	var days = $('selectedDateRange').innerHTML;
	
	//get value of brand
	var brand = $('brand').options[$('brand').selectedIndex].value;
	
	//get value of category
	var category = $('category').options[$('category').selectedIndex].value;
	
	window.location='topsellers.php?days='+days+'&brand='+brand+'&category='+category;	
}
