if(!com) var com={};
if(!com.gogii) com.gogii={};
if(!com.gogii.autocomplete) com.gogii.autocomplete={};
var showForwardToFriendDialog = false;
var friendsArray = new Array();
/**
This function removes a child element from the UI
Takes care of removing element from friendsArray as well.
**/
function removeFriend(child) {
	for (i=0; i<friendsArray.length; i++) {
		if (friendsArray[i]==child.getAttribute('id')){
			friendsArray.splice(i,1);
			$('item_' + child.id).remove();
			return;
		}
	}
}

function removeAllFriends() {
	if ($('itemContainer')) {
		$('itemContainer').innerHTML = '';
	}
	friendsArray = new Array();
	friendsCount = 0;
}

com.gogii.autocomplete = {
	createElement : function(eName, eClass) {
		var elem = document.createElement(eName);
		elem.className = eClass;
		return elem;
	},
	createAutocompleteItem : function(pNode, txtId, txt) {
		var cgaAcItem = com.gogii.autocomplete;
		var item = cgaAcItem.createElement('span', 'item');
		item.id = 'item_' + txtId;
		var txtSpan = cgaAcItem.createElement('span', 'itemText');
		/*
		var btn = document.createElement('a');
		btn.id = txt;
		btn.href = 'javascript:void(0)';
		btn.onclick = function () {removeFriend(this);};
		*/
		var btn = txt + "<a href='javascript:void(0)' onclick='removeFriend(this);' id='" + txtId + "'><img src='../images/token_x.gif' /></a>";
		/*var btnImg = document.createElement('img');

		btnImg.src='/images/token_x.gif';
		// start appending elements
		btn.appendChild(btnImg);
		*/
		item.appendChild(txtSpan);
		txtSpan.appendChild(cgaAcItem.createCurvyBoxWithNode(txt, btn));
		txtSpan.innerHTML += " ";
		//item.appendChild(btnSpan);
		pNode.appendChild(item);
		if ($('inviteWidgetContainer').offsetWidth < $('itemContainer').offsetWidth) {
			item.insert(document.createElement('br'), {position: 'before'});
		}
	},
	createCurvyBox : function (txt) {
		returnTxt = '<span class="roundedCorner"><span><span><span><span><a href="javascript:void(0)">' + txt + '</a></span></span></span></span></span>';
		return returnTxt;
	},
	createCurvyBoxWithNode : function (txt, nodeElem) {
		var cgaAcItem = com.gogii.autocomplete;
		var returnSpan = document.createElement('span');
		var span1 = cgaAcItem.createElement('span', 'roundedCorner');
		var span2 = document.createElement('span');
		var span3 = document.createElement('span');
		var span4 = document.createElement('span');
		var span5 = document.createElement('span');
		span5.innerHTML = txt;
		span5.innerHTML = nodeElem;
		span4.appendChild(span5);
		span3.appendChild(span4);
		span2.appendChild(span3);
		span1.appendChild(span2);
		returnSpan.appendChild(span1);
		return returnSpan;
	}
}
var cga = com.gogii.autocomplete;
var itemContainer = $('itemContainer');

/*
New Javascript Object to handle invite on landing page
@author Chandan
*/
com.gogii.InviteToGogii = function () {
	this.friendsCount = 0;
	this.data = '';
	this.delimiters = [",", ";"];
	this.pNode = 'itemContainer';
	this.itemCount = 0;
	// Adds item as selected item to submit
	this.addOnDelimit = function (/*DOM input*/text,/*Event*/ e) {
		// Delimited text array.
		for (i=0; i < this.delimiters.length; i++) {
			var delimit = this.delimiters[i];
			var splitArr = text.value.split(delimit);
			if (!validate_email(splitArr[0])) {
				var textId = cleanPhoneNumber(splitArr[0]);
			} else {
				var textId = splitArr[0];
			}
			var attachTo = $(this.pNode);
			if (checkEnter(e) && validateInput(text.value)) {
				this.addFriend(textId, text, textId, attachTo, splitArr);
			} else if (splitArr.length >1 && validateInput(splitArr[0])) {
				this.addFriend(textId, text, textId, attachTo, splitArr);
			}
			if (splitArr.length>1 || checkEnter(e)) {
				text.value="";
				return;
			}
		}
	}
	this.addFriend = function (value, text, textId, attachTo, splitArr) {
		for (i=0; i<friendsArray.length; i++) {
			if (friendsArray[i]==value){return false;}
		}
		text.value="";
		friendsArray.push(textId);
		cga.createAutocompleteItem(attachTo,textId,splitArr[0]);
		this.itemCount++;
	}
}
var inviteToGogii = new com.gogii.InviteToGogii();

/*
MOVED INLINE JAVASCRIPT FROM _invite_widget3.vm below
*/

var imgsrc = '../images/cancel_disabled.gif' ;
var friendsCount = 0;
function getSelectionId(text, li) {
	var liId = li.id;
	setValue(liId);
}
function setValue(/*String*/ value) {
	if (value!='') {
		addFriend(value);
		$('invitePeople').setValue('');
	}
}
/**
This function adds a child element to UI
Takes care of populating friendsArray as well. Does not allow
insertion of duplicate entries
**/
function addFriend(/*string*/ value) {
	var valueArray = value;
	for (i=0; i<friendsArray.length; i++) {
		if (friendsArray[i]==value){return false;}
	}
	friendsArray.push(value);
	addItem(value);
}
function addItem(value) {
	cga = com.gogii.autocomplete;
	if($('itemContainer')) {
		itemContainer = $('itemContainer');
	}
	cga.createAutocompleteItem(itemContainer,value, $('invitePeople').value);
	return false;
}

function checkName(/*string*/ name, /*string*/ url) {
	var params = "message=" + name;
	new Ajax.Request(url, {parameters: params, method: 'post',
	 onSuccess:function (transport) {
		checkNameCallback(transport);
	 }
	});
}
function checkNameCallback(transport) {
	data = transport.responseText.evalJSON()
	if (data.result == "true") {
		setValue($('invitePeople').value);
	} else {
		//alert('not found');
	}
}
/**

Used: This widget is being used on mail compose
@author Chandan
**/
function InviteWidget() {
	this.container = $("itemContainer");
	this.input = $("invitePeople");
	this.delimiters = [",", ";"];
	this.currentText = null;
	this.currentTextId = null;
	this.inputId = null;
	this.securityCheck = true;
	this.securityCheckfor = 3;
	// item type 0 for email, 1 for phone and 2 for megii
	this.securityCheckCallback = null;
	this.currentItemType = 0;
	this.megiiUrl = "../gogii/application_MegiiExistence.html?ajax=true";
	// mode 0 would add "email", "phone" or "personal gogii id"
	// mode 1 would add "email" or "phone"
	this.mode = 0;
	this.addItem = function(e) {
		this.checkElements();
		if (this.evaluateDelimit(e)) {
			switch (this.mode) {
				case 0:
					this.addMode0();
					break;
				case 1:
					this.addMode1();
			}
			this.input.value = "";
		}
	}

	this.evaluateDelimit = function (e) {
		if (checkEnter(e)) {
			if (this.input.value.trim() == "") {
				return false;
			}
			if (validateUSAPhone(this.input.value)) {
				this.currentTextId = cleanPhoneNumber(this.input.value);
				this.currentText = this.input.value;
				this.currentItemType = 0;
			} else if (validate_email(this.input.value)){
				this.currentTextId = this.input.value;
				this.currentText = this.input.value;
				this.currentItemType = 1;
			} else {
				this.currentTextId = this.input.value;
				this.currentText = this.input.value;
				this.currentItemType = 2;
			}
			return true;
		}
		// iterate over dilimiters and if delimiter is found then set text and its id
		var delimited = false;
		for (i=0; i < this.delimiters.length; i++) {
			var delimit = this.delimiters[i];
			var splitArr = this.input.value.split(delimit);
			if (splitArr.length > 1)  {
				delimited = true;
				break;
			}
		}
		if (delimited) {
			var splitArr = this.input.value.split(delimit);
			if (splitArr.length > 1) {
				if (this.validateInput(splitArr[0])) {
					if (validateUSAPhone(splitArr[0])) {
						this.currentTextId = cleanPhoneNumber(splitArr[0]);
						this.currentText = splitArr[0];
						this.currentItemType = 1;
						return true;
					} else if (validate_email(splitArr[0])) {
						this.currentTextId = splitArr[0];
						this.currentText = splitArr[0];
						this.currentItemType = 0;
						return true;
					}
				} else {
					if (this.mode == 0) {
						this.currentTextId = splitArr[0];
						this.currentText = splitArr[0];
						this.currentItemType = 2;
						return true;
					} else {
						return false;
					}
				}
			}
		}
	}
	this.addEmailOrPhone = function () {
		for (i=0; i< friendsArray.length; i++) {
			if (friendsArray[i]== this.currentTextId) {
				return false;
			}
		}
		friendsArray.push(this.currentTextId);
		cga.createAutocompleteItem(this.container,this.currentTextId,this.currentText);
		this.currentTextId = null;
		this.currentText = null;
		this.input.value="";
		this.itemCount++;
	}
	// performs server side lookup to find if entered entry is an existing megii
	this.addMegii = function() {
		var params = "message=" + this.currentTextId;
		var parentRef = this;
		new Ajax.Request (this.megiiUrl, {
			parameters : params,
			method : "post",
			onSuccess : function(transport) {
				transTxt = transport.responseText.evalJSON();
				if (transTxt.result == "true") {
					// check if privacy check is enabled
					if (parentRef.securityCheck) { // This is introduced due to security check on compose ~ CHANDAN
						//for forward to a friend box
						/*
						if(dijit.byId('forwardToFriend')) {
							dijit.byId('forwardToFriend').hide();
						}*/
						// Below function is declared in gogii.view.js javascript basically trying to figure out if security check is enabled for selected megii
						sendMessageRequest('../gogii/rq_securityCheck.html?ajax=true' + '&gogii.id=' + transTxt.gogiiId, parentRef.securityCheckfor, 'gogii.id=' + transTxt.gogiiId);
						// Set name and hidden field values in the security check light box
						$("gogiiName1").innerHTML = parentRef.currentTextId.toUpperCase();
						$("gogiiName2").innerHTML = parentRef.currentTextId.toUpperCase();
						$("gogiiName3").value = transTxt.gogiiId;
						// assigning callback function which would be invoked after security answer is entered and is correct
						parentRef.securityCheckCallback = function () {
                            parentRef.addEmailOrPhone();
                            
                            //for forward to a friend box
                            if(dijit.byId('forwardToFriend')) {
                                dijit.byId('forwardToFriend').show();
                            }
                        };
					} else {
						parentRef.addEmailOrPhone();
					}
				}
			}
		});
	}
	// New function added due to privacy check. This method would stop adding item directly
	this.forkSecurityCheck = function () {
	}
	this.validateInput = function(value){
		if(validate_email(value)){
			return true;
		}
		else if(validateUSAPhone(value)){
			return true;
		}
		else{
			return false;
		}
	}
	// checks for gogii name, email and phone
	this.addMode0 = function() {
		if (this.currentItemType < 2) {
			this.addEmailOrPhone();
		} else {
			this.currentText = this.currentText.toUpperCase();
			this.addMegii();
		}
	}
	// checks for email and phone
	this.addMode1 = function() {
		this.addEmailOrPhone();
	}
	this.checkElements = function() {
		if (!this.input) {
			this.input = $(this.inputId);
		} 
	}
}
autocompleteNotify = function(msg) {
	if ($("autoCompleteNotification")) {
		$("autoCompleteNotification").show();
		$("autoCompleteNotification").innerHTML = msg;
	} else {
		alert (msg);
	}
}
setSecuritycheckLbValues = function(gogiiName, id) {
	$("gogiiName1").innerHTML = gogiiName;
	$("gogiiName2").innerHTML = gogiiName;
	$("gogiiName3").value = id;
}
dojo.addOnLoad(
	function () {
		dijit.byId('securityCheckLb').onCancel = function() {
            if(showForwardToFriendDialog == true) {
                if (dijit.byId('forwardToFriend')) {
                    dijit.byId('forwardToFriend').show();
                }
            }
			if (dijit.byId('securityCheckLb')) {
				dijit.byId('securityCheckLb').hide();
			}
		}

        
        dojo.connect(dijit.byId('forwardToFriend'), "onCancel", "cats");

	}
);

function cats() {
    showForwardToFriendDialog = false;
}



