/********************************************************
*	Creates a Username ComboBox Object
*	Extends ylib_List by JChu
*
*	@author      Ava Hristova
*	@version     1.00
*	@copyright   Yahoo! Inc
********************************************************/

var canHide = false;
var canTraverse = false;
var inDD = false;
document.onclick = clearMenu;
document.onkeydown = travMenu;
document.onkeyup = autoComplete;

var offsetX = 0;	// x offset of dropdown
var offsetY = 22;	// y offset of dropdown

	
// list constructor
function UserList(id, width, fmField, nFocField) {
	this.name = id;
	this.base = ylib_List;
	this.base(id, width);
	this.w = width;
	this.els = this.hideEl = this.holder = this.refObj = this.itmStyle = this.hdrStyle = null;
	this.isOpen = false;
	this.locX = this.locY = 0; this.selIdx = -1;
	this.color.onBg = '#C6F2F9';
	this.color.offBg = '#ECF9FD';
	this.color.bdyBg = null;
	this.formField = fmField;
	this.nextField = nFocField;
	this.ddImg = ylib_getObj("ddCtrlr");
	
	this.addItms = ulAdd;
	this.autocomplete = ulAutocomplete;
	this.build = ulBuild;
	this.getPos = ulGetPos;
	this.init = ulInit;
	this.over = ulItmOver;
	this.selItm = ulSelItm;
	this.show = ulShow;
	this.turnOn = ulTurnOn;
	this.handleImg = ulHandleImg;
	
	//this.init();
}
UserList.prototype = new (ylib_List);

/********************************************************
*	function: ulAdd()
*	adds a number of elements to the dropdown menu
*	parameters: items - the array of items
********************************************************/
function ulAdd(items) {
	if (items != null) {
		items[0] = txtOther; 
		this.els = new (Array)(); this.els = items;
		nItems = this.els.length;
		
		for (var i = 0; i < nItems; i++) {
			 _proxy_jslib_assign('', this.items, (i), '=', ( new (Array)()));
			 _proxy_jslib_handle(this.items, (i), 0, 0).val =  _proxy_jslib_handle(this.els, (i), 0, 0);
			 _proxy_jslib_handle(this.items, (i), 0, 0).lnk = '<a href="" onClick="' + this.id + '.selItm(' + i + ');" style="width: 100%; ' + this.itmStyle + '">' +  _proxy_jslib_handle(this.items, (i), 0, 0).val + '</a>';
			 _proxy_jslib_assign('', this.items, (i), '=', ( '<div id="' + this.id + i + '" onClick="' + this.id + '.selItm(' + i + '); return false;" onMouseOver="' + this.id + '.over(' + i + ', 1)" style="width: 100%; cursor : pointer;"><div style="width:' + (this.w - 10) + '; padding: 5px 5px ; overflow: hidden;">' +  _proxy_jslib_handle(this.items, (i), 0, 0).lnk + '</div></div>\n'));
		}
	}
}

/********************************************************
*	function: ulAutocomplete()
*	autocompletes the form field with the available entries
*	parameters: keyCd - the calling key
********************************************************/
function ulAutocomplete(keyCd) {
	var matchLoc = false;
	var curFieldVal =  _proxy_jslib_handle(this.formField, 'value', '', 0, 0);
	
	if ( _proxy_jslib_handle(this.formField, 'value', '', 0, 0).length == 0) {	// if nothing is entered, leave
		return;
	}
	
	switch (keyCd) {
		case 38: //up arrow  
		case 40: //down arrow
		case 37: //left arrow
		case 39: //right arrow
		case 33: //page up  
		case 34: //page down  
		case 36: //home  
		case 35: //end                  
		case 13: //enter  
		case 9:	 //tab  
		case 27: //esc  
		case 16: //shift  
		case 17: //ctrl  
		case 18: //alt  
		case 20: //caps lock
		case 8:  //backspace  
		case 46: //delete
			return true;
			break;
		default:
	}
	
	for (var i = 0; i < this.els.length; i++) {	// find the first matching item entry
		if (matchLoc =  _proxy_jslib_handle(this.els, (i), 0, 0).toLowerCase().indexOf(curFieldVal.toLowerCase()) == 0) {
			break;
		}
	}
	
	if (matchLoc) {
		if (typeof this.formField.selectionStart != 'undefined') { // handle Mozilla
			 _proxy_jslib_assign('', this.formField, 'value', '=', (  _proxy_jslib_handle(this.els, (i), 0, 0)));
			
			this.formField.setSelectionRange(curFieldVal.length,  _proxy_jslib_handle(this.formField, 'value', '', 0, 0).length);
		} else if (this.formField.createTextRange) { // handle IE
			 _proxy_jslib_assign('', this.formField, 'value', '=', (  _proxy_jslib_handle(this.els, (i), 0, 0)));
			
			var range = this.formField.createTextRange();
			range.moveStart('character', curFieldVal.length);
			range.moveEnd('character',  _proxy_jslib_handle(this.formField, 'value', '', 0, 0).length);
			range.select();
		}
	}
	
	this.selIdx = matchLoc ? i : 0;
}

/********************************************************
*	function: ulBuild()
*	creates the dropdown menu
*	parameters: none
********************************************************/
function ulBuild() {
	this.div = '<div id="' + this.id + 'holder" style="' + this.hdrStyle + 'visibility: hidden; position:absolute; left:-500px; top:-500px; width: ' + this.w + '; margin: 0; padding: 0; z-index: 100; overflow: hidden;">\n';
	this.div += this.items.join('');
	this.div += '</div>';
}

/********************************************************
*	function: ulGetPos()
*	gets the x and y coordinates of where the dropdown is to appear
*	parameters: none
********************************************************/
function ulGetPos() {
	this.locX = ylib_getPageX(this.refObj);
	this.locY = ylib_getPageY(this.refObj);
}

/********************************************************
*	function: ulHandleImg()
*	determines which image to display for dropwdown handler
*	parameters: onState - weather the flydown menu is open or not
********************************************************/
function ulHandleImg(onState) {
	newImgLoc = "https://sec.yimg.com/i/us/plus/el/";
	
	if (!this.isOpen) {
		newImgLoc += onState ? 'cb_sdd_up.gif' : 'cb_sdd_dn.gif';
	} else {
		newImgLoc += 'cb_sdd_dn.gif';
	}
	
	 _proxy_jslib_assign('', this.ddImg, 'src', '=', ( newImgLoc));
}

/********************************************************
*	function: ulInit()
*	initializes the combobox menu
*	parameters: none
********************************************************/
function ulInit() {
	this.addItms(usersArr);
	this.build();
	 _proxy_jslib_handle(document, 'write', '', 1, 0)(this.div);
	
	this.holder = ylib_getObj(this.id + 'holder');
	this.refObj = ylib_getObj('comboBox');
	this.els[0] = "";	// if user selects '( other user )', username field value should be empty
}

/********************************************************
*	function: ulItmOver()
*	handle item hover state
*	parameters: idx - the element to be highlighted, state - turn on or off state
********************************************************/
function ulItmOver(idx, state) {
	for (var i = 0; i < this.els.length; i++) {
		this.turnOn(ylib_getObj(this.id + i), 0);
	}
	this.turnOn(ylib_getObj(this.id + idx), state);
}

/********************************************************
*	function: ulSelItm()
*	writes the item value within the form field
*	parameters: idx - the item chosen
********************************************************/
function ulSelItm(idx) {
	 _proxy_jslib_assign('', this.formField, 'value', '=', (  _proxy_jslib_handle(this.els, (idx), 0, 0)));
	this.selIdx = idx;

	if ((idx == 0) || (this.nextField == null)) {
		this.formField.focus();
	} else if (this.nextField != null) {
		this.nextField.focus();
	}
}

/********************************************************
*	function: ulShow()
*	hides and shows the dropdown menu
*	parameters: none
********************************************************/
function ulShow() {
	this.getPos();
	if (!this.isOpen) {	// display menu
		canScroll = false;
		ylib_show(this.holder);
        this.holder.style.visibility = 'visible';
        this.holder.style.display = 'block';
        login_input =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)('login');
        var dv = document.defaultView;

        var new_x = 0;
        var new_y = 0;

        if (login_input.getBoundingClientRect) { // IE
            /* remove it from it's current location in the document & insert it as a child of the body */
            this.holder.parentNode.removeChild(this.holder);
             _proxy_jslib_handle(document, 'body', '', 0, 0).appendChild(this.holder);
            /* Reset the Width of the object */
            this.holder.style.width = this.w + 'px';
            this.holder.style.textAlign = 'left';
            /* Get it's location on the page  */
            box = login_input.getBoundingClientRect();
            var doc = document;
            var scrollTop = Math.max(doc.documentElement.scrollTop,  _proxy_jslib_handle(doc, 'body', '', 0, 0).scrollTop);
            var scrollLeft = Math.max(doc.documentElement.scrollLeft,  _proxy_jslib_handle(doc, 'body', '', 0, 0).scrollLeft);
            new_x = ((box.left + scrollLeft) - 2);
            new_y = ((( _proxy_jslib_handle(box, 'top', '', 0, 0) + scrollTop) + offsetY) - 2);
        } else { //Good Browsers
            var login_f =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)('login_form');
            var ua = navigator.userAgent.toLowerCase();
            if (ua.indexOf('opera') > -1) {
                /* This is not right.. I should not have to do this. */
                if (login_f.tagName.toLowerCase() == 'a') {
                    login_f = login_f.nextSibling.nextSibling;
                }
            }
            this.holder.parentNode.removeChild(this.holder);
            login_f.appendChild(this.holder);
            new_x = login_input.offsetLeft;
            new_y = (login_input.offsetTop + login_input.offsetHeight);
        }
        //alert('X: ' + new_x + "\nY: " + new_y);
		ylib_moveTo(this.holder, new_x, new_y);
		//ylib_moveTo(this.holder, this.locX + offsetX, this.locY);
		this.isOpen = true;
	} else {	// hide menu
		canScroll = true;
		ylib_hide(this.holder);
		this.isOpen = false;
		
		// redraw screen for Mac IE (bug #: 152029)
		if ((oBw.mac &&  oBw.ie5) && (this.color.bdyBg != null)) {
			//document.body.style.backgroundColor = "red";
			//document.body.style.backgroundColor = this.color.bdyBg;
		}
	}
	
	if (this.selIdx != -1) {
		this.over(this.selIdx, 1);
	}
}

/********************************************************
*	function: ulTurnOn()
*	(un)highlights a specific element if hovered over
*	parameters: obj - the object to modify, state - the highlight state
********************************************************/
function ulTurnOn(obj, state) {
	if (state == 1) {
		ylib_setStyle(obj, "backgroundColor", this.color.onBg);
	} else {
		ylib_setStyle(obj, "backgroundColor", this.color.offBg);
	}
}






/*************************** Non-Object Functions ***************************/
var canScroll = true;
window.onscroll = handleScroll;

/********************************************************
*	function: clearMenu()
*	hides the menu if user clicks outside of it
*	parameters: none
********************************************************/
function clearMenu() {
	if (canHide && usersMenu.isOpen) {
		usersMenu.show();
	}
}

/********************************************************
*	function: handleScroll()
*	enables scrolling on page depending on set flag
*	parameters: none
********************************************************/
function handleScroll() {
	return canScroll;
}

/********************************************************
*	function: travMenu()
*	traverses the values within the dropdown in the form field
*	parameters: evt - key stroke
********************************************************/
function travMenu(evt) {
	if (canTraverse) {
		// get key code
		keyCd = document.layers ? evt.which : document.all ? event.keyCode :  _proxy_jslib_handle(document, 'getElementById', '', 0, 0) ? evt.keyCode : 0;
		if (keyCd == 40) { // scroll down
			canScroll = false;
			if (usersMenu.selIdx < usersMenu.els.length - 1) {
				 _proxy_jslib_assign('', usersMenu.formField, 'value', '=', (  _proxy_jslib_handle(usersMenu.els, (usersMenu.selIdx + 1), 0, 0)));
				usersMenu.selIdx++;
				usersMenu.over(usersMenu.selIdx, 1);
			}
		} else if (keyCd == 38) { // scroll up
			canScroll = false;
			if (usersMenu.selIdx > 0) {
				 _proxy_jslib_assign('', usersMenu.formField, 'value', '=', (  _proxy_jslib_handle(usersMenu.els, (usersMenu.selIdx - 1), 0, 0)));
				usersMenu.selIdx--;
				usersMenu.over(usersMenu.selIdx, 1);
			}
		} else if (keyCd == 27) { // escape
			if (usersMenu.isOpen) {
				usersMenu.show();
			}
		} else if (keyCd == 32) { // space
			if (!usersMenu.isOpen && inDD) {
				usersMenu.show();
			}
		} else {
			// determine if we are in dropdown element or not
			if (inDD) {	// we are
				/* get the alphanumeric value of the keycode */
				keychar = String.fromCharCode(keyCd);
				
				/* declare permissible characters */
				alphaNumStr = "abcdefghijklmnopqrstuvwxyz0123456789";	// NOTE: WILL have to change this to include international characters

				/* check to see if key pressed is within allowed characters */				
				if (alphaNumStr.indexOf(keychar.toLowerCase()) > -1) { // it is
					/* clear password input field and focus onto it */
					 _proxy_jslib_assign('', usersMenu.nextField, 'value', '=', ( ""));
					usersMenu.nextField.focus();
				}
			}
		}
	}
}

/********************************************************
*	function: autoComplete()
*	tried to guess what the entry is and autocompletes username
*	parameters: evt - key stroke
********************************************************/
function autoComplete(evt) {
	if (canTraverse) {
		// get key code
		keyCd = document.layers ? evt.which : document.all ? event.keyCode :  _proxy_jslib_handle(document, 'getElementById', '', 0, 0) ? evt.keyCode : 0;
		if ((keyCd != 38) && (keyCd != 40) && (keyCd != 27)) {
			usersMenu.autocomplete(keyCd);
			canScroll = true;
		}
	}
}

/********************************************************
*	function: enableScroll()
*	stop scrolling of window when dropdown is open
*	parameters: none
********************************************************/
function enableScroll() {
	if (usersMenu.isOpen) {
		window.scrollTo(0, 0);
	}
}
 ;
_proxy_jslib_flush_write_buffers() ;