// forced to add this variable to store value of gogii id which is being added as friend
// this variable is introduced due to security check feature and in the callback we need
// value which was originally passed to the function.
var addFriendOption = null;
/*
This function posts comment data to server.
Performs some jazz of updating the progress in a fixed div.
@author ChandanK
*/
function postmegiicomment(/*String*/ frm,/*String*/ btn,/*String*/ resultDiv,/*String*/ resultNotification) {
	frm = $(frm);
	sanatizeForm(frm);
	resultNotification = $('errorMessage');
	resultDiv = $(resultDiv);
	btn = $(btn);
	if (!validateCommentFrm()) {
		return false;
	}
	params = frm.serialize();
	url = frm.action+'?ajax=true';
	resultNotification.innerHTML = 'Posting comment';
	$('errorDiv').show();
	btn.disable();
	new Ajax.Request(url, {
		parameters: params, method: 'post', onComplete: function(transport) {
			if (200 == transport.status) {
				resultNotification.innerHTML = 'Message posted';
				resultDiv.innerHTML = transport.responseText;
				frm.post_comment.value = '';
			} else {
				resultNotification.innerHTML = 'Something went wrong';
			}
			btn.enable();
		}
	});

}
// global flag which keeps reference if an active request is on.
var canDelete = false;
/*
This function is called when user performs delete comment action
@author Chandank
*/
function deletemegiicomment(/*String*/ id,/*String*/ url, /*String*/ resultDiv,/*String*/ resultNotification) {
	ans = confirm("Are you sure that you want to delete this comment?");
	if (ans) {
		resultNotification = $('errorMessage');
		resultNotification.innerHTML = "Deleting comment..";
		$('errorDiv').show();
		var params = 'gogiiDto.gogiiComment.id=' + id;
		new Ajax.Request (url, {
			parameters: params,
			onSuccess: function(transport) {deleteSuccessCallback(transport, resultNotification, resultDiv);},
			onFailure: function() {alert('something went wrong');}
		});
	}
}

/*
This function is called when user performs delete post action
@author Akhil Jain
*/
function deletewegiipost(/*String*/ id,/*String*/ url, /*String*/ resultDiv,/*String*/ resultNotification) {
	ans = confirm("Are you sure that you want to delete this comment?");
	if (ans) {
		resultNotification = $('errorMessage');
		resultNotification.innerHTML = "Deleting comment..";
		$('errorDiv').show();
		var params = 'gogiiDto.wegiiPost.id=' + id;
		new Ajax.Request (url, {
			parameters: params,
			onSuccess: function(transport) {deleteSuccessCallback(transport, resultNotification, resultDiv);},
			onFailure: function() {alert('something went wrong');}
		});
	}
}

function deleteSuccessCallback(transport, resultNotification, resultDiv){
	if (transport.responseText !="access.denied") {
		resultNotification.innerHTML = "Comment deleted";
		resultDiv.innerHTML = transport.responseText;
	}
}

function showResultNotification(target) {
	target.appear({duration:1, queue: 'front'});
}
function hideResultNotification(target) {
	target.shrink({duration:3, queue: 'end'});
}

/*
This is the main function which gets invoked when adding
a tag
@author ChandanK
*/
function checkTag(frm) {
	$('resultNotification').innerHTML = 'Adding tags';
	showResultNotification($('resultNotification'));
	frm = $(frm);
	if (frm.inputString.value.trim() !='') {
		// before creating new tag element perform ajax call to save to database and return json value like
		// {"result":"success", "data" : "['tag1', 'tag2']"} or {"result":"duplicate"} or {"result" : "error"}
		params = frm.serialize();
		new Ajax.Request(tagUrl, {
			parameters : params,
			method: 'post',
			onSuccess : function (transport) {populateTagList(transport.responseText);frm.inputString.value = '';dijit.byId('tagDialog').hide();},
			onFailure : function (transport) {$('resultNotification').innerHTML = message;hideResultNotification($('resultNotification'));}
		});
	}
}
function populateTagList(resultString) {
	response = resultString.evalJSON();
	if (response.result == "success" && response.data != null) {
		for (i=0; i<response.data.length; i++) {
			createNewTagElement(response.data[i]);
			$('resultNotification').innerHTML = 'tags added';
		}
	} else {
		$('resultNotification').innerHTML = 'no new tags added';
	}
	hideResultNotification($('resultNotification'));
}
/*
This function creates a new Tag element and appends it to the existing list
@author ChandanK
*/
function createNewTagElement(tagText) {
	var newDiv = document.createElement('div');
	newDiv.className = "dottedborder";
	var childDiv1 = document.createElement('div');
	childDiv1.innerHTML = '<a href="#">' + tagText + '</a>';
	var childDiv2 = document.createElement('div');
	childDiv2Img = document.createElement('img');
	childDiv2Img.src = "../images/cross.gif";
	childDiv2Img.alt = "delete";
	childDiv2.appendChild(childDiv2Img);
	newDiv.appendChild(childDiv1);
	newDiv.appendChild(childDiv2);
	var tagList = $('tagList');
	tagList.appendChild(newDiv);
}

function processResult(data, target){
	if(data.result == "error"){
		target.innerHTML = data.message;
		target.style.color = 'red';
	} else {
		target.innerHTML = data.message;
		target.style.color = 'green';
	}
}

//Added by Akhil Jain----
/*This function cuts the long enough words by inserting breaks in between.*/
function regexout(content, targetDiv){
  var textOut = content;
  var reMatch = /(?:(?!\])\S){30,}(?=[^\[\]]*(?:\[|$))/g;
  var sliceLength = 30;
  var parts = new Array;
  for (var matches = reMatch.exec(textOut); matches != null; matches = reMatch.exec(textOut)) {
    parts=Array();
    for (i=0; i < matches[0].length; i=i+sliceLength) {
       parts.push(matches[0].slice(i,i+sliceLength));
    }
    textOut = textOut.replace(matches[0], parts.join(" "));
  }
	$(targetDiv).innerHTML = textOut;
}
//Added by Akhil Jain----
/*This function cuts the long enough words by inserting breaks in between.*/
function regexout(content){
  var textOut = content;
  var reMatch = /(?:(?!\])\S){30,}(?=[^\[\]]*(?:\[|$))/g;
  var sliceLength = 30;
  var parts = new Array;
  for (var matches = reMatch.exec(textOut); matches != null; matches = reMatch.exec(textOut)) {
    parts=Array();
    for (i=0; i < matches[0].length; i=i+sliceLength) {
       parts.push(matches[0].slice(i,i+sliceLength));
    }
    textOut = textOut.replace(matches[0], parts.join(" "));
  }
	return textOut;
}

function forwardToFriend (/*string*/ url, /*string*/ resultDiv, frm) {
	resultDiv = $('errorMessage');
	sanatizeForm(frm);
	var params = frm.serialize();
	$(resultDiv).innerHTML = "Sending message";
	$('errorDiv').show();
	new Ajax.Request(url, {parameters: params, method: 'post',
		onSuccess: function (transport) { sendMessageCallback(transport, resultDiv); frm.reset();dijit.byId('sendMessage').hide();},
		onFailure: function(transport){hideResultNotification($(resultDiv)); alert('Something went wrong...');}
		});
}

function sendMessage (/*string*/ url, /*string*/ resultDiv, frm) {
	if (validateSendMessageDialog(frm)) {
		sanatizeForm(frm);
		var params = frm.serialize();
		resultDiv = $('errorMessage');
		$('errorDiv').show();
		$(resultDiv).innerHTML = "Sending message";
		showResultNotification($(resultDiv));
		if ($('sendMessageSbmt')) {$('sendMessageSbmt').disabled=true;}
		new Ajax.Request(url, {parameters: params, method: 'post',
			onSuccess: function (transport) { sendMessageCallback(transport, resultDiv); frm.reset();dijit.byId('sendMessage').hide();if ($('sendMessageSbmt')) {$('sendMessageSbmt').disabled=false;}},
			onFailure: function(transport){alert('Something went wrong...');if ($('sendMessageSbmt')) {$('sendMessageSbmt').disabled=false;}}
		});
	}
}

function  sendMessageCallback(transport, resultDiv) {
	resultDiv = "errorMessage";
	data = transport.responseText.evalJSON();
	processResult(data, $(resultDiv));
}

function validateSendMessageDialog(frm) {
	if ($('sendMessageFrm').invitationMessage.value.trim()=="") {
		$('sendMessageResult').innerHTML="Message body cannot be blank";
		return false;
	} else if ($('sendMessageFrm').invitationMessage.value.length>110) {
		$('sendMessageResult').innerHTML="Max message length is 110 characters";
		return false;
	}
	return true;
}

function setGlobalMessage(text) {
	$('errorDiv').show();
	$('errorMessage').innerHTML = text;
}
function inviteToGroup(/*string*/url,/*string*/ resultDiv,/*int*/ megiiId, /*int*/wegiiId, /*string*/ invitationMessage, frm) {
	// simple validation before sending message
	if (wegiiId==null || ''==wegiiId.trim()) {
		alert('Please select a Group GOGII and/or custom message cannot be blank');
		return ;
	}
	if ('' == invitationMessage.trim()) {
		invitationMessage = customMessage;
	}
	resultDiv = $('errorMessage');
	resultDiv.innerHTML = "Sending invite..";
	$('errorDiv').show();
	var params = 'gogii.id='+wegiiId;
	params += '&listItems[0]=' + megiiId;
	params +='&message='+escape(invitationMessage.stripTags());
	dijit.byId('inviteWegii').hide();
	new Ajax.Request (url, {
		parameters:params,
		method:'post',
		onSuccess : function (transport) {
			inviteToGroupCallback(transport, resultDiv);
			frm.reset();
		},
		onFailure: function(transport){alert('Something went wrong...');}
	});
}

function inviteToGroupCallback(transport, resultDiv) {
	data = transport.responseText.evalJSON();
	$(resultDiv).innerHTML = "Sending message";
	showResultNotification($(resultDiv));
	processResult(data, $(resultDiv));
}
/**
The actual method which does the job of sending friend
request to the server
@author Chandan
**/
function addFriendRequest(url) {
	var resultNotification = $('errorMessage');
	$('errorDiv').show();
	resultNotification.innerHTML = 'Sending request to add friend';
	showResultNotification(resultNotification);
	new Ajax.Request(url, {
		onSuccess: function (transport) {
			message = transport.responseText.evalJSON();
			resultNotification.innerHTML = (message.data.indexOf("existing") != -1) ? "You are already friends with this user.": message.data;
		},
		onFailure: function (transport) { alert ("something went wrong"); }
	});
	return false;
}
/**
This method checks if security check is required before sending friends request
lightbox.
@author Chandan
**/
function checkFriendRequest(url, checkFor, option) {
	resetSecurityCheckLightbox();
	var params = "inputString=" + checkFor;
	new Ajax.Request(url, {
		onSuccess: function (transport) {
			var message = transport.responseText.evalJSON();
			if (message.result == true) {
				$('securityCheckType').value = checkFor;
				addFriendOption = option;
				buildSecurityCheckOptions(message);
				dijit.byId('securityCheckLb').show();
			}
			else if (message.result == false){
				addFriendRequest( "../gogii/rq_addFriend.html?ajax=true&" + option);
			} else {
				alert("something went wrong");
			}
		},
		onFailure: function (transport) {alert ("something went wrong");},
		parameters: params
	});
}
/**
This method checks if security check is required before showing send message light window
@author Chandan
**/
function sendMessageRequest(url, checkFor, option) {
	resetSecurityCheckLightbox();
	var params = "inputString=" + checkFor;
	new Ajax.Request(url, {
		onSuccess: function (transport) {
			var message = transport.responseText.evalJSON();
			if (!message.allowAction) {
				autocompleteNotify("Sorry. You must be a friend of this user to send them a message.");
				return;
			}
			if (message.result == true) {
				// set this hidden value in the form so that we can use it in the callback to figure out if its send message or add as a friend
				$('securityCheckType').value = checkFor;
				if(dijit.byId('forwardToFriend')) {
					dijit.byId('forwardToFriend').hide();
				}
				buildSecurityCheckOptions(message);
				dijit.byId('securityCheckLb').show();
			} else if (message.result == false){
				if (checkFor == 3) { // this check is required for compose mail
					try {
						iw.securityCheckCallback();
					} catch (err) {
						iw.addEmailOrPhone();
					}
				} else if (checkFor==4) {
					iw.securityCheckCallback();
				} else {
					dijit.byId('sendMessage').show();
				}
			} else {
				alert("something went wrong");
			}
		},
		onFailure: function (transport) {alert ("something went wrong");},
		parameters: params
	});
}

function buildSecurityCheckOptions(message) {
	if (message.hasName && message.hasEmail && message.hasPhone) {
		$('lastNameSpan').innerHTML = ' last name, email or mobile phone number.';
	} else if (message.hasName && message.hasEmail && !message.hasPhone) {
		$('lastNameSpan').innerHTML = ' last name or email.';
	} else if (message.hasName && !message.hasEmail && message.hasPhone) {
		$('lastNameSpan').innerHTML = ' last name or mobile phone number.';
	} else if (!message.hasName && !message.hasEmail && message.hasPhone) {
		$('lastNameSpan').innerHTML = ' mobile phone number.';
	} else if (!message.hasName && message.hasEmail && !message.hasPhone) {
		$('lastNameSpan').innerHTML = ' email.';
	} else if (!message.hasName && message.hasEmail && message.hasPhone) {
		$('lastNameSpan').innerHTML = ' email or mobile phone number.';
	}
	$('lastNameSpan').show();
	/*
	if (message.hasName == false && $('lastNameSpan')) {
		$('lastNameSpan').hide();
	} else {
		$('lastNameSpan').show();
	}
	if (message.hasEmail == false && $('emailSpan')) {
		$('emailSpan').hide();
	} else {
		$('emailSpan').show();
	}
	if (message.hasPhone == false && $('phoneSpan')) {
		$('phoneSpan').hide();
	} else {
		$('phoneSpan').show();
	}
	if ((message.hasName || message.hasEmail) && message.hasPhone && $('orSpan')) {
		$('orSpan').show();
	} else if ($('orSpan')) {
		$('orSpan').hide();
	}
	if (message.hasName && message.hasEmail && message.hasPhone) {
		$('commaSpan').show();
	} else {
		$('commaSpan').hide();
	}*/
}
/**
This method is invoked once user submits verification answer.
If answer is correct appropriate lightbox is shown or friend
request is sent to the owner of profile
@author Chandan
**/
function verifySecurityCheck(frm) {
	if (frm.message.value.trim() == "") {
		$("securityCheckDiv").show();
		$("securityCheckError").innerHTML = "Please enter security check answer.";
		return;
	}
	if ($("loginForm_submit")) {
		$("loginForm_submit").disabled=true;
	}
	new Ajax.Request(frm.action, {
		onSuccess: function (transport) {
			var message = transport.responseText.evalJSON();
			if (message.result == true) {
				if ($('securityCheckType').value == 1) {
					dijit.byId('securityCheckLb').hide();
					dijit.byId('sendMessage').show();
				} else if ($('securityCheckType').value == 2){
					dijit.byId('securityCheckLb').hide();
					addFriendRequest( "../gogii/rq_addFriend.html?ajax=true&" + addFriendOption);
				} else if ($('securityCheckType').value == 3) { // This check was added for security check on compose mail
					try {
						iw.securityCheckCallback();
					} catch (err) {
						iw.addEmailOrPhone();
					}
					dijit.byId('securityCheckLb').hide();
				} else if ($('securityCheckType').value == 4) {
					try {
						if (groupInviteCallback != null) {
							groupInviteCallback ();
						}
					} catch (err) {
						iw.securityCheckCallback();
						dijit.byId('securityCheckLb').hide();
					}
				}
			} else {
				$("securityCheckDiv").show();
				$("securityCheckError").innerHTML = "Security check failed!!";

			}
			if ($("loginForm_submit")) {
				$("loginForm_submit").disabled=false;
			}
		},
		onFailure: function (transport) {alert ("something went wrong");if ($("loginForm_submit")) {$("loginForm_submit").disabled=false;}},
		parameters: frm.serialize()
	});
}
/*
This function is required to reset the state of the security check lightwindow
@author Chandan
*/
function resetSecurityCheckLightbox() {
	$("securityCheckDiv").hide();
	$("friendRequestCheck").value = "";
}

checkGroupInvite = function (url) {
	resetSecurityCheckLightbox();
	var params = "inputString=4";
	new Ajax.Request (url, {
		onSuccess: function (transport) {
			var message = transport.responseText.evalJSON();
			if (message.result == true) {
				// set this hidden value in the form so that we can use it in the callback to figure out if its send message or add as a friend
				$('securityCheckType').value = 4;
				buildSecurityCheckOptions(message);
				dijit.byId('securityCheckLb').show();
			} else {
				dijit.byId('inviteWegii').show();
			}
		},
		parameters: params
	});
}

/*
Methods below are used for previewing any gogii on web or phone
@author Akhil Jain
@date March 3rd 2009
*/

function saveAndViewOnPhone(url, giiWord){
	 saveAllTabs();
     viewOnPhone(url,giiWord);
}

function saveAndViewOnWeb(url, giiWord ){
	saveAllTabs();
    viewOnWeb(url, giiWord);
}

function saveAndViewOnWebAndPhone(webUrl, phoneUrl, giiWord){
	 saveAllTabs();
	 viewOnWeb(webUrl, giiWord);
     viewOnPhone(phoneUrl,giiWord);
}

function viewOnPhone(url, giiWord){
	new Ajax.Request(url+"&giiWord="+giiWord, {method: 'post',
		onSuccess: function(transport) {
		    $('errorDiv').show();
			$('errorMessage').innerHTML = transport.responseText;
		}
	});
}

function viewOnWeb(url, giiWord){
	window.open(url+"gogiiName="+giiWord,'','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes')
}
