//////////////////////////////////////
// Email - Jonghoon Park (04.11.08) //
//----------------------------------//
//1. name of Friend objects should  //
//be 'ref'							//
//////////////////////////////////////

var emailFormOpen = false;	// (bool) check if any form is open
var emailFormErr = "Only one form can be open at a time";	// error message

// 1: occur in a current tour, or itinerary page
// 2: occur in an Account page of My Trip Planner
// 3: occur in a Friends page of My Trip Planner
function Email ( action, userName )
{
	this.id = "emailForm";
	this.userName = userName?userName:'';
	this.action = action;
	this.fileForEmail = "/myTrips/Ajax_Email.php5"; // a file to which parameters in email form are sent by AJAX
	this.fileForFriend = "/myTrips/Ajax_Friend.php5"; // a file to which parameters in My Friends Form are sent by AJAX
	
	this.itineraryLinkTitle = '';
	this.receiver = document.getElementById("friend0"); // div that contains input boxes for receiver's name and email field
	this.sender = document.getElementById("sender");  // div that contains input boxes for sender's name and email field
	this.comment = document.getElementById("comments");  // div that contains text area for additional comments
	
	this.counter = 1;  // (int) index # of new friends added to the list of receivers
	this.maximumEntries = 5; // maximum number of entries you can add friends up to
	this.myFriendsOpen = false; // (bool) tell whether friends list window is open
	
	this.friendsListBoxID = "friendList";
	this.friends = new Array();	// array holding friend's information including name and email address	
	this.numOfFriends = 0;
	this.selectedFriendsCounter = this.maximumEntries+1;

	//this.setAction(action);
	this.emailForm(); // create an email form dynamically
}

Email.prototype.initialization = function ()
{	
	this.friends = new Array();
	this.counter = 1;
	this.myFriendsOpen = false;
	this.numOfFriends = 0;	
	this.selectedFriendsCounter = this.maximumEntries+1;
}

Email.prototype.setAction = function (action)
{
	switch ( action )
	{
		case 1:
			this.action = '';
			break;
		case 2:
			this.action = '';
			break;
		case 3:
			this.action = 'friends';
			break;
		default:
			this.action = '';
			break;
	}
}

// add input boxes to enter friend's email information
Email.prototype.addFriend = function ()
{
	if ( this.counter < this.maximumEntries) {
		var div = document.createElement("DIV");
			div.id = 'friend'+this.counter;
			div.className = "friend";
			div.appendChild(document.createTextNode("\n"));		
		var txt = document.createTextNode(" Name ");
		
		div.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "friend[" + this.counter + "][name]";
			
		div.appendChild(input);
		
		var txt = document.createTextNode(" E-mail ");
		
		div.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "friend[" + this.counter + "][email]";
			
		div.appendChild(input);
		div.appendChild(document.createTextNode("\n"));
		
		var friendsToEmail = document.getElementById('friendsToEmail');
		
		friendsToEmail.appendChild(div);
		
		this.counter++;
		this.realCounter++;
		
	} else {
		alert("Please limit the number of friends you are sending an e-mail to " + this.maximumEntries);
	}
}

// add friends from user's registered friends data in DB
Email.prototype.openMyFriends = function ()
{
	if ( this.friends.length > 0 ) {
		var myFriends = $(this.friendsListBoxID);
		
		if ( this.numOfFriends > 0 ) { // are all friends added to emailForm?
				myFriends.style.display = "block";
		} else {
			myFriends.style.display = "none";
			alert("You added all your friends!");
		}			
	} else { // create MyFriends form
		var emailForm = $(this.id);
	
		var myFriends = document.createElement("DIV");
			myFriends.id = this.friendsListBoxID;
			
		emailForm.appendChild(myFriends);
		
		var pars = "";
				
		var ajax = new Ajax.Request(this.fileForFriend,
								   {parameters: pars,
									onComplete: this.getFriends.bind(this)} );
	}
} // END openMyFriends


//Ajax: get friends from DB
Email.prototype.getFriends = function ( oReq, oJSN )
{
	var count = 0; // index of friends array
	var flag = false; // true: has at least one friend with an email
					  // false: none of user's friends has email address	
					  
	//alert("length = " + oJSN['friends'].length);
	if ( oJSN['friends'].length > 0 )
	{		
		for (var i=0; i<oJSN['friends'].length; i++)
		{
			if ( !oJSN['friends'][i].error && oJSN['friends'][i].email != '' )
			{
				this.friends[count] = new Array("fName", "lName", "email", "inMyfriends");
				
				this.friends[count]['email'] = oJSN['friends'][i].email;				
				
				if ( oJSN['friends'][i].fName ) {
					this.friends[count]['fName'] = oJSN['friends'][i].fName;
				}
				
				if ( oJSN['friends'][i].lName ) {
					this.friends[count]['lName'] = oJSN['friends'][i].lName;
				} else {
					this.friends[count]['lName'] = "";
				}
				
				this.friends[count]['inMyfriends'] = true;
				
				count++;
			}
		}
	}
	
	this.numOfFriends = this.friends.length;	
	
	if ( this.numOfFriends > 0 ) {
		this.createMyFriends();
		var myFriends = $(this.friendsListBoxID);
			myFriends.style.display = "block";
	} else {
		alert("You have no registered friends with their emails in your account.");
	}
}

// create friends list in MyFriends form
Email.prototype.createMyFriends = function ()
{
	var that = this;
	
	var myFriends = $(this.friendsListBoxID);
	
	while ( myFriends.childNodes[0] )
	{
		myFriends.removeChild(myFriends.childNodes[0]);
	}
	
	// create X(Exit) button
	var button = document.createElement("INPUT");
		button.id = "close";
		button.type = "button";
		button.onclick = function () { that.hideMyfriends(); }
		button.value = "X";
	myFriends.appendChild(button);
		
	// add title of MyFriends form
	var div = document.createElement("DIV");
		div.className = "titleMyfriends";
	var b = document.createElement("B");	
		b.style.fontSize = "130%";
		b.appendChild(document.createTextNode("My Friends"));	
		
	div.appendChild(b);
	myFriends.appendChild(div);
	
	var br = document.createElement("BR");
			myFriends.appendChild(br);	
	
	// add friend lists obtained from Database into MyFriends form
	for (var i=0; i<that.friends.length; i++)
	{
		if ( that.friends[i]['inMyfriends'] ) {
			var fullName = "";
			var emailTxt = "";
			var pars = "";		
			
			if (that.friends[i]['fName']) {			
				fullName = that.friends[i]['fName'];
				//pars += "'"+that.friends[i]['fName']+"', ";
			}
			
			if (that.friends[i]['lName']) {
				fullName += " "+that.friends[i]['lName'];
				//pars += "'"+that.friends[i]['lName']+"', ";
			}

			if (that.friends[i]['email']) {
				emailTxt = " - "+that.friends[i]['email'];
				//pars += "'"+that.friends[i]['email']+"'";
			}

			var div = document.createElement("DIV");
				div.id = "registeredFriend"+i;
				div.className = "registeredFriends";

			var	b = document.createElement("B");
				b.appendChild(document.createTextNode(emailTxt));

			var a = document.createElement("A");
				a.index = i;
				a.onclick = function () { that.insertMyFriends(this.index); };		
			
			var	b = document.createElement("B");
			
			b.appendChild(document.createTextNode(fullName));
			a.appendChild(b);
			a.appendChild(document.createTextNode(emailTxt));
			div.appendChild(a);
			myFriends.appendChild(div);
		}
	}
	
	that.myFriendsOpen = true;	
		
} // END createMyFriends

// hide MyFriends form
Email.prototype.hideMyfriends = function ()
{
	var myFriends = $(this.friendsListBoxID);
		myFriends.style.display = "none";
	
	this.myFriendsOpen = false;
} // END hideMyfriends


//cut the friend from MyFriends and past it in Email form
Email.prototype.insertMyFriends = function (index)
{
	var that = this;

	var el = document.getElementById('friend0');

	var parent = el.parentNode;

	var div = document.createElement("DIV");
		div.id = "selectedFriend"+index;
		div.className = "selectedEntry";
		
	var fullname = that.friends[index]['fName']+" "+that.friends[index]['lName'];
		
	var input = document.createElement("INPUT");
		input.type = "hidden";
		input.id = "friend["+that.selectedFriendsCounter+"][name]";
		input.name = "friend["+that.selectedFriendsCounter+"][name]";
		input.value = fullname;

	div.appendChild(input);

	var b = document.createElement("B");
		b.appendChild(document.createTextNode(fullname));
		
	div.appendChild(b);

	var input = document.createElement("INPUT");
		input.type = "hidden";
		input.id = "friend["+that.selectedFriendsCounter+"][email]";
		input.name = "friend["+that.selectedFriendsCounter+"][email]";
		input.value = that.friends[index]['email'];
		
	div.appendChild(input);

	var email = document.createTextNode(" <"+that.friends[index]['email']+"> - ");
	
	div.appendChild(email);

	that.selectedFriendsCounter++;

	var a = document.createElement("A");
		a.index = index;
		a.onclick = function () { that.insertBack(this.index); };
		a.appendChild(document.createTextNode("remove"));
	
	div.appendChild(a);

	parent.insertBefore(div, el);
	
	that.friends[index]['inMyfriends'] = false;
	
	var deleteFriend = $("registeredFriend"+index);
	deleteFriend.parentNode.removeChild(deleteFriend);
	
	that.numOfFriends--;
	
	that.openMyFriends();
}

//cut the friend back to MyFriends form
Email.prototype.insertBack = function (index)
{
	var el = $('selectedFriend'+index);
	
	var parent = el.parentNode;
	
	parent.removeChild(el);
	
	this.friends[index]['inMyfriends'] = true;
	
	this.createMyFriends();
	
	this.numOfFriends++;
}

// send links to entered friends
Email.prototype.sendEmail = function ()
{
	var that = this;
	var pars = Form.serialize($(that.id));
	
	if ( that.action == 'alumni' )	{
		pars += "&action=alumni";
	} else if ( that.action == 'savedLinks' ) {	
		var index = 0;
		
		for ( var i in link )
		{
			if ( link[i].checked )
			{
				//pars += "&linkTitle["+ i +"]="+ link[i].title +"&linkURL["+ i +"]="+ link[i].domain + link[i].uri;
				pars += "&linkNum["+index+"]=" + i;
				index++;
			}
		}
		
		pars += "&action=savedLinks";
	} else if ( that.action == 'itinerary' ) {
		pars += "&action=itinerary&itineraryLinkTitle="+that.itineraryLinkTitle;
	}
	
	var ajax = new Ajax.Request(that.fileForEmail,
							    {method: 'post', 
								 parameters: pars,
								 onLoading: this.inSending.bind(this),
								 onComplete: this.completeSending.bind(this)} );
}

// After 'Send' button is clicked, display results : AJAX 
Email.prototype.completeSending = function (oReq, oJSN)
{
	var that = this;
	var resultMessageBox = '';
	var invalidEmail = '';
	var length = 0;
	
	if ( that.action == 'savedLinks' || that.action == 'itinerary' ) {	
		var friendsToEmail = document.getElementById('friendsToEmail');	
		
		// remove current friends list
		for ( var i=0; i<that.counter; i++ ) {
			var el = document.getElementById('friend'+i);
			friendsToEmail.removeChild(el);
		}
	}
	
	if ( !oJSN.error ) {
		that.closeEmailForm();	// delete current email form
		that.emailForm();		// create new email form
		that.initialization();	// initialize values
		
		for ( var i=0; i<oJSN.receiver.length; i++ ) {
			resultMessageBox += oJSN.receiver[i].name.value + " was successfully sent an email.<Br/>";
		}
		
		$('errorMsg').className = "errorFalse";
	} else {
		resultMessageBox = oJSN.error;
		
		if ( oJSN.receiver.length < 1 ) {
			length = 1;			
		} else {
			length = oJSN.receiver.length - ( that.friends.length - that.numOfFriends );
		}		
		// build new friends list excluding field where both name and email fiels are empty	
		that.counter = 0;	
	
		for ( var i=0; i<length; i++ ) {
			var div = document.createElement("DIV");
				div.id = "friend"+i;
				div.className = "friend";
				div.style.paddingLeft = "10px";
				div.appendChild(document.createTextNode("\n"));
		
			var txt = document.createTextNode(" Name ");
			
			div.appendChild(txt);
			
			var input = document.createElement("INPUT");
				input.name = "friend["+i+"][name]";
				
			if ( oJSN.receiver.length < 1 ) {
				input.value = "";
				input.className = "";
			} else {
				input.value = oJSN.receiver[i].name.value;
				
				if ( oJSN.receiver[i].name.error ) {
					errorFlag = true;
					input.className = "error";
				}
			}
				
			div.appendChild(input);
			
			var txt = document.createTextNode(" E-mail ");
			
			div.appendChild(txt);			
			
			var input = document.createElement("INPUT");
				input.name = "friend["+i+"][email]";
				
			if ( oJSN.receiver.length < 1 ) {
				input.value = "";
				input.className = "";
			} else {
				input.value = oJSN.receiver[i].email.value;
				
				if ( oJSN.receiver[i].email.error ) {
					errorFlag = true;
					input.className = "error";
					
					if ( oJSN.receiver[i].email.error != '1' ) {
						invalidEmail = oJSN.receiver[i].email.error;
					}
				}
			}

			that.counter = i+1;

			div.appendChild(input);
			friendsToEmail.appendChild(div);
		}// END for statement			

		// display error messages if errors occured
		resultMessageBox += invalidEmail?invalidEmail:'';
		$('errorMsg').className = "errorTrue";
	}

	// display result message in erroMsg Box
	$('errorMsg').innerHTML = resultMessageBox;	
	$('errorMsg').style.display = "block";
	
	// close a sending image
	window.setTimeout(function () {that.inSendingClose();}, 1000);
}

// show sending image
Email.prototype.inSending = function ()
{
	document.getElementById('sendingImg').style.display = "block";
}

// remove sending image
Email.prototype.inSendingClose = function ()
{
	document.getElementById('sendingImg').style.display = "none";
}

// delete existing email form
Email.prototype.closeEmailForm = function ()
{
	var el = $(this.id);
	
	if ( el ) {
		el.parentNode.removeChild(el);
		window.onscroll = function () {};
		emailFormOpen = false;
	}
}

// create new email form 
Email.prototype.emailForm = function ()
{	
	var that = this;
	var error = false;
	var errMsg = '';
	
	var boundary = document.createElement("FORM");
		boundary.id = that.id;
		boundary.style.display = "none";
	
	var closeButton = document.createElement("INPUT");
		closeButton.id = "close";
		closeButton.type = "button";
		closeButton.onclick = function () { that.closeEmailForm(); } // close function
		closeButton.value = "X";
		
	boundary.appendChild(closeButton);
	
	var title = document.createElement("DIV");
	var h2 = document.createElement("H2");	
	
	if ( that.action == 'savedLinks' || that.action == 'itinerary' ) {
		var txt = document.createTextNode("E-mail links to friends and family:");
	} else if ( that.action == 'alumni' ) {		
		var txt = document.createTextNode("Tell your friends and family:");
	}
			  
	h2.appendChild(txt);
	title.appendChild(h2);

	if ( that.action == 'savedLinks' ) {		
		var ul = document.createElement("UL");
			ul.id = "selectedLinks";
			title.appendChild(ul);
		boundary.appendChild(title);
	}
	else if (that.action == 'alumni') {		
		boundary.appendChild(title);
		boundary.appendChild(document.createTextNode("\n"));
		boundary.appendChild(document.createElement("BR"));
	} else if ( that.action == 'itinerary' ) {
		var ul = document.createElement("UL");
			ul.id = "selectedLinks";
			
		var li = document.createElement("LI");
		
		that.itineraryLinkTitle = document.getElementsByTagName("HEAD")[0].getElementsByTagName("TITLE")[0].innerHTML;
		
		li.innerHTML = that.itineraryLinkTitle;
		ul.appendChild(li);
			
		title.appendChild(ul);
		boundary.appendChild(title);
	}
	
	// error message division
	var div = document.createElement("DIV");
		div.id = "errorMsg";
		boundary.appendChild(div);
	// display sending message
	var loadingMsg = document.createElement("DIV");
		loadingMsg.id = "sendingImg";
		loadingMsg.style.display = "none";
		loadingMsg.style.verticalAlign = "middle";
		loadingMsg.align = "center";
	var img = document.createElement("IMG");
		img.src = "/myTrips/img/loading.gif";
		img.style.width = "50px";
		img.style.height = "48px";
	var txt = document.createTextNode("Sending...");
	
	loadingMsg.appendChild(img);
	loadingMsg.appendChild(txt);
	boundary.appendChild(loadingMsg);
		
	if ( that.action == 'savedLinks'|| that.action == 'itinerary' )
	{
		
		var a = document.createElement("A");
			a.id = "addFriend";
			a.onclick = function () { that.addFriend(); }
		var txt = document.createTextNode("Add Another Friend ");
		
		a.appendChild(txt);
		boundary.appendChild(a);
		
		// creatung a button for selecting friends to send emails
		if ( that.userName != '' ) {
			boundary.appendChild(document.createElement("BR"));
			
			var button = document.createElement("INPUT");
				button.id = "selectButton";
				button.className = "selectButton";
				button.type = "button";
				button.onclick = function () { that.openMyFriends(); }
				button.value = "select from My Friends";
			
			boundary.appendChild(button);
			boundary.appendChild(document.createElement("BR"));
			boundary.appendChild(document.createElement("BR"));
		}
	}
	else if ( that.action == 'alumni' ) 
	{			
		var div = document.createElement("DIV");
			div.style.color = "#900";
			div.style.fontSize = "140%";
			div.style.fontWeight = "bold";
		var txt = document.createTextNode("To:");
		
		div.appendChild(txt);
		boundary.appendChild(div);
	}
		
	if ( that.action == 'savedLinks' || that.action == 'itinerary' )
	{
		var friendsToEmail =document.createElement("DIV");
			friendsToEmail.id = "friendsToEmail";
			
		var div = document.createElement("DIV");
			div.id = "friend0";
			div.className = "friend";
			
		div.appendChild(document.createTextNode("\n"));		
	
		var txt = document.createTextNode(" Name ");
		
		div.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "friend[0][name]";
			
		div.appendChild(input);
		
		var txt = document.createTextNode(" E-mail ");
		
		div.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "friend[0][email]";
			
		div.appendChild(input);
		div.appendChild(document.createTextNode("\n"));
		friendsToEmail.appendChild(div);
		boundary.appendChild(friendsToEmail);		
	}			
	else if ( that.action == 'alumni' )
	{
		var count = 0;
		
		var friendsToSend = document.createElement("DIV");
			friendsToSend.id = "friendsToSend";			
		
		for(var i in friend)
		{
			if (friend[i].checked == true)
			{
				if (friend[i].email)
				{
					var div = document.createElement("DIV");
					div.id = "friend"+count;					
					div.style.paddingLeft = "10px";
					div.appendChild(document.createTextNode("\n"));
					
					var name = document.createElement("B");						
						name.appendChild(document.createTextNode(friend[i].firstName+"  "+friend[i].lastName));
						
					div.appendChild(name);
					
					var input = document.createElement("INPUT");
						input.type = "hidden";
						input.name = "friend["+count+"][name]";
					
					if (friend[i].lastName != '')
					{						
						input.value = friend[i].firstName+"  "+friend[i].lastName;
					}
					else
					{
						input.value = friend[i].firstName;
					}
					
					div.appendChild(input);						
					
					var input = document.createElement("INPUT");
					input.type = "hidden";
					input.name = "friend["+count+"][email]";
					input.value = friend[i].email;
					
					div.appendChild(input);
					div.appendChild(document.createTextNode("\n"));
					friendsToSend.appendChild(div);				
					count++;						
				}
				else
				{
					errMsg += friend[i].firstName+" has no e-mail address\n";						
					error = true;
				}
			}
		}
		
		boundary.appendChild(friendsToSend);
	}		
	
	if (that.userName != '')
	{
		var div = document.createElement("DIV");
			div.id = "comments";		
		
		var b = document.createElement("B");
			b.style.fontSize = "140%";
			b.style.color = "#900";
		
		var txt = document.createTextNode("From:");
		
		b.appendChild(txt);
		div.appendChild(b);
		div.appendChild(document.createElement("BR"));			
	
		var b = document.createElement("B");
			b.style.fontSize = "110%";
			b.style.fontWeight = "bold";
			b.style.paddingLeft = "10px";			
		
		var txt = document.createTextNode(that.userName);
		
		b.appendChild(txt);
		div.appendChild(b);
		div.appendChild(document.createElement("BR"));
		div.appendChild(document.createElement("BR"));
		
		var txt = document.createTextNode("Add optional comments:\n");
		
		div.appendChild(txt);
		div.appendChild(document.createElement("BR"));		
		
		var textarea = document.createElement("TEXTAREA");
			textarea.name = "comments";
			textarea.rows = "5";
			textarea.cols = "35";
			div.appendChild(textarea);
		boundary.appendChild(div);
		
		var button = document.createElement("INPUT");
			button.type = "button";
			button.name = "submit";
			button.onclick = function () { that.sendEmail(); } // sending email method
			button.value = "Send";
			
		boundary.appendChild(button);		
	}
	else
	{		
		var div = document.createElement("DIV");
			div.id = "sender";
			div.className = "friend";		
		var br = document.createElement("BR");
		
		div.appendChild(br);
		
		var b = document.createElement("B");
			b.style.fontSize = "140%";
			b.style.color = "#F00";
		var txt = document.createTextNode("From");
		
		b.appendChild(txt);
		div.appendChild(b);
		
		var div2 = document.createElement("DIV");
			div2.className = "form";	
			div2.style.paddingLeft = "10px";
			div2.appendChild(document.createTextNode("\n"));
		var txt = document.createTextNode(" Name ");
		
		div2.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "sender[name]";
			
		div2.appendChild(input);
		
		var txt = document.createTextNode(" E-mail ");
		
		div2.appendChild(txt);
		
		var input = document.createElement("INPUT");
			input.name = "sender[email]";
			
		div2.appendChild(input);
		div2.appendChild(document.createTextNode("\n"));
		div.appendChild(div2);
		boundary.appendChild(div);		
		
		var div = document.createElement("DIV");
			div.id = "comments";
		
		var txt = document.createTextNode("Add optional comments:\n");
		
		div.appendChild(txt);
		div.appendChild(document.createElement("BR"));		
		
		var textarea = document.createElement("TEXTAREA");
			textarea.name = "comments";
			textarea.rows = "5";
			textarea.cols = "35";
			
		div.appendChild(textarea);
		boundary.appendChild(div);
		
		var button = document.createElement("INPUT");
			button.type = "button";
			button.name = "submit";
			button.onclick = function () { that.sendEmail(); }
			button.value = "Send";
			boundary.appendChild(button);
	}
	
	if (error == false)
	{
		document.body.appendChild(boundary);
		boundary.style.display = "block";
		that.position();
		window.onscroll = function () { that.position(); };
	
		emailFormOpen = true;
	}
	else
	{
		errMsg += "Please enter the e-mail address and try again!";
		alert(errMsg);
	}
	
}	

Email.prototype.position = function ()
{
	var object = document.getElementById(this.id);

	object.style.left = posLeft() + 270 + "px";
	object.style.top = posTop() + 50 + "px";
}

///////////////////////////////////////////////////////////
// Browser Window Size and Position						 //
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005 //
///////////////////////////////////////////////////////////

function pageWidth()
{
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

function pageHeight()
{
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

function posLeft()
{
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

function posTop()
{
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

function posRight()
{
	return posLeft()+pageWidth();
}

function posBottom()
{
	return posTop()+pageHeight();
}
