//-----( @Cookies )--------------------------------------------
var Cookies = {
	getCookie: function(name) {
		var start = document.cookie.indexOf(name + "=");
		var len = start + name.length + 1;
		if ((!start) && (name != document.cookie.substring(0, name.length))) {
			return null;
		}
		if (start == -1) { return null; }
		var end = document.cookie.indexOf(";", len);
		if (end == -1) { end = document.cookie.length; }
		return unescape(document.cookie.substring(len, end));
	},
	setCookie: function(name, value, expires, path, domain, secure) {
		var today = new Date();z
		today.setTime(today.getTime());
		
		if (expires) { expires = expires * 1000 * 60 * 60 * 24; }
		var expires_date = new Date(today.getTime() + (expires));
		
		document.cookie = name + "=" + escape(value)
		+ ((expires) ? ";expires="+expires_date.toGMTString() : "")
		+ ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=" + domain : "")
		+ ((secure) ? ";secure" : "");
	},
	deleteCookie: function(name, path, domain) {
		if (Cookies.getCookie(name)) document.cookie = name + "="
		+ ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=" + domain : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
};
//-----( END )-------------------------------------------------

//-----( overwrites getElementsByClassName w/ a faster one)----
function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;    
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();                              
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';   
  var arrClass = strClass.split(delim);    
  for (var i = 0, j = objColl.length; i < j; i++) {                         
    var arrObjClass = objColl[i].className.split(' ');   
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if ((delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]); 
          break comparisonLoop;
        }
      }
    }
  }
  return arr; 
}
//-----( END )-------------------------------------------------

//-----( @Tables )---------------------------------------------
 var Tables = {
	init: function() {
		var tables = getElementsByClassName("zebra-grid");
		tables.each(function(table) {
			Tables.stripe(table, '#eee', '#fff');
		});
	},
	stripe: function(tableId, evenColor, oddColor) {
    var counter = 0;
    var odd = "odd";
		var table = $(tableId);
		if (typeof tableId == "object") { table = tableId; }
		if (!table) { return; } // if no such table exists, abort
  
		var tbodies = $A(table.getElementsByTagName("tbody"));
		tbodies.each(function(tbody) {
			var trs = $A(tbody.getElementsByTagName("tr"));
			trs.each(function(tr) {
        if(counter % 2 == 1){
          tr.className = odd;
        }  
        counter++;
			});
		});
	}
};

//-----( END )-------------------------------------------------


//-----( @ProductSearch )--------------------------------------
var ProductSearch = {
	form: Object,
	terms: Object,
	init: function() {
		ProductSearch.form = $("search-form");
		ProductSearch.terms = $("search-terms");
		//ProductSearch.terms.focus();
		Event.observe(ProductSearch.form, "submit", ProductSearch.submit, false);
	},
	submit: function(ev) {
		if (trim(ProductSearch.terms.value) == "") {
			alert("Enter search criteria before searching.");
			ProductSearch.terms.focus();
			Event.stop(ev);
		}
	}
};
//-----( END )-------------------------------------------------


//-----( @StoreLocator )---------------------------------------
var StoreLocator = {
	form: Object,
	terms: Object,
	init: function() {
		StoreLocator.form = $("sl_form");
		StoreLocator.terms = $("sl_postal");
		if (StoreLocator.form != null) {
			Event.observe(StoreLocator.form, "submit", StoreLocator.submit, false);
		}
	},
	submit: function(ev) {
		if (StoreLocator.terms != null) {
			if (trim(StoreLocator.terms.value) == "") {
				alert("Enter a store location before searching.");
				StoreLocator.terms.focus();
				Event.stop(ev);
			}
		}
	}
};
//-----( END )-------------------------------------------------


//-----( @ProductRefinements )---------------------------------
var Refinements = {
	init: function() {
		var container = $('ProductRefinements');
		if (container != null) {
			var dropdowns = $A(container.getElementsByTagName('select'));
			dropdowns.each(function(dropdown){
				Event.observe(dropdown, 'change', Refinements.refineSearch.bind(this), false);
			});
		}
	},
	refineSearch: function(event) {
		var obj = Event.element(event);
		var value = obj.value; // obj.value="";
		if (value != "") { gotoUrl(SITE_ROOT + "products.ex?" + value); }
	}
}
//-----( END )-------------------------------------------------


//-----( @ResultsSorter )--------------------------------------
var ResultsSorter = {
	init: function() {
		var sorters = getElementsByClassName('resultssorter');
		sorters.each(function(sorter){
			Event.observe(sorter, 'change', ResultsSorter.sortReults.bind(this), false);
		});
	},
	sortReults: function(event) {
		var obj = Event.element(event)
		var value = obj.value; // obj.value="";
		if (value != "") { gotoUrl(value); }
	}
}
//-----( END )-------------------------------------------------


//-----( @ShoppingCart )---------------------------------------
var ShoppingCart = {
	form: Object,
	init: function() {
		ShoppingCart.form = $("updateCart");
		if (ShoppingCart.form) {
			Event.observe(ShoppingCart.form, "submit", ShoppingCart.updateCart, false);
		}
		if($('showLocations') != null && $('showLocations').value == "true")
			ShoppingCart.addLocations();
	},
  updateCart: function(ev) {
		var allNodes = document.getElementsByClassName("cartQtyTextBox");
		allNodes.each(function(node) {
			qty = $F(node);
			var num = parseInt(qty);
	    
			if (isNaN(qty) || qty < 0) {
				alert("Enter a valid value for quantity.");
				node.select();
				Event.stop(ev);
			}
		});
  },
  empty: function(url) {
		var alertMsg = "Are you sure you want to empty your cart?";
		if (confirm(alertMsg)) {
                    gotoUrl(url); 
                }
  },
  remove: function(url) {
		var alertMsg = "Are you sure you want to remove this line item?";
		if (confirm(alertMsg)) { gotoUrl(url); }
  },
  addLocations: function() {
		var allLocations = document.getElementsByClassName("cartLocation", "div", $('updateCart'));
		allLocations.each(function(location) {
      		location.style.display = "block";
		});
		$("addLocations").style.display= "none";
  }
};
//-----( END )-------------------------------------------------


//-----( @Textarea )-------------------------------------------
var Textarea = {
	init: function() {
		Textarea.setMaxLength();
	},
	isMaxLength: function(obj) {
		obj = this;
		var maxlen = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
		if (obj.getAttribute && obj.value.length>maxlen) {
			obj.value = obj.value.substring(0, maxlen);
		}
	},
	setMaxLength: function() {
	  var counter = document.createElement("div");
	  counter.setAttribute("class", "");    
    
	  var textareas = $A(document.getElementsByTagName("textarea"));
	  textareas.each(function(textarea) {
			if (textarea.getAttribute("maxlength")) {
      
        //Added for one step checkout special instructions textarea so it does
        //not keep stacking divs.  Instead delete div if it exists before
        //redrawing the "X of Y characters used" text.
        var sDivId = "div" + textarea.getAttribute("id");
        if ( $(sDivId) != null ) {
          removeElement( $(sDivId) );
        }
        counter.setAttribute("id", sDivId);
      
			  var counterClone = counter.cloneNode(true);
  			counterClone.relatedElement = textarea;
	  		counterClone.innerHTML = "<span>0</span> of " + textarea.getAttribute("maxlength") + " characters used";
		  	textarea.parentNode.insertBefore(counterClone, textarea.nextSibling);
			  textarea.relatedElement = counterClone.getElementsByTagName("span")[0];
  			textarea.onkeyup = Textarea.checkMaxLength;
  			textarea.onchange = Textarea.checkMaxLength;
	  		textarea.onkeyup();
		  }
	  });
  }, 
	checkMaxLength: function() {
	  var maxLength = this.getAttribute("maxlength");
	  var currentLength = this.value.length;
    if (currentLength > maxLength) {
		  this.relatedElement.className = "overlimit";
    } else {
	  	this.relatedElement.className = "";
    }
	  this.relatedElement.firstChild.nodeValue = currentLength;
  }
}
//-----( END )-------------------------------------------------


//-----( @CheckBox )-------------------------------------------
var CheckBox = {
	checkAll: function(chkAll, checks) {
		chkAll = document.getElementById(chkAll);
		checks = document.getElementsByName(checks);
		
		if (chkAll.checked == true) {
			for (var i=0; i<checks.length; i++) {
				checks[i].checked = true;
			}
		} else {
			for (var i=0; i<checks.length; i++) {
				checks[i].checked = false;
			}
		}
	},
	checkOnce: function(chkAll, checks) {
		var allChecked = false;
		chkAll = document.getElementById(chkAll);
		checks = document.getElementsByName(checks);
		
		for (var i=0; i<checks.length; i++) {
			if (checks[i].checked == true) {
				allChecked = true;
				continue;
			} else {
				allChecked = false;
				break;
			}
		}
		
		if (allChecked == true) {
			chkAll.checked = true;
		} else {
			chkAll.checked = false;
		}
	}	,
	getTotalChecked: function(checks) {
		var totalChecked = 0;
		checks = document.getElementsByName(checks);
		
		for (var i=0; i<checks.length; i++) {
			if (checks[i].checked == true) {
				totalChecked++;
			}
		}
		return totalChecked;
	}
        ,
        ifCheckedOne: function (checks,errorDiv) {
                var checked = false;
                checks = document.getElementsByName(checks);
                for (var i=0; i<checks.length; i++) {
                        if (checks[i].checked == true) {
                                checked = true;
                                break;
                        }
                }
                if(!checked){
                        document.getElementById(errorDiv).className = "error";
                        document.getElementById(errorDiv).style.visibility = 'visible';
                        return false;
                }
                else{
                        document.getElementById(errorDiv).className = "";
                        document.getElementById(errorDiv).style.visibility = 'hidden';
                        return true;
                }
        }
};
//-----( END )-------------------------------------------------


//-----( @GoogleMap )------------------------------------------
var GoogleMap = {
  createMarker: function( p_aGMap2, p_aGLatLngPoint, p_sMarkerLabel ) {
    var aGMarker = new GMarker(p_aGLatLngPoint);
    
    GEvent.addListener(aGMarker, "click", function() {
      aGMarker.openInfoWindowHtml(p_sMarkerLabel);
    });

    // add listener for when a info window is closed
    GEvent.addListener(aGMarker, "infowindowclose", function() {
      p_aGMap2.panTo(p_aGLatLngPoint);
    });
  
    return aGMarker;
  },
  loadMap: function( p_dbLat, p_dbLng, p_sMarkerLabel ) {
    var aGMap2 = new GMap2(document.getElementById("locationgmap"));
    var aGLatLngPoint = new GLatLng(p_dbLat, p_dbLng);
    var iZoomLevel = 14;
    var sMarkerLabel = '<div class="divinfowindow">' + p_sMarkerLabel + '<\/div>';

    // add map controls
    aGMap2.addControl(new GSmallMapControl());
    aGMap2.addControl(new GMapTypeControl());
    aGMap2.setCenter(aGLatLngPoint, iZoomLevel);
    
		// create and add the marker
    var aGMarker = GoogleMap.createMarker(aGMap2, aGLatLngPoint, sMarkerLabel);
    aGMap2.addOverlay(aGMarker);
    
    //display info window initially
    aGMarker.openInfoWindowHtml(sMarkerLabel);
	}
}
//-----( END )-------------------------------------------------


//-----( @Help )-----------------------------------------------
var Help = {
	init: function() {
		var helpLinks = getElementsByClassName("help");
    
    
		helpLinks.each(function(helpLink) {
			Event.observe(helpLink, "click", Help.showPopup.bind(this), false);
		});
	},
	showPopup: function(event) {
		var href = Event.element(event);
		if (href != null || href != "") {
			var name = "fcom_help_popup";
			var features = "width=500,height=400,";
			features += "directories=no,location=no,menubar=no,";
			features += "resizable=no,scrollbars=yes,status=yes,toolbar=no";
			popupUrl(href, name, features);
			Event.stop(event);
		}
	}
}
//-----( END )-------------------------------------------------


//-----( @Msds )-----------------------------------------------
var Msds = {
	init: function() {
		var msdsLinks = getElementsByClassName("msds");
		msdsLinks.each(function(msdsLink) {
			Event.observe(msdsLink, "click", Msds.showPopup.bind(this), false);
		});
	},
	showPopup: function(event) {
		var href = Event.element(event);
		if (href != null || href != "") {
			var name = "fcom_msds_popup";
			var features = "width=785,height=589,";
			features += "directories=no,location=yes,menubar=yes,";
			features += "resizable=yes,scrollbars=yes,status=yes,toolbar=yes";
			popupUrl(href, name, features);
			Event.stop(event);
		}
	}
}
//-----( END )-------------------------------------------------


//-----( @Thumbnails )-----------------------------------------
var Thumbnails = {
	init: function() {
		var thumbnails = document.getElementsByClassName("thumbnail");
		thumbnails.each(function(thumbnail) {
			Event.observe(thumbnail, "error", Thumbnails.noProductThumbnail, false);
		});
	},
	noProductThumbnail: function(element, root) {
		element.src = root + "/common/images/misc/notavailable.gif";
	}
}
//-----( END )-------------------------------------------------

//-----( @SalesDrawings )-----------------------------------------
var SalesDrawings = {
	init: function() {
		var salesDrawings = document.getElementsByClassName("salesDrawings");
		salesDrawings.each(function(salesDrawing) {
			Event.observe(salesDrawing, "error", SalesDrawings.noSalesDrawing, false);
		});
	},

	noSalesDrawing: function(element, root) {
		element.src = root + "/common/images/misc/nosalesdrawingavailable.jpg";
	}
}
//-----( END )-------------------------------------------------


//-----( @LinkPreview )----------------------------------------
// DESCRIPTION: Preview Your Links with Unobtrusive JavaScript 
//              (http://particletree.com/features/preview-your-links)
var LinkPreview = {
	extensions: new Array("doc", "pdf", "ppt", "txt", "xls", "zip", "mdi", "vcf", "mdb", "pub", "mpp"),
	
	// gets all non-image links from the page
	init: function() {
		var links = document.getElementsByTagName("a");

		for (var i=0; i<links.length; i++) {
			var currentLink = links[i];
			var	images = currentLink.getElementsByTagName("img");
			
	 		// check if the link is an image we don't want icons next to images
			if (images.length == 0) {
				var linkHref = currentLink.href;
				LinkPreview.checkLink(linkHref, currentLink)
			}
		}
	},
	
	// checks if the link goes to an external file (ie. .doc, .pdf)
	checkLink: function(linkHref, currentLink) {
		var linkHrefParts = linkHref.split(".");
			
		// extension is the last element in the LinkSplit array
		var extension = linkHrefParts[linkHrefParts.length - 1];
		
		// in some browsers there is a "/" placed after the link. removes the "/"
		extension = extension.replace("/","");
		
		for (var i=0; i<LinkPreview.extensions.length; i++) {
			if (extension == LinkPreview.extensions[i]) {
				LinkPreview.appendClass(currentLink, extension);
			}
		}
	},
	
	// creates a span after the object passed in and sets the class to the link type
	appendClass: function(currentLink, extension) {
		var span = document.createElement('span');
		span.innerHTML = "&nbsp;";
		currentLink.parentNode.insertBefore(span, currentLink.nextSibling);
		span.className = extension;
	}
};
//-----( END )-------------------------------------------------


//-----( @Reflector )------------------------------------------
var Reflector = {
	reflect: function(element) {
		element = $(element);
		options = $H({
			amount: 1/3,
			opacity: 1/3
		}).merge(arguments[1] || {});
		
		var p = element.parentNode, n = element.nextSibling;
		var d = 1.0/(element.height*options.amount);
			
		(element.height*options.amount).times( function(line) {
			var h = Builder.node('div',{style:'height:1px;overflow:hidden'},
				[Builder.node('img',{src:element.src, 
					style:'margin-top:-'+(element.height-line-1)+'px'
				})]);
			p.insertBefore(h,n);
			$(h).setOpacity((1-d*line)*options.opacity);
		});
	}
};
//-----( END )-------------------------------------------------


//-----( @avDescribe )-----------------------------------------
var avDescribe = {
	toolTip: Object,
	iframe: Object,
	init: function() {
  
  
		if (!document.getElementById 
		|| !document.createElement
		|| !document.getElementsByTagName) {
			return;
		}
		
		avDescribe.toolTip = document.createElement('div');
		avDescribe.toolTip.id = 'toolTip';
		document.getElementsByTagName('body')[0].appendChild(avDescribe.toolTip);
		avDescribe.toolTip.style.top = 0;
		avDescribe.toolTip.style.visibility = 'hidden';
		
		var helpLinks = getElementsByClassName('help');
		helpLinks.each(function(helpLink) {
			if (helpLink.rel != "") {
				Event.observe(helpLink, 'mouseover', avDescribe.tipOver, false);
				Event.observe(helpLink, 'mouseout', avDescribe.tipOut, false);
			}
		});
    
    
	},
	tipOut: function() {
		avDescribe.toolTip.style.visibility = 'hidden';
		if (avDescribe.iframe != null) {
			avDescribe.iframe.style.display = "none";
		}
	},
	tipOver : function(event) {		
		var avhtml = avDescribe.getTip(Event.element(event).rel);
		avDescribe.toolTip.innerHTML = "<p>" + avhtml + "</p>";
		avDescribe.toolTip.style.left = (Event.pointerX(event) + 15) + 'px';
		avDescribe.toolTip.style.top = (Event.pointerY(event) + 10) + 'px';
		avDescribe.toolTip.style.visibility = 'visible';
		avDescribe.makeIframe(avDescribe.toolTip);

		//avDescribe.toolTip.style.opacity = '.90';
		//avDescribe.toolTip.style.filter = "alpha(opacity:90)";
	},
	makeIframe: function(tt) {
		// make the iframe
		var iframetemp = document.createElement("iframe");
		iframetemp.frameBorder = 0;
		iframetemp.src = "javascript:false";
		iframetemp.style.display = "none";
		iframetemp.style.position = "absolute";
		iframetemp.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		tt.iframetemp = tt.parentNode.insertBefore(iframetemp, tt);

		// position the iFrame under the tooltip
		tt.iframetemp.style.top  = tt.style.top;
		tt.iframetemp.style.left = tt.style.left;
		tt.iframetemp.style.width  = tt.offsetWidth + "px";
		tt.iframetemp.style.height = tt.offsetHeight + "px";
		tt.iframetemp.style.display = "block";
		
		avDescribe.iframe = tt.iframetemp;
	},
	getTip: function(avcode) {
		switch (avcode) {
			case "avSTR":
				avhtml = "Inventory generally available in the majority of our "
				+ "local store locations for immediate in-store pick-up or shipping.";
				break;
			case "avSTK":
				avhtml = "Inventory generally available for immediate shipping from a "
				+ "Fastenal stocking location. Inventory may also be stocked in some local "
				+ "stores. Inventory is usually available for in-store pick-up in 1-2 days.";
				break;
			case "avSFM":
				avhtml = "Inventory generally available directly from a Fastenal approved "
				+ "manufacturer. Item is not generally stocked in our local store or stocking "
				+ "location. Lead times may vary and product may be available for in-store "
				+ "pick-up. Contact your local store for specific information.";
				break;
			case "avSLL":
				avhtml = "Inventory only available in a limited number of Fastenal locations. "
				+ "Product may be available to ship immediately and usually available for in-store "
				+ "pickup in 1-4 days. Contact your local store for specific information.";
				break;
			case "avLTV":
				avhtml = "Product generally not stocked in our local store location but usually "
				+ "available to ship in 2-5 days with local in-store pick-up in 3-10 days. "
				+ "Lead times, minimum order quantities, and freight are subject to change. "
				+ "Contact your local store for specific information.";
				break;
			case "avDIS":
				avhtml = "Product has been discontinued but still may be available in "
				+ "limited quantities. Find an alternative part or contact your local "
				+ "store for specific information.";
				break;
		}
		return avhtml;
	}
};
//-----( END )-------------------------------------------------

//-----( @CMIListOperations )--------------------------------------
    var CMIListOperations = {
      target: 'importUI', 
      url: SITE_ROOT + 'cmiListAction.ex', 
      /**
      init: function() {
        CMIListOperations.target = 'importUI';
        CMIListOperations.url = '/web/cmiListAction.ex';//'/web/cmi/cmiListAction.ex';//'/web/cmi/importCSV.html';
      },
      **/
      importUI: function(action) {
        var pars = 'noRedirect=true&action='+ action; 
        //var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onSuccess: showResponse});
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        {method: 'get', onComplete: CMIListOperations.showResponse, parameters: pars, evalScripts: true, asynchronus: true}
                                      );
      },  //end importUI

      lookupSku: function(action) {
        var sku =document.cmiForm.sku.value;
        
        var pars = 'noRedirect=true&action='+ action + '&sku=' + sku; 
        //var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onSuccess: showResponse});
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showLookupSkuResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
            
            
      },  //end lookupSku
      
      addSku: function(action, listId, sku, productId, partType, qty) {
        //var sku =document.cmiForm.sku.value;
        var pars = 'noRedirect=true&action='+ action 
                    + '&listId='    + listId
                    + '&addSku='    + sku 
                    + '&productId=' + productId
                    + '&qty=' + qty
                    + '&partType='  + partType; 
        //alert (pars);
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showAddSkuResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
      },  //end addSku
      
      listQuantities: function(e, reviewId, recordId) {
        //var sku =document.cmiForm.sku.value;
        var mouseX = Event.pointerX(e);
        var mouseY = Event.pointerY(e); 
        var action = 'displayListQtys';
        var pars = 'noRedirect=true&action='+ action 
                    + '&reviewId='  + reviewId
                    + '&recordId='  + recordId ; 
        //alert (pars);
        mouseX+=20 ;
        mouseY-=65
        $("QuantityList").style.left = mouseX + 'px';
        $("QuantityList").style.top = mouseY + 'px';
        var myAjax = new Ajax.Request(  CMIListOperations.url, 
                                        { method: 'get'
                                        , onComplete: CMIListOperations.showQtyListResponse
                                        , parameters: pars
                                        , evalScripts: true
                                        , asynchronus: true}
                                      );
        return false;
      },  //end listQuantities
      
      printSubLocation: function(){
        CMIListOperations.importUI('displayPrintSubLocation');
		CMIListOperations.NLBparam = 'subLocationContainer';
		CMIListOperations.callbackNLBfadeBg();
      }, //end printSubLocation
      
	  NLBparam:"",
      printBinLocation: function(){
        CMIListOperations.importUI('displayPrintBinLocation');
		CMIListOperations.NLBparam = 'binLocationContainer';
		CMIListOperations.callbackNLBfadeBg();
      }, //end printBinLocation

	  callbackNLBfadeBg: function(){
			if(document.getElementById(CMIListOperations.NLBparam) != null){
				NLBfadeBg(CMIListOperations.NLBparam, '#fff776', '#ffffff', '2000');
			}else{
				setTimeout('CMIListOperations.callbackNLBfadeBg()', 200);
			}
	  },
      
      importSku: function(){
        CMIListOperations.importUI('displayImportSku');
        
      }, //end importSku
      
      importCSV: function() {
        CMIListOperations.importUI('displayImportCSV');
      },  //end importCSV
      
      importCart: function() {
        CMIListOperations.importUI('displayImportCart');
      },  //end importCart
      
      importCart: function() {
        CMIListOperations.importUI('displayImportCart');
      },  //end importCSV
      
      importOrdTemplate: function() {
        CMIListOperations.importUI('displayImportOrdTemplate');
      },  //end importOrdTemplate
      
      showResponse: function(originalRequest){
        var response=originalRequest.responseText;
//        alert('show response: ' + response);
//        alert('target:' + CMIListOperations.target);
		document.getElementById(CMIListOperations.target).innerHTML = response;	
        //$(CMIListOperations.target).innerHTML = response;
	
        //set focus
        if(document.cmiForm.sku){
          document.cmiForm.sku.focus();
        }

        //window.innerHTML = originalRequest.responseText;
      }, //end showResponse
      
      showLookupSkuResponse: function(originalRequest){
        var skuNo=document.cmiForm.sku.value;
        var response=originalRequest.responseText;
        //alert('show response: ' + response);
        try{
          //look for a possible error redirect
          var json= eval('(' + response + ')');
          if (json.url && json.url.length > 0){//some error occurred display the error and forward to page
            alert('Unable to service request.  \nReason:  [' + json.reason + ']');
            window.location = json.url;
          }else if (json.found){
            //alert('sku found:' + json.sku);
            var beginTag = '<span class="item-data" align="left" >';
            var endTag = '</span>';
            
            //alert('orig price: ' + json.price);           
            var sFinalPrice = json.price + "";
            if (sFinalPrice.indexOf(".") + 2 >= sFinalPrice.length || sFinalPrice.indexOf(".") == -1) {
              sFinalPrice = parseFloat(sFinalPrice).toFixed(2);
            }
            //alert('sFinalPrice: ' + sFinalPrice);
            
            //$('sku').innerHTML = beginTag + 'json.sku' + endTag;
            $('item-description').innerHTML = beginTag + json.description + endTag;
            $('item-pkgQty').innerHTML = beginTag + json.pkgQty + endTag;
            $('item-price').innerHTML = beginTag + "$" + sFinalPrice + endTag;
            //enable the add qty functionality
            document.cmiForm.addSku.value=json.sku;
            document.cmiForm.productId.value=json.productId;
            document.cmiForm.qty.disabled=false;
            document.cmiForm.add.disabled=false;
            //set focus
            document.cmiForm.qty.focus();
          }else if((skuNo==null)||(skuNo=="")||(skuNo.length==0) ){//not found
            alert("Enter a valid SKU.");
           }
           else{
            //alert("SKU not found!");
            CMIListOperations.showUnknownPartPopup();
            
           }
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
        
        
        //window.innerHTML = originalRequest.responseText;
      }, //end showLookupSkuResponse
      
      showAddSkuResponse: function(originalRequest){
        var pkgQty=document.cmiForm.qty.value;
        var response=originalRequest.responseText;
        //alert('show response: ' + response);
        try{
          //look for a possible error redirect
          var json= eval('(' + response + ')');
          if (json.url && json.url.length > 0){//some error occurred display the error and forward to page
            alert('Unable to service request.  \nReason:  [' + json.reason + ']');
            window.location = json.url;
          }else if (json.added){
            //alert('Successfully added item to list.');
            //CMIListOperations.importSku();
            //reset the form
            //$('sku').innerHTML = beginTag + 'json.sku' + endTag;
           CMIListOperations.resetSkuForm();
            
          }else if((pkgQty==null)||(pkgQty=="")||(pkgQty.length==0)||(isNaN(pkgQty))){//not found
            alert("Enter a valid package quantity.");
          }
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
        //window.innerHTML = originalRequest.responseText;
      }, //end showAddSkuResponse
      
      showQtyListResponse: function(originalRequest){
        var response=originalRequest.responseText;
        try{
           $("QuantityList").innerHTML = response;
           CMIListOperations.showQuantityListPopup();
          return;
        }catch(e){
          alert('Unable to service request.  \nReason:  [' + json.reason + ']' + e);
        }
      }, //end showQuantityListResponse
      
      resetSkuForm: function(){
        $('item-description').innerHTML = '';
        $('item-pkgQty').innerHTML = '';
        $('item-price').innerHTML = '';
        //enable the add qty functionality
        document.cmiForm.addSku.value='';
        document.cmiForm.productId.value='';
        document.cmiForm.sku.value='';
        document.cmiForm.qty.value='';
        document.cmiForm.qty.disabled=true;
        document.cmiForm.add.disabled=true;
        //set focus
        document.cmiForm.sku.focus();
      },//end resetSkuForm
      
      updateAction: function (actionValue){
        document.cmiForm.action.value = actionValue;
      }, //end updateAction
      
      validateImportOrdTemplate: function (){
        //updateAction('addTemplateToList');
        //var templateId = $F('templateId'); //buggy for Firefox
        var templateId =document.cmiForm.templateId.value;
        //alert(templateId);
        if (templateId==''){
          //alert('Select an Order Template.');
          return false;
        }else{
          //alert('else');
          CMIListOperations.updateAction('addTemplateToList');
          //form should now submit
          return true;
        }//end else
        return false;
      }, //end validateImportOrdTemplate
      
      validateImportCart: function (){
        CMIListOperations.updateAction('addCartToList');
        return true;
      }, //end validateImportOrdTemplate
      
      validateImportCsv: function (){
        var form = document.cmiForm;
        var csvVal=document.cmiForm.csvFile.value;
        form.encoding='multipart/form-data';
        
        if(csvVal){
        //alert(form.encoding);
          CMIListOperations.updateAction('addCsvToList');
          return true;
        }else{
          alert("Select a file");
          return false;
        }
      }, //end validateImportCsv
      
      validateCreateList: function (){
        //var listName =document.cmiManagementForm.listName.value;
        var listNameVal=document.cmiForm.listName.value;
        
        if(listNameVal.length==0){
          alert("Enter a name for the new list");
          return false;
        }else{
          CMIListOperations.updateAction('createList');
          return true;
        }
      }, //end validateImportOrdTemplate
      validateAddSku: function (){
        
        //validate the value of the sku and the qty
        //CMIListOperations.updateAction('addSku');
        var listId =document.cmiForm.listId.value;
        var sku =document.cmiForm.sku.value;
        var productId = document.cmiForm.productId.value;
        var partType = document.cmiForm.partType.value;
        var qty = document.cmiForm.qty.value;
        CMIListOperations.addSku('addSku', listId, sku, productId, partType, qty);
        return false;
      },
      
      validateLookupSku: function (){
        //CMIListOperations.updateAction('lookupSku');
        //make ajax call
        var sku =document.cmiForm.sku.value;
        CMIListOperations.lookupSku('lookupSku');
        return true;
       },
      
      deleteSelected: function (){
        //TODO some validation mabye
        if (confirm('Are you sure you want to delete the selected items?')){
          CMIListOperations.updateAction('deleteSelectedItems');
          return true;
        }else{
          return false;
        }
      }, //end deleteSelected
      
      deleteList: function(url) {
        var alertMsg = "Are you sure you want to delete this Item List?";
    		if (confirm(alertMsg)) { gotoUrl(url); }
      }, 
      
      printSelected: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to print the selected items?\n'
                        + 'When the print dialog appears, select your Zebra Label Printer from the list of available printers.';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('printSelectedItems');
          //window.open();
          return true;
        }else{
          return false;
        }
      }, //end printSelected
      
      updateSelected: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to update the selected items?\n';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('updateSelectedItems');
          return true;
        }else{
          return false;
        }
      }, //end updateSelected
      
      updateListProperties: function (){
        //TODO some validation mabye
        var confirmMsg = 'Are you sure you want to update the Item List Properties\n';
        if (confirm(confirmMsg)){
          CMIListOperations.updateAction('updateListProperties');
          return true;
        }else{
          return false;
        }
      }, //end updateSelected
      handleKeyPressCreateList : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          return CMIListOperations.validateCreateList();
          
        }else{
          return true;
        }//end else
      }, //end handleKeyPressCreateList
      handleKeyPressItems : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          return false;
        }else{
          return true;
        }//end else
      }, //end handleKeyPressItems
      
      handleKeyPressLookup : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.validateLookupSku();
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeyPressLookup
      
      handleKeyAddSku : function (e) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.validateAddSku();
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeyPressAddSku
      
      handleKeypressQtyIssue : function (e, form, recordId) {
        //alert('keypress called');
        var key = e.keyCode || e.which;
        if (key == 13) {
          CMIListOperations.updateSuggestedQty(form, recordId);
          return false;
        }else{
          return true;
        }//end else
      }, // end handleKeypressQtyIssue

      showQuantityListPopup : function () {
        $("QuantityList").style.visibility = "visible";
      }, // end showListPopup
      hideQuantityListPopup : function () {
        $("QuantityList").style.visibility = "hidden";
      }, //end hideQuantityListPopup      
      
      showUnknownPartPopup : function () {
        $("UnknownPartPopupCMI").style.visibility = "visible";
        $("btnFastenal").focus();
      }, // end showUnknownPartPopup
      hideUnknownPartPopup : function () {
        $("UnknownPartPopupCMI").style.visibility = "hidden";
        //$("btnFastenal").focus();
      }, //end hideUnknownPartPopup
      customFastenalPart : function () {
        CMIListOperations.hideUnknownPartPopup();
        var beginTag = '<span class="item-data" align="left" >';
        var endTag = '</span>';
        //$('sku').innerHTML = beginTag + 'json.sku' + endTag;
        $('item-description').innerHTML = beginTag + 'CUSTOM FASTENAL PART' + endTag;
        $('item-pkgQty').innerHTML = beginTag + '1' + endTag;
        $('item-price').innerHTML = beginTag + 'N/A' + endTag;
        //enable the add qty functionality
        document.cmiForm.addSku.value=document.cmiForm.sku.value;
        //document.cmiForm.productId.value=
        document.cmiForm.qty.disabled=false;
        document.cmiForm.add.disabled=false;
        //set focus
        document.cmiForm.qty.focus();
        //$("btnFastenal").focus();
      }, //end customFastenalPart
      cancelPart : function () {
        CMIListOperations.hideUnknownPartPopup();
        $('item-description').innerHTML = '';
        $('item-pkgQty').innerHTML = '';
        $('item-price').innerHTML = '';
        //enable the add qty functionality
        document.cmiForm.addSku.value='';
        document.cmiForm.productId.value='';
        //document.cmiForm.sku.value='';
        document.cmiForm.qty.value='';
        document.cmiForm.qty.disabled=true;
        document.cmiForm.add.disabled=true;
        document.cmiForm.sku.focus();
      }, //end cancelPart
      
      updateSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        var newQty = qty.value;
        
        var pkgQty = form.elements['pkgQty|'+recordId].value;
        var newSugQty = newQty * pkgQty;
        //alert('before set' + form.elements['qty-issue|'+recordId].value);
        $('sug-qty|' + recordId).innerHTML = newSugQty;
        //alert('after set');
        return false;
      }, //end updateSuggestedQty
      
      updateSuggestedQtyFromPopup : function (recordId, newQty) {
        var form = document.cmiForm;
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        qty.value=newQty;
        
        CMIListOperations.updateSuggestedQty(form, recordId);
        CMIListOperations.hideQuantityListPopup();
      }, //end updateSuggestedQty
      
      incSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        
        qty.value++;
        CMIListOperations.updateSuggestedQty(form, recordId);
        return false;
      }, //incSuggestedQty
      
      decSuggestedQty : function (form, recordId) {
        var qty = form.elements['qty-issue|'+recordId];
        if (! qty){
          qty = form.elements['qty|'+recordId];
        }
        if (qty.value > 1){
          qty.value--;
        }
        CMIListOperations.updateSuggestedQty(form, recordId);
        return false;
      } //decSuggestedQty
    };
    
//-----( END )-------------------------------------------------    

// Returns true if child is contained within element

var Position = {
  getWindowSize:  function(w) {
        w = w ? w : window;
        var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
        var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
        alert("width:"+width);
        alert("height:"+height);
        return [width, height]
  }
}
   
/*// use: ElementToBeMoved.centerOn(LocToBeCenteredOn);
Element.addMethods({
  centerOn: function(element, centerLoc) {
  //if the element is off the screen, once it is moved on the screen it will apply this margin to space it
  var windowMargins = 10; 
  //this gets the top [0] and left [1] offset of the item the Element is being centered to
  var centerLocPos = Position.cumulativeOffset(centerLoc);
  var centerLocHeight = 0;
  //certain browsers don't have a height attribute for all types of elements, so it defaults to 0 if none can be found
  if (centerLoc.getHeight) centerLocHeight = centerLoc.getHeight();
  
  //var parentLocPos = Position.cumulativeOffset(parentElement);
  //var parentLocWidth = 0;
  //if (parentElement.getWidth) parentLocWidth = parentElement.getWidth();
  //var elementWidth = 0;
  //if (element.getWidth) elementWidth = element.getWidth();
  
  //var leftOffSet = ((parentLocWidth - elementWidth) + parentLocPos[1])
  //element.style.left = leftOffSet +'px';
  
  var elementHeight = 0;
  //certain browsers don't have a height attribute for all types of elements, so it defaults to 0 if none can be found
  if (element.getHeight) elementHeight = element.getHeight();
  //this finds the center of the centerLoc element and how far that is from the top of the page  
  var centerCenterLoc = centerLocPos[1] + Math.round(centerLocHeight/2);
  //This figures out what the top offset should be for the element based on it's center and the center of the centerLoc  
  var topOffSet = centerCenterLoc - Math.round(elementHeight/2);
  //This gets the viewing area size of the current browser of the user [0] height, [1] width  
  var windowSize = Position.getWindowSize();
  //This centers the element based on the center Loc, we need to do this first to check for screen overlap
  element.style.top = topOffSet +'px';
  //To get the page position of the element, we first need to toggle it's display on, and back off once position is read
  element.style.display = 'block';
  //this is the space on the screen from the top of the element to the top of the browser window
  var spaceVisibleAboveElement = Position.page(element);
  //hides the element again, we want to make sure the element isn't shown early
  element.style.display = 'none';
  //This adds up the height of the elemnt, the margin required and the visible space on the screen
  //It then compares it to the viewable height of the browser
  //This will be true if the element extends below the viewing area of the browser
  if (windowSize[1] < (spaceVisibleAboveElement[1] + elementHeight + windowMargins))
    //this will move the element up such that it's lowest part is above the bottom of the window by the margin
    topOffSet = (topOffSet - spaceVisibleAboveElement[1]) + (windowSize[1] - elementHeight) - windowMargins;
  //this applies the offset, moving the element up if needed, we need to move it up before checking if it is past the top
  element.style.top = topOffSet +'px';
  
  //The bottom of the window is checked before the top incase the element is so large it extends past both.
  //In that case we would rather have it overflow the bottom of the window then the top
  
  //To get the page position of the element, we first need to toggle it's display on, and back off once position is read
  element.style.display = 'block';
  //this is the space on the screen from the top of the element to the top of the browser window
  //it needs to be re-calculated incase the element was moved up
  spaceVisibleAboveElement = Position.page(element);
  //hides the element again, we want to make sure the element isn't shown early
  element.style.display = 'none';
  
  //if the element is above the margin, the space will be less then it, most likely negative
  //this will be true when the element is above the top viewing area of the window
  if (spaceVisibleAboveElement[1] < windowMargins )
    //this will move the offset down however much it is over the top + the window margin
    topOffSet += Math.abs(spaceVisibleAboveElement[1]) + windowMargins;
  
  //this applies the offset in is current position, moving the element down if need be.
  element.style.top = topOffSet +'px';
  element.style.left = '300px';
}
});*/
 