// JavaScript Document
var errorbrd = '#ff9900';
var errorbg = '#ffffcc';
var errors = 0;
var errormsg = "";
var activeForm = null;

var phone = "()- 0123456789";
var numb = "0123456789";
var dec = ".01234567890";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";

function restrict(t,v){
var w = "";
	for (i=0; i < t.value.length; i++) {
		x = t.value.charAt(i);
		if (v.indexOf(x,0) != -1)
			w += x;
	}
	t.value = w;
}


function resetField(f){
	f.style.borderColor = '#cccccc';
	f.style.backgroundColor = '#ffffff';
	f.style.borderWidth = '1';
	f.onfocus = null;
	resetErrorMsg();
}

function setOptions(SI,ops,mode){
	switch(mode){
		case 'value':
			for(i=0; i<ops.length; i++){
				if(ops[i].value == SI) return i;
			}
		break;
	}
}

function SwapOptions(itm,arr,id,SI,addBlank){
	var ops = document.getElementById(itm);
	if(id != null){
		var array = eval(arr.toUpperCase());
		var values = array[id];
		var l = ops.options.length;
		for (m=ops.length-1;m>0;m--) ops.options[m]=null;	
		l = 0;
		if(addBlank){
			ops.options[0] = new Option('Select sub-category', '');
			l = 1;
		}
		for(i=0; i<values.length; i++){
			ops.options[l] = new Option(values[i][1], values[i][0]);
			l++;
		}
		if(SI){
			ops.selectedIndex =setOptions(SI, ops,'value');
		}
		ops.style.display = 'block';
		//ops.selectedIndex = 0;
	}
}

function resetErrorMsg(){
	var name = activeForm.name;
	document.getElementById(name+'_errormsg').innerHTML = '';
}

function hlField(f){
	f.style.borderColor = errorbrd;
	f.style.backgroundColor = errorbg;
	//f.style.borderWidth = 2;
	f.onfocus = function(){resetField(this)};
}

function addError(msg){
	var toadd = (errors) ? '<br/>'+msg : msg;
	errormsg += toadd;
	errors++;	
	return;
}

function validEmailAddress(a){
	var addresses = a.split(","); 
	var doAllPass; 
	for (var i = 0; i < addresses.length; i++) {
		var a1 = addresses[i]; 
		var domainString=a1.substring(a1.indexOf("@"), a1.length); 
		if( a1.indexOf("@")>0 && a1.indexOf(".")< a1.length-1 && a1.indexOf(".")> 0 && domainString.indexOf("..") < 0 && domainString.lastIndexOf(".") != (domainString.length - 1) && domainString.lastIndexOf(".>") != (domainString.length - 2)){
			/*return true;*/}	
		else{		
		return false;	
		}
	} 	
	return true;
}

function validateField(field, type){
	switch(type){
		case 'text':
			var tfield = activeForm.elements[field];
			if (tfield.value != "")	{
				return;
			} else {
				hlField(tfield);		
				errormsg = " &raquo; PLEASE FILL IN THE HIGHLIGHTED FIELDS";
				errors++;
			}
		break;
		case 'email':
			var tmp = field.split(':');
			if (tmp[1]){
				if (activeForm.elements[tmp[1]][0].checked){
					var f1 = activeForm.elements[tmp[0]+'1'];
					var f2 = activeForm.elements[tmp[0]+'2'];
					if (f1.value == '' || validEmailAddress(f1.value) == false){
						addError(" &raquo; PLEASE ENTER A VALID EMAIL ADDRESS");	
						hlField(f1);
					} else if (f1.value != f2.value){
						addError('&raquo; YOUR EMAIL ADDRESSES DO NOT MATCH');		
						hlField(f1);	
						hlField(f2);	
					} 
				}
				return;
			}
			var tfield = activeForm.elements[field];
			if (validEmailAddress(tfield.value)) {
				return;
			} else {
				hlField(tfield);	
				addError(" &raquo; PLEASE ENTER A VALID EMAIL ADDRESS");
			}
		break;
		case 'checkgroup':
			var one_checked = false;
			for(i=0;i<activeForm.elements.length;i++){
				if (activeForm.elements[i].name.indexOf(field+'|' != -1 && activeForm.elements[i].type =='checkbox') ){
					if (activeForm.elements[i].checked){
						one_checked = true;
					}
				}
			}
			if (!one_checked){
				hlField(document.getElementById(field+'_div'));
				addError('&raquo; PLEASE SELECT AT LEAST ONE ITEM');
			}
		break;			
		case 'password':
			var tmp = field.split(':');
			var minval = tmp[1];
			var pw1 = activeForm.elements[tmp[0]+'1'];
			var pw2 = activeForm.elements[tmp[0]+'2'];
			if (pw1.value.length < minval){
				addError('&raquo; PASSWORD MUST BE AT LEAST '+minval+' CHARACTERS');		
				hlField(pw1);
				hlField(pw2);	
			} else if (pw1.value != pw2.value){
				addError('&raquo; YOUR PASSWORDS DO NOT MATCH');		
				hlField(pw1);	
				hlField(pw2);	
			} 
			return;
		break;	
		case 'netid':
			var tfield = activeForm.elements[field];
			if (tfield.value == ''){
				addError('&raquo; PLEASE ENTER AN EMAIL ADDRESS');	
				hlField(tfield);	
			} else if (tfield.value.match(/[^A-Za-z\d_]/)){
				addError('&raquo; YOUR NETID APPEARS TO INCLUDE INVALID CHARACTERS');	
				hlField(tfield);	
			}
			return;
		break;
		case 'url':
			var tfield = activeForm.elements[field];
			if (tfield.value == "")	{
				return;
			} else if (tfield.value.indexOf('http://') != -1){
				return;
			} else {
				hlField(tfield);		
				addError('&raquo; PLEASE ENTER A FULL URL (including the http://)');
			}
		break;
		case 'sdate':
			var val = activeForm.elements[field+'_ms'].value;
			//if (val < NOW){
				//document.getElementById(field+'_html').innerHTML = dateinpast;
				//errors++;			
				//errormsg = ' &raquo; PLEASE FIX THE HIGHLIGHTED ERRORS';
			//} else 
			if (val > 0){
				return;
			} else {
				document.getElementById(field+'_html').innerHTML = nosdate;
				errors++;
			} 
		break;
		case 'edate':
			var val = activeForm.elements[field+'_ms'].value;
			var start = activeForm.elements['start_ms'].value;
			if (val != ''){
				if (val < start){
					document.getElementById(field+'_html').innerHTML = enderror;
					errors++;
				}
			}
		break;
		case 'SI':
			//var ops = activeForm.elements[field].options;
			//si = testOptions(ops,val);
			//activeForm.elements[field].options.selectedIndex = si;
			var tfield = activeForm.elements[field];
			var ops = tfield.options;
			var SI = tfield.selectedIndex;
			var val = ops[SI].value;
			if (val == '' || val == 'null'){
				hlField(tfield);		
				errormsg = " &raquo; PLEASE FILL IN THE HIGHLIGHTED FIELDS";
				errors++;
			}
		break;
	}
}			
	

function validateForm(form){
	setActiveForm(form+'_form');
	var guide = eval(form+'_form_validation');
	var fields = guide[0].split('|');
	var ftypes = guide[1].split('|');
	errors = 0;
	for(i=0; i<fields.length; i++){
		validateField(fields[i], ftypes[i]);
	}
	if(errors == 0){
		document.getElementById(form+'_form_errormsg').innerHTML = '';
		var task = guide[2];
		switch(task){
			case 'summary':
				var target = guide[3];
				showSummary(target);
			break;
			case 'submit':
				activeForm.submit();
			break;
		}
	} else {
		document.getElementById(form+'_form_errormsg').innerHTML = errormsg;
		if (guide[4]){
			togglePanes(guide[4]);
		}
	}
}

function setTitle(obj, text){
	document.getElementById(obj+'_title').innerHTML = text;
}

function setSpan(obj, text){
	document.getElementById(obj+'_html').innerHTML = text;
}

function testOptions(ops, targ, chkTxt){
	for (i=0; i<ops.length; i++){
		if(chkTxt){
			if (ops[i].text == targ){
				ops.selectedIndex = i;
				return i;
			}
		}
		else if (ops[i].value == targ){
			ops.selectedIndex = i;
			return i;
		}
	}	
}

function optionValue(sel){
	var SI = sel.selectedIndex;
	var ops = sel.options;
	return(ops[SI].text);
}

function fillField(field, type, val){
	//alert(field+' -- '+val+' --'+type);
	switch(type){
		case 'value':
			activeForm.elements[field].value = val;
		break;
		case 'innerHTML':
			document.getElementById(field).innerHTML = val;
		break;
		case 'SIS':
			var ops = activeForm.elements[field].options;
			testOptions(ops,val);
			activeForm.elements[field+'_cur'].value = val;
		break;
		case 'SI':
			var ops = activeForm.elements[field].options;
			si = testOptions(ops,val);
			activeForm.elements[field].options.selectedIndex = si;
		break;
		case 'SI_txt':
			var ops = activeForm.elements[field].options;
			testOptions(ops,val,true);
			//activeForm.elements[field].options.selectedIndex = si;
		break;
		case 'date':
			var pre = '';
			activeForm.elements[field].value = val;
			if (field == 'end_date'){
				var dateObj = endDate;
				pre = 'end_';
				dateObj._setTime(val);
				if (endDate.date.valueOf() == startDate.date.valueOf()){
					dateObj._clearDate();
					break;
				}
			} else if(field == 'start_date'){
				var dateObj = startDate;
				pre = 'start_';
				dateObj._setTime(val);
			}	
			//alert(dateObj.date);
			var h = dateObj.date.getHours();
			var m = dateObj.date.getMinutes();
			var AMPM = 0;
			if (h > 12){
				h = h-12;
				AMPM = 1;
			}
			m = Math.floor(m/5);
			var AD = activeForm.elements[pre+'allDay'].checked;
			dateObj.allDay = AD
			var AD_vis = AD ? 'none' : 'block';
			objectVis(pre+'timeselect', AD_vis);				
			activeForm.elements[pre+'hour'].options.selectedIndex = h;
			activeForm.elements[pre+'min'].options.selectedIndex = m;
			testOptions(activeForm.elements[pre+'hour'].options,h);
			testOptions(activeForm.elements[pre+'min'].options,m);
			activeForm.elements[pre+'min'].options.selectedIndex = m;
			dateObj._updateDate();
		break;
		case 'check':
			if (val == '1'){
				activeForm.elements[field].checked = true;
			} else {
				activeForm.elements[field].checked = false;
			}
		break;
	}
}
		
function fillForm(guide_id, values, invert){
	var guide = eval(guide_id);
	var fields = guide[0].split('|');
	var ftypes = guide[1].split('|');
	var hide = guide[2].split('|');
	var show = guide[3].split('|');
	for(v=0; v<values.length; v++){
		fillField(fields[v], ftypes[v], values[v]);
	}
	if (invert){
		for (i=0; i<hide.length; i++){
			if(hide[i] != ''){
				objectVis(hide[i], 'block');
			}
		}
		for (i=0; i<show.length; i++){
			if(show[i] != ''){
				objectVis(show[i], 'none');
			}
		}
	} else {
		for (i=0; i<hide.length; i++){
			if(hide[i] != ''){
				objectVis(hide[i], 'none');
			}
		}
		for (i=0; i<show.length; i++){
			if(show[i] != ''){
				objectVis(show[i], 'block');
			}
		}
	}
}

function setnew(type, option){
	setActiveForm(type+'_form');
	var title = ''
	switch (type){
		case 'officer':
			var values = new Array('','','','','', 'new')
		break;
		case 'resource':
			var values = new Array('','','','','','', 'new')
		break;
		case 'event':
		if (!option) {
			option = Math.floor(new Date().valueOf()/60000);
			var mod = option%5;
			option = (option-mod+5)*60;
		}
		var title = ' Event'
		var values = new Array('','','','','',1,1,option,option,'','','','','new')
		break;
		case 'announcement':
			var values = new Array('','','','','','','','new')
		break;
	}
	setTitle(type+'_form', 'Add New'+title);
	fillForm(type+'_form_guide', values, true);
}

function submitForm(form){
	setActiveForm(form+'_form');
	activeForm.submit();
}

function edit(type, id){
	setActiveForm(type+'_form');
	setTitle(type+'_form', 'Edit');
	switch (type){
		case 'officer':
			var values = OFFICERS[id];
			values.push('update');
		break;
		case 'resource':
			var values = RESOURCES[id];
			values.push('update');
		break;
		case 'announcement':
			var values = ANNOUNCEMENTS[id];
			values.push('update');
		break;
		case 'event':
			var values = EVENTS[id];
			values.push('update');
		break;
	}
	fillForm(type+'_form_guide', values);
}

function setActiveForm(frm){
	activeForm = document.forms[frm];
}
function summaryField(type,field,title){
	var txt;
	switch(type){
		case 'titletd':
			txt = activeForm.elements[field].value;
			return(html_titletd(title, txt));
			break;
		case 'check':
			if (activeForm.elements[field].checked){
				return(html_td(title));
			} else {
				return('');
			}
			break;
		case 'td':
			txt = activeForm.elements[field].value;
			return(html_td(txt));
			break;
		case 'sdate':
		case 'edate':
			txt = document.getElementById(field).innerHTML;
			return(html_titletd(title, txt));
			break;
		case 'list':
			return(html_itemlist(title, TextList(field)));
			break;
	}
}
		
		
function showSummary(){
	var html = '';
	html += html_tablestart('100%', 0, 1, 'standard');
	html += summaryField('titletd', 'title', 'Event:');
	var cat = optionValue(activeForm.elements['category_id'])
	html += html_titletd('Category:', cat);
	html += summaryField('sdate', 'start_html', 'Start Date:');
	html += summaryField('edate', 'end_html', 'End Date:');
	html += summaryField('titletd', 'location', 'Location:');
	html += html_spacer(10,5);
	html += summaryField('td', 'info');
	html += html_spacer(10,5);
	html += summaryField('check', 'is_private', 'event is private');
	html += summaryField('check', 'is_addable', 'event is addable to personal calendars');	
	html += html_spacer(10,5);
	if (!is_group){
		var invites =  TextList('invites_groups');
		if (invites) invites += delim;
		invites +=  TextList('invites_friends');
		if (invites != ''){	
			html += html_itemlist('Current Invitations', invites);
			html += summaryField('list', 'invites_add', 'To Add:');
			html += summaryField('list', 'invites_remove', 'To Remove:');
		} else {
			html += summaryField('list', 'invites_add', 'Invitations:');
		}	
		html += html_spacer(10,5);
		html += summaryField('check', 'restricted', 'event is restricted to invitees only');
		html += summaryField('check', 'restrictions_1', 'invitees can invite additional friends');
	}
	html += html_tableend();
	//when
	document.getElementById('summary_fields').innerHTML = html;
	togglePanes('summary');	
}
