var sort_field = "last_name";
var alphabet_asc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
var alphabet_desc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'].reverse();

var alphabet = alphabet_asc;
var yh_contact_array = new Array();
var yh_groups = new Object();
var yh_sort_order = "n";
var yh_group_order = "g";

var yh_loading = false;
var yh_searching = false;
var yh_complete_object = null;

function load_yahoo_contacts(search, complete_object)
{
	if (!search)
	{
		// prevent simultaneous queries 
		if (yh_loading)
			return;
			
		var ab_page_url = ab_full_url;
		yh_loading = true;
		document.body.style.cursor = "wait";
		var type = "full";
	} else {
		// prevent simultaneous queries 
		if (yh_searching)
			return;
			
		var ab_page_url = ab_search_url + "&var1=" + encodeURIComponent(search);
		yh_searching = true;
		yh_complete_object = complete_object;
		var type = "search";
	}

	var doc_head = document.getElementsByTagName('head')[0];
	try
	{
		var old_script = document.getElementById('agi-yh-' + type + '-script');
	} catch(e) {
		var old_script = null;
	}
	var script = document.createElement("script");
	
	script.setAttribute("id", "agi-yh-load-script");
	script.setAttribute("src", ab_page_url);
	
	// replace or insert to yh ab load script tag
	if (old_script != null)
		doc_head.replaceChild(script, old_script);
	else
		doc_head.appendChild(script);
}

function contactClone(contact)
{
    for (i in contact) {
        this[i] = contact[i];
    }
}
function Contact()
{
	var contact = new Object()
	this.first_name = "";
	this.last_name = "";
	this.email = "";
	this.gender = null;
	this.relationship = "";
	this.relate_type = null;
	this.emails = new Array();
}

function init_yahoo_abload()
{
	yh_contact_array = new Array();
	yh_groups = new Object();
	
	if (typeof(ab_response.total_matches) == "undefined")
		var type = "full";
	else
		var type = "search";
		
	for (var i = 0; i < ab_response.contacts.length ; i++)
	{
		var contact = new Contact();
		ycontact = ab_response.contacts[i];
		for (var j = 0; j < ycontact.fields.length; j++)
		{
			field = ycontact.fields[j];
			if (field.type == "email")
			{
				var email = new Object()
				email.id = field.fid;
				email.email = trim(field.data);
				contact.emails.push(email);
			} else if (field.type == "name") {
				if (field.first)
					contact.first_name = trim(field.first);
				if (field.last)
					contact.last_name = trim(field.last);
			}
		}			
		//contact.full_name = make_contact_name(contact);

		for (email in contact.emails)
		{	
			var clone = new contactClone(contact);
			clone.email = contact.emails[email].email;
			clone.id = contact.emails[email].id;
			yh_contact_array.push(clone);
		}    

		if (ycontact.categories)
		{
			for (var k = 0; k < ycontact.categories.length; k++)
			{
				if (!yh_groups[ycontact.categories[k].catid])
				{
					var group = new Object();
					group.label = ycontact.categories[k].data;
					group.id = ycontact.categories[k].catid;
					group.contacts = [clone.id];
					yh_groups[ycontact.categories[k].catid] = group;
				} else {
					yh_groups[ycontact.categories[k].catid].contacts.push(clone.id);
				}
			}
		}
	}
	
	var yh_group_array = new Array();
	for (yh in yh_groups)
	{
		yh_group_array.push(yh_groups[yh]);
	}
	yh_group_array.sort(compare_contacts);

	// sort the contacts and add them to pl_contact object
	yh_contact_array.sort(yh_compare_lname);
	
	if (type == "full")
	{
		for (var i = 0; i < yh_contact_array.length; i++)
		{
			pl_contacts[yh_contact_array[i].id] = yh_contact_array[i];
		}
	
	
		for (var i = 0; i < yh_group_array.length; i++)
		{
			pl_groups[yh_group_array[i].id] = yh_group_array[i];
		}
	
		preloaded = true;
		groups_loaded = true;

		yh_loading = false;
		populate_popup_contacts();
	} else {
		yh_searching = false;
		yh_complete_object.doSearch(yh_contact_array, new Array());
	}
}

function sort_groups(order)
{
	var yh_group_array = new Array();
	for (pl in pl_groups)
	{
		yh_group_array.push(pl_groups[pl]);
	}
	yh_group_array.sort(compare_contacts);
	
	if (yh_group_order == order)
	{
		yh_group_array.reverse();
		yh_group_order = order + "d";
		document.getElementById("agi-sort-" + order + "d").style.display = "inline";
		document.getElementById("agi-sort-" + order).style.display = "none";
	} else {
		yh_group_order = order;
		document.getElementById("agi-sort-" + order + "d").style.display = "none";
		document.getElementById("agi-sort-" + order).style.display = "inline";
	}
	pl_groups = new Object();
	for (var i = 0; i < yh_group_array.length; i++)
	{
		pl_groups[yh_group_array[i].id] = yh_group_array[i];
	}
	
	populate_popup_groups();	
	
}
function sort_contacts(order)
{
	var container = document.getElementById('agi-contact-container');
	container.removeChild(document.getElementById("agi-contact-list-body"));
	var arrow_ids = ['agi-sort-e', 'agi-sort-ed', 'agi-sort-n', 'agi-sort-nd', 'agi-sort-fn', 'agi-sort-fnd'];
	
	for (id in arrow_ids)
	{
			document.getElementById(arrow_ids[id]).style.display = "none";
	}
	
	if (yh_sort_order == "n" && order == "n")
		yh_contact_array.sort(yh_reverse_compare_lname);
	else if (yh_sort_order != "n" && order == "n")
		yh_contact_array.sort(yh_compare_lname);
	else if (yh_sort_order != "fn" && order == "fn")
		yh_contact_array.sort(yh_compare_fname);
	else if (yh_sort_order == "fn" && order == "fn")
		yh_contact_array.sort(yh_reverse_compare_fname);
	else if (yh_sort_order != "e" && order == "e")
		yh_contact_array.sort(yh_compare_email);
	else if (yh_sort_order == "e" && order == "e")
		yh_contact_array.sort(yh_reverse_compare_email);
	
	if (yh_sort_order == order)
	{
		document.getElementById("agi-sort-" + order + "d").style.display = "inline";
		yh_sort_order = order + "d";
	} else {
		document.getElementById("agi-sort-" + order).style.display = "inline";
		yh_sort_order = order;
	}

	pl_contacts = new Object();
	for (var i = 0; i < yh_contact_array.length; i++)
	{
		pl_contacts[yh_contact_array[i].id] = yh_contact_array[i];
	}
	populate_popup_contacts();	
}

function populate_popup_groups()
{
	if (yh_group_order.lastIndexOf('d') == yh_group_order.length -1)
		alphabet = alphabet_desc;
	else
		alphabet = alphabet_asc;
	
	document.body.style.cursor = "wait";	
	try{
		var div = document.getElementById("agi-contact-list-body");
		div.removeChild(document.getElementById("agi-contact-table"));
	} catch(e){ console_log(e)}
	
	document.getElementById('agi-th-name').style.display = "none";
	document.getElementById('agi-th-email').style.display = "none";
	document.getElementById('agi-th-group').style.display = (isIE) ? "block" : "table-cell";

	var table = document.createElement("table");
	table.setAttribute("id", "agi-contact-table");
	table.setAttribute("width", "100%");
	table.setAttribute("border", "0");
	table.setAttribute("cellspacing", "0");
	table.setAttribute("cellpadding", "2");
	table.cellPadding = "2";
	table.cellSpacing = "0";
	
	div.appendChild(table);
	
	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	
	var rows = ['row1', 'row2'];
	var i = 0;
	var alpha_idx = -1;
	var last_letter = '';
	
	for (pl in pl_groups)
	{
		group = pl_groups[pl];
		
		first = group.label.substr(0,1).toUpperCase();
					
		if (first != last_letter)
		{
			new_idx = arrayIndexOf(alphabet, first);
			
			for (var i = alpha_idx + 1; i <= new_idx; i++)
			{
				add_alpha_divider(alphabet[i], tbody);
			}
			last_letter = first;
			alpha_idx = new_idx;
		}
		
		id_str = "g-" + group.id;

		var tr = document.createElement("tr");
		tr.setAttribute("id", "row-" + id_str)
		tr.setAttribute("style", "cursor: pointer; overflow: hidden;");
		tr.setAttribute("className", rows[i % 2]);
		tr.setAttribute("class", rows[i % 2]);
		tr.style.cursor = "pointer";
		tr.style.overflow = "hidden";
				
		i++;
		tbody.appendChild(tr);
		tr = document.getElementById("row-" + id_str);
	
		tr.onclick = function(event){select_item(get_event(event), this.id.substring(4))};
		tr.onmouseover = function(){highlight(this.id)};
		tr.onmouseout = function(){lowlight(this.id)};
	
		var td1 = document.createElement("td");
		td1.setAttribute("style", "text-align: center;")
		td1.setAttribute("className", "agi-check-column");
		td1.setAttribute("class", "agi-check-column");
		td1.setAttribute("width", "20");
		td1.style.textAlign = "center";
		
		tr.appendChild(td1);
		
		var checkdiv = document.createElement("div");
		checkdiv.setAttribute("style", "width:20px;");
		checkdiv.style.width = "20px";
		
		td1.appendChild(checkdiv);

		var checker = document.createElement("input");
		checker.setAttribute("type", "checkbox")
		checker.setAttribute("className", "agi-except");
		checker.setAttribute("class", "agi-except");
		checker.setAttribute("name", "cid");
		checker.setAttribute("id", "check-" + id_str);
		checker.setAttribute("value", id_str);
	
		checkdiv.appendChild(checker);
		//checker.onclick = function(){alert(this.name);};
		
		var td2 = document.createElement("td");
		td2.setAttribute("className", "agi-last-column");
		td2.setAttribute("class", "agi-last-column");
	
		tr.appendChild(td2);
		td2.appendChild(document.createTextNode(group.label));
		
		var emaildiv = document.createElement("div");
		emaildiv.setAttribute("id", "agi-email-" + id_str);
		emaildiv.setAttribute("style", "display: none;");
		emaildiv.style.display = "none";
				
		td2.appendChild(emaildiv);

		var email_list = "";
		
		for (var j = 0; j < group.contacts.length; j++)
		{
			if (email_list.length > 0)
				email_list += ", ";
			email_list += pl_contacts[group.contacts[j]].email;
		}
		
		emaildiv.innerHTML = email_list;
	}
	
	for (var i = alpha_idx + 1; i < alphabet.length; i++)
	{
		add_alpha_divider(alphabet[i], tbody);
	}
	div.scrollTop = 0;
	document.body.style.cursor = "auto";	
}

function populate_popup_contacts()
{
	if (yh_sort_order.lastIndexOf('d') == yh_sort_order.length -1)
		alphabet = alphabet_desc;
	else
		alphabet = alphabet_asc;

	document.body.style.cursor = "wait";
	
	try{
		var div = document.getElementById("agi-contact-list-body");
		div.removeChild(document.getElementById("agi-contact-table"));
	} catch(e){ console_log(e)}

	document.getElementById('agi-th-name').style.display = (isIE) ? "block" : "table-cell";
	document.getElementById('agi-th-email').style.display = (isIE) ? "block" : "table-cell";
	document.getElementById('agi-th-group').style.display = "none";

	var container = document.getElementById('agi-contact-container');

	if (!div)
	{
		var div = document.createElement("div");
		div.setAttribute("className", "agi-popup-list")
		div.setAttribute("class", "agi-popup-list")
		div.setAttribute("id", "agi-contact-list-body");
		container.appendChild(div);
	}
	
	var table = document.createElement("table");
	table.setAttribute("id", "agi-contact-table");
	table.setAttribute("width", "100%");
	table.setAttribute("border", "0");
	table.setAttribute("cellspacing", "0");
	table.setAttribute("cellpadding", "2");
	table.cellPadding = "2";
	table.cellSpacing = "0";
	
	div.appendChild(table);

	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	
	var rows = ['row1', 'row2'];
	var i = 0;
	var alpha_idx = -1;
	var last_letter = '';
	
	for (pl in pl_contacts)
	{
		contact = pl_contacts[pl];
		
		compare_contact = prepare_sort_contact(contact)
		
		if (yh_sort_order == "n" || yh_sort_order == "nd")
			first = compare_contact.last_name.substr(0,1).toUpperCase();
		else if (yh_sort_order == "fn" || yh_sort_order == "fnd")
			first = compare_contact.first_name.substr(0,1).toUpperCase();
		else if (yh_sort_order == "e" || yh_sort_order == "ed")
			first = compare_contact.email.substr(0,1).toUpperCase();
					
		if (first != last_letter)
		{
			new_idx = arrayIndexOf(alphabet, first);
			
			for (var i = alpha_idx + 1; i <= new_idx; i++)
			{
				add_alpha_divider(alphabet[i], tbody);
			}
			last_letter = first;
			alpha_idx = new_idx;
		}
		
		id_str = contact.id + "-" + contact.id;

		var tr = document.createElement("tr");
		tr.setAttribute("id", "row-" + id_str)
		tr.setAttribute("style", "cursor: pointer; overflow: hidden;");
		tr.setAttribute("className", rows[i % 2]);
		tr.setAttribute("class", rows[i % 2]);
		tr.style.cursor = "pointer";
		tr.style.overflow = "hidden";
				
		i++;
		tbody.appendChild(tr);
		tr = document.getElementById("row-" + id_str);
	
		tr.onclick = function(event){select_item(get_event(event), this.id.substring(4))};
		tr.onmouseover = function(){highlight(this.id)};
		tr.onmouseout = function(){lowlight(this.id)};
	
		var td1 = document.createElement("td");
		td1.setAttribute("style", "text-align: center;")
		td1.setAttribute("className", "agi-check-column");
		td1.setAttribute("class", "agi-check-column");
		td1.setAttribute("width", "20");
		td1.style.textAlign = "center";
		
		tr.appendChild(td1);
		
		var checkdiv = document.createElement("div");
		checkdiv.setAttribute("style", "width:20px;");
		checkdiv.style.width = "20px";
		
		td1.appendChild(checkdiv);

		var checker = document.createElement("input");
		checker.setAttribute("type", "checkbox")
		checker.setAttribute("className", "agi-except");
		checker.setAttribute("class", "agi-except");
		checker.setAttribute("name", "cid");
		checker.setAttribute("id", "check-" + id_str);
		checker.setAttribute("value", id_str);
	
		checkdiv.appendChild(checker);
		//checker.onclick = function(){alert(this.name);};
		
		var td2 = document.createElement("td");
		td2.setAttribute("width", "195");
	
		tr.appendChild(td2);

		var namediv = document.createElement("div");
		namediv.setAttribute("className", "agi-popup-name-col");
		namediv.setAttribute("class", "agi-popup-name-col");
		
		td2.appendChild(namediv);

		namediv.innerHTML = make_contact_name(contact);;
	
		var td3 = document.createElement("td");
		td3.setAttribute("className", "agi-last-column");
		td3.setAttribute("class", "agi-last-column");

		tr.appendChild(td3);

		var emaildiv = document.createElement("div");
		emaildiv.setAttribute("className", "agi-popup-email-col");
		emaildiv.setAttribute("class", "agi-popup-email-col");
		emaildiv.setAttribute("id", "agi-email-" + id_str);
		emaildiv.style.whiteSpace = "nowrap";
		td3.appendChild(emaildiv);

		if (contact.email)
			emaildiv.innerHTML = contact.email;
	}

	for (var i = alpha_idx + 1; i < alphabet.length; i++)
	{
		add_alpha_divider(alphabet[i], tbody);
	}

	document.getElementById("popup-select-none").onclick = function(){select_rows(false);};
	document.getElementById("popup-select-all").onclick = function(){select_rows(true);};
	document.getElementById("popup-add-button").onclick = append_popup_addresses;

	div.scrollTop = 0;
	document.body.style.cursor = "auto";	
}

function add_alpha_divider(letter, tbody)
{
	letter = letter.toUpperCase();
	
	var tr = document.createElement("tr");
	
	tbody.appendChild(tr);
	
	var td1 = document.createElement("td");
	td1.setAttribute("id", "agi-goto-letter-" + letter);
	td1.setAttribute("className", "agi-alpha-divider-label");
	td1.setAttribute("class", "agi-alpha-divider-label");
	td1.setAttribute("colspan", "1");
	
	tr.appendChild(td1);
	
	td1.innerHTML = letter;
	 	
	var td2 = document.createElement("td");
	td2.setAttribute("className", "agi-alpha-divider");
	td2.setAttribute("class", "agi-alpha-divider");
	td2.setAttribute("colspan", "3");
	td2.colSpan = "3";
	td2.innerHTML = "&nbsp;";
	tr.appendChild(td2);
}

function make_contact_name(contact)
{
	if (contact.first_name && contact.last_name)
		return contact.last_name + ", " + contact.first_name;
	else if (contact.first_name && !contact.last_name)
		return contact.first_name;
	else if (contact.last_name && !contact.first_name)
		return contact.last_name;
	else
		return "&nbsp;";
}

function get_event(ev)
{
	if(ev)			//Moz
		return ev;
		
	if(window.event)	//IE
		return window.event;
}

var my_page = document.location.href;
if (my_page.indexOf('custom.pd') != -1 || my_page.indexOf('edit.pd') != -1)
{
	setPage = function()
	{
		select_rows(false);
		return;
	}
}

function select_rows(doit)
{
	boxes = document.getElementsByTagName('INPUT');

	for(var i=0; i < boxes.length; i++)
	{
		if (boxes[i].name == "cid")
		{
			boxes[i].checked = doit;
			select_row(boxes[i], boxes[i].value);
		}
	}
	try {
		dojo.byId('agi-toggle').checked = doit;
	} catch (e) {}
}

function yh_open_popper(attached_id)
{
	area_id = attached_id;
	var area = dojo.byId(area_id);
	var popper = dojo.byId('agi-contact-popper');
	if (!popper)
	{
		var popper = create_popper();
		popper.innerHTML = yh_initial_popper_html;
		place_popper(popper);

		load_yahoo_contacts();
		//populate_popup_contacts();		
	} else if (popper.style.display != "block"){
		popup_set_type('c');
		place_popper(popper);
	}
}

function prepare_sort_contact(a)
{
	if (!a.email)
		a.email = ""
	if (!a.first_name)
		a.first_name = ""
	if (!a.last_name)
		a.last_name = ""
//	a.last_name = a.last_name.toUpperCase();
//	a.first_name = a.first_name.toUpperCase();
//	a.email = a.email.toUpperCase();
	return a;
}

function yh_compare_email(a, b)
{
	a = prepare_sort_contact(a);
	b = prepare_sort_contact(b);
		
	if (a.email.toUpperCase() > b.email.toUpperCase())
	{
		return 1;
	}else if (a.email.toUpperCase() == b.email.toUpperCase()){
		if (a.last_name.toUpperCase() > b.last_name.toUpperCase())
		{
			return 1;
		} else if (a.last_name.toUpperCase() == b.last_name.toUpperCase()) {
			if (a.first_name.toUpperCase() > b.first_name.toUpperCase())
			{
				return 1;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	} else {
		return -1;
	}
}

function yh_compare_fname(a, b)
{
	a = prepare_sort_contact(a);
	b = prepare_sort_contact(b);
			
	if (a.first_name.toUpperCase() > b.first_name.toUpperCase())
	{
		return 1;
	}else if (a.first_name.toUpperCase() == b.first_name.toUpperCase()){
		if (a.last_name.toUpperCase() > b.last_name.toUpperCase())
		{
			return 1;
		} else if (a.last_name.toUpperCase() == b.last_name.toUpperCase()) {
			if (a.email.toUpperCase() > b.email.toUpperCase())
			{
				return 1;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	} else {
		return -1;
	}
}

function yh_compare_lname(a, b)
{
	a = prepare_sort_contact(a);
	b = prepare_sort_contact(b);
			
	if (a.last_name.toUpperCase() > b.last_name.toUpperCase())
	{
		return 1;
	}else if (a.last_name.toUpperCase() == b.last_name.toUpperCase()){
		if (a.first_name.toUpperCase() > b.first_name.toUpperCase())
		{
			return 1;
		} else if (a.first_name.toUpperCase() == b.first_name.toUpperCase()) {
			if (a.email.toUpperCase() > b.email.toUpperCase())
			{
				return 1;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	} else {
		return -1;
	}
}

function yh_reverse_compare_lname(a, b)
{
	return -1 * yh_compare_lname(a, b);
}

function yh_reverse_compare_fname(a, b)
{
	return -1 * yh_compare_fname(a, b);
}

function yh_reverse_compare_email(a, b)
{
	return -1 * yh_compare_email(a, b);
}

if (typeof _complete == "undefined")
	var _complete = {};

// yahoo textarea email autocomplete
function YahooAreaComplete(elId)
{
	var textcomplete = this;
	if (_complete[elId])
	{
		var complete = _complete[elId];
		complete.bind_element(document.getElementById(elId));
	} else {
		var complete = new AutoComplete(document.getElementById(elId), ahost + '/reminders/contactsearch.pd');
	}
    
    // Expose this as property of "class" so that its functions can be decorated later
    this.baseCompleter = complete;
	
	var oldcomplete = complete.searchSuggestions;
	complete.searchSuggestions = function()
	{
		var search = (complete.getSearchValue(complete.element) + "").toLowerCase();

		if (!preloaded)
			load_yahoo_contacts(search, complete);
		else
			complete.doSearch(pl_contacts, pl_groups);
	}

	complete.doSearch = function(contacts, groups)
	{
		var search = (complete.getSearchValue(complete.element) + "").toLowerCase();
		complete.suggestions = new Array();
		for (g in groups)
		{
			var label = (groups[g].label + "").toLowerCase();
			
			if (label.indexOf(search) == 0)
				complete.suggestions.push(groups[g]);
		}
		for (i in contacts)
		{
			var first_name = (contacts[i].first_name + "").toLowerCase();
			var last_name = (contacts[i].last_name + "").toLowerCase();
			var email = (contacts[i].email + "").toLowerCase();
			var f = (first_name.length > 0) ? first_name + " " : "";
			var l = (last_name.length > 0) ? last_name + " " : "";
			var full = f + l;
			
			if (email.toLowerCase() == search)
			{
				complete.suggestions = new Array();
				break; 
			}
			
			if (((email.indexOf(search) == 0 ||
					first_name.indexOf(search) == 0 ||
					last_name.indexOf(search) == 0) ||
					full.indexOf(search) == 0) &&
					(email.length > 0))
				complete.suggestions.push(contacts[i]);
		}
		complete.suggestions.sort(compare_contacts);	
		complete.createSuggestions(search);
		complete.positionPopup();
		if (complete.suggestions.length > 0)
			complete.showPopup();
		else
			complete.hidePopup();
	}
	
	complete.getDisplaySuggestion = function(suggestion)
	{
		return textcomplete.assembleContact(suggestion).replace("<","&#60;").replace(">", "&#62;");
	}
	
	complete.applySuggestion = function(suggestion)
	{
		var elStr = this.element.value;
		var position = get_cursor_position(this.element);
		var start = position - complete.getSearchValue(complete.element).length;
		var before_text = elStr.substring(0, start);
		var after_text = elStr.substring(position);
		
		var white_before = (before_text.search(/\s+$/g) != -1 || before_text.length == 0);		
		var white_after = (after_text.search(/^\s+/g) != -1);
		
		var prefix = (white_before) ? "" : " ";
		var postfix = (white_after) ? "," : ", ";
		
		if (!suggestion.label)
			var suggestion_text = suggestion.email;
		else
			var suggestion_text = get_group_emails(suggestion)

		var newValue = prefix + suggestion_text + postfix;
		this.element.value =  before_text + newValue + after_text;
		this.cursor = start + newValue.length;pl_contacts
		//textcomplete.setPosition(this.element, this.cursor, this.cursor);
	}
		
	complete.getSearchValue = function(el)
	{
		var elStr = el.value;
		var position = get_cursor_position(el);
		var idx = elStr.lastIndexOf(",", position);
	 	var start = (idx == -1) ? 0 : idx + 1;
		idx = elStr.indexOf(",", position);
	 	var end = (idx == -1) ? elStr.length - 1 : idx - 1;
	 	return elStr.substring(start, position).replace(/^\s*|\s*$/g,"");
	}
	
	this.assembleContact = function(suggestion)
	{
		if (!suggestion.label)
		{
			var fname = (suggestion.first_name == null) ? "" : suggestion.first_name;
			var lname = (suggestion.last_name == null) ? "" : suggestion.last_name;
			var space = (lname.length > 0 && fname.length > 0) ? " " : "";
			var name = (lname.length > 0 || fname.length > 0) ? '"' + fname + space + lname +'"' : "";
			var email = (suggestion.email == null || suggestion.email.length == 0) ? "" : " <" + suggestion.email + ">";
			return name + email;
		} else {
			return suggestion.label + " (group)";
		}
	}
	
}

//yahoo textarea email autocomplete
function YahooAreaCompleteNew(elId)
{
	var textcomplete = this;
	if (_complete[elId])
	{
		var complete = _complete[elId];
		complete.bind_element(document.getElementById(elId));
	} else {
		var complete = new ag.widget.autocomplete.AutoComplete(document.getElementById(elId), ahost + '/reminders/contactsearch.pd');
	}
    
    // Expose this as property of "class" so that its functions can be decorated later
    this.baseCompleter = complete;
	
	var oldcomplete = complete.searchSuggestions;
	complete.searchSuggestions = function()
	{
		var search = (complete.getSearchValue(complete.element) + "").toLowerCase();

		if (!preloaded)
			load_yahoo_contacts(search, complete);
		else
			complete.doSearch(pl_contacts, pl_groups);
	}

	complete.doSearch = function(contacts, groups)
	{
		var search = (complete.getSearchValue(complete.element) + "").toLowerCase();
		complete.suggestions = new Array();
		for (g in groups)
		{
			var label = (groups[g].label + "").toLowerCase();
			
			if (label.indexOf(search) == 0)
				complete.suggestions.push(groups[g]);
		}
		for (i in contacts)
		{
			var first_name = (contacts[i].first_name + "").toLowerCase();
			var last_name = (contacts[i].last_name + "").toLowerCase();
			var email = (contacts[i].email + "").toLowerCase();
			var f = (first_name.length > 0) ? first_name + " " : "";
			var l = (last_name.length > 0) ? last_name + " " : "";
			var full = f + l;
			
			if (email.toLowerCase() == search)
			{
				complete.suggestions = new Array();
				break; 
			}
			
			if (((email.indexOf(search) == 0 ||
					first_name.indexOf(search) == 0 ||
					last_name.indexOf(search) == 0) ||
					full.indexOf(search) == 0) &&
					(email.length > 0))
				complete.suggestions.push(contacts[i]);
		}
		complete.suggestions.sort(compare_contacts);	
		complete.createSuggestions(search);
		complete.positionPopup();
		if (complete.suggestions.length > 0)
			complete.showPopup();
		else
			complete.hidePopup();
	}
	
	complete.getDisplaySuggestion = function(suggestion)
	{
		return textcomplete.assembleContact(suggestion).replace("<","&#60;").replace(">", "&#62;");
	}
	
	complete.applySuggestion = function(suggestion)
	{
		var elStr = this.element.value;
		var position = ag.widget.autocomplete.get_cursor_position(this.element);
		var start = position - complete.getSearchValue(complete.element).length;
		var before_text = elStr.substring(0, start);
		var after_text = elStr.substring(position);
		
		var white_before = (before_text.search(/\s+$/g) != -1 || before_text.length == 0);		
		var white_after = (after_text.search(/^\s+/g) != -1);
		
		var prefix = (white_before) ? "" : " ";
		var postfix = (white_after) ? "," : ", ";
		
		if (!suggestion.label)
			var suggestion_text = suggestion.email;
		else
			var suggestion_text = get_group_emails(suggestion)

		var newValue = prefix + suggestion_text + postfix;
		this.element.value =  before_text + newValue + after_text;
		this.cursor = start + newValue.length;pl_contacts
		//textcomplete.setPosition(this.element, this.cursor, this.cursor);
	}
		
	complete.getSearchValue = function(el)
	{
		var elStr = el.value;
		var position = ag.widget.autocomplete.get_cursor_position(el);
		var idx = elStr.lastIndexOf(",", position);
	 	var start = (idx == -1) ? 0 : idx + 1;
		idx = elStr.indexOf(",", position);
	 	var end = (idx == -1) ? elStr.length - 1 : idx - 1;
	 	return elStr.substring(start, position).replace(/^\s*|\s*$/g,"");
	}
	
	this.assembleContact = function(suggestion)
	{
		if (!suggestion.label)
		{
			var fname = (suggestion.first_name == null) ? "" : suggestion.first_name;
			var lname = (suggestion.last_name == null) ? "" : suggestion.last_name;
			var space = (lname.length > 0 && fname.length > 0) ? " " : "";
			var name = (lname.length > 0 || fname.length > 0) ? '"' + fname + space + lname +'"' : "";
			var email = (suggestion.email == null || suggestion.email.length == 0) ? "" : " <" + suggestion.email + ">";
			return name + email;
		} else {
			return suggestion.label + " (group)";
		}
	}
	
}

var yh_initial_popper_html = "<div id=\"agi-ab-popup\" class=\"agi-contactpopup\">\n<div class=\"agi-close\">\n<span><strong>Your Yahoo! Address Book<\/strong><\/span>\n<a href=\"javascript:\/\/\" onClick=\"hide_popper()\"><img src=\"" + imghost + "\/yh07\/x-grey.gif\" width=\"11\" height=\"11\" border=\"0\" \/><\/a><br style=\"clear:both;\" \/><\/div>\n<div id=\"agi-contact-or-groups\">\nview:&nbsp;<span id=\"agi-popup-contacts\" class=\"agi-popup-pseudolinkcurrent\" onClick=\"populate_popup_contacts()\">contacts<\/span>&nbsp;|&nbsp;<span id=\"agi-popup-groups\" class=\"agi-popup-pseudolink\" onClick=\"populate_popup_groups()\">categories<\/span>\n<\/div>\n\n\n<div>\n<div id=\"agi-alpha-filter\" class=\"agi-alpha-filter\"><ul>go to: &nbsp;<li class=\"pagenumber\" onClick=\"setLetter('A')\" title=\"go to A\">A<\/li><li class=\"pagenumber\" onClick=\"setLetter('B')\" title=\"go to B\">B<\/li><li class=\"pagenumber\" onClick=\"setLetter('C')\" title=\"go to C\">C<\/li><li class=\"pagenumber\" onClick=\"setLetter('D')\" title=\"go to D\">D<\/li><li class=\"pagenumber\" onClick=\"setLetter('E')\" title=\"go to E\">E<\/li><li class=\"pagenumber\" onClick=\"setLetter('F')\" title=\"go to F\">F<\/li><li class=\"pagenumber\" onClick=\"setLetter('G')\" title=\"go to G\">G<\/li><li class=\"pagenumber\" onClick=\"setLetter('H')\" title=\"go to H\">H<\/li><li class=\"pagenumber\" onClick=\"setLetter('I')\" title=\"go to I\">I<\/li><li class=\"pagenumber\" onClick=\"setLetter('J')\" title=\"go to J\">J<\/li><li class=\"pagenumber\" onClick=\"setLetter('K')\" title=\"go to K\">K<\/li><li class=\"pagenumber\" onClick=\"setLetter('L')\" title=\"go to L\">L<\/li><li class=\"pagenumber\" onClick=\"setLetter('M')\" title=\"go to M\">M<\/li><li class=\"pagenumber\" onClick=\"setLetter('N')\" title=\"go to N\">N<\/li><li class=\"pagenumber\" onClick=\"setLetter('O')\" title=\"go to O\">O<\/li><li class=\"pagenumber\" onClick=\"setLetter('P')\" title=\"go to P\">P<\/li><li class=\"pagenumber\" onClick=\"setLetter('Q')\" title=\"go to Q\">Q<\/li><li class=\"pagenumber\" onClick=\"setLetter('R')\" title=\"go to R\">R<\/li><li class=\"pagenumber\" onClick=\"setLetter('S')\" title=\"go to S\">S<\/li><li class=\"pagenumber\" onClick=\"setLetter('T')\" title=\"go to T\">T<\/li><li class=\"pagenumber\" onClick=\"setLetter('U')\" title=\"go to U\">U<\/li><li class=\"pagenumber\" onClick=\"setLetter('V')\" title=\"go to V\">V<\/li><li class=\"pagenumber\" onClick=\"setLetter('W')\" title=\"go to W\">W<\/li><li class=\"pagenumber\" onClick=\"setLetter('X')\" title=\"go to X\">X<\/li><li class=\"pagenumber\" onClick=\"setLetter('Y')\" title=\"go to Y\">Y<\/li><li class=\"pagenumber\" onClick=\"setLetter('Z')\" title=\"go to Z\">Z<\/li><\/ul><\/div><\/div><div class=\"clear\"><\/div><div class=\"agi-popup-container\" id=\"agi-contact-container\">\n<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\" id=\"agi-contact-table-header\">\n<tr class=\"tableheader\" valign=\"top\">\n<th style=\"text-align: center;\" width=\"20\" class=\"agi-last-column agi-check-column\"><div style=\"width:20px;\">&nbsp;<\/div><\/th>\n<th  id=\"agi-th-name\" width=\"195\" class=\"\"><div style=\"width: 195px;\"><a href=\"javascript:\/\/\" id=\"agi-sort-link-n\" onClick=\"sort_contacts('n')\">last name&nbsp;<span id=\"agi-sort-n\" style=\"\">&#9650;<\/span><span id=\"agi-sort-nd\" style=\"display: none;\">&#9660;<\/span><\/a>, <a href=\"javascript:\/\/\" id=\"agi-sort-link-fn\" onClick=\"sort_contacts('fn')\">first name&nbsp;<span id=\"agi-sort-fn\" style=\"display:none;\">&#9650;<\/span><span id=\"agi-sort-fnd\" style=\"display: none;\">&#9660;<\/span><\/a><\/div><\/th>\n<th  id=\"agi-th-email\" class=\"agi-last-column\"><a href=\"javascript:\/\/\" id=\"agi-sort-link-e\" onClick=\"sort_contacts('e')\">email&nbsp;address&nbsp;<span id=\"agi-sort-e\" style=\"display: none;\">&#9650;<\/span><span id=\"agi-sort-ed\" style=\"display: none;\">&#9660;<\/span><\/a><\/th>\n<th id=\"agi-th-group\" class=\"agi-last-column\" style=\"display: none;\"><a href=\"javascript:\/\/\" id=\"agi-sort-link-g\" onClick=\"sort_groups('g')\">category&nbsp;name&nbsp;<span id=\"agi-sort-g\" style=\"display: inline;\">&#9650;<\/span><span id=\"agi-sort-gd\" style=\"display: none;\">&#9660;<\/span><\/a><\/th>\n<\/tr>\n<\/table><\/div>\n<div id=\"agi-popup-footer\">\n<div class=\"agi-popup-select-all\">\n<strong>select<\/strong>: <a href=\"javascript:\/\/\" id=\"popup-select-all\">all<\/a>&nbsp;|&nbsp;<a href=\"javascript:\/\/\" id=\"popup-select-none\">none<\/a>\n<\/div>\n<img src=\"" + imghost + "\/yh07\/button\/add.gif\" border=\"0\" class=\"agi-popup-add-button\" alt=\"Add\" id=\"popup-add-button\"\/>\n<div class=\"clear\"><\/div>\n<\/div>\n<\/form>\n<\/div>"
