// General Ajax section

var isIE;
var isIE7;
var gbCategoryAware;	// Added MM 10/06/2006
var gsType;				// Added MM 01/31/2007
var bInit;				// Added MM 03/19/2007
window.onload = init;

function AJAXInteraction(url) {
    this.url = url;
    var req = AjaxInit();
    req.onreadystatechange = processRequest;

    function AjaxInit() {

      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        isIE = true;
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }

    function processRequest () {
       if (req.readyState == 4) {
        if (req.status == 200) {
          postProcess(req.responseXML);
        }
      }
    }

    this.send = function() {
        req.open("GET", url, true);
        req.send(null);
    }
}

function getElementY(e){
	var targetTop = 0;
	if (e.offsetParent) {
		while (e.offsetParent) {
			targetTop += e.offsetTop;
            e = e.offsetParent;

		}
	} else if (e.y) {
		targetTop += e.y;
    }
	return targetTop;

}

function getElementX(e){
	var targetLeft = 0;
	if (e.offsetParent) {
		while (e.offsetParent) {
			targetLeft += e.offsetLeft;
            e = e.offsetParent;

		}
	} else if (e.y) {
		targetLeft += e.y;
    }
	return targetLeft;

}


function escapeme(strValue)
{
	strValue = strValue.replace(/'/g,"\\'");
	return strValue;
}

// Specific Ajax section, for brand selction functionality
// Requires the HTML variables below

var completeTable;
var brandname;
var productname;
var autorow;
var myForm;


function doCompletion(bCategoryAware,sType,e) {
	// MM 10/9/2008 if ads are slow init doesn't fire
	if (bInit!=true)
		init();

	var toggle = document.getElementById('completeTable');

	/*Handle up/down arrow keys*/
	var unicode = e.keyCode? e.keyCode : e.charCode;

	//Get the current selection for the hidden field
	var current = document.getElementById("curajax");
	var currentvalue = parseInt(current.value);

	if (((unicode==13)||(unicode==38)||(unicode==40))&&(toggle.className == 'ShowAjaxTable'))
		{
		var ajaxtable = document.getElementById('completeTable');
		var ajaxtableRows = ajaxtable.getElementsByTagName("tr");

		//Check for enter key
		if ((unicode==13)&&(currentvalue>-1))
			{

				var currentselectionid = 'aj'+ currentvalue;
				var currentselection =document.getElementById(currentselectionid);
				var selection_array=currentselection.href.split(",");

				var x_brandid = selection_array[1];
				
				var x_brandname = selection_array[0].replace("javascript:fillSelection(\'","");
				x_brandname = replaceSubstring(x_brandname,"\\","");
				x_brandname = x_brandname.substring(0,(x_brandname.length)-1);
				
				fillSelection(x_brandname,x_brandid,sType);
				return;
			}
		//Change the class of the currently selected item to not selected
		if ((currentvalue>=0)&&(currentvalue<=ajaxtableRows.length))
			{
				var currentselectionid = 'aj'+ currentvalue;
				var currentselection =document.getElementById(currentselectionid);
				currentselection.className='popupAjaxItem';
			}
		//act based on the key hit
		switch(unicode)
			{
				case 40:
					//alert('up key');
					if ((currentvalue+1) < ajaxtableRows.length)
						currentvalue += 1;
					else
						currentvalue = 0;
					break;
				case 38:
					//alert('down key');
					if ((currentvalue-1) >=0 )
						currentvalue -= 1;
					else
						currentvalue = ajaxtableRows.length-1;
					break;
			}
		current.value = currentvalue;
		var ajaxLinkID ='aj'+ currentvalue;
		var ajaxLink = document.getElementById(ajaxLinkID);
		ajaxLink.className='selectedpopupAjaxItem popupAjaxItem';
		if (sType=="BRAND")
			brandname.focus();
		if (sType=="PRODUCT")
			productname.focus();
		return;
		}
	else
		//reset current value for when the list changes
		current.value = -1;


	gbCategoryAware = bCategoryAware;
	gsType = sType;


	/*Show ajax table*/
	var toggle = document.getElementById('completeTable');
	toggle.className = 'ShowAjaxTable';
	clearTable();

    if (sType=="BRAND")
    {
		if (brandname.value == "")
		{
			clearTable();
		}
		else
		{
			var Catind = myForm.CategoryID.selectedIndex;
			var Catval = myForm.CategoryID.options[Catind].value;
			var url = "/ajax/AjaxGetBrands.asp?q="  + escape(brandname.value);
			if (bCategoryAware==true)
				{
					url += '&categoryid=' + Catval;
				}
			var ajax = new AJAXInteraction(url);
			ajax.send();
		}
	}
    if (sType=="PRODUCT")
    {
		// Clear previous selection
		clearSelection("PRODUCT");

		if (productname.value == "")
		{
			clearTable();
		}
		else
		{
			var url = "/ajax/AjaxSearchProducts.asp?q="  + escape(productname.value);
			var ajax = new AJAXInteraction(url);
			ajax.send();
		}
	}

}

function init() {
    var menu;
    brandname = document.getElementById("brandname");
    productname =  document.getElementById("productname");
    myForm =  document.getElementById("horizontalForm");
    if (myForm==null)
    	myForm =  document.getElementById("verticalForm");

   	if (!(brandname==null))
   		{
			brandname.readOnly = false;
			// get the brand name box for its location
			menu = document.getElementById("brandname");
		}
	else
		// get the brand name box for its location
		menu = document.getElementById("productname");
	// Get the complete table div
    autorow = document.getElementById("menu-popupAjax");
   	// move it to just below and to the right of theb input box
   	if (!(autorow==null) && !(menu==null))
	{
		autorow.style.top = (getElementY(menu)+20) + "px";
		autorow.style.left = (getElementX(menu)+20) + "px";
	}
    completeTable = document.getElementById("completeTable");
   	if (!(completeTable==null))
   	{
    	completeTable.setAttribute("bordercolor", "white");
    	//MM 3/3/2007 trying to set z-index
    	//completeTable.setAttribute("z-index","10");
	}
    // MM detect IE7
    var is = new Is();
    isIE7 = is.ie7;
    bInit = true;
}




function postProcess(objResponseXML)
{

    clearTable();
    var items = objResponseXML.getElementsByTagName("items")[0];

    if (items.childNodes.length > 0)
    	{
    	    completeTable.setAttribute("bordercolor", "black");
    	    completeTable.setAttribute("border", "1");
    	}
    else
    	{
    	    clearTable();
    	    // MM added 10/10/2006 to clear the brand id if no results found
    	    if (!(brandname==null))
    	    myForm.Brand.value="";
    	    clearSelection("PRODUCT");
		}
		for (loop = 0; loop < items.childNodes.length; loop++) {
	    var item = items.childNodes[loop];
        if (isIE)
        	{
			var itemName = item.getElementsByTagName("n")[0];
			var itemId = item.getElementsByTagName("i")[0];
			var itemStatus = item.getElementsByTagName("s")[0];
    		appendItem(itemName.childNodes[0].nodeValue,itemId.childNodes[0].nodeValue, itemStatus.childNodes[0].nodeValue,loop);
			}
		else
			{
				if (item.childNodes.length>0)
					{
						var itemName = item.getElementsByTagName("n")[0];
						var itemId = item.getElementsByTagName("i")[0];
						var itemStatus = item.getElementsByTagName("s")[0];
						appendItem(itemName.childNodes[0].nodeValue,itemId.childNodes[0].nodeValue, itemStatus.childNodes[0].nodeValue,loop);
					}
			}
    	}
}

function clearTable() {

    if (completeTable) {
      completeTable.setAttribute("bordercolor", "white");
      completeTable.setAttribute("border", "0");
      completeTable.style.visible = false;
      for (loop = completeTable.childNodes.length -1; loop >= 0 ; loop--) {
      	completeTable.removeChild(completeTable.childNodes[loop]);
      }
    }
}

function appendItem(Item,itemId,itemStatus,loop) {
    var row;
    var nameCell;
    var attr;

    if ((isIE) || (isIE7)) {
        row = completeTable.insertRow(completeTable.rows.length);
        nameCell = row.insertCell(0);
    } else {
        row = document.createElement("tr");
        nameCell = document.createElement("td");
        row.appendChild(nameCell);
        completeTable.appendChild(row);
    }
    row.className = "popupAjaxRow";
    nameCell.setAttribute("bgcolor", "#FFFAFA");

    var linkElement = document.createElement("a");
    linkElement.className = "popupAjaxItem";
    if (itemStatus==0)
    {
    	Item += " *discontinued*";
    }
    var hRef = "javascript:fillSelection('" + escapeme(Item) + "'," + itemId + ",'" + gsType + "')";
    linkElement.setAttribute("href", hRef);
    linkElement.setAttribute("id",'aj'+loop);
    linkElement.appendChild(document.createTextNode(Item ));
    nameCell.appendChild(linkElement);
}

function fillSelection(itemText,itemId,itemType) {
   	if (itemType=="BRAND")
   	{
  	 	myForm.brandname.value = itemText;
   		myForm.Brand.value = itemId;
	}
   	if (itemType=="PRODUCT")
   	{
  	 	myForm.productname.value = itemText;
   		myForm.Product.value = itemId;
   		myForm.submit.disabled = false;
	}
   	if (!(completeTable==null))
		completeTable.className = 'HideAjaxTable';

   clearTable();
}

function clearSelection(sType) {
	if (sType=="BRAND")
	{
   		myForm.Brand.value = "";
	}
	if (sType=="PRODUCT")
   	{
		if (!(productname==null))
		{
   		myForm.Product.value = "";
   		myForm.submit.disabled = true;
		}

	}
}

function checkValue(sType) {
	if (sType=="BRAND")
	{
   		if (myForm.brandname.value=='')
   			clearSelection(sType)
	}
}

function changeCategorySelectionForAjax()
{
	brandname = document.getElementById("brandname");
	if (gbCategoryAware==true)
		{	brandname.value = '';
		}
}
// free to use just leave this copyright notice intact
// eddie traversa etraversa@dhtmlnirvana.com
// http://dhtmlnirvana.com/
function Is() {
  agent       = navigator.userAgent.toLowerCase();
  this.major  = parseInt(navigator.appVersion);
  this.minor  = parseFloat(navigator.appVersion);

  this.ns     = ((agent.indexOf('mozilla')   != -1) &&
                (agent.indexOf('spoofer')    == -1) &&
                (agent.indexOf('compatible') == -1) &&
                (agent.indexOf('opera')      == -1) &&
                (agent.indexOf('webtv')      == -1) &&
                (agent.indexOf('hotjava')    == -1));

  this.ns2    = (this.ns && (this.major      ==  2));
  this.ns3    = (this.ns && (this.major      ==  3));
  this.ns4    = (this.ns && (this.major      ==  4));
  this.ns6    = (this.ns && (this.major      >=  5));

  this.ie     = ((agent.indexOf("msie")      != -1) &&
                (agent.indexOf("opera")      == -1));

  this.ie3    = (this.ie && (this.major      <   4));

  this.ie4    = (this.ie && (this.major      ==  4) &&
                (agent.indexOf("msie 4")     != -1));

  this.ie5    = (this.ie && (this.major      ==  4) &&
                (agent.indexOf("msie 5.")    != -1) &&
                (agent.indexOf("msie 5.5")   == -1) &&
                (agent.indexOf("mac")        == -1));

  this.iem5   = (this.ie && (this.major      ==  4) &&
  				(agent.indexOf("msie 5.")    != -1) &&
				(agent.indexOf("mac")        != -1));

  this.ie55   = (this.ie && (this.major      ==  4) &&
  				(agent.indexOf("msie 5.5")   != -1));

  this.ie6    = (this.ie && (this.major      ==  4) &&
  				(agent.indexOf("msie 6.")    != -1));
  this.ie7    = (this.ie && (this.major      ==  4) &&
  				(agent.indexOf("msie 7")    != -1));
  this.nsdom  = (this.ns4 || this.ns6);
  this.ie5dom = (this.ie5 || this.iem5   || this.ie55);
  this.iedom  = (this.ie4 || this.ie5dom || this.ie6);
  this.w3dom  = (this.ns6 || this.ie6 ||this.ie7);
}


function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;
     else
          key = e.which;

     if(key == 13)
          return false;
     else
          return true;
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function



 