//drop downs 
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");

	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}

		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// product tools roll over
sfHover2 = function() {
	if(document.getElementById("productTools")){
		var sfEls = document.getElementById("productTools").getElementsByTagName("DIV");
	
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover2";
			}
	
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover2\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover2);

//More images roll over
sfHover2 = function() {
	if (document.getElementById("moreImagesBox")){
		var sfEls = document.getElementById("moreImagesBox").getElementsByTagName("DIV");
	
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover2";
			}
	
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover2\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover2);

// color roll over
sfHover3 = function() {
	if (document.getElementById("colorsBox")){
		var sfEls = document.getElementById("colorsBox").getElementsByTagName("P");
	
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover3";
			}
	
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover3\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover3);

// item page color roll over
sfHover7 = function() {
	if(document.getElementById("optionsBlock")){
		var sfEls = document.getElementById("optionsBlock").getElementsByTagName("P");
	
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover7";
			}
	
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover7\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover7);

//////////////////////////////////////////////////////////////////////////////////////
// AJAX SETUP AND OUTPUT FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////

// JavaScript Document
//Get HTTP Object for AJAX Processing
function getHTTPObject(){
	if (window.ActiveXObject) 
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		return new XMLHttpRequest();
	else {
		alert("Your browser does not support AJAX.");
		return null;
	}
}

// setOutput()
// Loads the output of an AJAX call to a element with the given id
// args: id - id of element to load output into, ajaxHandle - AJAX object 
function setOutput(id, ajaxHandle){
	if(ajaxHandle.readyState == 4){
		if( ajaxHandle.responseText != null && ajaxHandle.responseText != "" ){
			document.getElementById(id).innerHTML = ajaxHandle.responseText;
		}
	}
}

// runAJAXasync()
// Runs a 'asyncronous' AJAX call and load the out put to a given location
// args: pageName - page name of AJAX script, outputID - id of element to load output into
//		 argsArray - array of arguments for AJAX call
function runAJAXasync(pageName,outputID,argsArray){
	var urlArgs = "";
	
	//Build string of arguments for AJAX call
	for(var i=0;i<argsArray.length;i++){
		urlArgs += argsArray[i][0] + "=" + argsArray[i][1] + "&";
	}
	//Adds date to arguments to force browser to reload the called page
	urlArgs += "pseudoParam="+new Date().getTime();
	
	httpObject = getHTTPObject();
	//Send comment data to submit_comment.php return all comments
	if (httpObject != null) {
		httpObject.open("GET", "/components/scripts/ajax/"+pageName+".php?"+urlArgs, true);
		httpObject.send(null);
		httpObject.onreadystatechange = function () { setOutput(outputID,httpObject); return false; };
	} else {
		document.write('Failed to get httpObject');
	}
}

// runAJAXasync()
// Runs a 'syncronous' AJAX call and load the out put to a given location
// args: pageName - page name of AJAX script, argsArray - array of arguments for AJAX call
function runAJAXsync(pageName,argsArray){
	var urlArgs = "";
	
	//Build string of arguments for AJAX call
	for(var i=0;i<argsArray.length;i++){
		urlArgs += argsArray[i][0] + "=" + argsArray[i][1] + "&";
	}
	//Adds date to arguments to force browser to reload the called page
	urlArgs += "pseudoParam="+new Date().getTime();
	
	httpObject = getHTTPObject();
	//Send comment data to submit_comment.php return all comments
	if (httpObject != null) {
		httpObject.open("GET", "/components/scripts/ajax/"+pageName+".php?"+urlArgs, false);
		httpObject.send(null);
		return httpObject.responseText;
	} else {
		document.write('Failed to get httpObject');
	}
}

//////////////////////////////////////////////////////////////////////////////////////
// END AJAX SETUP AND OUTPUT FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////
// PAGE DISPLAY FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////

//Show div with id
function showDivs(id){
	if( document.getElementById(id) ) { document.getElementById(id).style.display = 'inline'; }
}
//Hide div with id
function hideDivs(id){
	if( document.getElementById(id) ) { document.getElementById(id).style.display = 'none'; }
}

// showHide()
// Shows/Hides element with the given id
// id: num - the id name
function showHide(id){
	if( document.getElementById(id) ) {
		if( document.getElementById(id).style.display == 'none' )
			showDivs(id);
		else
			hideDivs(id);
	}
}

//Desc: Switch tab box display style when tab is clicked
//Args: name - id of clicked tab
function switchTabs(name){
	if( document.getElementById("featBox") ){ document.getElementById("featBox").style.display = "none"; }
	if( document.getElementById("descBox") ){document.getElementById("descBox").style.display = "none"; }
	if( document.getElementById("reviewsBox") ){document.getElementById("reviewsBox").style.display = "none"; }
	if( document.getElementById("colorsBox") ){document.getElementById("colorsBox").style.display = "none"; }
	if( document.getElementById("imagesBox") ){document.getElementById("imagesBox").style.display = "none"; }
	document.getElementById(name).style.display = "inline";
}

// openWindow(url)
// Opens the whats this pop
// args: what - the content to load
function whatsThis(what){
	window.open('/components/popups/whats-this.php?what='+what,'','toolbar=no,location=no,scrollbars=yes,status=no,width=450,height=300,top=30,left=30');
}

// openWindow(url)
// Opens the whats this pop
// args: what - the content to load
function windowOpen(url){
	window.open('/'+url,'','resizable=no,toolbar=no,location=no,scrollbars=yes,status=no,width=625,height=625,top=30,left=30');
}

// openWindow(url)
// Opens the whats this pop
// args: what - the content to load
function windowOpenSize(url,height,width){
	window.open('http://www.briteinc.com/'+url,'','resizable=yes,toolbar=no,location=no,scrollbars=yes,status=no,width='+width+',height='+height+',top=30,left=30');
}


///////////////////////////////////////////////////////////////////////////////////////
// END PAGE DISPLAY FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////
// SAMPLE CART FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////

// sizeup()
// swaps out styles and enlarges the swatch 
// args: handle - the id of the div
function sizeup(handle){
	document.getElementById(handle).className = "abPosOver";
}

// sizedown()
// swaps out styles and shrinks the swatch 
// args: handle - the id of the div
function sizedown(handle){
	document.getElementById(handle).className = "abPos";
}

// removeSample()
// Sends an AJAX call that removes the given sample from the sample cart
// args: sample_id - id of the row to delete, handle - id of the sample div
function removeSample(sample_id,handle){
	var status = "";
	argsArray = new2DArray(2,2);
	
	//Hide the given div
	hideDivs(handle);
	
	//set up arguments for ajax call
	argsArray[0][0] = "sample";
	argsArray[0][1] = "remove";
	argsArray[1][0] = "sample_id";
	argsArray[1][1] = sample_id;
		
	//Run ajax	
	status = runAJAXsync("fabrics_ajax",argsArray);
	
	//There are no sample in the cart redirect to previous page
	if( status == 0 ){
		document.write("<script>window.location='https://www.briteinc.com/secure/sample_cart.php'</script>");
	}
}
///////////////////////////////////////////////////////////////////////////////////////
// END SAMPLE CART FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////
// GENERAL FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////

// addToCart(qtyID,sku_grp_id,item_id,price)
// Add item to shopping cart
// args: qtyID -  the id of the quantity field, sku_grp_id - SKU group id, item_id - the item id, price - the price

// Desc: Add item to cart by sending an AJAX call to add_to_cart.php
function ajaxAddToCart(){
	var returnData = "";
	var num_options = document.getElementById('numOptions').value;
	
	//Set up arguments array
	cartArgs = new2DArray((eval(6)+eval(num_options)),2);
	cartArgs[0][0] = "sku_grp_id";
	cartArgs[0][1] = document.getElementById('skuID').value;
	cartArgs[1][0] = "item_sku";
	cartArgs[1][1] = document.getElementById('itemSKU').value;
	cartArgs[2][0] = "type";
	cartArgs[2][1] = document.getElementById('itemType').value;
	cartArgs[3][0] = "sales_price";
	cartArgs[3][1] = document.getElementById('salesPrice').value;
	cartArgs[4][0] = "qty";
	cartArgs[4][1] = document.getElementById('prodQty').value;
	cartArgs[5][0] = "num_options";
	cartArgs[5][1] = num_options;
	
	//Set up options
	for(var i=0;i<num_options;i++){
		cartArgs[(i+6)][0] = "option"+i;
		cartArgs[(i+6)][1] = document.getElementById('option'+i).value;
	}
	
	//Make item added box invisible / write loading screen
	document.getElementById('itemAddedDiv').innerHTML = "<center><br /><br /><img src='/images/graphics/page-loading.gif' /><br />Loading...</center>";
	
	returnData = runAJAXsync('add_to_cart',cartArgs);
	
	window.setTimeout( function() {
		//Load 'items in cart display' by getting a substring from the begginging of temp to BREAK
		//Load 'item added to cart div' by getting a substring from BREAK to the end of temp
		document.getElementById('cartItems').innerHTML = returnData.substr(0, returnData.indexOf('BREAK') );
		document.getElementById('itemAddedDiv').innerHTML = returnData.substr( (returnData.indexOf('BREAK')+5) );
		
		//Fade in then fade out 'item added to cart' box
		//Set display of 'item added to cart' box to none to kill the links inside of it
		opacity('itemAddedOpacity',0,100,500);
		window.setTimeout("opacity('itemAddedOpacity',100,0,500)", 5000);
		window.setTimeout("document.getElementById('itemAddedOpacity').style.display = 'none';", 7000);
	}
	, 1000);
}


function addToCart(buttonID,qtyID,sku_grp_id,item_id,price){
	var argsArray = new2DArray(6,2);
	var status = "";
	var qty = document.getElementById(qtyID).value;
	
	if( isNumeric(qty) && qty > 0 ){
		//Display loading graphic
		showDivs('addedToCartDiv');
		document.getElementById("itemAddedDiv").innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Adding item to cart...</center><br />";
	
		//Replace button
		document.getElementById(buttonID).innerHTML = "<img src='/images/graphics/prod-added.gif' alt='Item Added' border='0' />";
		
		//Set up arguments array
		argsArray[0][0] = "sku_grp_id";
		argsArray[0][1] = sku_grp_id;
		argsArray[1][0] = "item_sku";
		argsArray[1][1] = item_id;
		argsArray[2][0] = "num_options";
		argsArray[2][1] = 0;
		argsArray[3][0] = "type";
		argsArray[3][1] = "ITEM";
		argsArray[4][0] = "qty";
		argsArray[4][1] = qty;
		argsArray[5][0] = "sales_price";
		argsArray[5][1] = price;
		
		//Execute AJAX call
		returnData = runAJAXsync("add_to_cart",argsArray);
		
		window.setTimeout( function() {
			//Load 'items in cart display' by getting a substring from the begginging of temp to BREAK
			//Load 'item added to cart div' by getting a substring from BREAK to the end of temp
			document.getElementById('itemAddedDiv').innerHTML = returnData.substr(0, returnData.indexOf('[BREAK]') );
			document.getElementById('cartItems').innerHTML = returnData.substr( (returnData.indexOf('[BREAK]')+7) );
			
			//Fade in then fade out 'item added to cart' box
			//Set display of 'item added to cart' box to none to kill the links inside of it
			opacity('itemAddedOpacity',0,100,500);
			window.setTimeout("opacity('itemAddedOpacity',100,0,500)", 5000);
			window.setTimeout("document.getElementById('itemAddedOpacity').style.display = 'none';", 7000);
		}
	, 1000);
		
	} else{
		alert("ALERT: You must enter a valid quantitiy.");
	}
}


function autocomplete(searchTerm){
	if( searchTerm.length > 0 ){
		var returnData = "";
		searchArgs = new2DArray(2,1);
		showDivs('suggestions');	
		
		searchArgs[0][0] = "queryString";
		searchArgs[0][1] = searchTerm;
		
		returnData = runAJAXsync("auto_complete",searchArgs);
					
		if( returnData != 0 ){
			document.getElementById('autoSuggestionsList').innerHTML = returnData;
		} else {
			hideDivs('suggestions');	
		}
	} else {
		hideDivs('suggestions');	
	}
}


// runSearch()
// executes an ajax call and runs the search
function runSearch(){
	searchArgs = new2DArray(2,1);
	var searchTerm = document.getElementById('advanced_search').value;
	
	//set up search arguments array
	searchArgs[0][0] = "search";
	searchArgs[0][1] = searchTerm;

	document.getElementById('searchHeaderRes').innerHTML = 'You searched for "' + searchTerm + '"';
	document.getElementById('searchRes').innerHTML = "<center id='searchLoader'><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br /><b>Loading...</b></center>";
	runAJAXasync("run_search","searchRes",searchArgs);
}

// new2DArray()
// Sets up a new 2D array
// args: length - length of array, width - width of array
// return: the new array
function new2DArray(length, width){
	returnArray = new Array(length);
	for(var i=0;i<length;i++){
		returnArray[i] = new Array(width);	
	}
	return returnArray;
}

// isInArray()
// check if a value is in a given array
// args: checkVal - value to be checked, checkArray - array with values to be checked
// return: true or false
function isInArray(checkVal,checkArray){
	var flag = false;
	//check if value is in the array
	for(var i=0;i<checkArray.length;i++){
		if( checkArray[i] == checkVal){ return true; }	
	}
	return false;
}


// isNumeric()
// checks if a value is numeric with a decimal
// args: value - value to check
function isNumericDecimal(value){
  var anum=/(^\d+$)|(^\d+\.\d+$)/;

  if (anum.test(value) && value != null )
 	 return true;
	 
  return false;
}

// isNumeric()
// checks if a value is numeric without a decimal
// args: value - value to check
function isNumeric(value){
  var anum=/(^\d+$)/;

  if (anum.test(value) && value != null )
 	 return true;
	 
  return false;
}

function roundUp(number) {
	var formatedNumber = Math.ceil(number * 100) / 100;
	return formatedNumber.toFixed(2);
}

// getScrollY
// Gets the y scroll position and returns
function getScrollY() {
  scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

//bookmarkpage
function bookmarksite(title,url){
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
}


// JavaScript Document
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// preloadImages()
// preloads the nav bar and loading graphic images
function preloadImages(){
	if (document.images){
	  pic1 = new Image(135,31); 
	  pic1.src ='/images/layout/btn-company-over.gif'; 
	  pic2 = new Image(135,31); 
	  pic2.src ='/images/layout/btn-products-over.gif';
	  pic3 = new Image(135,31); 
	  pic3.src ='/images/layout/btn-tools-over.gif';
	  pic4 = new Image(135,31); 
	  pic4.src ='/images/layout/btn-info-over.gif';
	  pic5 = new Image(135,31); 
	  pic5.src ='/images/layout/btn-support-over.gif';
	  pic6 = new Image(136,31); 
	  pic6.src ='/images/layout/btn-contactus-over.gif';
	  
	  pic7 = new Image(32,32); 
	  pic7.src ='/images/graphics/page-loading.gif';
	}
}

// setAutoComplete
// attachs the auto complete function
function setAutoComplete(){
	document.getElementById('inputString').onkeyup = function() { autocomplete(this.value); return false; }	
}

// hideLoading()
// Hides the loading screen if it exists
function hideLoading(){ 
	if( document.getElementById('loading') )
		document.getElementById('loading').className = "loading-invisible";
}

// hideJavaAlert
// hides the javascript alert if it is present on the page
function hideJavaAlert(){
	if( document.getElementById('javaAlert') ){ document.getElementById('javaAlert').style.display = "none"; }
}

// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}

// clear field on focus
function autoclear(thefield,thedefault) {
	if (thefield.value==thedefault) thefield.value = "";
}
///////////////////////////////////////////////////////////////////////////////////////
// END GENERAL FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////
// OPACITY FUNCTIONS
/////////////////////////////////////////////////////////////////////

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}
//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}
/////////////////////////////////////////////////////////////////////
// END OPACITY FUNCTIONS
/////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////
// ADD LOAD EVENTS
///////////////////////////////////////////////////////////////////////////////////////
addLoadEvent(hideJavaAlert);
addLoadEvent(preloadImages);
//addLoadEvent(setAutoComplete);
///////////////////////////////////////////////////////////////////////////////////////
// END ADD LOAD EVENTS
///////////////////////////////////////////////////////////////////////////////////////