/////////////////////////////////////////////////////////////////////////////////////
// AJAX 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 FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////
// DROP DOWNS
/////////////////////////////////////////////////////////////////////////////////////

// more images roll over
sfHover2 = function() {
	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() {
	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);

// product tools roll over
sfHover4 = 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+=" sfhover4";
			}
	
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover4\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover4);

// 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);

////////////////////////////////////////////////////////////////////////////////////
// END DROP DOWNS
////////////////////////////////////////////////////////////////////////////////////

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

//bookmark this page
function bookmarkThisPage(){
	if (window.sidebar || (window.opera && window.print)) // firefox
		alert("Your browser does not support this function. Please click OK then press CTRL+D on your keyboard to bookmark this page."); 
	else if(document.all)// ie
		window.external.AddFavorite('http://www.usmarkerboard-green.com', 'USMarkerboard Green');
}

//collapse or expand links
function linkCollapse(name, sectionNum, linkText){
	var divElement = document.getElementById(name);
	if (divElement.style.display == "none"){
		var linkHandle;
		for( var i=1; i<=sectionNum; i++){	
			document.getElementById("hideDiv"+i).style.display = "none";
			linkHandle = document.getElementById("catLink"+i);
			linkHandle.innerHTML = linkHandle.innerHTML.replace("arrow-down.gif","arrow-up.gif");
		}
		divElement.style.display = "inline";
		linkText.innerHTML = linkText.innerHTML.replace("arrow-up.gif","arrow-down.gif");
	} else {
		divElement.style.display = "none";
		linkText.innerHTML = linkText.innerHTML.replace("arrow-down.gif","arrow-up.gif");
	}
}

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

// 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;
}

// Switches the tabs on the product tab box
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("colorsBox") ){ document.getElementById("colorsBox").style.display = "none"; }
	if( document.getElementById("imagesBox") ){ document.getElementById("imagesBox").style.display = "none"; }
	document.getElementById(name).style.display = "inline";
}

//Shows the element with the given id if it exists
function showElement(id){
	if( document.getElementById(id) ){ document.getElementById(id).style.display = "inline"; }	
}

//Hides the element with the given id if it exists
function hideElement(id){
	if( document.getElementById(id) ){ document.getElementById(id).style.display = "none"; }	
}

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

///////////////////////////////////////////////////////////////////////////////////
// END GENERAL FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////

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

//fade in/out 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
///////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
// AUTO COMPLETE FUNCTIONS
///////////////////////////////////////////////////////////////////////////

// Auto complete for the quick search
// Args: searchTerm - the string that is in the quicksearch input
// Returns: a list of products that match the term
function autocomplete(searchTerm){
	if( searchTerm.length > 0 ){
		var returnData = "";
		searchArgs = new2DArray(2,1);
		showElement('suggestions');	
		
		searchArgs[0][0] = "queryString";
		searchArgs[0][1] = searchTerm;
		
		returnData = runAJAXsync("auto_complete",searchArgs);
					
		if( returnData != 0 ){
			document.getElementById('autoSuggestionsList').innerHTML = returnData;
		} else {
			hideElement('suggestions');	
		}
	} else {
		hideElement('suggestions');	
	}
}

// Used with the autocomplete - sets the quicksearch input to the sku name that is selected
// Args: term - the sku name
function fill(term){
	document.getElementById('inputString').value = term;	
}
///////////////////////////////////////////////////////////////////////////
// END AUTO COMPLETE FUNCTIONS
///////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////
// PAGE INITIALIZATION
//////////////////////////////////////////////////////////////////

// loadImages()
// Image preloader
function loadImages(){
  if( document.images ){
  pic1= new Image(65,25); 
  pic1.src='/images/layout/btn_home_over.gif'; 
  pic2= new Image(81,25); 
  pic2.src='/images/layout/btn_about_over.gif'; 
  pic3= new Image(88,25); 
  pic3.src='/images/layout/btn_contact_over.gif';
  pic4= new Image(135,25); 
  pic4.src='/images/layout/btn_cs_over.gif';
  pic5= new Image(107,25); 
  pic5.src='/images/layout/btn_info_over.gif';
  pic6= new Image(51,25); 
  pic6.src='/images/layout/btn_blog_over.gif';
  pic7= new Image(66,25); 
  pic7.src='/images/layout/btn_brands_over.gif';
  pic8= new Image(32,32); 
  pic8.src='/images/graphics/page-loading.gif';
  }
}

// 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;
}

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

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

// autoCompleteHide
function autoCompleteHide(){
	//INITIALIZE STEPS LINKS AND STYLES LINKS
	if (!document.getElementsByTagName){ return; }
	var bodyTag = document.getElementsByTagName("body");

	if( bodyTag.length > 0 ){ 
		bodyTag[0].onclick = function(){ hideElement('suggestions'); } 
	}
}

// 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();
		}
	}
}

addLoadEvent(loadImages);
addLoadEvent(setAutoComplete);
addLoadEvent(autoCompleteHide);
addLoadEvent(hideLoading);
//////////////////////////////////////////////////////////////////
// END PAGE INITIALIZATION
//////////////////////////////////////////////////////////////////

