var EUS_PATH = '';

function trim(s) {return s.replace(/^\s+|\s+$/g, '');}

var proceed = 0;
function signBack(){
	proceed = 0
	mooValidateSignup(0)
	toogleElements('signup_div','host_user_div')
}

function validateSignUp(x) {
	var country = document.form_signup.country.options[document.form_signup.country.selectedIndex].value;
	var zip = document.getElementById('zip');
	var zip_err = document.getElementById('zip-err');
	if(zip.value.length > 4){
		var span=document.createElement("label")
		span.setAttribute("id", "zip-err")
		span.setAttribute("class", "error")
		if(country == 'US') {
			var alphaNumericTest = zip.value.test(/^[0-9]{5}$/i);
		}else if(country == 'CA') {
			//var alphaNumericTest = zip.value.test(/^[a-z]{1}[0-9]{1}[a-z]{1}[ ]{1}[0-9]{1}[a-z]{1}[0-9]{1}$/i);  # If you need A0A 0A0[A-Alphabet & 0 - Number] (with space) format of canada postal code  -- uncomment this line
			var alphaNumericTest = zip.value.test(/^[a-z]{1}[0-9]{1}[a-z]{1}[0-9]{1}[a-z]{1}[0-9]{1}$/i); // This validation for A0A0A0 (with no space) format, If you need A0A 0A0 format of canada postal code  -- comment this line
		}else {
			var alphaNumericTest = zip.value.test(/^[a-z0-9]*$/i);
		}
		if(!alphaNumericTest){
			zip.style.border = '1px solid red'
			if(zip_err == undefined){
				span.innerHTML=" Enter a valid zip"
				document.getElementById("zipNodes").insertBefore(span, zip.nextSibling)
				return false;
			}else{
				zip_err.innerHTML = " Enter a valid zip"
				return false;
			}
		}else zip.style.border = '1px solid #7f9db9'
		
	}
	if(!mooValidateSignup(1)) return false;
	proceed = 1;
	if(x){
		mooValidateSignup(0)
		toogleElements('host_user_div','signup_div')
	}
}
function getTelPhone(val){
	var p1 = document.getElementById(val+'1').value;
	var p2 = document.getElementById(val+'2').value;
	var p3 = document.getElementById(val+'3').value;
	return p1+p2+p3;
}
function mooValidateSignup(x){
	
	if(!proceed){
		document.getElementById('valPhone').value = getTelPhone('host_phone');
		var country = document.form_signup.country.options[document.form_signup.country.selectedIndex].value;
		if(country == 'US' || country == 'CA' || country=='') {	var fields = {
			name:'Required [5-65]',
			address1:'Required',
			country:'Required',
			state:'Required',
			city:'Required',
			zip:'Required [5]',
			valPhone:'Required [10]',
			time_zone_id:'Required'
			};
		}else {
			var fields = {
				name:'Required [5-65]',
				address1:'Required',
				country:'Required',
				inter_state:'Required',
				city:'Required',
				zip:'Required [5]',
				valPhone:'Required [10]',
				time_zone_id:'Required'
			};
		}
	}else{
		document.getElementById('valUserPhone').value = getTelPhone('phone_phone');
		document.getElementById('valCellPhone').value = getTelPhone('cell_phone_phone');
		var fields = {
			first_name:'Required',
			last_name:'Required',
			email:'Required Email',
			valUserPhone:'Custom [10]',
			valCellPhone:'Custom [10]',
			new_username:'Required Code [5-20]',
			new_password:'Required [4-26]',
			password_v:'Required Identical [4-26]'
		};
	}
	var val = new validate('form_signup', fields);
	if(x) return val.onButtonClick();
}

function validateHostUser(x) {
	switch(x){
		case 1:
			if(!mooValidateSignup(1)) return false;
			document.form_signup.submit();
			break;
		case 2:
			if(!mooValidateUsers(1)) return false;
			document.form_user.submit();
			break;
		case 3:
			if(!mooValidateUserInfo(1)) return false;
			document.form_user.submit();
			break;
	}
}

function mooValidateUsers(x){
	document.getElementById('valUserPhone').value = getTelPhone('phone_phone');
	document.getElementById('valCellPhone').value = getTelPhone('cell_phone_phone');
	var fields = {
			first_name:'Required',
			last_name:'Required',
			email:'Required Email',
			valUserPhone:'Custom [10]',
			valCellPhone:'Custom [10]',
			new_username:'Required Code [5-20]',
			new_password:'Required [4-20]',
			password_v:'Required Identical [4-20]'
		};
	var val = new validate('form_user', fields);
	if(x){
		var is_permission = document.getElementById('permission').value;
		if(is_permission !=0 ) if(accessMooValidate()) return false;
		return val.onButtonClick();
	}
}

function mooValidateUserInfo(x){
	document.getElementById('valUserPhone').value = getTelPhone('phone_phone');
	document.getElementById('valCellPhone').value = getTelPhone('cell_phone_phone');
	var fields = {
			first_name:'Required',
			last_name:'Required',
			email:'Required Email',
			valUserPhone:'Custom [10]',
			valCellPhone:'Custom [10]',
			new_password:'Required [4-20]',
			password_v:'Required Identical [4-20]'
		};
	var val = new validate('form_user', fields);
	if(x){
		var is_permission = document.getElementById('permission').value;
		if(is_permission !=0 ) if(accessMooValidate()) return false;
		return val.onButtonClick();
	}
}

function accessMooValidate(){
	var myobj = document.getElementsByName('permission_id[]');
	var error = document.getElementById('access-error');
	error.innerHTML = '';
	if(!myobj[0].checked && !myobj[1].checked && !myobj[2].checked){
		error.innerHTML = 'Select atleast one user access';
		return true;
	}
	//document.getElementById(hid) = isSelected++
}

/* Ajax Username validation */
function checkDataExist(obj,msg){
	var type = obj.id;
	var val = obj.value;
	if(type=='email'){
		/*var emailTest = val.test(/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i);
		if(!emailTest) return false;*/
	}else{
		var alphaNumericTest = (val.length > 4)?val.test(/^[a-z0-9._]+$/i):false;
		if(!alphaNumericTest) return false;
	}	
	var msgObj = document.getElementById(msg);
	var request = new Request({
		url: EUS_PATH+'/account/?a=signup&for=is_exist',
		method: 'post',
		data:type+'='+val,
		onRequest: function() {
			//msgObj.style.display = "block";
			//msgObj.innerHTML = '<img src="../includes/smarty/templates/images/spinner.gif" />';
		},
		onComplete: function(response) {
			if(response == 1){
				msgObj.innerHTML = '';
				msgObj.style.display = "none";
				obj.removeClass('errorElement');
			}else{
				msgObj.style.display = "block";
				obj.addClass('errorElement');
				msgObj.innerHTML = 'Username already taken. Please choose another';
			}
			return false;
		}
	}).send();
	
}

function mooValidateBilling(x){
	var fields = {
			b_name:'Required',
			b_adr1:'Required',
			b_city:'Required',
			b_state:'Required',
			b_zip:'Required'
	};
	var val = new validate('xbox-window', fields);
	if(x) return val.onButtonClick();
}

function processBilling(hbi){
	if(!mooValidateBilling(1)) return false;
	b_name = document.getElementById('b_name');
	b_adr1 = document.getElementById('b_adr1');
	b_adr2 = document.getElementById('b_adr2');
	b_city = document.getElementById('b_city');
	b_state = document.getElementById('b_state');
	b_country = document.getElementById('b_country');
	b_zip = document.getElementById('b_zip');
	b_error = document.getElementById('error');
	if(hbi){
		var para = 'edit';
		var post_data = 'hbi='+hbi+'&';
	}else{
		var para = 'add';
		var post_data = '';
	}
	var req = new Request({
		method: 'post',
		url:'?a='+para+'_bill&ajaxcall=1',
		data:post_data+'bill_name='+b_name.value+'&bill_adr1='+b_adr1.value+'&bill_adr2='+b_adr2.value+'&bill_city='+b_city.value+'&bill_state='+b_state.value+'&bill_country='+b_country.value+'&bill_zip='+b_zip.value,
		onRequest: function(){b_error.innerHTML = 'processing......';},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			var msg = response.split('|');
			if(msg[0] == 'success'){
				b_error.innerHTML = 'Updated Successfully';
				window.location.reload(true);
			}else
				b_error.innerHTML = msg[1];
		},
		onCancel: function(){ alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function mooValidateForm(x){
	var fields = {ad_title: 'Required'};
	var val = new validate('c-list-2', fields);
	if(x) return val.onButtonClick();
}

function disableAccessCheckBox(){
	var x = document.getElementsByName('permission_id[]');
	if(document.form_user.primary_contact.checked){
		for(i=0;i<x.length;i++){
			document.getElementById(x[i].id).checked="checked";
			document.getElementById(x[i].id).disabled="disabled";
		}
	}else{
		for(i=0;i<x.length;i++){
			document.getElementById(x[i].id).checked="";
			document.getElementById(x[i].id).disabled="";
			if(i == (x.length - 1)) {
				document.getElementById(x[i].id).checked="checked";
				document.getElementById(x[i].id).disabled="disabled";
			}
		}
	}
}

function rmUser(obj,uid){
	if(confirm('Are you sure want to delete this user?')){
		var req = new Request({
			method: 'post',
			url:'?a=dhu&ajaxcall=1',
			data:'hui='+uid,
			onRequest: function(){
				//obj.innerHTML = 'processing......'
				mkMessageBox('processing......',1);
			},
			onComplete: function(response) {
				if(!chkResponse(response)) return false;
				//document.getElementById('s-msg').innerHTML = 'Successfully Deleted';
				//mkMessageBox('User deleted sucessfully');
				mkMessageBox('');
				var i=obj.parentNode.parentNode.rowIndex;
				document.getElementById('users-table').deleteRow(i);
			},
			onCancel: function(){ alert('Cannot connect to Link Server'); },
			onFailure: function(xhr){ /*alert('Internet connection error');*/ }
		}).send();
	}
}

//This function need to be removed after changing Account and Rounting number functionality
function getDisplayBillDetails(flag){
	
	if(flag == 'bill_address') {
		document.getElementById('add-bill-form').style.display = "block";
		document.getElementById('bill_add_list_div').style.display = "none";
		document.getElementById('bill_acc_form_div').style.display = "none";
		//document.getElementById('bill_add_form_div').style.display = "block";
		document.getElementById('add_address_div').style.display = "none";
	} else if(flag == 'bill_info') {
		document.getElementById('add-bill-form').style.display = "block";
		document.getElementById('bill_add_list_div').style.display = "block";
		document.getElementById('bill_acc_form_div').style.display = "none";
		//document.getElementById('bill_add_form_div').style.display = "none";
		document.getElementById('add_address_div').style.display = "block";	
	} else {
		document.getElementById('add-bill-form').style.display = "none";
		document.getElementById('bill_add_list_div').style.display = "block";
		document.getElementById('bill_acc_form_div').style.display = "block";
		//document.getElementById('bill_add_form_div').style.display = "none";
		document.getElementById('add_address_div').style.display = "none";
	}
}
/**************************************************************/
/*************** Reusable and Dynamic functions starts here***************/
function getTimeStamp(){
	var d = new Date();
	return d.getTime();
}

function isNumberKey(evt){	
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
	return true;
}

function isDollarFormat(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) return false;
	return true;
}

function loadForm(links){document.location.href=links;}

function autoTab(current, to){
	if (current.getAttribute && current.value.length == current.getAttribute("maxlength"))
		to.focus();
}

toogleElements = function(show,hide){
	document.getElementById(show).style.display = 'block';
	document.getElementById(hide).style.display = 'none';
}

switchElements = function(element_id,input_id,input_value){
	if(parseInt(input_value)){
		document.getElementById(element_id).style.display = "none";
		document.getElementById(input_id).value=0;
	}else{
		document.getElementById(element_id).style.display = "block";
		document.getElementById(input_id).value=1;
	}
}

hideElements=function(id,val){
	document.getElementById(id).style.display = !parseInt(val)?'none':'block';
}

hideMsgElement = function(id){
	var myObj = document.getElementById(id);
	myObj.style.display = 'none';
	myObj.innerHTML = '';
}
	
var div_count = 0;
function addElements(id){
	var myobj = document.getElementById(id);
	var get_div_count = myobj.getElementsByTagName('div').length;
	if(div_count > get_div_count)
		div_count++;
	else
		div_count = get_div_count+1;
	var new_elements = document.createElement("div");
	new_elements.id = id+div_count;
	myobj.appendChild(new_elements);
	switch(id){
		case 'contact-list':
			/*new_elements.className = 'div_pos1';*/
			new_elements.innerHTML = '<table border="0" cellpadding="0" cellspacing="5" align="left" class="clear-div"><tr><td colspan="2" class="general_hd">Address </td></tr><tr><td align="left" width="100">Contact Name:</td><td align="left"><input name="contact['+div_count+'][name]" id="contact_name_'+div_count+'" value="" class="coninp_width itext" maxlength="40" type="text"></td></tr><tr><td align="left">Contact Phone:</td><td align="left"><input name="contact['+div_count+'][phone1]" id="contact_phone1_'+div_count+'" size="3" maxlength="3" value="" onkeyup="autoTab(this, document.getElementById(\'contact_phone2_'+div_count+'\'))" onkeypress="return isNumberKey(event);" type="text" class="itext"/> <input name="contact['+div_count+'][phone2]" id="contact_phone2_'+div_count+'" size="3" maxlength="3" value="" onkeyup="autoTab(this, document.getElementById(\'contact_phone3_'+div_count+'\'))" onkeypress="return isNumberKey(event);" type="text" class="itext"/> <input name="contact['+div_count+'][phone3]" id="contact_phone3_'+div_count+'" size="4" maxlength="4" value="" onkeypress="return isNumberKey(event);" type="text" class="itext"/></td></tr><tr><td align="left">Contact E-mail:</td><td align="left"><input name="contact['+div_count+'][email]"  value="" type="text" maxlength="100" class="coninp_width itext" ></td></tr></table><span id="con-rem-'+div_count+'" class="pointer-div spl_txt mar-div  clear-div">Remove</span>';
				document.getElementById('con-rem-'+div_count).onclick=function(){remove(this.id)}
			break;
		case 'date-list':
			var data_array = div_count - 1;
			new_elements.innerHTML = '<strong>The next date we will meet will be</strong>';
			new_elements.innerHTML += '<br /> When will this event begin?<br />';
			new_elements.innerHTML += '<span class="error">*</span>Date:&nbsp;<input name="datetime['+data_array+'][start_date]" readonly="readonly" id="date_start_'+data_array+'" value="" onfocus="showCalendar(\'\',\'date_start_'+data_array+'\',\'date_end_'+data_array+'\',\'\',\'date_start_'+data_array+'\',0,0,1)" size="10" maxlength="10" type="text" class="idisabled"/><a href="javascript:showCalendar(\'\',\'date_start_'+data_array+'\',\'date_end_'+data_array+'\',\'\',\'date_start_'+data_array+'\',0,0,1)"> <img src="../includes/smarty/templates/images/calendar_icon.gif" alt="calendar" border="0" width="20" height="20" align="top" /></a> &nbsp;Time:&nbsp;';
			new_elements.innerHTML += '<select name="datetime['+data_array+'][start_hour]" id="time_startHour'+data_array+'" class="time-sel iselect"><option label="" value="" selected="selected"></option>';				
			new_elements.innerHTML += '</select>';
			new_elements.innerHTML += ' <select name="datetime['+data_array+'][start_minute]" id="time_startMinute'+data_array+'" class="time-sel iselect"><option label="" value="" selected="selected"></option>';				
			new_elements.innerHTML += '</select>';
			new_elements.innerHTML += ' <select name="datetime['+data_array+'][start_meridian]" class="am-sel iselect"><option label="" value="" selected="selected"></option><option label="AM" value="am">AM</option><option label="PM" value="pm">PM</option></select><br />When will this event end? <br />';
			
			new_elements.innerHTML += '<span class="error">*</span>Date:&nbsp;<input name="datetime['+data_array+'][end_date]" readonly="readonly" id="date_end_'+data_array+'" value="" onfocus="showCalendar(\'\',\'date_end_'+data_array+'\',\'date_end_'+data_array+'\',\'\',\'date_end_'+data_array+'\',0,0,1)" size="10" maxlength="10" type="text" class="idisabled"/><a href="javascript:showCalendar(\'\',\'date_end_'+data_array+'\',\'date_end_'+data_array+'\',\'\',\'date_end_'+data_array+'\',0,0,1)"> <img src="../includes/smarty/templates/images/calendar_icon.gif" alt="calendar" border="0" width="20" height="20" align="top" /></a> &nbsp;Time:&nbsp;';
			new_elements.innerHTML += '<select name="datetime['+data_array+'][end_hour]" id="time_endHour'+data_array+'" class="time-sel iselect"><option label="" value="" selected="selected"></option>';
			new_elements.innerHTML += '</select>';
			new_elements.innerHTML += ' <select name="datetime['+data_array+'][end_minute]" id="time_endMinute'+data_array+'" class="time-sel iselect"><option label="" value="" selected="selected"></option>';
			new_elements.innerHTML += '</select>';
			new_elements.innerHTML += ' <select name="datetime['+data_array+'][end_meridian]" class="am-sel iselect"><option label="" value="" selected="selected"></option><option label="AM" value="am">AM</option><option label="PM" value="pm">PM</option></select> <span id="new-date-time-'+data_array+'" class="pointer-div spl_txt">Remove</span><br />';
			document.getElementById('new-date-time-'+data_array).onclick=function(){
				remove(this.id)
			}
			document.getElementById('date_option').style.display = 'none';
			document.getElementById('event_date_type1').checked = true;
			for(var i=0; i<=59; i++){
				if(i > 0 && i<=12){
					addOptions('time_startHour'+data_array, i)
					addOptions('time_endHour'+data_array, i)
				}
				addOptions('time_startMinute'+data_array, i)
				addOptions('time_endMinute'+data_array, i)
			}	
			break;
		case 'link-list':
			new_elements.innerHTML = '<strong>Url :</strong><br /><span class="pr-link-x">Name of Link:<input name="pr_link['+div_count+'][name]" id="name_'+div_count+'" value="" type="text" size="34"  maxlength="50" /></span><br />';
			new_elements.innerHTML +=  'Web Address:<input name="pr_link['+div_count+'][url]" id="url_'+div_count+'" value="" type="text" size="34" /> <span id="re-pr-'+div_count+'" class="pointer-div spl_txt">Remove</span><br /><span class="pr-link-ex">(http://www.example.com)</span><br /><br />';
			document.getElementById('re-pr-'+div_count).onclick = function(){
				remove(this.id);
			}
			break;
		default:
	}
}

addOptions = function(id, value, option_type, selected){
	var data = new String(value);
	var optn = document.createElement("OPTION");
	if(option_type == 'payment_plan') {
		optn.label = optn.text = data + '%';
		optn.value = data;
		if (selected == true) optn.selected = true;
	}
	else {
		optn.label = optn.value = optn.text = (data.length > 1) ? data : '0' + data;
	}
	document.getElementById(id).options.add(optn);
}

moreElements = function(id, how_many){
	for (var i = 0; i < how_many; i++){addElements(id);}
}

function windowOpen(url,window_name,hgt,wth){
	window_name = window.open(url,window_name,"status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height="+hgt+",width="+wth);
	//window_name.moveTo(250,250);
	window_name.focus();
}
var popUp;
function popUpOpen(url,name,w,h){
	if(popUp==undefined){
		//do something
	}else{
		popUp.close();
	}
	popUp = window.open(url,name,"status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height="+h+",width="+w);
	popUp.focus();
}

// check/uncheck all checkboxes	#parameters - (form-id, 0/1)
function checkAllBoxes(form,checked){
	var formObj = document.getElementById(form);
	var cnt = formObj.elements.length;
	for(i=0; i<cnt; i++){
		var el = formObj.elements[i];
		if(el.type=="checkbox") el.checked=checked;
	}
}

//Switch css for mouseover and mousemove i.e roll over effect (used in visual option, etc)
function setClasss(obj,css){obj.className = css;}

//Reset SWFUpload tool
function sendBackSWF(){
	document.getElementById('load-swf-contents').innerHTML = '<div id="fsUploadProgress"></div><span id="spanButtonPlaceHolder"></span>';
	toogleElements('show-list','import-csv');
}

/* XBox (Light Box) Created By Muthu Kumaran */
function resizeXBox(w,h){
	var size = {x:w,y:h};
	var box = document.getSize(), scroll = document.getScroll(); //using mootools functions
	var to = {
		width: size.x,
		height: size.y,
		left: (scroll.x + (box.x - size.x - 20) / 2).toInt(),
		top: (scroll.y + (box.y - size.y - 20) / 2).toInt()
	};
	return to;
}

function preloadXBox(w,h){

	//document.html.style.overflow='hidden'; //fix for IE
	//document.body.style.overflow='hidden';
	var newPos = resizeXBox(w,h);
	var size = document.getScrollSize();
	
	var overlay = document.getElementById('xbox-overlay').style;
	var xboxwin = document.getElementById('xbox-window').style;

	overlay.zIndex='65555'
	overlay.filter = 'alpha(opacity=70)';
	overlay.visibility = 'visible';
	overlay.display = 'block';
	overlay.width = size.x+'px';
	overlay.zoom = '1';
	overlay.height = size.y+'px';
	overlay.opacity = '0.7';
	xboxwin.zIndex='65557';
	xboxwin.left = newPos.left+'px';
	xboxwin.top = newPos.top+'px';
	xboxwin.width = newPos.width+'px';
	xboxwin.display = 'block';
	
	document.getElementById('xbox-window').innerHTML='Loading...<div align="left" class="xbox-loading"></div>';
	var select_box = document.getElementsByTagName('select');
	var cnt = select_box.length;
	for(i=0;i<cnt;i++){
		select_box[i].style.visibility = 'hidden';
	}
	if(Browser.Engine.gecko){
		var embed_tag = document.getElementsByTagName('object');
		var embed_cnt = embed_tag.length;
		for(i=0;i<embed_cnt;i++){
			embed_tag[i].style.visibility = 'hidden';
		}
	}
}

function closeXBoxPopUp(div_id){
	if(div_id){
		var div_show = document.getElementById(div_id);
		if(div_show.style.display=="none") div_show.style.display = "block";
	}
	try{xc_cm(0);}catch(e){};
	var overlay = document.getElementById('xbox-overlay').style;
	var xboxwin = document.getElementById('xbox-window').style;
	overlay.zIndex = overlay.filter = overlay.visibility = overlay.width = overlay.zoom = overlay.height = overlay.opacity = '';
	xboxwin.zIndex = xboxwin.left = xboxwin.top = xboxwin.width = xboxwin.height = '';
	overlay.display = xboxwin.display = 'none';
	document.getElementById('xbox-window').innerHTML='Loading...<div align="left" class="xbox-loading"></div>';
	var select_box = document.getElementsByTagName('select');
	var cnt = select_box.length;
	for(i=0;i<cnt;i++){
		select_box[i].style.visibility = 'visible';
	}
	if(Browser.Engine.gecko){
		var embed_tag = document.getElementsByTagName('object');
		var embed_cnt = embed_tag.length;
		for(i=0;i<embed_cnt;i++){
			embed_tag[i].style.visibility = 'visible';
		}
	}
	mkMessageBox('');
}
/* End of XBox */

/* Use this function to load Xbox popup */
function loadXboxWindow(url,w,h,anything,div_id){
	if(div_id){
		var div_hide = document.getElementById(div_id);
		if(div_hide.style.display=="block") div_hide.style.display="none";
	}
	var req = new Request({
		method:'post',
		url:url+'&ajaxcall=1',
		onRequest:function () {
			mkMessageBox('Loading...',1)
			preloadXBox(w,h)
		},
		onComplete: function(response){
			if(!chkResponse(response)) return false;
			mkMessageBox('')
			var data = response.split('|')
			document.getElementById('xbox-window').innerHTML=response;
			switch(anything){
				case 'terms':
					var xboxwin = document.getElementById('xbox-window').style;
					xboxwin.height='400px';
					xboxwin.overflow='auto';
					break;
				case 'reorder':
					customSortable();
					break;
				case 'invite':
					initializeTinyMceEditor();
					break;
				case 'invite_cust':
					initializeTinyMceEditorFull();
					break;
				case 'event_schedule':
					var xboxwin = document.getElementById('xbox-window').style;
					xboxwin.height='500px';
					xboxwin.overflow='auto';
					break;
			}
		},
		onCancel: function(){ alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function loadXboxInFrame(url,w,h,id){
	mkMessageBox('Loading...',1)
	var content='<div id="xbox-x" style="float:right; cursor:pointer" onclick="closeXBoxPopUp();"><img src="../includes/smarty/templates/images/close.gif" alt="X" /></div><iframe style="overflow-x:hidden;" id="'+id+'-frame" src="'+url+'" width="'+w+'" height="'+h+'" frameborder="0"><p>Your browser does not support iframes.</p></iframe>';
	loadXboxStatic(w,h,content);
}

function loadXboxStatic(w,h,content,div_id){//non-ajax usability
	if(div_id){
		var div_hide = document.getElementById(div_id);
		if(div_hide.style.display=="block") div_hide.style.display="none";
	}
	preloadXBox(w,h);
	document.getElementById('xbox-window').innerHTML=content;
}

function loadXboxFromElement(w,h,id,anything){//non-ajax usability
	preloadXBox(w,h);
	switch(anything){
		case 'event_schedule':
			var xboxwin = document.getElementById('xbox-window').style;
			xboxwin.height='250px';
			xboxwin.overflow='auto';
			break;
	}
	document.getElementById('xbox-window').innerHTML=document.getElementById(id).innerHTML;
}

function mkMessageBox(txt,stay){
	var msgbox = document.getElementById('top-center-div');
	msgbox.innerHTML = txt;
	msgbox.style.visibility = 'visible';
	msgbox.style.opacity=1;
	if(txt == ''){
		//msgbox.innerHTML = 'Loaded';
		msgboxFx.cancel()
		msgbox.style.opacity=0;
		msgbox.style.visibility = 'hidden';
		//msgboxFx.start.pass([0,0], msgboxFx).delay(1000);
		return false;
	}else{
		msgbox.style.marginLeft = "-" + parseInt(msgbox.offsetWidth / 2) + "px";
		//msgbox.style.marginTop = "-" + parseInt(msgbox.offsetHeight / 2) + "px";
		msgboxFx.start.pass([0,1], msgboxFx).delay(0);
		if(!stay) msgboxFx.start.pass([1,0], msgboxFx).delay(4000);
	}
}

function chkResponse(r){
	switch(r){
		case 'expire':
			closeXBoxPopUp();
			mkMessageBox('Session expired. <span onclick="window.location.reload(true);" class="spl_txt pointer-div">Click here to re-login</span>',1);
			return false;
			break;
		case undefined:
			closeXBoxPopUp();
			mkMessageBox('Unable to reach UEvent. Please check your internet connection. <span id="countdown"></span>',1);
			var el = document.getElementById('countdown');
			el.innerHTML = 'Connecting in 10s...';
			var Site = { counter: 10 };
			var addCount = function(){  
				this.counter--;
				if(this.counter<=0){
					$clear(set_timer)
					el.innerHTML = 'Retrying now...'
					is_conn_dead = 1;
					chkConn();
				}else{
					el.innerHTML = 'Connecting in ' + this.counter + 's...';
				}
			};
			var set_timer = addCount.periodical(1000, Site);
			return false;
			break;
	}
	return true;
}
//For confirm actions
function deleteRecord(url,msg){
	var msg = (msg == '' || msg == undefined)?'Are you sure want to delete?':msg;
	if(confirm(msg)) loadForm(url); else return false;
}
//on screen preview while typing
function txtAreaPreview(from,to) {
	document.getElementById(to).innerHTML = document.getElementById(from).value;
}

//To remove parent tag elements
function remove(id){
	var obj = document.getElementById(id);
	var list = obj.parentNode;
 	if(list.parentNode.id == 'date-list') {
		var myobj = list.parentNode;
		var get_div_count = myobj.getElementsByTagName('div').length;
		if(get_div_count == 2) {
			document.getElementById('date_option').style.display = 'block';
			div_repeat = document.getElementById('div-event-repeat'); 
			if(div_repeat) document.getElementById('div-event-repeat').style.display = 'block'; 
		}
	}
	list.parentNode.removeChild(list);
}

//To show status of message
function loadingProgressMsg(id,msg){
	var prg = document.getElementById(id);
	prg.innerHTML = msg;
	prg.style.display = 'block';
}

function detectFlashVersion(){try{try{var a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");try{a.AllowScriptAccess="always"}catch(b){return"6,0,0"}}catch(c){}return(new ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version").replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}catch(d){try{if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)return(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}catch(e){}}return"0,0,0"};

function chkFlashVersion(x,txt){
	x = (!x)?9:x;txt = txt?txt:'';
	v = detectFlashVersion().split(',').shift();
	if(!v || v < x){
		document.getElementById('load-swf-contents').innerHTML = '<div class="no-plugins">Flash player is required to '+txt+'upload files. Click here to download the latest version <a href="http://get.adobe.com/flashplayer/" target="blank">http://get.adobe.com/flashplayer/</a></div>';
		return false;
	}else return true;
}

function initialMooToolTips(){
/* var Tip = new Tips('.reg-tips',{fixed: false}); */
	tooltip.init('reg-tips');
}


function initializeDragContainer(obj){ 
	var container = $(obj.container);
	var handle = $(obj.handle)
	var block = $(obj.block);
	if(block != undefined){
		var myMove = new Drag.Move(block, {
			handle: handle,
			container: container,
			grid: false, 
			preventDefault: true/*,
			onSnap: function(){ //while dragging } */
		});
	}
}

function initializeTinyMceEditor(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		plugins : "paste,spellchecker",
		editor_deselector : "mceNoEditor",
		strict_loading_mode: tinymce.isWebKit, //fix for safari and chrome for breaking html tags
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,undo,redo,cleanup,|,bullist,numlist,|,spellchecker",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "bottom",
		setup : function(ed) {
			if(ed.id == 'sender_message'){
				ed.onKeyUp.add(function(ed, e) { 
					document.getElementById('onscr_opt_message').innerHTML = tinyMCE.get(ed.id).getContent(); 
				});
				ed.onClick.add(function(ed, e) { 
					document.getElementById('onscr_opt_message').innerHTML = tinyMCE.get(ed.id).getContent(); 
				});
			}
		}

	});
}

function initializeTinyMceEditorFull(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		editor_selector : "mceAdvance",
		convert_urls : false,//fix for url issue
		plugins : "safari,spellchecker,style,table,inlinepopups,preview,searchreplace,paste,directionality,fullscreen,images",
		strict_loading_mode: tinymce.isWebKit, //fix for safari and chrome for breaking html tags
		theme_advanced_buttons1 : "fullscreen,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor,styleprops",
		theme_advanced_buttons2 : "pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,undo,redo,|,link,unlink,anchor,image,images,|,spellchecker,hr,removeformat",
		theme_advanced_buttons3 : "tablecontrols,|,visualaid,charmap,|,cleanup,code,preview",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "external",//top
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		setup : function(ed) {
		if(ed.id == 'instruction_message'){
			ed.onKeyPress.add(function(ed, e) {
				document.getElementsByName('instruction_message_type')[1].checked = "checked"
			});
		}
		if(ed.id == 'event_reminder_email'){
			ed.onKeyPress.add(function(ed, e) {
				document.getElementsByName('event_reminder_email_type')[1].checked = "checked"
			});
		}
		if(ed.id == 'description'){
				ed.onInit.add(function(ed, e){
					obj = document.getElementById('invt_description');
					if(obj!=null)tinyMCE.get('description').setContent(obj.innerHTML, {format : 'raw'});
				});
			}
		}
	});
}

function initializeTinyMceEditorSimpleBox(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		editor_selector : "mceSimpleBox",
		plugins : "safari,maxchars,inlinepopups",
		strict_loading_mode: tinymce.isWebKit, //fix for safari and chrome for breaking html tags
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor,|,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "external",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : false
	});
}

function initializeTinyMceEditorEventFull(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		editor_selector : "mceAdvance",
		plugins : "safari,spellchecker,style,table,inlinepopups,preview,searchreplace,directionality,fullscreen,images",		
		strict_loading_mode: tinymce.isWebKit, //fix for safari and chrome for breaking html tags
		theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,forecolor,backcolor,|,bullist,numlist,|,outdent,indent,|,ltr,rtl",
		theme_advanced_buttons2 : "undo,redo,|,link,unlink,image,images,|,spellchecker,|,charmap,|,cleanup,code,preview",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",//external
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		setup : function(ed) {
			ed.onKeyUp.add(function(ed, e){
					var title_desc=tinyMCE.get(ed.id).getContent();
					var title_desc_strip_tags=removeHtmlTags(title_desc);
					var title_length=title_desc_strip_tags.length;
					displayed_length=5000-title_length;
					document.getElementById('disp_desc_chrcount').innerHTML=displayed_length;
				});
			ed.onChange.add(function(ed, e){
				var title_desc=tinyMCE.get(ed.id).getContent();
					var title_desc_strip_tags=removeHtmlTags(title_desc);
					var title_length=title_desc_strip_tags.length;
					displayed_length=5000-title_length;
					document.getElementById('disp_desc_chrcount').innerHTML=displayed_length;
			});
		}
	});
}

function removeHtmlTags(input_string){
	 input_string = input_string.replace(/&(lt|gt);/g, function (strMatch, p1){
	return (p1 == "lt")? "<" : ">";
	});
	input_string=input_string.replace(/<\/?[^>]+(>|$)/g, ""); 
	return input_string.replace( /\&nbsp;/g, ' ' );
}

function initializeTinyMceEditorEventSimpleBox(){
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		editor_selector : "mceSimpleBox",
		plugins : "safari,inlinepopups",
		strict_loading_mode: tinymce.isWebKit, //fix for safari and chrome for breaking html tags
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor,|,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "external",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : false,
		setup : function(ed) {
			ed.onKeyUp.add(function(ed, e){
					var title=tinyMCE.get(ed.id).getContent();
					var title_strip_tags=removeHtmlTags(title);
					var title_length=title_strip_tags.length;
					displayed_length=500-title_length;
					document.getElementById('disp_title_chrcount').innerHTML=displayed_length;
				});
			ed.onChange.add(function(ed, e){
					var title=tinyMCE.get(ed.id).getContent();
					var title_strip_tags=removeHtmlTags(title);
					var title_length=title_strip_tags.length;
					displayed_length=500-title_length;
					document.getElementById('disp_title_chrcount').innerHTML=displayed_length;
				});
		}
	});
}

function backButtonOverrideBody(){
	try{
		history.forward();
	}catch(e){}
	//Every quarter-second, try again. The only guaranteed method for Opera, Firefox, and Safari, which don't always call onLoad but *do* resume any timers when returning to a page
	setTimeout("backButtonOverrideBody()", 500);
	/* *** SAFARI FIX -not yet implemented*** */
	//Work around a Safari bug that sometimes produces a blank page
	//setTimeout("backButtonOverrideBody()", 1);
}

function sendMooAjaxReq(O){
	var req = new Request({
			method: 'post',
			url: O.url + '&ajaxcall=1',
			data: O.data,
			onRequest: function(){O.onReq()},
			onComplete: function(response){
				if(!chkResponse(response)) return false;
				O.onComplete(response)
			},
			onCancel: function(){ alert('Cannot connect to Link Server'); },
			onFailure: function(xhr){ /*alert('Internet connection error');*/}
		}).send();
}
//Common function for loading SWFUpload
var swfuObj;
loadImgUpload = function(dataObj) {
	var settings = {
		flash_url : "../includes/SWFUpload/swfupload.swf",
		upload_url: dataObj.url,
		post_params: {"PHPSESSID" : dataObj.sid},
		file_size_limit : "2 MB",
		file_types : "*.JPG;*.GIF;*.PNG",
		file_types_description : "Images",
		file_upload_limit : 0,
		file_queue_limit : 1,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// Button settings
		button_image_url: "../includes/SWFUpload/css/TestImageNoText_65x29.png",
		button_width: "60",
		button_height: "27",
		button_placeholder_id: "spanButtonPlaceHolder",
		button_cursor: SWFUpload.CURSOR.HAND,
		/* button_text: '<span class="theFont">Browse</span>',
		button_text_style: ".theFont { font-size: 14; color: #ffffff; }",
		button_text_left_padding: 10,
		button_text_top_padding: 3, */
		
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete
	};
	swfuObj = new SWFUpload(settings);
};

/*************** Reusable and Dynamic functions ends here ***************/
/************************************************************************/
function displayOption(val){
	if(val == 3){
		document.getElementById('display_eventdate').style.display = 'block';
		if(document.getElementById('chkdate2').checked)
			document.getElementById('event_datefields').style.display = 'block';
		else
			document.getElementById('event_datefields').style.display = 'none';
	}else{
		toogleElements('event_datefields','display_eventdate')
	}
}

function isSuccessCSV(serverData){
	if(serverData) window.location = serverData; else if(!serverData) alert('Upload a proper CSV file');
}

function sendAjaxRequestList(){
	if(!mooValidateForm(1))
		return false;
	var my_title = document.getElementById('ad_title').value;
	var my_desc = document.getElementById('ad_description').value;
	var req = new Request({
		method: 'post',
		url:'?a=create_list&ajaxcall=1',
		data:'title='+my_title+'&desc='+my_desc,
		onRequest: function(){progressMsg()},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			var data = response.split('|')
			if(data[0] == 'success'){
				var row = document.getElementById('table-list').insertRow(0);
				var chkbox=row.insertCell(0);
				chkbox.innerHTML='<input type="checkbox" name="list" value="'+data[1]+'" checked="checked" /> '+my_title+' - 0 Contacts';
				isSelected++;
				chkbox.onclick=function(){setValue(this)}
			}else{
				alert('There was a problem in processing your request. Please try again');
			}
			closeXBoxPopUp();
		},
		onCancel: function(){ alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function progressMsg(){
	document.getElementById('c-list-2').style.display='none';
	loadingProgressMsg('progress','Saving...')
}

//Show calendar in front of Xbox window
function loadXcal(input_id, dest_input_id){
	if(dest_input_id!=undefined) 
		showCalendar('',input_id,dest_input_id,'',input_id,0,0,1);
	else
		showCalendar('',input_id,'','',input_id,0,0,1);
	document.getElementById('xcalender').style.zIndex='75557';
}

function showDefaultMessage(default_value){ 
	tinyMCE.execInstanceCommand('confirmation_email', 'mceSetContent', false, default_value);
}
function showInstructionDefaultMessage(default_value){ 
	tinyMCE.execInstanceCommand('instruction_message', 'mceSetContent', false, default_value);
}
function showDefaultEventReminderMessage(){
	for (i=0;i<document.extras_form.event_reminder_email_type.length;i++){
		if (document.extras_form.event_reminder_email_type[i].checked){
				 event_reminder_email_type = document.extras_form.event_reminder_email_type[i].value;
		}
	}
	var title = document.getElementById('hidden_title').value;
	var contacts = document.getElementById('hidden_contacts').value;
	var date = document.getElementById('hidden_date').value;
	if(document.getElementById('event_remind_type1')){
		if(document.getElementById('event_remind_type1').checked){
			var date = '&lt;&lt;EACH RECURRING DATE&gt;&gt;';
		}else{
			var date = document.getElementById('hidden_date').value;
		}
	}
	if(event_reminder_email_type == 'default'){
		var message = 'This is a reminder that  '+title+' is coming up on  '+date+'. Our records show a registration from you was submitted on &lt;&lt;REGISTRATION DATE&gt;&gt;. If you have any questions, feel free to contact '+contacts+'. <br /><br />'; 
		tinyMCE.execInstanceCommand('event_reminder_email', 'mceSetContent', false, message);
		document.getElementById('hidden_event_reminder_email').value = message;
	}
}
function showEventReport(report_type, event_id, sort, sort_order) {
	//var report_window = window.open ('?a=report&t=1{if $smarty.get.eid}&eid={$smarty.get.eid}{/if}&sort_key=reg.regt_date&order=DESC', 'mywindow', 'menubar=1, resizable=1, scrollbars=1, width=800,height=700');report_window.focus();
	var report_window = window.open ('?a=report&t=' + report_type +'&eid=' + event_id + '&sort_key=reg.regt_date&order=DESC', 'event_report', 'menubar=1, resizable=1, scrollbars=1, width=800,height=700');
	report_window.focus();
}
function reloadParentWindow(){
	if (window.opener != null && !window.opener.closed) window.opener.location.reload();
}
function validateCreateRefund() {
	if (isNaN(document.create_refund.refund_amount.value) || document.create_refund.refund_amount.value == 0) {
		alert('Please enter the valid Amount');
		document.create_refund.refund_amount.focus();
		return false;
	}
	return true;
}

function getHostList(host_name, load_type){
	if(load_type) load_type = '&load_type='+load_type;
	else load_type='';
	var req = new Request({
		method: 'get',
		url:'?a=ghl&ajaxcall=1'+load_type,
		data:'rng='+document.getElementById('hosts_range').value,
		onRequest: function(){},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			document.getElementById('div_host_list').innerHTML = response;
			document.getElementById('hosts_name').value=host_name;
		},
		onCancel: function(){ alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function getRegistrantDetails(){document.getElementById('registrant_details').style.display = "block";}

function validateResendInv() {
	var cnt = document.inv_pending.elements.length;
	for(var i = 0; i < cnt; i++) {
		var element = document.inv_pending.elements[i];
		if (element.type == 'checkbox') if (element.checked) return true;
	}
	alert('Please choose at least one Field in the Resend column');
	return false;
}

function validateCopy(){
	var frm = document.copy_event;
	var title=trim(frm.title.value);
	if(title == ""){
		document.getElementById('cp-title').style.color = "red";
		frm.title.focus();
		return false;
	}
	if(title.length>500){
		alert('Please enter less than (or) equal to 500 characters for event title');
		frm.title.focus();
		return false;
	}
}

function mailAutoComplete(){
	var inputWord = $('sender_to_mail');
	new Autocompleter.Request.HTML(inputWord, '../contact/?a=ac&invite=1&ajaxcall=1', {
		'indicatorClass': 'autocompleter-loading', // class added to the input during request
		'minLength': 1, // We need at least 1 character
		'multiple': true, // Tag support, by default comma separated
		'isMail':true	// added by MK
	});
}

function openResendInvite(){
	if(validateResendInv()){
		document.getElementById('resend-custom-message').value='';
		loadXboxWindow('?a=resend_invite',450,300,'invite');
	}
}

var init_ms = 720000, /* init_ms = 15000, */ run_timer = 0, cTimer, count_down = init_ms, is_conn_dead = 0;
function startTimers(){ cTimer=setTimeout("check();",count_down);}
function check() { if(document.getElementById('keep_alive').value || is_conn_dead) chkConn(); }
function isKillResponse(){
	clearTimeout(cTimer);
	mkMessageBox('Redirecting........')
	alert('Page expired. You are logged out.');
	window.location.href = EUS_PATH+'/?a=logout';
}
function chkConnResponse(r){
	if(!chkResponse(r)){ 
		is_conn_dead = 1
		count_down = 9000
		run_timer = run_timer+count_down;
	}else{
		if(is_conn_dead) mkMessageBox('and, we\'re back!')
		is_conn_dead = 0
		count_down = init_ms
		run_timer = run_timer+count_down;
	}
}
function chkConn(){
	var req = new Request({
		url:EUS_PATH+'/?a=isAlive&ajaxcall=1',
		onComplete: function(response){
			chkConnResponse(response);
			if(response == 'chance'){
				alert('Your have been logged in for almost 3 hours. For security reasons, your session is about to expire. Please save your work, logout, and log back in if you would like to continue.');
				extConn();
				return false;
			}
			if(response == 'kill' || response == 'expire'){ isKillResponse(); return false; }
			if(!is_conn_dead) startTimers(count_down);
		}
	}).send();
}

function extConn(){
	var req = new Request({
		url:EUS_PATH+'/?a=extAlive&ajaxcall=1',
		onComplete: function(response){
			chkConnResponse(response);
			if(response == 'kill' || response == 'expire'){ isKillResponse(); return false; }
			if(!is_conn_dead) startTimers(count_down);
		}
	}).send();
}

function windowClose(){window.close();}

function showOptDesc(parent,child){
	var pObj = document.getElementById(parent);
	var childSpan = pObj.getElementsByTagName('SPAN');
	var ln=childSpan.length;
	for(var i=0; i<ln; i++){childSpan[i].style.display="none";}
	var cObj = document.getElementById(child);
	var earlyObj = document.getElementById(child+'-early');
	if(cObj != undefined) cObj.style.display="inline";
	if(earlyObj != undefined) earlyObj.style.display="inline";
}

function processQuestions(x,val){
	document.getElementById('reg_submit').value=val;
	document.getElementById('custom_'+x).submit();
	document.getElementById('cont-'+x).disabled = document.getElementById('back-'+x).disabled = 'disabled';
}
var __isFormAdded = 0;
function buildTermsForm(data,fid){
	var decode = JSON.decode(data);
	__isFormAdded = 1;
	if(fid){
		var obj = document.getElementById('f-title-'+decode.fid);
		obj.innerHTML = decode.title;
	}else{
		var list = document.getElementById('form-list');
		var li = document.createElement('li');
		li.innerHTML = '<span id="f-title-'+decode.fid+'" class="f-title">'+decode.title +'</span><span class="f-change pointer-div txt_clr" onclick="loadXboxInFrame(\'?a=edit_form&fid='+decode.fid+'&eid='+decode.eid+'\',720,520,\'add-form\')">Change Form Settings</span><span id="rm-form-'+decode.fid+'" class="f-rm-form pointer-div txt_clr" onclick="rmTermsForm('+decode.eid+','+decode.fid+',this)">Remove Form</span>';
		list.appendChild(li);
		list.style.display = 'block';
		closeXBoxPopUp();
	}
}

function formInclude(O){
	if(O.elem.value == 1){
		O.elem.checked = false;
		O.elem.value = 0;
		hideElements('terms-form-2',0)
		hideElements('instruction-msg-div',0)

	}else if(O.elem.value == 0){
		O.elem.checked = true;
		O.elem.value = 1;
		__isFormAdded = O.isFormAdded;
		if(!__isFormAdded) loadXboxInFrame('?a=add_form&eid='+O.eid+'&check=1',720,520,'add-form');
		hideElements('terms-form-2',1)
		hideElements('instruction-msg-div',1)

	}
	return false;
}

function rmTermsForm(eid,fid,spanObj){
	if (confirm('Are you sure you want to permanently remove this form ? \n\nThis cannot be undone')) {
		var O = {
			url: '?a=rm_form&eid=' + eid + '&fid=' + fid,
			data: 'action=1',
			onReq: function(){
				mkMessageBox('Processing......',1);
				spanObj.innerHTML = 'Removing...';
			},
			onComplete: function(r){
				spanObj.innerHTML = '';
				remove(spanObj.id);
				mkMessageBox('');
			}
		}
		sendMooAjaxReq(O);
	}
}
//XDownloader Plugin
var xDLoader = {
	swfDownloadResponse : function (file, serverResponse, progressID){
		//var prg = xDLoader.Progress(progressID);
		var prgContainer = document.getElementById(progressID);
		var elems = prgContainer.getElementsByTagName('div');
		var prg = {nameObj:elems[2],statusObj:elems[3],prgObj:elems[4],prgContainer:prgContainer}
		prg.nameObj.innerHTML = file;
		prg.statusObj.innerHTML = 'completed'
		prg.prgObj.style.width = '100%';
		$$('#'+progressID+' span.progressCancel').setStyles({visibility: 'hidden'});
		
		var o = JSON.decode(serverResponse);
		if(o.downloaded && o.loadupload && o.mail){
			setTimeout(function(){
				swfobject.removeSWF("xdownload_"+o.key);
				document.getElementById('flashcontent'+o.key).innerHTML = '<div class="form-btn-green">Downloaded</div>';
				formUploadSettings(o.key,o.fid);
				document.getElementById('form-mail-'+o.fid).style.display = 'block';
			}, 100);
		}else if(o.downloaded && o.loadupload){
			setTimeout(function(){
				swfobject.removeSWF("xdownload_"+o.key);
				document.getElementById('flashcontent'+o.key).innerHTML = '<div class="form-btn-green">Downloaded</div>';
				formUploadSettings(o.key,o.fid);
			}, 100);
		}else if(o.mail){
			setTimeout(function(){
				swfobject.removeSWF("xdownload_"+o.key);
				document.getElementById('flashcontent'+o.key).innerHTML = '<div class="form-btn-green">Downloaded</div>';
				document.getElementById('form-mail-'+o.fid).style.display = 'block';
			}, 100);
		}else{
			alert('Download failed');
		}
		document.getElementById('form-status-'+o.fid).style.display = 'none';
		mkFadeInOut(progressID).fadeOut(1000, function() {
			//prg.prgContainer.style.height = '0px';
			prg.prgContainer.style.display = 'none';
		});
	},
	errorInFileDownloading : function(x,elemId,errData){
		/* If x is
		 1 = no_extension||old file name with extension||modified file name with or without extenstion
		 2 = file_opened
		 3 = net_disconnected
		*/
		switch(x){
			case '1':	//no_extension
				//alert(errData);
				var str = errData.split('||');
				var old_file = str[0];
				var old_file_type = str[1].replace(".", "");
				//var new_file = str[2];
				//var new_file_type = (str[3]==null || !str[3])?'':str[3];
				var s = "<div style=\"float:left;width:180px;\"><img src=\"../includes/smarty/templates/images/red-x-icon-1.png\" /></div><h2>Oops</h2><br />The File you're downloading has the extension '"+old_file_type+"', but you have renamed it without this extension (or you've used another extension).<br /><br />Please click on the Download button again and either leave the filename as it is, or give the file a name that ends with ."+old_file_type+". <br /><br /><input type=\"button\" onclick=\"closeXBoxPopUp();\" value=\"Close\" class=\"srch_btn\" /> ";
				loadXboxStatic(500,300,s);
				break;
			case '2':	//file already opened
				alert('There is a problem in downloading the file. Please check whether file is already opened');
				break;
			case '3':	//Internet problem
				formDownloadSettings(elemId);
				alert('Unable to connect UEvent server. Please check your internet connection and try again.');
				break;
		}
	},
	xDownloadProgress : function (file,progressID,percent){	      
		//var prg = xDLoader.Progress(progressID);
		var prgContainer = document.getElementById(progressID);
		var elems = prgContainer.getElementsByTagName('div');
		var prg = {nameObj:elems[2],statusObj:elems[3],prgObj:elems[4],prgContainer:prgContainer}
		prg.nameObj.innerHTML = file;
		prg.statusObj.innerHTML = 'downloading...'
		prg.prgObj.style.width = percent+'%';
		prg.prgContainer.style.display = 'block';
	},
	stopDownloading : function (id){
		var flaObj = document.getElementById("xdownload_"+id);
		flaObj.terminateMethod();
		//var prg = xDLoader.Progress("xprogressbar"+id);
		var prgContainer = document.getElementById("xprogressbar"+id);
		var elems = prgContainer.getElementsByTagName('div');
		var prg = {nameObj:elems[2],statusObj:elems[3],prgObj:elems[4],prgContainer:prgContainer}
		
		prg.statusObj.innerHTML = '<span class="error">cancelled</span>';
		setTimeout(function(){prg.prgContainer.style.display = 'none';},1000)
	}/* ,
	Progress: function(el){
		var prgContainer = document.getElementById(progressID);
		var elems = prgContainer.getElementsByTagName('div');
		return {nameObj:elems[2],statusObj:elems[3],prgObj:elems[4],prgContainer:prgContainer}
	} */
};


function mkFadeInOut(id){
	var mkFadeOut = document.getElementById(id);
	mkFadeOut.fadeIn = function(delay,callbk,out){
		var _this = this;
		for (i=1; i<=100; i++){
			(function(j){
				setTimeout(function(){
					if (out==true) j=100-j;
					_this.style.opacity = j/100;
					_this.style.MozOpacity = j/100;
					_this.style.KhtmlOpacity = j/100;
					_this.style.zoom = 1; //for ie, set haslayout
					_this.style.display = "block";
					if (j==100&&callbk!=undefined) callbk.call(_this);
					else if (out==true&&callbk!=undefined&&j==0) callbk.call(_this);
					_this.style.filter = "alpha(opacity=" + j + ");";
				}, j*delay/100);
			})(i);
		}
	};
	mkFadeOut.fadeOut = function(delay,callbk){mkFadeOut.fadeIn(delay,callbk,true);};
	return mkFadeOut;
}


function isSuccessFormUpload(r){
	var decode = JSON.decode(r);
	if(decode.status){
		document.getElementById('form-status-'+decode.fid).style.display = 'block';
		document.getElementById('form-mail-'+decode.fid).style.display = 'none';
		document.getElementById('form-status-'+decode.fid).innerHTML = "<span class=\"pointer-div form-remove\" onclick=\"rmUpForm("+decode.key+","+decode.fid+")\">Remove</span>";
		document.getElementById('lsc-'+decode.key).innerHTML = '<span id="spanButtonPlaceHolder'+decode.key+'"><div class="form-btn-green">Uploaded</div></span>';
		document.getElementById('upload-params-'+decode.fid).style.display = 'none';
	}else{
		//display error message
	}
}

function rmUpForm(key,fid){
	var O = {
		url: '?a=terms',
		data: 'fid='+fid+'&rm-upload=1&elemKey='+key,
		onReq: function(){
			mkMessageBox('Processing......',1);
			document.getElementById('form-status-'+fid).innerHTML = "<span class='error'>Removing...</span>";
		},
		onComplete: function(r){
			var decode = JSON.decode(r);
			document.getElementById('form-status-'+fid).innerHTML = '';
			if(decode.mail) document.getElementById('form-mail-'+fid).style.display = 'block';
			formUploadSettings(key,fid);
			mkMessageBox('');
		}
	}
	sendMooAjaxReq(O);
}

var qTipTag,qTipX=0,qTipY=15;tooltip={name:"qTip",offsetX:qTipX,offsetY:qTipY,tip:null};
tooltip.init=function(a){a=a;if(!c)var c="qTip";var b=document.getElementById(c);if(!b){b=document.createElementNS?document.createElementNS("http://www.w3.org/1999/xhtml","div"):document.createElement("div");b.setAttribute("id",c);document.getElementsByTagName("body").item(0).appendChild(b)}if(document.getElementById){if(this.tip=document.getElementById(this.name))document.onmousemove=function(e){tooltip.move(e)};b=$$('.'+a);if(b)for(var d=0;d<b.length;d++){a=b[d];if(c=a.getAttribute("title")){a.setAttribute("tiptitle",c);a.removeAttribute("title");a.removeAttribute("alt");a.onmouseover=function(){tooltip.show(this.getAttribute("tiptitle"))};a.onmouseout=function(){tooltip.hide()}}}}};tooltip.move=function(a){var c=0,b=0;if(document.all){c=document.documentElement&&document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft;b=document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;c+=window.event.clientX;b+=window.event.clientY}else{c=a.pageX;b=a.pageY}this.tip.style.left=c+this.offsetX+"px";this.tip.style.top=b+this.offsetY+"px"};tooltip.show=function(a){if(this.tip){this.tip.innerHTML=a;this.tip.style.display="block"}};tooltip.hide=function(){if(this.tip){this.tip.innerHTML="";this.tip.style.display="none"}};

function updateFormTypeDiv(data) {
	var obj = document.getElementById(data.div_id);
	obj.innerHTML = data.html;
	obj.className = "pointer-div spl_txt "+data.classname;
	closeXBoxPopUp();
}

function openFormInstruction(id){
	var text = document.getElementById(id).innerHTML;
	var s = text+"<br /><br /><input type=\"button\" onclick=\"closeXBoxPopUp();\" value=\"Close\" class=\"srch_btn\" /> ";
	loadXboxStatic(500,300,s);
}

function updateCustomInvite() {
	var invt_des = tinyMCE.get('description').getContent();
	invt_des.replace('&nbsp','');
	if(invt_des!='') {
	obj = document.getElementById('invite_custom');
	obj.value = tinyMCE.get('description').getContent();
	objInvtDiv = document.getElementById('invt_description');
	objInvtDiv.innerHTML = obj.value;
	tinyMCE.execCommand('mceRemoveControl',false,'description'); 
	closeXBoxPopUp();
	window.location.href="#preview";
	}
	else {
		alert('Please enter description');
		tinyMCE.get('description').focus();
		return false;
	}
}
function showEventDate(event_date_type) {
	if(event_date_type == '1'){
		hideElements('date-list', 1);
		hideElements('div-add-date', 1);
	}
	else if(event_date_type == '3'){
		hideElements('date-list', 0);
		hideElements('div-add-date', 0);
	}
}

function setEventDate(){
	var occurrence = getRadioButtonValue('occurrence');
	var arr_date = document.getElementById('start_date').value.split('-');
	var start_date = new Date(arr_date[0], arr_date[1], arr_date[2]);
	if(occurrence == undefined) {
		alert('please check your daily, weekly or monthly repeat schedule');
		return false;
	}
	if(occurrence == 'daily'){
		var dt_repeat_until = document.getElementById('date_repeat_until1').value;
		var daily = getRadioButtonValue('daily');
		var num_days = document.getElementById('numdays');
		if(daily == undefined) {
			alert('please check your daily repeat schedule');
			return false;
		}
		if(daily == 'every') {
			if(num_days.value<=0) {
				alert('Please enter valid day(s)');
				num_days.focus();
				return false;
			}
		}
		if(dt_repeat_until == '') {
			alert('please select an ending repeat date for your daily event');
			return false;
		}
		var arr_repeat_dt = dt_repeat_until.split('-');
		dt_repeat_date = new Date(arr_repeat_dt[0], arr_repeat_dt[1], arr_repeat_dt[2]);
		if(dt_repeat_date<start_date) {
			alert('Your \'repeat until date\' is set to a date before your event start date.');
			return false;
		}
		var post_data = 'occurrence=daily&daily='+daily+'&numdays='+num_days.value+'&repeat_date1='+dt_repeat_until;
	}
	else if(occurrence == 'weekly') {
		var week_days = getCheckBoxSelectedOptions('week_day');
		var num_weeks = document.getElementById('numweeks');
		var week_start = document.getElementById('week_start').value;
		var dt_repeat_until = document.getElementById('date_repeat_until2').value;
		if(num_weeks.value<=0) {
			alert('Please enter valid week(s)');
			num_weeks.focus();
			return false;
		}
		if(week_days == '') {
			alert('Please select at least one day for your weekly repeat schedule');
			return false;
		}
		if(dt_repeat_until == '') {
			alert('please select an ending repeat date for your weekly event');
			return false;
		}
		var arr_repeat_dt = dt_repeat_until.split('-');
		dt_repeat_date = new Date(arr_repeat_dt[0], arr_repeat_dt[1], arr_repeat_dt[2]);
		if(dt_repeat_date<start_date) {
			alert('Your \'repeat until date\' is set to a date before your event start date.');
			return false;
		}
		var post_data = 'occurrence=weekly&numweeks='+num_weeks.value+'&week_start='+week_start+'&week_days='+week_days+'&repeat_date2='+dt_repeat_until;
	}
	else if(occurrence == 'monthly') {
		var monthly = getRadioButtonValue('monthly');
		var numday = document.getElementById('day_month');
		var num_months1 = document.getElementById('num_months1');
		var position = document.getElementById('position').value;
		var weekday = document.getElementById('weekday').value;
		var num_months2 = document.getElementById('num_months2');
		var dt_repeat_until = document.getElementById('date_repeat_until3').value;
		if(monthly == undefined) {
			alert('please check your monthly repeat schedule');
			return false;
		}
		if(monthly == 'int') {
			if(numday.value<=0) {
				alert('Please enter valid day(s)');
				numday.focus();
				return false;
			}
			else if(numday.value>28) {
				if(!confirm('Some months have fewer that 29 days. For these months, the occurrence will fall on the last day of the month.')) {
					numday.focus();
					return false;
				}
			}
			if(num_months1.value<=0) {
				alert('Please enter valid month(s)');
				num_months1.focus();
				return false;
			}
		}
		else if(monthly == 'day') {
			if(num_months2.value<=0) {
				alert('Please enter valid month(s)');
				num_months2.focus();
				return false;
			}
		}

		if(dt_repeat_until == '') {
			alert('please select an ending repeat date for your montly event');
			return false;
		}
		var arr_repeat_dt = dt_repeat_until.split('-');
		dt_repeat_date = new Date(arr_repeat_dt[0], arr_repeat_dt[1], arr_repeat_dt[2]);
		if(dt_repeat_date<start_date) {
			alert('Your \'repeat until date\' is set to a date before your event start date.');
			return false;
		}
		var post_data = 'occurrence=monthly&monthly='+monthly+'&day_month='+numday.value+'&num_months1='+num_months1.value+'&position='+position+'&weekday='+weekday+'&num_months2='+num_months2.value+'&repeat_date3='+dt_repeat_until;
	}
	if(document.getElementById('is_cust_schedule').value == 1) {
		if(!confirm('You currently have a custom date pattern in place. You have this because you edited or deleted an occurrence from your event.  If you edit the dates using the template editor, you will lose all the changes you have made to the occurrence date and times.  Press \'OK\' to continue.'))
			return false;
	}
	var req = new Request({
		method: 'post',
		url:'?a=recurring_event&ajaxcall=1',
		data:post_data,
		onRequest: function(){},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			var msg = response.split('|');
			if(msg[0] == 'error')
				document.getElementById('error').innerHTML = msg[1];
			else if(msg[0] == 'success') {
				setEventDateParams();
				document.getElementById('customize_recu_event').style.display = 'block';
				setTimeout(function() {closeXBoxPopUp();}, 10);
			}
		},
		onCancel: function(){ alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function getRadioButtonValue(name){
	var obj = document.getElementsByName(name);
	for (var i=0; i <obj.length; i++)
		if (obj[i].checked)
			return obj[i].value;
}

function getCheckBoxSelectedOptions(chkbox_name) {
	var obj = document.getElementsByName(chkbox_name);
	var values = [];
	for (var i=0; i <obj.length; i++)
		if (obj[i].checked)
			values.push(obj[i].value);
	return values;
}

function getStates(div_id, name, id, country, style, css_class, disable_mk_msg, default_state){
	var divObj = document.getElementById(div_id);
	var req = new Request({
		method: 'post',
		url:'../event/?a=list_state&ajaxcall=1',
		data:'name='+name+'&id='+id+'&country='+country+'&style='+style+'&class='+css_class+'&state='+default_state,
		onRequest: function() {if(disable_mk_msg != true) mkMessageBox('Loading...',1);},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			if(response){
				divObj.innerHTML=response;
				if(disable_mk_msg != true) mkMessageBox('');
			}else{
				divObj.innerHTML='';
				divObj.style.display = 'none';
			}
		},
		onCancel: function(){alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function validateState(obj, div_id, name, id, country, style, css_class, disable_mk_msg, default_state) {
	if(default_state == undefined) default_state = '';
	var stateobj = document.getElementById(div_id);
	if(stateobj!=null) {
		if(obj.options[obj.selectedIndex].value == 'US' || obj.options[obj.selectedIndex].value == 'CA' || obj.options[obj.selectedIndex].value == '') {
			getStates(div_id, name, id, country, style, css_class, disable_mk_msg, default_state);
			document.getElementById('div_state').style.display="block";
			document.getElementById('div_inter_state').style.display="none";
		}else {
			document.getElementById('div_inter_state').style.display="block";
			document.getElementById('div_state').style.display="none";
		}
	}
}

function customizeSchedule() {
	document.getElementById('event_date_type2').checked=true;
	var start_date = document.getElementById('date_start_0').value;
	var start_hour = document.getElementById('time_startHour0').value;
	var start_min = document.getElementById('time_startMinute0').value;
	var start_mer = document.getElementById('time_startMeridian0').value;

	var start_time = start_hour + ':' + start_min + ' ' + start_mer;
	if(start_time.length < 8) start_time = '';

	var end_date = document.getElementById('date_end_0').value;
	var end_hour = document.getElementById('time_endHour0').value;
	var end_min = document.getElementById('time_endMinute0').value;
	var end_mer = document.getElementById('time_endMeridian0').value;

	var end_time = end_hour + ':' + end_min + ' ' + end_mer;
	if(end_time.length < 8) end_time = '';

	if(start_date == end_date && (start_time.length < 8 || end_time.length < 8)) {
		alert('End Date/Time should not less than or equal to Start Date/Time');
		document.getElementById('time_startHour0').focus();
		return false;
	}

	var is_cust_schedule = document.getElementById('is_cust_schedule').value;
	return 'start_date='+start_date+'&start_time='+start_time+'&end_date='+end_date+'&end_time='+end_time+'&is_cust_schedule='+is_cust_schedule;
}

function showAddSchedule() {
	document.getElementById('date_rc_start_0').value = '';
	document.getElementById('time_rc_startHour0').value = '';
	document.getElementById('time_rc_startMinute0').value = '';
	document.getElementById('time_rc_startMeridian0').value = '';

	document.getElementById('date_rc_end_0').value = '';
	document.getElementById('time_rc_endHour0').value = '';
	document.getElementById('time_rc_endMinute0').value = '';
	document.getElementById('time_rc_endMeridian0').value = '';
	hideElements('add_edit_schedule', 1);
	document.getElementById('add_options').style.display = 'block';
	document.getElementById('update_options').style.display = 'none';
}

function addUpdateEventDate(opt) {
	var start_date = document.getElementById('date_rc_start_0');
	var end_date = document.getElementById('date_rc_end_0');
	
	var start_time_hour = document.getElementById('time_rc_startHour0');
	var start_time_min = document.getElementById('time_rc_startMinute0');
	var start_time_mer = document.getElementById('time_rc_startMeridian0');
	var start_time = start_time_hour.value + ':' + start_time_min.value + ' ' + start_time_mer.value;

	var end_time_hour = document.getElementById('time_rc_endHour0');
	var end_time_min = document.getElementById('time_rc_endMinute0');
	var end_time_mer = document.getElementById('time_rc_endMeridian0');
	var end_time = end_time_hour.value + ':' + end_time_min.value + ' ' + end_time_mer.value;
	var key = document.getElementById('schedule_id').value;
	if(start_date.value == '') {
		alert('Please select start date');
		start_date.focus();
		return false;
	}
	if(end_date.value == '') {
		alert('Please select end date');
		end_date.focus();
		return false;
	}

	if(start_time.length != 2 && start_time.length < 8) {
		alert('Please select a valid start time');
		start_time_hour.focus();
		return false;
	}

	if(end_time.length != 2 && end_time.length < 8) {
		alert('Please select a valid end time');
		end_time_hour.focus();
		return false;
	}
	
	if(start_time.length == 8 && end_time.length < 8) {
		alert('Please select end time');
		end_time_hour.focus();
		return false;
	}

	if(end_time.length == 8 && start_time.length < 8) {
		alert('Please select start time');
		start_time_hour.focus();
		return false;
	}
	if(start_date.value == end_date.value && (start_time.length < 8 || end_time.length < 8)) {
		alert('End Date/Time should not less than or equal to Start Date/Time');
		start_time_hour.focus();
		return false;
	}
	var st_dt = start_date.value.split('-');
	st_dt = st_dt[1]+'/'+st_dt[2]+'/'+st_dt[0];

	var en_dt = end_date.value.split('-');
	en_dt = en_dt[1]+'/'+en_dt[2]+'/'+en_dt[0];

	st_dt = (start_time.length == 2) ? st_dt : st_dt + ' ' + start_time;
	en_dt = (end_time.length == 2) ? en_dt : en_dt + ' ' + end_time;
	var stObj = new Date(st_dt);
	var enObj = new Date(en_dt);
	if(stObj > enObj) {
		alert('Start date should be less than end date');
		return false;
	}

	if(start_time.length < 8)
		start_time = '';
	if(end_time.length < 8)
		end_time = '';

	var req = new Request({
		method: 'post',
		url:'../event/?a=cust_schedule&t='+opt+'&id='+key+'&ajaxcall=1',
		data:'start_date='+start_date.value+'&start_time='+start_time+'&end_date='+end_date.value+'&end_time='+end_time,
		onRequest: function() {mkMessageBox('Loading...',1);},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			if(response){
				showCustomSchedule();
				hideElements('add_edit_schedule', 0);
				setAllCustomScheduledParams();
				mkMessageBox('');
			}
		},
		onCancel: function(){alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function editCustomSchedule(key, start_date, start_time, end_date, end_time) {
	document.getElementById('date_rc_start_0').value = start_date;
	var st = start_time.split(/[ :]/);
	var en = end_time.split(/[ :]/);
	document.getElementById('time_rc_startHour0').value = (st[0]) ? st[0] : '';
	document.getElementById('time_rc_startMinute0').value = (st[1]) ? st[1] : '';
	document.getElementById('time_rc_startMeridian0').value = (st[2]) ? st[2].toLowerCase() : '';

	document.getElementById('date_rc_end_0').value = end_date;
	document.getElementById('time_rc_endHour0').value = (en[0]) ? en[0] : '';
	document.getElementById('time_rc_endMinute0').value = (en[1]) ? en[1] : '';
	document.getElementById('time_rc_endMeridian0').value = (en[2]) ? en[2].toLowerCase() : '';
	document.getElementById('schedule_id').value = key
	document.getElementById('add_options').style.display = 'none';
	document.getElementById('update_options').style.display = 'block';
	hideElements('add_edit_schedule', 1);
	window.location.href='#edit';
}

function deleteCustomSchedule(key) {
	if(key != undefined) 
		document.getElementById('schedule_'+key).checked = true;

	var items = getCheckBoxSelectedOptions('schedule');
	if(items == '') {
		alert('Please choose at least one date');
		return false;
	}
	var req = new Request({
		method: 'post',
		url:'../event/?a=cust_schedule&t=delete&ajaxcall=1',
		data:'ids='+items,
		onRequest: function() {mkMessageBox('Loading...',1);},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			if(response){
				showCustomSchedule();
				setAllCustomScheduledParams();
				mkMessageBox('');
			}
		},
		onCancel: function(){alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function timeChanged(id, obj) {
	if(id == 'time_startHour0')
		setEventDateParams('start_hour', obj);
	else if(id == 'time_endHour0')
		setEventDateParams('end_hour', obj);
	else if(id == 'time_startMinute0')
		setEventDateParams('start_minute', obj);
	else if(id == 'time_endMinute0')
		setEventDateParams('end_minute', obj);
	else if(id == 'time_startMeridian0')
		setEventDateParams('start_meridian', obj);
	else if(id == 'time_endMeridian0')
		setEventDateParams('end_meridian', obj);
}

function showCustomSchedule() {
	var req = new Request({
		method: 'post',
		url:'../event/?a=cust_schedule&t=view&ajaxcall=1',
		onRequest: function() {mkMessageBox('Loading...',1);},
		onComplete: function(response) {
			if(!chkResponse(response)) return false;
			if(response){
				document.getElementById('view_schedule').innerHTML=response;
				mkMessageBox('');
			}else{
				document.getElementById('view_schedule').innerHTML='<td align="center" colspan="3">No event schedule Found for this event</td>';
			}
		},
		onCancel: function(){alert('Cannot connect to Link Server'); },
		onFailure: function(xhr){ /*alert('Internet connection error');*/ }
	}).send();
}

function setEventDateParams(id, obj) {
	var myobj = document.getElementById('date-list');
	var div_count = myobj.getElementsByTagName('div').length;
	if(div_count>1) return false;

	var event_date_changed = false;
	var update_schedule = false;
	var event_date_type = getRadioButtonValue('event_date_type');
	var is_cust_schedule = document.getElementById('is_cust_schedule').value;

	if(id == undefined && obj == undefined)
		event_date_changed = false;
	else if(id != undefined && obj != undefined) {
		var elObj = document.getElementById(id);
		event_date_changed = true;
		update_schedule = (elObj.value == '' || elObj.value == obj.value || is_cust_schedule != 1);
	}

	if(event_date_type == 2) {
		if(update_schedule && event_date_changed) {
			elObj.value = obj.value;
		}
		else {
			if(event_date_changed) {
				if(!confirm('You currently have a custom date pattern in place. You have this because you edited or deleted an occurrence from your event.  If you edit the dates using the template editor, you will lose all the changes you have made to the occurrence date and times.  Press \'OK\' to continue.')) {
					if(event_date_changed) {
						obj.value = elObj.value;
						if(id == 'start_date') {
							document.getElementById('date_end_0').value = elObj.value;
						}
					}
					return false;
				}
			}
			var url = customizeSchedule();
			var req = new Request({
				method: 'post',
				url:'../event/?a=cust_schedule&t=generate&ajaxcall=1&'+url,
				onRequest: function() {},
				onComplete: function(response) {
					if(!chkResponse(response)) return false;
					if(response) {
						document.getElementById('is_cust_schedule').value = 0;
						document.getElementById('start_date').value = '';
						document.getElementById('start_hour').value = '';
						document.getElementById('start_minute').value = '';
						document.getElementById('start_meridian').value = '';

						document.getElementById('end_date').value = '';
						document.getElementById('end_hour').value = '';
						document.getElementById('end_minute').value = '';
						document.getElementById('end_meridian').value = '';
						mkMessageBox('');
					}
				},
				onCancel: function(){alert('Cannot connect to Link Server'); },
				onFailure: function(xhr){ /*alert('Internet connection error');*/ }
			}).send();
		}
	}
	return true;
}

function setAllCustomScheduledParams() {
	document.getElementById('start_date').value = document.getElementById('date_start_0').value;
	document.getElementById('start_hour').value = document.getElementById('time_startHour0').value;
	document.getElementById('start_minute').value = document.getElementById('time_startMinute0').value;
	document.getElementById('start_meridian').value = document.getElementById('time_startMeridian0').value;
	
	document.getElementById('end_date').value = document.getElementById('date_end_0').value;
	document.getElementById('end_hour').value = document.getElementById('time_endHour0').value;
	document.getElementById('end_minute').value = document.getElementById('time_endMinute0').value;
	document.getElementById('end_meridian').value = document.getElementById('time_endMeridian0').value;

	document.getElementById('is_cust_schedule').value = 1;
}

function openCustomSchedule() {
	var url = customizeSchedule();
	if(url)
		loadXboxWindow('?a=cust_schedule&'+url, 600, 460, 0);
}
var unique = function(origArr) {
    var newArr = [],
        origLen = origArr.length,
        found,
        x, y;

    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArr.length; y++ ) {
            if ( origArr[x] === newArr[y] ) {
              found = true;
              break;
            }
        }
        if ( !found) newArr.push( origArr[x] );
    }
   return newArr;
};
function checkBeforeSend(){
	var tot_num_codes;
	var invite_code=new Array();
	var j=0;
	var emailids=new Array();
	var tot_input=document.getElementsByTagName("input");
	for (var i = 0; i < tot_input.length; i++) {
		var val = tot_input[i];        
		if (val.type != 'checkbox')
			var email=val.value;
		if (val.type == 'checkbox' && val.checked==true){
			if(val.value!='on'){
				invite_code[j]=val.value;
				j=j+1;
			}
		}
	}
	
	tot_num_codes = invite_code.length;
	if(tot_num_codes>1000){
		alert("You are allowed to send only 1000 invitations at a time");
		return false;
	}else{
		openResendInvite();
	}
}
function processResendInvite(){
	var limit=20;
	var len_email;
	var invite_list=new Array();
	var disp_email=new Array();
	var invite_code=new Array();
	var emailids=new Array();
	var email_list=new Array();
	var tot_num_codes;
	var j=0;
	var key = 0;
	var start = 0;
	var end = limit;
	document.getElementById('resend-custom-message').value = tinyMCE.get('resender_message').getContent();
	closeXBoxPopUp();
	var prg_bar = document.getElementById('resendprogress-bar');
	var resend = document.getElementById('resend');
	resend.style.display = 'none';
	var cancel = document.getElementById('cancel');
	cancel.style.display = 'block';
	var tot_input=document.getElementsByTagName("input");
	for (var i = 0; i < tot_input.length; i++) {
		var val = tot_input[i];        
		if (val.type != 'checkbox')
			var email=val.value;
		if (val.type == 'checkbox' && val.checked==true){
			if(val.value!='on'){
				invite_code[j]=val.value;
				emailids[j]=email;
				j=j+1;
			}
		}
	}
	
	tot_num_codes = invite_code.length;
	len_mod = tot_num_codes/limit;
	len_email = Math.floor(tot_num_codes/limit);
	if(len_mod>0)len_email = len_email+1;
	document.getElementById('resendprogress-bar').style.display="block";
	for(var i=0;i<len_email;i++){
		invite_list[i]=invite_code.slice(start,end);
		email_list[i]=emailids.slice(start,end);
		if(tot_num_codes>1)
			disp_email[i] = emailids[start]+'...';
		else
			disp_email[i] = emailids[start];
		start=end;
		end=end+limit;
	}
	if(invite_list.length>0 && invite_list[i]!='')
		resendmail(0,len_email,tot_num_codes,0,invite_list,disp_email);
	//document.getElementById('inv_pending').submit();
}

function resendmail(key,len_email,tot_num_codes,tot_res,invite_list,disp_email){
	var eid = document.getElementById('eid').value;
	var status='pending';
	var custom_message=document.getElementById('resend-custom-message').value;
	var req = new Request({
			method: 'post',
			url: '../event/?a=invite_sent&eid='+eid,
			data: 'invitation_codes='+invite_list[key]+'&status='+status+'&resend-custom-message='+encodeURIComponent(custom_message),
			onRequest: function() { processbarResend(key,len_email,tot_num_codes,disp_email)},
			onComplete: function(response) {
			if(response == 'success'){
				tot_res = tot_res+1;
					key = key+1;
					if(key<len_email && invite_list[key]!=''){
						resendmail(key,len_email,tot_num_codes,tot_res,invite_list,disp_email);
					}
					if((tot_res+1)>len_email || (tot_res+1)==len_email){
						window.location.href = '?a=invite_sent&eid='+eid;
					}
				}
			},
			onCancel: function(){ alert('Cannot connect to Learn Server'); },
			onFailure: function(xhr){ /*alert('Internet connection error'); */	}
		}).send();
}

function processbarResend(cur_length,length,tot_num_codes,disp_email){
		var limit=20;
		var prg_loaded = document.getElementById('invloaded');
		var prg_stats_1 = document.getElementById('invstats-1');
		var prg_stats_2 = document.getElementById('invstats-2');
		var prg_stats_3 = document.getElementById('invstats-3');
		var prg_stats_4 = document.getElementById('invstats-4');
		var completed = length - cur_length;
		var disp_completed;
		if(tot_num_codes>limit)
			disp_completed=cur_length * limit
		else
			disp_completed=tot_num_codes
		var value = 100 - (Math.floor(100 - ((cur_length / length) * 100)));
		prg_stats_1.innerHTML = disp_email[cur_length];
		prg_stats_2.innerHTML = value+'% &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+ disp_completed +'/'+ (tot_num_codes);
		prg_loaded.style.width = value+'%';
}

function processEmailids(){
	var limit=20;
	var len_email;
	var tot_num_emails;
	var email_list=new Array();
	var disp_email=new Array();	
	var s_btn = document.getElementById('s-btn');
	s_btn.style.display = 'none';
	var prg_bar = document.getElementById('invprogress-bar');
	var sender_to_mail = document.getElementById('sender_to_mail').value;
	sender_to_mail = sender_to_mail.split(' ').join('');
	sender_to_mail = sender_to_mail.replace(/(\r\n|\r|\n)/g, "");
	var temparray = sender_to_mail.split(',');
	temparray = unique(temparray);
	sender_to_mail = temparray.join(",");
	arr_email = sender_to_mail.split(',',limit);
	var num_emails=arr_email.length;
	var key = 0;
	var start = 0;
	var end = limit;

	tmp = sender_to_mail.split(',');
	tot_num_emails = tmp.length;
	if(tmp[tot_num_emails-1]=='')tot_num_emails = tot_num_emails-1;
	if(tot_num_emails>1000){
		s_btn.style.display = 'block';
		prg_bar.style.display = 'none';
		alert("You are allowed to send only 1000 invitations at a time");
		return false;
	}
	len_mod = tot_num_emails/limit;
	len_email = Math.floor(tot_num_emails/limit);
	if(len_mod>0)len_email = len_email+1;

	document.getElementById('invprogress-bar').style.display="block";
	for(var i=0;i<len_email;i++){
		email_list[i]=tmp.slice(start,end);

		if(tot_num_emails>1)
			disp_email[i] = tmp[start]+','+tmp[start+1]+'...';
		else{
			disp_email[i] = tmp[start];
			var atpos = sender_to_mail.indexOf("@");
			var dotpos = sender_to_mail.lastIndexOf(".");
			if (atpos<1 || dotpos<atpos+2 || dotpos+2>=sender_to_mail.length){
				s_btn.style.display = 'block';
				prg_bar.style.display = 'none';
				alert("Not a valid e-mail address");
				return false;
			}
		}
		start=end;
		end=end+limit;
	}
	if(email_list.length>0 && email_list[i]!='')
		sendmail(0,len_email,tot_num_emails,0,email_list,disp_email);
}

function sendmail(key,len_email,tot_num_emails,tot_res,email_list,disp_email){
	var eid = document.getElementById('eid').value;
	var sender_name = document.getElementById('sender_name').value;
	var sender_email = document.getElementById('sender_email').value;
	var sender_subject = document.getElementById('sender_subject').value;
	var sender_message = tinyMCE.get('sender_message').getContent();
		
	var req = new Request({
			method: 'post',
			url: '../event/?a=process_invite&eid='+eid,
			data: 'email_list='+email_list[key]+'&sender_name='+encodeURIComponent(sender_name)+'&sender_email='+sender_email+'&sender_subject='+encodeURIComponent(sender_subject)+'&sender_message='+encodeURIComponent(sender_message)+'&eid='+eid,
			onRequest: function() { processbar(key,len_email,tot_num_emails,disp_email)},
			onComplete: function(response) {
			if(response == 'success'){
				tot_res = tot_res+1;
					key = key+1;
					if(key<len_email && email_list[key]!=''){
						sendmail(key,len_email,tot_num_emails,tot_res,email_list,disp_email);
					}
					if((tot_res+1)>len_email || (tot_res+1)==len_email){
						window.location.href = '?a=show_sent&eid='+eid;
					}
				}
			},
			onCancel: function(){ alert('Cannot connect to Learn Server'); },
			onFailure: function(xhr){ /*alert('Internet connection error'); */	}
		}).send();
}

function processbar(cur_length,length,tot_num_emails,disp_email){
		var limit=20;
		var prg_loaded = document.getElementById('invloaded');
		var prg_stats_1 = document.getElementById('invstats-1');
		var prg_stats_2 = document.getElementById('invstats-2');
		var prg_stats_3 = document.getElementById('invstats-3');
		var prg_stats_4 = document.getElementById('invstats-4');
		var completed = length - cur_length;
		var disp_completed;
		if(tot_num_emails>limit)
			disp_completed=cur_length * limit
		else
			disp_completed=tot_num_emails
		var value = 100 - (Math.floor(100 - ((cur_length / length) * 100)));
		prg_stats_1.innerHTML = disp_email[cur_length];
		prg_stats_2.innerHTML = value+'% &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+ disp_completed +'/'+ (tot_num_emails);
		prg_loaded.style.width = value+'%';
}

function beforeCloseBoxPopUp(){
	tinyMCE.get('resender_message').remove();
}

function instantAlert(type,url){
	switch(type){
		case 'event_date':
			var alert_msg = '<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  Current registrants have registered under the date and time originally created and you wish to change the date, time or both.<br /><br />Suggestion:  Be sure to communicate your date or time change to those already registered.';
			loadXboxFromInsatantAlert(alert_msg,url);
			break;
		case 'event_type':
			MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  By changing the Event Type, not all of the question types in the Personalized Questions tab will be available.<br /><br />Suggestion:  If the Event Type must be altered, first copy the event, make the necessary changes and repost the new Url where the first Url was located.  This will capture any future registrants\' information correctly.');
			break;
		case 'allow_group_reg':
			MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  By changing the group registering option, you will lose the information already collected and your reports will be inaccurate. <br /><br />Suggestion:  If Group Registering must be altered, take the event off line, copy the event, make the necessary changes and repost the new Url in the place of the first Url.  The newly modified event will then capture future registrants\' information correctly.');
			break;
		case 'registrant_info':
			MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  Modifying existing selections will alter the data that previous registrants may have already answered/not answered.<br /><br />Suggestion:  Reports will reflect only the answers that have been given by the registrants to this point.  Reporting will not be consistent if a Registrant Information option is deleted or added after registrants are attached to the event.');
			break;
		case 'apply_type':
				MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  Changing "who" the question is directed to can have severe consequences!   Depending on how your event is constructed it may delete, change or corrupt the data already entered by previous registrants.<br /><br />Suggestion 1:   Only change this option if absolutely necessary!  Take the event off line, change and test for results.  Check reports.  If unacceptable errors appear do not make the event live.  Go to suggestion 2 below.<br /><br />Suggestion 2:  If the person answering this question must be changed it is best to copy the event, make the necessary changes, test to make sure the changes are satisfactory and repost the new event Url in the place of the original.');
			break;
		case 'question_type':
				MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  Changing the question type may have consequences such as incorrect calculations in reports and possible data loss.<br /><br />Suggestion:   Only change this option if absolutely necessary.  If the question type must be changed, take the event off line, copy the event, make the necessary changes, test for accuracy, then repost the new Url in the place of the original.');
			break;
		case 'add_price':
			var alert_msg = '<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue: Prices should be determined, fixed and verified as correct before any event is made live.  Adjusting prices once an event is live will cause reports to show a variation in prices.<br /><br />Suggestion:  Plan ahead!  Double check that the correct pricing is in place BEFORE the launch of an event.  Please contact a UEvent team member for assistance before you change pricing in live events!';
			loadXboxFromInsatantAlert(alert_msg,url);
			break;
		case 'logic_type':
			var alert_msg = '<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br />What you\'re about to change could negatively affect how your event operates<br /><br />Issue:  If branching has been applied, changing the answer sequence could cause a series of errors in the path the registrant takes to answering the event\'s questions as well as the way the data is collected.  The changed sequence could be confusing for the registrant, and could make the reporting information scrambled.<br /><br />Suggestion 1:  Have the correct order of questions in place before the launch of an event.  Test the event with all the possibilities you have put in before taking the event live.<br /><br />Suggestion 2:  If changing the order of questions, make sure to double check the final sequence to ensure it makes sense to the registrants.  Take the event off-line, test the path that registrants take to verify it was correct, then return the event to a live registration.';
			loadXboxFromInsatantAlert(alert_msg,url);
			break;
		case 'report_field':
			MooBox.alert('<br /><p align="center" style="padding-right:40px"><b>Caution!</b></p><br /><br />The number of choices for this report has exceeded the system. You can choose as many choices under Registration Basic Information, but please limit your selections to only 27 choices for the other sections. After choosing your choices, please rerun the report.');
			break;
	}
}

function loadXboxFromInsatantAlert(alert_msg,url) {
	MooBox.alert(alert_msg,{ onComplete: 
	function(returnvalue) {
		if(url){
			if(returnvalue){
				var params = url.split(',');
				loadXboxWindow(params[0],params[1],params[2],params[3]);
			}
		}
	}
	});
}
