
/**
 * A location suggest div control
 * @class
 * @scope public
 */
function LocationSuggestControl(oPositionAnchor /*:Anchor to use as position offset point */,
									oFieldPrefix /*:Which location fields to update*/,
									oLeftOffset, oTopOffset) {
    
    this.selectionNodeStartIndex = 2;
    this.cur = this.selectNodeStartIndex - 1;
    this.leftOffset = oLeftOffset;
    this.topOffset = oTopOffset;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;
    
    /**
     * An anchor to use as an offset position point
     * @scope private
     */
    this.positionAnchor /*:HTMLInputElement*/ = oPositionAnchor;
   /**
     * The selected location code
     * @scope private
     */
   	this.fieldPrefix = oFieldPrefix;  
   	this.cellPrefix = "";
   	this.cellSuffix = "&nbsp;";
   	
   	this.estScrollBarWidth = 26;

    //initialize the control
    this.init();
    
}

/**
 * Creates Layer
 * Initializes layer with event functions
 * auto suggest functionality.
 * @scope private
 */
LocationSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //create the suggestions dropdown
    this.createDropDown();
    //assign onkeydown event handler
    this.layer.onkeydown = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };
    this.layer.onmousedown = 
	this.layer.onmouseup = 
	this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
       
        var eventX = oEvent.offsetX ? oEvent.offsetX : oEvent.layerX;
        var layerWidth = oThis.layer.childNodes[0].offsetWidth - oThis.estScrollBarWidth;
        var eventY = oEvent.offsetY ? oEvent.offsetY : oEvent.layerY;
        var layerHeight = oThis.layer.childNodes[0].offsetHeight - oThis.estScrollBarWidth;
        //alert (" event x is " + eventX + " layer width is " + layerWidth + " event y is " + eventY + " layer height is " + layerHeight);
			if (eventX > layerWidth || eventY > layerHeight) {
			   //alert ("eventX is greater than layerWidth or EventY greater than layer Height");
			   return;
			}
	    if (oTarget.nodeName != "TR") {
	    	oTarget = oThis.getSelectedRow(oTarget);
	    	//alert("target is " + oTarget.nodeName);
	    } 
        if (oEvent.type == "mousedown") {
            if (oTarget.rowIndex >= oThis.selectionNodeStartIndex) {
               if ("company_" == oThis.fieldPrefix) {
                  oThis.setOrderByFields(oThis.getSelectionNodes()[oThis.cur]);
               } else {
        		  oThis.setLocationFields(oTarget);
        	   }
        	}
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
        	if (oTarget.rowIndex >= oThis.selectionNodeStartIndex) {
            	oThis.hideSuggestions();
        	}
        }
    };
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
LocationSuggestControl.prototype.createDropDown = function () {

    var oThis = this;
	this.layer = document.getElementById('locSuggest');
	if (!this.layer) {
    	//create the layer and assign styles
    	this.layer = document.createElement("div");
    	this.layer.id = "locSuggest";
    	this.layer.className = "suggestions";
    	this.layer.style.visibility = "hidden";
    }
    document.body.appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
LocationSuggestControl.prototype.getLeft = function () {

    var oNode = this.positionAnchor;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY" && oNode.tagName != "HTML") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
    return iLeft + this.leftOffset;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
LocationSuggestControl.prototype.getTop = function ()  {

    var oNode = this.positionAnchor;
    var iTop = 0;
    
    while(oNode.tagName != "BODY" && oNode.tagName != "HTML") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop + this.topOffset;
};
/**
 * Returns the table rows in the div
 * @scope private
 */
LocationSuggestControl.prototype.getSelectionNodes = function ()  {
    return this.layer.childNodes[0].childNodes[0].childNodes;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
LocationSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
 		oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            this.layer.focus();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            this.layer.focus();
            break;
        case 13: //enter
            if ("company_" == this.fieldPrefix) {
            	this.setOrderByFields(this.getSelectionNodes()[this.cur]);
            } else {
            	this.setLocationFields(this.getSelectionNodes()[this.cur]);
            }
            this.hideSuggestions();
            break;
    }

};
LocationSuggestControl.prototype.getSelectedRow = function(oTarget) {
    if (oTarget.nodeName == "TR") return oTarget;
	else if (oTarget.nodeName == "DIV" || oTarget.nodeName == "TABLE" || oTarget.nodeName == "TBODY") {
		return this.getSelectedRow(oTarget.childNodes[0]);
	} else {
	    return this.getSelectedRow(oTarget.parentNode);
	}
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
LocationSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
LocationSuggestControl.prototype.highlightSuggestion = function (tableRow) {
    //alert ("in highlight suggestion");
    var tableRows = this.getSelectionNodes();
    
    for (var i=this.selectionNodeStartIndex; i < tableRows.length; i++) {
        var oNode = tableRows[i];
        if (oNode == tableRow) {
            oNode.className = "current"
            this.cur = i;
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
    this.layer.focus();
};



/**
 * Highlights the next suggestion in the dropdown
 * @scope private
 */
LocationSuggestControl.prototype.nextSuggestion = function () {
   
    var cSuggestionNodes = this.getSelectionNodes();
    if (cSuggestionNodes.length > this.selectionNodeStartIndex && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
    }
    this.layer.focus();
};

/**
 * Highlights the previous suggestion in the dropdown
 * @scope private
 */
LocationSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.getSelectionNodes();

    if (cSuggestionNodes.length > 0 && this.cur > this.selectionNodeStartIndex) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
    }
    this.layer.focus();
};
/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
LocationSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
    var oThis = this;
    this.layer.innerHTML = "";  //clear contents of the layer
    var tableEl = document.createElement("table");
    this.layer.appendChild(tableEl);
    var tbody = document.createElement("tbody");
    tableEl.appendChild(tbody);
    tbody.appendChild(this.getHeaderRow1());
    tbody.appendChild(this.getHeaderRow2());
    for (var i=0; i < aSuggestions.length; i++) {
        tableRow = document.createElement("tr");
        tbody.appendChild(tableRow);
        for (var k = 0; k < aSuggestions[i].length; k++) {
            var nextCell = document.createElement("td");
            nextCell.className = "Col" + k;
            nextCell.style.whiteSpace = "nowrap";
            tableRow.appendChild(nextCell);
        	nextCell.innerHTML = this.cellPrefix + aSuggestions[i][k] + this.cellSuffix;
        }
    }
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = this.getTop() + "px";
    this.layer.style.visibility = "visible";
    this.layer.focus();
    this.highlightSuggestion(this.layer.childNodes[0].childNodes[0].childNodes[this.selectionNodeStartIndex]);

};
LocationSuggestControl.prototype.getHeaderRow1 = function () {
    var oThis = this;
 	var tableRow = document.createElement("tr");
 	var cell = document.createElement("td");
 	cell.colSpan = 7;
 	cell.className = "titleText";
 	var closeWindow = document.createElement("img");
 	closeWindow.src = "/LTMSLite/images/closeSearchResults.gif";
 	closeWindow.width=197;
 	closeWindow.height=22;
 	closeWindow.hspace=25;
 	closeWindow.onclick = function (){
 		oThis.hideSuggestions();
 	}; 
	cell.appendChild(closeWindow);
	tableRow.appendChild(cell);
    return tableRow;
};
LocationSuggestControl.prototype.getHeaderRow2 = function () {
 	var tableRow = document.createElement("tr");
    var header1 = document.createElement("td");
    header1.className="header";
    header1.innerHTML = this.cellPrefix + 'Phone #' + this.cellSuffix;
    tableRow.appendChild(header1);
    var header2 = document.createElement("td");
    header2.className="header";
    header2.innerHTML = this.cellPrefix + 'Name' + this.cellSuffix;
    tableRow.appendChild(header2);
    var header5 = document.createElement("td");
    header5.className="header";
    header5.innerHTML = this.cellPrefix + 'City' + this.cellSuffix;
    tableRow.appendChild(header5);
    var header6 = document.createElement("td");
    header6.className="header";
    header6.innerHTML = this.cellPrefix + 'State' + this.cellSuffix;
    tableRow.appendChild(header6);
    var header3 = document.createElement("td");
    header3.className="header";
    header3.innerHTML = this.cellPrefix + 'Address1' + this.cellSuffix;
    tableRow.appendChild(header3);
    var header4 = document.createElement("td");
    header4.className="header";
    header4.innerHTML = this.cellPrefix + 'Address2' + this.cellSuffix;
    tableRow.appendChild(header4);
    var header7 = document.createElement("td");
    header7.className="header";
    header7.innerHTML = this.cellPrefix + 'Zip' + this.cellSuffix;
    tableRow.appendChild(header7);
    return tableRow;
};
LocationSuggestControl.prototype.setLocationFields = function (tableRow) {
    var locationNum = tableRow.cells[0].innerHTML;
    // if origin or destination set it now
    if (!isEmpty(this.fieldPrefix)) {
    	updateOriginDest(locationNum.substring(this.cellPrefix.length, locationNum.length - this.cellSuffix.length), this.fieldPrefix);
    }
    var locationName = tableRow.cells[1].innerHTML;
    var locationCity = tableRow.cells[2].innerHTML;
    var locationState = tableRow.cells[3].innerHTML;    
    var locationAddr1 = tableRow.cells[4].innerHTML;
    var locationAddr2 = tableRow.cells[5].innerHTML;
    var locationZip = tableRow.cells[6].innerHTML;
    if (this.fieldPrefix == "company_") {
        this.setOrderByFields(tableRow);
    } else {
		setInnerHTML(this.fieldPrefix + 'stopError','');
		setInnerHTML(this.fieldPrefix + 'numberDisplay',locationNum.substring(this.cellPrefix.length, locationNum.length - this.cellSuffix.length));
		setValue(this.fieldPrefix + 'stopLocationCode',locationNum.substring(this.cellPrefix.length, locationNum.length - this.cellSuffix.length));
		setValue(this.fieldPrefix + 'stopLocationName',locationName.substring(this.cellPrefix.length, locationName.length - this.cellSuffix.length));
		setInnerHTML(this.fieldPrefix + 'stopLocationAddress1',locationAddr1.substring(this.cellPrefix.length, locationAddr1.length - this.cellSuffix.length));
		setInnerHTML(this.fieldPrefix + 'stopLocationAddress2',locationAddr2.substring(this.cellPrefix.length, locationAddr2.length - this.cellSuffix.length));
		setValue(this.fieldPrefix + 'stopLocationCity',locationCity.substring(this.cellPrefix.length, locationCity.length - this.cellSuffix.length));
		setInnerHTML(this.fieldPrefix + 'stateDisplay',locationState.substring(this.cellPrefix.length, locationState.length - this.cellSuffix.length));
		setInnerHTML(this.fieldPrefix + 'stopLocationZipCode',locationZip.substring(this.cellPrefix.length, locationZip.length - this.cellSuffix.length));
	}
	changeImage(document.getElementById(this.fieldPrefix + 'findByNameButton'), 'images/findByName.gif');
};
LocationSuggestControl.prototype.clearLocationFields = function (tableRow) {
  if (this.fieldPrefix == "company_") {
    setInnerHTML('orderByCompanyError','');
	setInnerHTML(this.fieldPrefix + 'numberDisplay','');
	setValue('companyNumber','');
	setValue('companyName','');
	setInnerHTML('companyAddress1','');
	setValue('companyCity','');
	setInnerHTML(this.fieldPrefix + 'stateDisplay','');
	setInnerHTML('companyZipCode','');
  } else {
	setInnerHTML(this.fieldPrefix + 'stopError','');
	setInnerHTML(this.fieldPrefix + 'numberDisplay','');
	setValue(this.fieldPrefix + 'stopLocationCode','');
	setValue(this.fieldPrefix + 'stopLocationName','');
	setInnerHTML(this.fieldPrefix + 'stopLocationAddress1','');
	setInnerHTML(this.fieldPrefix + 'stopLocationAddress2','');
	setValue(this.fieldPrefix + 'stopLocationCity','');
	setInnerHTML(this.fieldPrefix + 'stateDisplay','');
	setInnerHTML(this.fieldPrefix + 'stopLocationZipCode','');
  }
};
LocationSuggestControl.prototype.setOrderByFields = function (tableRow) {
	showNumberSearchFields('company_');
    var compNum = tableRow.cells[0].innerHTML;
    setValue('companyNumber', compNum.substring(this.cellPrefix.length, compNum.length - this.cellSuffix.length));
    setRadioValue('companySearchType', 'company_phone');
    findCompanyByNumber();
};

