CARE2.autoComplete = function(t, u, param) {
	var obj = {};
	if(!param) param = {};

	obj.tofield = null;                                       // ajax request
	obj.tofield_drop = null;                                  // drop down div
	obj.field = $(t);                                         // target textarea
	obj.uri = u;                                              // ajax url
	obj.curvalues = [];                                       // array of current values
	obj.suggestions = [];                                     // array of suggestions
	obj.highlighted = null;                                   // highlighted index
	obj.class_name = (param.class_name||'auto_complete');     // class name for drop down
	obj.delimeter = (param.delimeter||',');                   // delimeter for current values
	obj.new_delimeter = (param.new_delimeter||', ');          // delimeter for new values
	obj.property = (param.property||false);                   // property with the desired value if ajax returns a json object
	obj.display = (param.display||false);                     // if param.property is an array, this is how to format the display
	obj.mouseover = false;                                    // see if the mouse is over the drop down or not

	obj.keys = {tab: 9, enter: 13, keyup: 38, keydown: 40, esc: 27};

	obj.hide = function() {							// hide drop down
		if(obj.tofield_drop) {
			obj.tofield_drop.parentNode.removeChild(obj.tofield_drop);
			obj.tofield_drop = null;
		}

		obj.tofield = null;
		return false;
	}

	obj.show = function() {
	    obj.fieldinfo = {top: CARE2.getElementPosition(obj.field).top + obj.field.offsetHeight + 3, left: CARE2.getElementPosition(obj.field).left, width: obj.field.offsetWidth - 2};

		if(!obj.tofield_drop) {
			obj.tofield_drop = document.createElement('ul');
			obj.tofield_drop.className = obj.class_name;
			obj.tofield_drop.onmouseover = function() { obj.mouseover = true; }
			obj.tofield_drop.onmouseout = function() { obj.mouseover = false; }
			CARE2.appendToBody(obj.tofield_drop);
		}else{
			for(var i = obj.tofield_drop.childNodes.length - 1; i >= 0; i--) obj.tofield_drop.removeChild(obj.tofield_drop.childNodes[i]);
		}

        obj.tofield_drop.style.width = obj.fieldinfo.width + "px";
        obj.tofield_drop.style.top = obj.fieldinfo.top + "px";
        obj.tofield_drop.style.left = obj.fieldinfo.left + "px";

		obj.highlighted = null;
		for(var x = 0; x < obj.li.length; x++) obj.tofield_drop.appendChild(obj.li[x]);
	}

	obj.useSuggestion = function(i) {					// use suggestion and hide drop down
		var email = obj.suggestions[(i) ? i : obj.highlighted];
		if(email) {
			obj.curvalues[obj.curvalues.length - 1] = email.replace(/^\s+|\s+$/g, '').replace(/&lt;/g, "<").replace(/&gt;/g, ">");
			obj.field.value = obj.curvalues.join(", ") + ", ";
		}
		obj.hide();
		setTimeout(function() { obj.field.focus() },0);
	}

	obj.highlight = function(i) {						// change highlighted suggestion
		obj.highlighted = i;
		for(var x = 0; x < obj.li.length; x++) obj.li[x].className = null;
		obj.li[i].className = "active";
	}

	obj.getCurValues = function() {					// get current values
		var curvalues = obj.field.value.split(obj.delimeter);
		for(var x = 0; x < curvalues.length; x++) curvalues[x] = curvalues[x].replace(/^\s+|\s+$/g, '');
		return curvalues;
	}

	obj.addOnMouseUp = function(func) {
		var oldfunc = document.onmouseup;
		if (typeof document.onmouseup != 'function') {
			document.onmouseup = func;
		}else{
			document.onmouseup = function() {
				if(oldfunc) oldfunc();
				func();
			}
		}
	}

	obj.addOnMouseUp(function() { if(!obj.mouseover) obj.hide(); });

	obj.field.onkeydown = function(ev) {
		if(obj.tofield_drop) {
			var ev=window.event?event:ev;
			var unicode=ev.keyCode?ev.keyCode:ev.charCode;
			switch(unicode) {
				case obj.keys.tab:
				case obj.keys.enter:
					obj.useSuggestion();
					break;
				case obj.keys.esc:
					obj.hide();
					break;
				case obj.keys.keyup:
					var newhi = ((obj.highlighted - 1 < 0)||(obj.highlighted == null)) ? obj.suggestions.length-1 : obj.highlighted - 1;
					obj.highlight(newhi);
					break;
				case obj.keys.keydown:
					var newhi = ((obj.highlighted+1 > obj.suggestions.length-1)||(obj.highlighted == null)) ? 0 : obj.highlighted + 1;
					obj.highlight(newhi);
					break;
			}
		}
	}

	obj.field.onkeyup = function(ev) {
		if(!obj.tofield) {
			var ev=window.event?event:ev;
			var unicode=ev.keyCode?ev.keyCode:ev.charCode;
			switch(unicode) {
				case obj.keys.tab:
				case obj.keys.enter:
				case obj.keys.keyup:
				case obj.keys.keydown:
				case obj.keys.esc:
					return;
				default:
				obj.curvalues = obj.getCurValues();
				obj.cursearch = obj.curvalues[obj.curvalues.length - 1];
				if(obj.cursearch.length < 1) { obj.hide(); return false; }
				obj.suggestions = new Array();

				obj.tofield = YAHOO.util.Connect.asyncRequest('GET', obj.uri, {
					success: function(o) {
						obj.li = new Array();
						var i = 0;
						var values = eval("("+o.responseText+")");
						for(var x=0;x<values.length;x++) {
							if(obj.property) {
								if(typeof obj.property != "string") {
									var y = false;
									for(var j = 0; j < obj.property.length; j++) {
										var temp = values[x][obj.property[j]].split(" ");
										for(var k = 0; k < temp.length; k++)
											if(temp[k].indexOf(obj.cursearch) == 0 && temp[k] != obj.cursearch)
												y = true;
									}
									if(y) {
										y = (obj.display) ? obj.display : obj.property.join(" ");
										for(var j = 0; j < obj.property.length; j++)
											while((y.indexOf(obj.property[j]) >= 0) && (obj.property[j] != values[x][obj.property[j]]))
												y = y.replace(obj.property[j], values[x][obj.property[j]]);
									}
								}else{
									var y = values[x][obj.property];
									y = (y.indexOf(obj.cursearch) == 0 && y != obj.cursearch) ? y : false;
								}
							}else{
								var y = (values[x].indexOf(obj.cursearch) == 0 && values[x] != obj.cursearch) ? values[x] : false;
							}
							if(y) {
								obj.suggestions[i] = y.replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
								obj.li[i] = document.createElement('li');
								obj.li[i].innerHTML = obj.suggestions[i].replace(obj.cursearch, "<strong>" + obj.cursearch + "</strong>");
								obj.li[i].onmouseover = function(i) { return function() { obj.highlight(i); }}(i);
								obj.li[i].onclick = function(i) { return function() { obj.useSuggestion(i); }}(i);
								i++;
							}
						}

						obj.tofield = null;
						if(obj.suggestions.length < 1) { obj.hide(); return false; }
						obj.show();
						if(!obj.highlighted) obj.highlight(0);
					},
					failure: function(o) {
						return false;
					}
				});
			}
		}
	}

	return obj;
}

var shareMe = function(id, args) {
	var obj = {
	    id:id,
	    url:args.url,
	    title:args.title,
	    system_key:args.system_key,
	    heights:{},
	    curView:'share_small',
	    hovering: false
	};

	obj.buttons = {
	    fav: $(id + "_fav"),
	    share: $(id + "_share"),
	    friend: $(id + "_friend"),
	    print: $(id + "_print")
	}

	obj.getHeight = function(d) {
	    return d.offsetHeight - parseInt(YAHOO.util.Dom.getStyle(d, 'padding-top')) - parseInt(YAHOO.util.Dom.getStyle(d, 'padding-bottom'));
	}

	obj.switchView = function(v) {
	    var oldView = $(this.id + "_" + this.curView);
	    var newView = $(this.id + "_" + v);
	    this.curView = v;

	    if(oldView != newView) {
            if(oldView) {
                if(!obj.heights[oldView.id]) obj.heights[oldView.id] = obj.getHeight(oldView);/*parseInt(YAHOO.util.Dom.getStyle(oldView, 'height'));*/
                var collapse = new YAHOO.util.Anim(oldView, {height: {to:0}});
                collapse.duration = parseInt(YAHOO.util.Dom.getStyle(oldView, 'height')) / 800;
            }

            if(newView) {
                if(!obj.heights[newView.id]) {
                    newView.style.visibility = "hidden";
                    newView.style.display = "block";
                    obj.heights[newView.id] = obj.getHeight(newView);/*parseInt(YAHOO.util.Dom.getStyle(newView, 'height'));*/
                    newView.style.display = "none";
                    newView.style.visibility = "visible";
                }

                var expand = new YAHOO.util.Anim(newView, {height: {from:0,to:obj.heights[newView.id]}});
                expand.duration = obj.heights[newView.id] / 800;
            }

            if(collapse) {
                collapse.onComplete.subscribe(function(){
                    oldView.style.display = "none";
                    if(newView) {
                        newView.style.height = 0;
                        newView.style.display = "block";
                        expand.animate();
                    }
                });
            }

            if(oldView) {
                collapse.animate();
            }else{
                newView.style.height = 0;
                newView.style.display = "block";
                expand.animate();
            }
        }
	}

	obj.viewEvent = function(e, obj) {
	    this.blur();
	    YAHOO.util.Event.preventDefault(e);

	    if(this.id.indexOf('share') > -1) {
	        obj.activateTab('share');
	        obj.switchView('share_big');
	    }else{
	        obj.activateTab('friend');
	        obj.switchView('tellafriend');
	    }
	}

    obj.activateTab = function(t) {
	    for(var i in this.buttons) {
	        if(this.buttons[i] && this.buttons[i].parentNode) {
	            CARE2.removeClassName(this.buttons[i], "active");
	            CARE2.removeClassName(this.buttons[i].parentNode, "active");
	        }
	    }

        if(this.buttons[t] && this.buttons[t].parentNode) {
            CARE2.addClassName(this.buttons[t], "active");
            CARE2.addClassName(this.buttons[t].parentNode, "active");
        }
    }

	obj.closeAll = function(e, obj) {
	    var obj = obj||this;
	    obj.activateTab('share');
	    obj.switchView('share_small');
	}

	obj.sendMessage = function(e, obj) {
	    this.blur();
	    YAHOO.util.Event.preventDefault(e);

        var requrl = "http://"+CARE2.stage+"www.care2.com/share/email.html?to="+escape($(obj.id+'_share_addresses').value)+"&name="+escape($(obj.id+'_share_name').value)+"&from="+escape($(obj.id+'_share_email').value);
        requrl += "&title="+obj.title+"&body="+escape($(obj.id+'_share_message').value)+"&url="+obj.url+"&system_key="+obj.system_key;

        var request = YAHOO.util.Connect.asyncRequest('GET', requrl, {
            success:function(o){
                obj.closeAll();
            },
            failure:function(o){
                alert("Unexpected error, please try again");
            }
        });
	}

	obj.mouseOver = function(e, obj) { obj.hovering = true; }
	obj.mouseOut = function(e, obj) { obj.hovering = false; }
	obj.mouseUp = function(e, obj) { if(!obj.hovering) obj.closeAll(); }

	if(obj.buttons.share) YAHOO.util.Event.addListener([obj.buttons.share,$(id+"_share_more")], "click", obj.viewEvent, obj);
	if(obj.buttons.friend) YAHOO.util.Event.addListener(obj.buttons.friend, "click", obj.viewEvent, obj);

	YAHOO.util.Event.addListener([id + "_share_close_button",id + "_friend_close_button"], "click", obj.closeAll, obj);

    CARE2.defaultEntry(id+'_share_addresses', 'Separate multiple e-mail addresses by a comma. You can send up to 100 recipients.')
    var auto_complete = CARE2.autoComplete(id+'_share_addresses', 'http://'+CARE2.stage+'www.care2.com/servlets/address_book/manager.php', {property: ["PersonalEmail", "NickName"], display: '"NickName" <PersonalEmail>'});

    YAHOO.util.Event.addListener(id+'_button', "click", obj.sendMessage, obj);

    var hoverObjects = [id,$(id).parentNode,$(id+"_dropdown_wrapper")];

    YAHOO.util.Event.addListener(hoverObjects, "mouseover", obj.mouseOver, obj);
    YAHOO.util.Event.addListener(hoverObjects, "mouseout", obj.mouseOut, obj);
    YAHOO.util.Event.addListener(document, "mouseup", obj.mouseUp, obj);

	return obj;
}
