// JavaScript routines for Webmail2 HT Concept
// Much of this code is simply to make the demo fly.
// Re-use if possible.

// cross-platform DOM access
function getEl(el)
{
	return( document.getElementById(el) );
}

// cross-platform Event listening
function addEvent(el,evType,fn,useCapture)
{
	if ( el.addEventListener )
	{
		el.addEventListener(evType,fn,useCapture);
		return true;
	}
	else if ( el.attachEvent )
	{
		var r = el.attachEvent('on' + evType, fn);
		return r;
	}
	else
	{
		el['on' + evType] = fn;
	}
}

// cross-platform event killer
function stopEventBubble(evt)
{
	if ( !evt )
		var evt = window.event;
	evt.cancelBubble = true;
	if ( evt.stopPropagation )
		evt.stopPropagation();
}

// cross-browser document height determination
// alistapart.com
function getWindowHeight()
{
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
        } else {
                if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                } else {
                        if (document.body && document.body.clientHeight) {
                                windowHeight = document.body.clientHeight;
                        }
                }
        }
        return windowHeight;
}

function getWindowWidthCrBr()
{
        var windowWidth = 0;
        if (typeof(window.innerWidth) == 'number') {
                windowWidth = window.innerWidth;
        } else {
                if (document.documentElement && document.documentElement.clientWidth) {
                        windowWidth = document.documentElement.clientWidth;
                } else {
                        if (document.body && document.body.clientWidth) {
                                windowWidth = document.body.clientWidth;
                        }
                }
        }
        return windowWidth;
}

function getWindowWidth()
{
	return window.innerWidth ? window.innerWidth : document.body.offsetWidth;
}

function popImporter()
{
	window.open("importer.html","importer","height=200,width=320,status=0,statusbar=0,scrollbars=0");
}

function toolbarOn(ico)
{
	document.images[ico].src = './themes/images/tbar' + ico + '_hov.png';
	if ( ico != "_new" && getEl('menuNew') )
		hideNewMenu();
}

function toolbarOff(ico)
{
	document.images[ico].src = './themes/images/tbar' + ico + '.png';
}

function toolbarCalendarOn(ico)
{
	document.images[ico].src = '../themes/images/tbar' + ico + '_hov.png';
	if ( ico != "_new" && getEl('menuNew') )
		hideNewMenu();
}

function toolbarCalendarOff(ico)
{
	document.images[ico].src = '../themes/images/tbar' + ico + '.png';
}

function setActive(app)
{
	apps = new Array("New","Mail","Contacts","Calendar","Prefs","Home");
	for (i=0; i<apps.length; i++)
	{
		if ( app == apps[i] )
			getEl('tbar' + apps[i]).style.borderTop = "2px solid #00f";
		else
			getEl('tbar' + apps[i]).style.borderTop = "2px solid #4299D1";
	}
}

// resize the main iframe to use all available height
function resizeView()
{
	getEl('wmView').style.height = (getWindowHeight() - 100) + 'px';
}

function maxHeight(elem)
{
	getEl(elem).style.height = (getWindowHeight() - 7) + 'px';
}

// bug 3120 - ddolgov
function maxHeight2(elem)
{
//	getEl(elem).style.height = (window.innerHeight - 35) + 'px';
	getEl(elem).style.height = (getWindowHeight() - 35) + 'px';
}
	

function maxWidth(elem)
{
	if (document.all)
                removal = 1;
        else
                removal = 10;

	if ( "creation" == elem )
		removal = 0;
	getEl(elem).style.width = (getWindowWidthCrBr() - removal) + 'px';
}

function openView(page)
{
	frames.wmView.location.href = page;
}

function hideNewMenu()
{
	getEl('menuNew').style.display = 'none';
}

function showNewMenu()
{
	getEl('menuNew').style.display = 'block';
}

function toggleNewMenu()
{
	menu = getEl('menuNew');
	if ( menu && menu.style.display == 'block' )
		hideNewMenu();
	else
		showNewMenu();
}

function clearAppMenu()
{
	getEl('appMenu').innerHTML = "&nbsp;&nbsp;&nbsp;";
}

function showContactsMenu()
{
	clearAppMenu();
	addAppMenuItem("New Contact","createNew('contact')","Create a new contact");
	addAppMenuItem("New Group","createNew('group')","Create a new group");
	addAppMenuItem("New List","createNew('list')","Create a new list");

	addAppMenuItem("separator","","");

	selItem = document.createElement("select");
	selItem.setAttribute('id','contactGroupSel');
	selItem.setAttribute('name','contactGroupSel');
	selItem.setAttribute('size',1);
	selItem.setAttribute('class','appMenuSelect');
	
	selItem.options[0] = new Option("Add contact to group","");
	
	getEl('appMenu').appendChild(selItem);
	
	addAppMenuItem("separator","","");

	lstItem = document.createElement("select");
	lstItem.setAttribute('id','contactListSel');
	lstItem.setAttribute('name','contactListSel');
	lstItem.setAttribute('size',1);
	lstItem.setAttribute('class','appMenuSelect');
	
	lstItem.options[0] = new Option("Add contact to list","");
	getEl('appMenu').appendChild(lstItem);		
}

function updateContactsMenu(groupSet,listSet)
{
	groupMenu = getEl('contactGroupSel');
	listMenu = getEl('contactListSel');

	// clear existing items (except the top one)
	groupMenu.options.length = 1;
	listMenu.options.length = 1;

	slot = 1;
	for ( i=0; i<groupSet.length; i++ )
	{
		groupMenu.options[slot] = new Option(groupSet[i].text,groupSet[i].value);
		slot++;
	}

	slot = 1;
	for ( i=0; i<listSet.length; i++ )
	{
		listMenu.options[slot] = new Option(listSet[i].text,listSet[i].value);
		slot++;
	}
}

function showMailMenu()
{
	clearAppMenu();

	addAppMenuItem("Compose","composeMessage()","Compose a new message.");
	addAppMenuItem("separator","","");
	addAppMenuItem("Check Mail","location.href='index.php?PID=2'","Check server for new mail.");
	addAppMenuItem("separator","","");
	addAppMenuItem("Reply","composeReply()","Reply to the selected message");
	addAppMenuItem("Reply All","composeReply()","Reply to all recipients of the selected message");
	addAppMenuItem("Forward","forwardMessage()","Forward the selected message");
	addAppMenuItem("Delete","deleteMessage()","Delete the selected message");
	addAppMenuItem("separator","","");
	
	addAppMenuFolderSelect("moveMessageToFolder","Move to...","moveMessages()");
	addAppMenuItem("separator","","");
	//addAppMenuFolderSelect("copyMessageToFolder","Copy to...","copyMessages()");
}

function showCalendarMenu()
{
	clearAppMenu();

	addAppMenuItem("New Event","popNewEvent()","Create new event.");
	addAppMenuItem("separator","","");
	addAppMenuItem("Day View","location.href='index.php?PID=5&frame=calendar/day.php'","Day Calendar");
	addAppMenuItem("Week View","location.href='index.php?PID=5&frame=calendar/week.php'","Week Calendar");
	addAppMenuItem("Month View","location.href='index.php?PID=5&frame=calendar/month.php'","Month Calendar");
}

/*
function addAppMenuItem(label,jsAction,tooltip)
{


	if ( label != "separator" )
	{
		menuItem = document.createElement("a");
		menuItem.setAttribute('class','appMenuItem');
		menuItem.setAttribute('title',tooltip);
		menuItem.setAttribute('href',"javascript:" + jsAction);
		menuItem.appendChild(document.createTextNode(label));
	}
	else
	{
		menuItem = document.createElement("span");
		menuItem.setAttribute('class','appMenuSeparator');
		menuItem.appendChild(document.createTextNode(" "));
	}
	
	getEl('appMenu').appendChild(menuItem);

}
*/

function addAppMenuItem(label,jsAction,tooltip)
{
	if ( label != "separator" )
	{
		getEl('appMenu').innerHTML += '<a href="javascript:'+jsAction+'" class="appMenuItem">'+label+'</a>';
	}
	else
	{
		getEl('appMenu').innerHTML += '<span class="appMenuSeparator"> </span>';
	}
	
}

function popNewContact()
{
	window.open("new_contact_window.html","newcontact","height=460,width=560,status=0,scrollbars=0");
}

function popConverter()
{
	window.open("services/importer.php","importer","height=200,width=320,status=0,statusbar=0,scrollbars=0");
}

function popNewEvent()
{
	window.open("calendar/new.php?top=1","newevent","height=590,width=600,status=0,scrollbars=0");
}

function popEditEvent(url)
{
	window.open(url,"editevent","height=580,width=600,status=0,scrollbars,resizable=1");
}

function composeMessage()
{
	window.open("mail/compose.php","compose","height=520,width=680,status=0,scrollbars=0,resizable=1");
}

function composeReply()
{
	if(!parent.frames[0].preview.document.messages)
	{
		alert('No message selected.');
		return;
	}		
	else with(parent.frames[0].preview.document)
	{
		arrIn 	= messages.start.value;
		msgID 	= messages.index.value;
		mailbox = messages.thismailbox.value;
	
		url = 'mail/compose.php?actionID=reply&index='+msgID+'&array_index='+arrIn+'&thismailbox='+mailbox;
		window.open(url ,"reply","height=520,width=680,status=0,scrollbars=0");
	}
}

function forwardMessage()
{
	if(!parent.frames[0].preview.document.messages)
	{
		alert('No message selected.');
		return;
	}		
	else with(parent.frames[0].preview.document)
	{
		arrIn 	= messages.start.value;
		msgID 	= messages.index.value;
		mailbox = messages.thismailbox.value;
	
		url = 'mail/compose.php?actionID=forward&index='+msgID+'&array_index='+arrIn+'&thismailbox='+mailbox;
		window.open(url ,"reply","height=520,width=680,status=0,scrollbars=0");
	}	
}

function deleteMessage()
{

	var multiple = 0;
	var single   = 0;
	
	// delete several messages from list
	
	with(parent.frames[0].messages.document.messages)
	{
		for (var i = 0; i < elements.length; i++)
		{
			if(elements[i].name == "indices[]" && elements[i].checked)
			{
				multiple = 1;
				break;
			}
		}
	}

	// delete single message

	if(parent.frames[0].preview.document.messages)
		single = 1;
	
	if(!multiple && !single)
		alert("No messages were selected");

	
	if(multiple && confirm("Are you sure that you want to delete messages?"))
	{
		with(parent.frames[0].messages.document.messages)
		{
			actionID.value = 'delete_messages';
			submit();
			return;
		}
	}
	
	if(single && confirm("Are you sure that you want to delete messages?"))
	{
		with(parent.frames[0].preview.document)
		{
			start 	= messages.start.value;
			msgID 	= messages.index.value;
			mailbox = messages.thismailbox.value;
	
			url = 'mail/message.php?actionID=delete_message&index='+msgID+'&start='+start+'&thismailbox='+mailbox;
			parent.frames[0].messages.location = url;
			parent.frames[0].messages.location = 'mail/mailbox.php';
			parent.frames[0].preview.location = 'mail/empty.php';
			return;
		}
	}


	

}

function moveContacts()
{
	select = getEl("contactGroupSel");
	var check = 0;
	if(select.options[select.selectedIndex].value == '')
		return;
	if(!parent.frames[0].contactListPane.document.contactListForm)
	{
		alert("No contacts were selected");
		return;
	}
	with(parent.frames[0].contactListPane.document.contactListForm)
	{
		for (var i = 0; i < elements.length; i++) 
			if(elements[i].name == "contactItem[]" && elements[i].checked)
				check = 1;

		if( check )
		{
			if(confirm("Are you sure that you want to move contact(s) to the '"+select.options[select.selectedIndex].text+"' group?"))
			{
				targetList.value = select.options[select.selectedIndex].value;
				actionId.value = 'MoveToGroup';
				submit();
			}
		}
		else alert("No contacts were selected");
	}
}

function moveToList()
{
	select = getEl("contactListSel");
	var check = 0;
	if(select.options[select.selectedIndex].value == '')
		return;
	if(!parent.frames[0].contactListPane.document.contactListForm)
	{
		alert("No contacts were selected");
		return;
	}
	with(parent.frames[0].contactListPane.document.contactListForm)
	{
		for (var i = 0; i < elements.length; i++) 
			if(elements[i].name == "contactItem[]" && elements[i].checked)
				check = 1;

		if( check )
		{
			if(confirm("Are you sure that you want to add contact to the '"+select.options[select.selectedIndex].text+"' list?"))
			{
				targetList.value = select.options[select.selectedIndex].value;
				actionId.value = 'add';
				submit();
			}
		}
		else alert("No contacts were selected");
	}
}

function moveMessages()
{
	select = getEl("moveMessageToFolder");
	var check = 0;
	
	if(select.options[select.selectedIndex].value == '')
		return;
	
	if(!parent.frames[0].messages.document.messages)
	{
		alert("No messages were selected");
		return;
	}

	with(parent.frames[0].messages.document.messages)
	{
		for (var i = 0; i < elements.length; i++) 
			if(elements[i].name == "indices[]" && elements[i].checked) check = 1

		if( check )
		{
			if(confirm("Are you sure that you want to move message to the "+select.options[select.selectedIndex].text+" folder?"))
			{
				targetMbox.value = select.options[select.selectedIndex].value;
				actionID.value = 'move_messages';
				submit();
			}
		}
		else alert("No messages were selected");
	}
}

function copyMessages()
{
	select = getEl("copyMessageToFolder");
	var check = 0;
	
	if(select.options[select.selectedIndex].value == '')
		return;
	
	if(!parent.frames[0].messages.document.messages)
	{
		alert("No messages were selected");
		return;
	}

	with(parent.frames[0].messages.document.messages)
	{
		for (var i = 0; i < elements.length; i++) 
			if(elements[i].name == "indices[]" && elements[i].checked) check = 1

		if( check )
		{
			if(confirm("Are you sure that you want to move message to the "+select.options[select.selectedIndex].text+" folder?"))
			{
				targetMbox.value = select.options[select.selectedIndex].value;
				actionID.value = 'copy_messages';
				submit();
			}
		}
		else alert("No messages were selected");
	}

}

function toggleSidebar()
{
	if ( getEl('maxView').style.display == "block" )
	{
		getEl('maxView').style.display = "none";
		getEl('minView').style.display = "block";
		if ( parent.document.all ) parent.document.all['leftView'].cols = "30,*" ;
		else parent.document.getElementById('leftView').cols = "30,*";
		
	}
	else
	{
		getEl('minView').style.display = "none";
		getEl('maxView').style.display = "block";
		if ( parent.document.all ) parent.document.all['leftView'].cols = "200,*" ;
		else parent.document.getElementById('leftView').cols = "200,*";
	}
}

function togglePreview(show)
{

	alert("inside webmail.js");
	if ( show )
	{
		with(parent.frames[1])
		{
			getEl('splitViewIndicator').src = "../themes/images/splitview_on.png";
			getEl('fullViewIndicator').src = "../themes/images/fullview_off.png";
		}
		
		if ( parent.document.all ) parent.document.all['rightView'].rows = "45%,*" ;
		else parent.document.getElementById('rightView').rows = "45%,*";
	}
	else
	{
		with(parent.frames[1])
		{
			getEl('splitViewIndicator').src = "../themes/images/splitview_off.png";
			getEl('fullViewIndicator').src = "../themes/images/fullview_on.png";
		}
		
		if ( parent.document.all ) parent.document.all['rightView'].rows = "100%,*" ;
		else parent.document.getElementById('rightView').rows = "100%,*";
	}
	
}


// In production, this routine should actually change the mail folder
// for now, it basically changes the title.
function openFolder(mailFolder)
{
	parent.frames['messages'].location.href = "mail_messages.html?" + mailFolder;
}

function hideDynamic(divItem)
{
	if(getEl(divItem))
		getEl(divItem).style.display = 'none';
}

function showDynamic(divItem)
{
	if(getEl(divItem))
		getEl(divItem).style.display = 'block';
}

function toggleDynamic(blockId)
{
	dynamic = getEl(blockId);
	if ( dynamic.style.display == 'block' )
		hideDynamic(blockId);
	else
		showDynamic(blockId);
}

function toggleContactBubble(evt,recipField)
{
	if ( getEl('contactBubble').style.display == 'block' && recipField == getEl('recipField').value )
	{
		hideDynamic('contactBubble');
	}
	else
	{
		if ( document.all )
		{
			x = window.event.x;
			y = window.event.y;
		}
		else
		{
			x = evt.pageX;
			y = evt.pageY;
		}
		
		y -= 30; // position it so the bubble appears to open from the icon
		x += 10; // prevent event swallowing
		getEl('contactBubble').style.top = y + "px";
		getEl('contactBubble').style.left = x + "px";
		getEl('recipField').value = recipField;
		showDynamic('contactBubble');
	}
}



// inserts a contact from the bubble into a recipient field
function addContact(contact)
{
	if ( contact.length < 1 ) {
		return;
	}
	
	fieldName = getEl('recipField').value;

	var insertVal = document.compose.elements[fieldName].value;
	insertVal = insertVal.replace(/,\s*$/i, "");
	insertVal = insertVal.replace(/;\s*$/i, "");
	
	if ( document.compose.elements[fieldName].value.length > 1 && contact.length != 0 )
		insertVal += ", " + contact;
	else
		insertVal += contact;

    // may be useful - ddolgov
/*	if ( inputEl.setSelectionRange )
    {
    	inputEl.focus();
        inputEl.setSelectionRange(inputEl.value.length, inputEl.value.length);
        if ( inputEl.scrollIntoView ) {
        	inputEl.scrollIntoView();
        }
    }
    else if ( inputEl.createTextRange )
    {
    	var range = inputEl.createTextRange();
        range.move("character", inputEl.value.length);
        range.select();
    }*/

	document.compose.elements[fieldName].value = insertVal;
	
}

function addAttendees(contact)
{
	if ( contact.length < 1 ) {
        return;
    }

	var insertVal = getEl('attendees').value;
    insertVal = insertVal.replace(/,\s*$/i, "");
    insertVal = insertVal.replace(/;\s*$/i, "");
				
	if ( document.event.elements['attendees'].value.length > 1 && contact.length != 0)
		insertVal += ", " + contact;
	else
		insertVal += contact;
	
	document.event.elements['attendees'].value = insertVal;
}
// context menu for folders
function toggleFolderMenu(evt,mailFolder)
{
	if ( getEl('folderMenu').style.display == 'block' )
	{
		hideDynamic('folderMenu');
	}
	else
	{
		if ( document.all )
		{
			x = window.event.x;
			y = window.event.y;
		}
		else
		{
			x = evt.pageX;
			y = evt.pageY;
		}
		
		x = 16;
		getEl('folderMenu').style.top = y + "px";
		getEl('folderMenu').style.left = x + "px";
		if ( mailFolder == "Personal" )
		{
			showDynamic('createNewFolder');
			hideDynamic('markRead');
			hideDynamic('markUnread');
			hideDynamic('clearFolder');
		}
		else
		{
			hideDynamic('createNewFolder');
			showDynamic('markRead');
			showDynamic('markUnread');
			showDynamic('clearFolder');
		}
		
		if ( mailFolder.indexOf("personal_") >= 0 )
		{
			showDynamic('deleteFolder');
			showDynamic('renameFolder');
		}
		else
		{
			hideDynamic('deleteFolder');
			hideDynamic('renameFolder');
		}
		showDynamic('folderMenu');
	}
	
	return false; // disables browser's default context menu
}

function expandContactEditor()
{
	maxHeight('contactEditPane');
	maxWidth = getWindowWidth() - 390; // 370 allows for combined width of the other 2 panels
	getEl('contactEditPane').style.width = maxWidth + 'px';
}

function openContactList(page, show)
{
	if ( page.substring(0,1) != "*" )
	{
		frames['contactListPane'].location.href = page;
	}
	else
	{
		selMenu = page.substring(1,page.length);
		chosen = getEl(selMenu).selectedIndex;
		if ( chosen >= 0 )
		{
			frames['contactListPane'].location.href = "browse.php?show="+show+"source=localsql&key=" + getEl(selMenu).options[chosen].value;
		}
	}
}

function openGroupEditor()
{
	groupNumber = getEl('contactGroups').selectedIndex;
	if ( groupNumber >= 0 )
	{
		group = getEl('contactGroups').options[groupNumber].value
		frames['contactEditPane'].location.href = "group.php?key=" + group + "&edit=1&source=localsql";
	}
}

function openListEditor()
{
	listNumber = getEl('contactLists').selectedIndex;
	if ( listNumber >= 0 )
	{
		list = getEl('contactLists').options[listNumber].value
		frames['contactEditPane'].location.href = "list.php?key=" + list + "&edit=1&source=localsql";
	}
}

function editContact(contact)
{
	parent.frames['contactEditPane'].location.href = "edit_contact.html?" + contact;
}

function expandPrefsPane()
{
	maxHeight('prefsPane');
	maxWidth = getWindowWidth() - 195 // allow room for the sidebar
	getEl('prefsPane').style.width = maxWidth + 'px';
	getEl('prefsPane').style.right = "0px";
	
}

function createNew(what)
{
	if (what == "contact")
		top.frames['wmView'].frames['contactEditPane'].location.href = "contacts/add.php";
	else if (what == "group")
		top.frames['wmView'].frames['contactEditPane'].location.href = "contacts/group.php";
	else if (what == "list")
		top.frames['wmView'].frames['contactEditPane'].location.href = "contacts/list.php";
	else
		top.frames['wmView'].frames['contactEditPane'].location.href = "new_" + what + ".html";
}

function openPref(page)
{
	frames['prefsPane'].location.href = page;
}

function recurHandler(frequency)
{
	freqs = new Array("1","2","3","5");
	for ( i=0; i<freqs.length; i++ )
	{
		hideDynamic('recur' + freqs[i]);
	}
		
	if ( getEl('recur'+frequency) )
	{
		showDynamic('recur'+frequency);
	}
	if ( frequency == 0 )
	{
		hideDynamic('recurUntil');
	}
	else
	{
		showDynamic('recurUntil');
	}
}

function popSearch()
{
	xpos = ( getWindowWidth() - 500 ) / 2;
	ypos = ( getWindowHeight() - 400 ) / 2;
	
	getEl('powerSearchBox').style.top = ypos + 'px';
	getEl('powerSearchBox').style.left = xpos + 'px';
	
	getEl('search_target').src = 'mail/search.php';
	getEl('powerSearchBox').style.display = "block";
	
	
	
}

function checkAttach()
{
	if(getEl('attachBox').getElementsByTagName('INPUT').length > 0 )
		attach('add_attachment', 'add');		
}

function createContact()
{
	url = "contacts/index.php?urlframe=add.php";
	top.frames["wmView"].location.href = url;
}

