function prepsel(form,fld,cas,mod) {
	var form_id = $(form).attr("id");
// mod: 0-select with conference_count>0    1-select all   2-select only states for country US (addconf)
	switch (cas) {

		case 'ctry': 
			if (fld.value=='US') {
				ajaxFunction(form.stat,'states','country_code',fld.value,'state_name','state_code',mod,'All');
				if (mod!=2) ajaxFunction(form.city,'cities','no city',fld.value,'city','city_code',1,'All');
				document.getElementById('stat').disabled=false;
			}
			else {
				if (mod!=2) ajaxFunction(form.city,'cities','country_code',fld.value,'city','city_code',mod,'All');
				ajaxFunction(form.stat,'states','no state',fld.value,'state_name','state_code',mod,'All');
				document.getElementById('stat').disabled=true;
			}
			break;
			
		case 'ctry1': 
			if (fld.value=='US') {
				ajaxFunction(form.stat1,'states','country_code',fld.value,'state_name','state_code',mod,'Select');
				if (mod!=2) ajaxFunction(form.city1,'cities','no city',fld.value,'city','city_code',1,'Select');
				document.getElementById('stat1').disabled=false;
			}
			else {
				if (mod!=2) ajaxFunction(form.city1,'cities','country_code',fld.value,'city','city_code',mod,'Select');
				ajaxFunction(form.stat1,'states','no state',fld.value,'state_name','state_code',mod,'Select');
				document.getElementById('stat1').disabled=true;
			}
			break;
				
		case 'bac_ctry': 
			if (fld.value=='US') {
				ajaxFunction(form.bac_stat,'states','bac_country_state',fld.value,'state_name','state_code',mod,'Select');
				if (mod!=2) ajaxFunction(form.city,'cities','no city',fld.value,'city','city_code',1,'All');
				document.getElementById('bac_stat').disabled=false;
			}
			else {
				if (mod!=2) ajaxFunction(form.city,'cities','bac_country_city',fld.value,'city','city_code',mod,'Select');
				ajaxFunction(form.bac_stat,'states','no state',fld.value,'state_name','state_code',mod,'All');
				document.getElementById('bac_stat').disabled=true;
			}
			break;

		case 'stat':
			ajaxFunction(form.city,'cities','state_code',fld.value,'city','city_code',mod,'All');
			break;
			
		case 'stat1':
			ajaxFunction(form.city1,'cities','state_code',fld.value,'city','city_code',mod,'Select');
			break;
		
		case 'bac_stat':
			ajaxFunction(form.city,'cities','bac_state_city',fld.value,'city','city_code',mod,'Select');
			break;

		case 'cat':
			ajaxFunction(form.subj,'subjects','category_code',fld.value,'subject','subject_code',mod,'All');
			break;
		
		case 'cat1':
			ajaxFunction(form.subj1,'subjects','category_code',fld.value,'subject','subject_code',mod,'Select');
			break;

		case 'ncat1':
			ajaxFunction(form.nsubj1,'subjects','category_code',fld.value,'subject','subject_code',mod,'Select');
			break;
			
		case 'city':
			ajaxFunction(form.ven,'venues','city_code',fld.value,'venue','venue_code',mod,'Select');
			break;
		
		case 'orgz':
			ajaxFunction(form.ver,'org_versions','org_code',fld.value,'version','version',mod,'Select');
			break;

		default:
			break;
	
	}
}

function ajaxFunction(selectbox,tab,fld1,val,fld2,key,mod,option1){
	// tab=table, fld1=field for select, val=value of fld1 for select, fld2/key=for output
	// mod=0-select only items with conferences 1-select all items 2-used for addconf
	var ajaxRequest;  // The variable that makes Ajax possible!

	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	//var url=phpfunc+"?dbt="+dbt"&code="+ccode;
	var url="/ajx_changeselect.php?tab="+tab+"&fld1="+fld1+"&val="+val+"&fld2="+fld2+"&key="+key;
	if (mod==0) url=url+"&mod=0";
	if (mod==1 || mod==2) url=url+"&mod=1";
	if (mod==4) url=url+"&mod=4";
	//alert(url);
	if (fld1=='no city') {
		removeAllOptions(selectbox);
		addOption(selectbox, "0", option1);
		return;
	}
	if (fld1=='no state') {
		removeAllOptions(selectbox);
		addOption(selectbox, "-1", " ");
		return;
	}
	
// Create a function that will receive data sent from the server

	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			removeAllOptions(selectbox);
			if (tab=='states' && val!='US') {
				addOption(selectbox, "-1", " ");
				return;
			}
			if (tab=='venues' || tab=='org_versions') {
				if (tab=='venues') {
					addOption(selectbox, "-1", "Select");
					addOption(selectbox, "0", "Notify soon");
				}
				if (tab=='org_versions') {
					addOption(selectbox, "99", "All");
				}
			}
			else addOption(selectbox, "0", option1);
			
			createOptions(selectbox,ajaxRequest.responseText);

		}
	};
	ajaxRequest.open("GET", url, true);
	ajaxRequest.send(null); 
}

function createOptions(selectbox,str)
{
      var array = str.split(";");
      var k=0;
      for (var i = 0; i < array.length-1; i=i+2) 
      {
    	  addOption(selectbox, array[i], array[i+1]);
      }
}

function removeAllOptions(selectbox)
{
//		var i;
		selectbox.options.length = 0;
//		for(i=selectbox.options.length-1;i>=0;i--) {
//			selectbox.options.remove(i);
////			selectbox.remove(i);
//		}
}

function addOption(selectbox, value, text )
{
		var optn = document.createElement("OPTION");
		optn.text = text;
		optn.value = value;
		selectbox.options.add(optn);
//		selectbox.add(optn);


}

//var ie4 = false; if(document.all) { ie4 = true; }
function getObject(id)
{
	if (ie4) { return document.all[id]; } 
	else { return document.getElementById(id); }
}

function toggle(link, divId, text1,text2) {
	if ($(link).html() == text1) $(link).html(text2);
	else $(link).html(text1);
	$("#"+divId).slideToggle();
}

function chg_text_style(link,id) 
{
//var d = getObject(id);
	var d = document.getElementById(id);
if (link.value=="Enter any text") link.value = '';
d.style.color = 'black';
}

function fld_empty (fld,name)
{
	if (fld.value.length == 0 || fld.value=="") {
		alert("'"+name+"' is missing.");
		fld.focus();
		return true;
	}	
	return false;
}

function fld_empty_tab (tab_num,fld,name)
{
	if (fld.value.length == 0 || fld.value=="") {
		alert("'"+name+"' is missing.");
		NextTab(tab_num);
		fld.focus();
		return true;
	}	
	return false;
}



function validate_sub (form) {
var mods = ['clear']; // a list of mods that should skip validation
	if (searchArray($("#frm_subscribe [name=mod]").get(0).value,mods)>=0) return true;

	if (fld_empty_tab(1,$("#frm_subscribe [name=fname]").get(0),'First name')) return false;
	if (fld_empty_tab(1,$("#frm_subscribe [name=lname]").get(0),'Last name')) return false;
	if (check_radio(form.mr_ms)=="") {
		alert("'Mr/Ms' is missing.");
		NextTab(1);
		$("#frm_subscribe [name=lname]").get(0).focus();
		return false;
	}
//	if ($("#frm_subscribe [name=ctry1]").get(0).value == 0) {
//		alert("Country is missing");
//		NextTab(1);
//		$("#frm_subscribe [name=ctry1]").get(0).focus();
//		return false;
//	}
//	if ($("#frm_subscribe [name=city1]").get(0).value == 0) {
//		alert("City is missing");
//		NextTab(1);
//		$("#frm_subscribe [name=city1]").get(0).focus();
//		return false;
//	}

//	if (fld_empty_tab(1,$("#frm_subscribe [name=adr]").get(0),'Address')) return false;
	if (fld_empty_tab(1,$("#frm_subscribe [name=email]").get(0),'E-mail')) return false;
	if (!emailcheck($("#frm_subscribe [name=email]").get(0).value)) {
		alert("Invalid 'Mail address' format.");
		NextTab(1);
		$("#frm_subscribe [name=email]").get(0).focus();
		return false;
	}
	if (($("#frm_subscribe [name=mod]").get(0).value=="" || 
			$("#frm_subscribe [name=mod]").get(0).value=="add") &&
			fld_empty_tab(1,$("#frm_subscribe [name=p]").get(0),'password')) return false;
	if (($("#frm_subscribe [name=mod]").get(0).value==""  || 
			$("#frm_subscribe [name=mod]").get(0).value=="add") &&
			$("#frm_subscribe [name=p]").get(0).value.length>0 &&
			$("#frm_subscribe [name=p]").get(0).value.length<6) { 
		alert("Password should be at least six characters.");
		NextTab(1);
		$("#frm_subscribe [name=p]").get(0).focus();
		return false;
	}
	if ($("#frm_subscribe [name=p]").get(0).value.length>0 && fld_empty_tab(1,$("#frm_subscribe [name=p1]").get(0),'Confirm password')) return false;
	if ($("#frm_subscribe [name=p]").get(0).value.length>0 && $("#frm_subscribe [name=p]").get(0).value!=$("#frm_subscribe [name=p1]").get(0).value) {
		alert("Confirmed password does not match password");
		NextTab(1);
		$("#frm_subscribe [name=p1]").get(0).focus();
		return false;
	}
	
	var itemsChecked = checkArray(form, "subjects[]");
	if(itemsChecked.length == 0) {
		alert ("Areas of interest were not selected.\r\nPlease, select at least one area of interest to receive Information about upcoming events.");
		NextTab(2,'scroll');
		return false;
	} 
	
	$("#frm_subscribe [name=p1]").get(0).value="";

	if ($("#frm_subscribe [name=mod]").get(0).value=='upd' &&
			($("#frm_subscribe [name=p]").get(0).value.length>0 ||
					$("#frm_subscribe [name=email]").get(0).value!=$("#frm_subscribe [name=nmail]").get(0).value)) {
		alert ("Changing your email or password will sign you out automatically");
	}
	
	return true;

}

function validate_contact (form) {
var mods = ['clear']; // a list of mods that should skip validation
	if (searchArray($("#frm_contact [name=mod]").get(0).value,mods)>=0) return true;

	if (fld_empty($("#frm_contact [name=name]").get(0),'Your name')) return false;
	if (fld_empty($("#frm_contact [name=mail]").get(0),'Your email address')) return false;
	if (!emailcheck($("#frm_contact [name=mail]").get(0).value)) {
		alert("Invalid 'Mail address' format.");
		$("#frm_contact [name=mail]").get(0).focus();
		return false;
	}	
	if (fld_empty($("#frm_contact [name=msg]").get(0),'message')) return false;	

}

function validate_publish (form) {
	if ($("#publish1 [name=image_file]").get(0).value=="" 
		|| tinyMCE.activeEditor.getContent()=="") {
		var answer=confirm("Missing Image or description. Standard image or description will be used\nAre you sure you want to proceed?\nPress 'OK' to proceed or 'Cancel' to return to form");
		if (answer) return true;
		else return false;
	}

}

function validate_addconf (addform)
{
var mods = ['clear']; // a list of mods that should skip validation

	if (searchArray($("#addconf [name=mod]").get(0).value,mods)>=0) return true;
	
	if (tinyMCE.activeEditor.isDirty()) {
		//alert("desc change");
		$("#addconf [name=desc_change]").get(0).value="1";
	}
	
	if (fld_empty_tab(1,$("#addconf [name=name]").get(0),'Your name')) return false;
	if (fld_empty_tab(1,$("#addconf [name=nmail]").get(0),'Your email')) return false;
	if ($("#addconf [name=nmail]").get(0).value.length > 0 && !emailcheck($("#addconf [name=nmail]").get(0).value)) {
		alert("'Your email' format is invalid.");
		NextTab(1);
		$("#addconf [name=nmail]").get(0).focus();
		return false;
	}

	if (fld_empty_tab(1,$("#addconf [name=event]").get(0),'Event name')) return false;
	if (fld_empty_tab(1,$("#addconf [name=web]").get(0),'Website')) return false;
	if ($("#addconf [name=web]").get(0).value.length > 0 && !urlcheck($("#addconf [name=web]").get(0).value)) {
		alert("Invalid 'Website' format. Should be http://www.xxx....");
		NextTab(1);
		$("#addconf [name=web]").get(0).focus();
		return false;
	}
	
	if (fld_empty_tab(1,$("#addconf [name=fdate]").get(0),'From date')) return false;
	if ($("#addconf [name=fdate]").get(0).value.length>0) {
		if (!chkdate($("#addconf [name=fdate]").get(0),'From date',$("#addconf [name=fdate]").get(0),0)) {
			NextTab(1);
			$("#addconf [name=fdate]").get(0).focus();	
			return false;
		}
		var d=prep_date(new Date(),0);
		if (!compare_dates($("#addconf [name=fdate]").get(0).value,d)) {
			alert("'From Date' cannot be before "+d);
			NextTab(1);
			$("#addconf [name=fdate]").get(0).focus();
			return false;
		}
	}
	if (fld_empty_tab(1,$("#addconf [name=tdate]").get(0),'To date')) return false;
	if ($("#addconf [name=tdate]").get(0).value.length>0) {
		if (!chkdate($("#addconf [name=tdate]").get(0),'To date',$("#addconf [name=tdate]").get(0),0)) {
			NextTab(1);
			$("#addconf [name=tdate]").get(0).focus();	
			return false;
		}
		if (!compare_dates($("#addconf [name=tdate]").get(0).value,$("#addconf [name=fdate]").get(0).value)) {
			alert("'To Date' must be later than 'From Date'.");
			NextTab(1);
			$("#addconf [name=tdate]").get(0).focus();
			return false;
		}
	}
	if ($("#addconf [name=ctry1]").get(0).value == 0) {
		alert("Country is missing.");
		NextTab(1);
		$("#addconf [name=ctry1]").get(0).focus();
		return false;
	}

	if ($("#addconf [name=ctry1]").get(0).value =='US' && $("#addconf [name=stat1]").get(0).value <= 0) {
		alert("Missing state for USA.");
		NextTab(1);
		$("#addconf [name=stat1]").get(0).focus();
		return false;
	}
	if ($("#addconf [name=city1]").get(0).value == 0 && $("#addconf [name=ncity]").get(0).value.length == 0) {
		alert("Missing 'City'.");
		NextTab(1);
		$("#addconf [name=city1]").get(0).focus();
		return false;
	}
	if ($("#addconf [name=city1]").get(0).value != 0 && $("#addconf [name=ncity]").get(0).value.length != 0) {
		alert("Duplicate Cities.");
		NextTab(1);
		$("#addconf [name=ncity]").get(0).focus();
		return false;
	}
	if (fld_empty_tab(1,$("#addconf [name=ven]").get(0),'Venue')) return false;
	
//	if (tinyMCE.activeEditor.getContent()=="") {
//		alert("Missing description");
//		NextTab(1);
//		$("#addconf [name=desc]").get(0).focus();
//		return false;
//	}

	if ($("#addconf [name=mail]").get(0).value.length > 0 && !emailcheck($("#addconf [name=mail]").get(0).value)) {
		alert("Invalid 'Email' format.");
		NextTab(1);
		$("#addconf [name=mail]").get(0).focus();
		return false;
	}
	if (fld_empty_tab(1,$("#addconf [name=org]").get(0),'Organizer')) return false;
	if ($("#addconf [name=fpr]").get(0).value.length > 0 && !numeric($("#addconf [name=fpr]").get(0).value)) {
		alert("'From price' is not numeric");
		NextTab(1);
		$("#addconf [name=fpr]").get(0).focus();
		return false;
	}
	if ($("#addconf [name=tpr]").get(0).value.length > 0) {
		if (!numeric($("#addconf [name=tpr]").get(0).value)) {
			alert("'To price'. is not numeric");
			NextTab(1);
			$("#addconf [name=tpr]").get(0).focus();
			return false;
		}
	}
	if ($("#addconf [name=tpr]").get(0).value.length > 0 && $("#addconf [name=fpr]").get(0).value.length > 0) {
		if (parseInt($("#addconf [name=tpr]").get(0).value) < parseInt($("#addconf [name=fpr]").get(0).value)) {
			alert("'From price' should be lower than 'To price");
			NextTab(1);
			$("#addconf [name=fpr]").get(0).focus();
			return false;
		}
	}
	if ($("#addconf [name=fpr]").get(0).value.length > 0 && $("#addconf [name=fpr]").get(0).value!=0 && $("#addconf [name=cur]").get(0).value=="") {
		alert("'Currency' is missing");
		NextTab(1);
		$("#addconf [name=cur]").get(0).focus();
		return false;
	}	
//	alert ('rl='+rdate.value.length+' pl='+pdate.value.length+' fl='+fdate.value);
	if ($("#addconf [name=rdate]").get(0).value.length>0) {
		if (!chkdate($("#addconf [name=rdate]").get(0),'Early registration',$("#addconf [name=rdate]").get(0),0)) {
			NextTab(1);
			$("#addconf [name=rdate]").get(0).focus();	
			return false;
		}
		if (!compare_dates($("#addconf [name=fdate]").get(0).value,$("#addconf [name=rdate]").get(0).value)) {
			alert("'Early registration' cannot be later than conferece begining.");
			NextTab(1);
			$("#addconf [name=rdate]").get(0).focus();
			return false;     
		}
	}	
	if ($("#addconf [name=pdate]").get(0).value.length>0) {
		if (!chkdate($("#addconf [name=pdate]").get(0),'Abstract submission',$("#addconf [name=pdate]").get(0),0)) {
			NextTab(1);
			$("#addconf [name=pdate]").get(0).focus();	
			return false;
		}
		if (!compare_dates($("#addconf [name=fdate]").get(0).value,$("#addconf [name=pdate]").get(0).value)) {
			alert("'Abstract submission' cannot be later than conference begining.");
			NextTab(1);
			$("#addconf [name=pdate]").get(0).focus();
			return false;     
		}
	}
	
	if ($("#addconf [name=freq]").get(0).value == 0) {
		alert("Frequency is missing.");
		NextTab(1);
		$("#addconf [name=freq]").get(0).focus();
		return false;
	}
	
	var itemsChecked = checkArray(addform, "subjects[]"); // check if there are categries
	if(itemsChecked.length == 0) {
		alert ("Categories are missing");
		NextTab(2,'scroll');
		return false;
	} 

}

function validate_reg (regform) {
	var reg_type=check_radio(regform.regt);
	if (reg_type=="") {
		alert("'Registration type' is missing.");
		return false;
	}
	
	if (fld_empty($("#frm_register [name=reg]").get(0),'Registrant name')) return false;
	if (check_radio(regform.mrms)=="") {
		alert("'Mr. / Ms.' is missing.");
		return false;
	}		
	if (fld_empty($("#frm_register [name=comp]").get(0),'Company name')) return false;
	
	if (fld_empty($("#frm_register [name=mail]").get(0),'E-mail')) return false;
	if ($("#frm_register [name=mail]").get(0).value.length > 0 && !emailcheck($("#frm_register [name=mail]").get(0).value)) {
		alert("'E-mail' format is invalid.");
		$("#frm_register [name=mail]").get(0).focus();
		return false;
	}
	if (fld_empty($("#frm_register [name=tel]").get(0),'Telephone')) return false;
	if ($("#frm_register [name=web]").get(0).value.length > 7 && !urlcheck($("#frm_register [name=web]").get(0).value)) {
		alert("Invalid 'Website' format. Should be http://www.xxx....");
		$("#frm_register [name=web]").get(0).focus();
		return false;
	}
	if ($("#frm_register [name=ctry1]").get(0).value == 0) {
		alert("Missing country.");
		$("#frm_register [name=ctry1]").get(0).focus();
		return false;
	}
	if (fld_empty($("#frm_register [name=adr]").get(0),'Address')) return false;
	if (reg_type==1 && $("#frm_register [name=sqm]").get(0).value.length==0 && $("#frm_register [name=boot]").get(0).value.length==0 && $("#frm_register [name=req]").get(0).value.length==0) {
		alert("'Booth information' is missing.");
		$("#frm_register [name=sqm]").get(0).focus();
		return false;
	}
	if (reg_type==2 && ($("#frm_register [name=sqm]").get(0).value.length>0 || $("#frm_register [name=boot]").get(0).value.length>0 || $("#frm_register [name=req]").get(0).value.length>0)) {
		alert("'Booth information' is for exhibitors only.");
		$("#frm_register [name=sqm]").get(0).focus();
		return false;
	}
	if (reg_type==2 && $("#frm_register [name=fld]").get(0).value.length==0) {
		alert("'Fields of interest' are missing.");
		$("#frm_register [name=sqm]").get(0).focus();
		return false;
	}
	
}



function confirm_action(action) {
	var answer=confirm("Are you sure you want to "+action+" ?\nPress 'OK' to proceed or 'Cancel' to return to form");
	if (answer) return true;
	else return false;
}

function compare_dates(frst_date,scnd_date) {
	var date1 = unprep_date(frst_date);
	var date2 = unprep_date(scnd_date);
	//alert ('a='+date1+' b='+date2);
	if (date1 < date2) {
		return false;
	}	
	else return true;
}

function unprep_date(ndate) {
	var dmy = ndate.split("-");
	var d = new Date();
	d.setFullYear(dmy[2],dmy[1]-1,dmy[0]);
	return d;
}

function prep_date1(ndate,weeks,format)
//format=0 dd-mm-YYYY  ,  format=1 dd-MON-YYYY
{
	var MonthNames = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var oneMinute = 60 * 1000;  // milliseconds in a minute
	var oneHour = oneMinute * 60;
	var oneDay = oneHour * 24;
	var oneWeek = oneDay * 7;
	var dateInMS = ndate.getTime() + oneWeek * weeks;
	var nextDate = new Date(dateInMS);
	var day = nextDate.getDate();
	var m = nextDate.getMonth();
	if (format==1) var month = MonthNames[m];
	else month=m+1;
	var year = nextDate.getFullYear();
	var newdate = day + "-" + month + "-" + year;
	return newdate;
}
function prep_date(now,days)
{
	now.setDate(now.getDate()+days);
	var next = now.getDate() + "-" + (now.getMonth()+1) + "-" + now.getFullYear();
	return(next);
}

function chkdate(ndate,name,tdate,mod) {
	if (!validate_date(ndate.value,name)) return false;
	if (mod==1 && compare_dates(ndate.value,tdate.value)) tdate.value = ndate.value;
	return true;
}

function validate_date(ndate,name) {
	if (ndate=="") return true;
	var re_date = /^\s*(\d{1,2})\-(\d{1,2})\-(\d{4})\s*$/;
	if (!re_date.exec(ndate)) {
		alert ("'"+name+"' is Invalid. Accepted format is dd-mm-yyyy.");
		return false;
	}
	var dmy = ndate.split("-");
	var nday = dmy[0];
	var	nmonth = dmy[1];
	var	nyear = dmy[2];

	if (nmonth < 1 || nmonth > 12) {
		alert ("Invalid month in '"+name+"'.");
		return false;
	}
	var dnumdays = new Date(nyear, nmonth, 0);
	if (nday > dnumdays.getDate()) {
		alert("Invalid day in '"+name+"'. Selected month has only " + dnumdays.getDate() + " days");
		return false;
	}
	return true;
}

function validate_qry (qry_type) {
	//alert(' type='+qry_type);
	// Check if at least one field was selected
	var fields = {
		"gen": ["cat","subj","ctry","event","fdate","tdate"],
		"org": ["orgz","cat","subj","ctry","fdate","tdate"],
		"ven": ["ctry","vnam","fdate","tdate"]
	};
	var str="";
	for (i in fields[qry_type]) {
		var fld = $("#"+fields[qry_type][i]).val();
		if (fld==0) var fld="";
		str += fld;	
	}
	//alert(' str='+str);
	if (str=="") {
		alert("Please select, at least, one search parameter");
		return false;
	}

	if ($("#fdate").get(0).value.length == 0 && $("#tdate").get(0).value.length > 0) {
		alert("'From Date' is missing.");
		$("#fdate").get(0).focus();
		return false;
	}
	if ($("#fdate").get(0).value.length > 0 && $("#tdate").get(0).value.length == 0) {
		alert("'To Date' is missing.");
		$("#tdate").get(0).focus();
		return false;
	}	
	if (!chkdate($("#fdate").get(0),'From date',$("#fdate").get(0),0)) {
		$("#fdate").get(0).focus();
		return false;
	}
	if (!chkdate($("#tdate").get(0),'To date',$("#tdate").get(0),0)) {
		$("#tdate").get(0).focus();
		return false;
	}
	if (!compare_dates($("#tdate").get(0).value,$("#fdate").get(0).value)) {
		alert("'To Date' must be later than 'From Date'.");
		return false;
	}
	// prepare url
	var Url="";
	if (qry_type=="org") Url="organizers";
	if (qry_type=="ven") Url="venues";
	
	for (i_fields in fields[qry_type]) {
		//alert(i_fields+'='+fields[qry_type][i_fields]);
		if (fields[qry_type][i_fields]=="orgz") {
			var Organizer=prep_url($("#orgz option:selected").text(),'-');
			if (Organizer!="" && Organizer!="All") {
				if (Url!="") Url += '/';
				Url += Organizer;
			}
		}
	
		if (fields[qry_type][i_fields]=="cat") {
			var cat=prep_url($("#cat option:selected").text(),'-');
			var subj=prep_url($("#subj option:selected").text(),'-');
			if (cat!="" && cat!='All') {
				if (Url!="") Url += '/';
				Url += "category/"+cat;
				if (subj!="" && subj!='All') Url += "+"+subj;
			}
		}
		
		if (fields[qry_type][i_fields]=="subj" && $("#cat option:selected").text()=="All" && $("#subj option:selected").text()!="All") {
			var subj_a = $("#subj option:selected").text().split(' (');
			var cat = subj_a[1];
			var ipos = cat.indexOf(')');
			cat = prep_url(subj_a[1].substr(0,ipos),'-');
			var subj = prep_url(subj_a[0],'-');
			if (Url!="") Url += '/';
			Url += "category/"+cat+"+"+subj;
		}

		if (fields[qry_type][i_fields]=="ctry") {
			var ctry=prep_url($("#ctry option:selected").text(),'-');
			var stat=prep_url($("#stat option:selected").val(),'-');
			var city=prep_url($("#city option:selected").text(),'-');
			var dist=$("#dist option:selected").val();
			if (ctry!="" && ctry!='All') {
				if (Url!="") Url += '/';
				Url += "country/"+ctry;
				if (ctry=="United-States" && stat!="" && stat!="-1" && stat!="0" && stat!="All") Url += "+"+stat;
				if (city!="0" && city!="" && city!="All") {
					Url += "+"+city;
					if (!empty(dist)) Url += "+"+dist;
				}
			}	
		}
		
		if (fields[qry_type][i_fields]=="event") {
			var Search_text=encodeURIComponent($("#event").val().replace(/&/g,"%26").replace(/\//g,"%2F"));
			if (Search_text!="") {
				if (Url!="") Url += '/';
				Url += "text/"+Search_text;
			}
		}

		if (fields[qry_type][i_fields]=="vnam") {
			var Venue_name=encodeURIComponent($("#vnam").val().replace(/&/g,"%26").replace(/\//g,"%2F"));
			if (Venue_name!="") {
				if (Url!="") Url += '/';
				Url += "text/"+Venue_name;
			}
		}
		
		if (fields[qry_type][i_fields]=="fdate" && $("#fdate").val()!="" && $("#tdate").val()!="") {
			if (Url!="") Url += '/';
			Url += $("#fdate").val()+"+"+$("#tdate").val();
		}
	
		
	} // end of loop	
	
	Url = "/" + Url + "/";
	//alert('url='+Url);
	location.href=Url;
}

function numeric(sText)
{
   var ValidChars = "0123456789.";
   var Char;
   for (i = 0; i < sText.length; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) { 
         return false;
      }
   }
   return true;
}
function ltnum (num)
{
//	var re_date = /^\s*(\d{1,3})\.(\d{1,7})\s*$/;
	var re_date = /^\s*-*\d{1,3}\.\d{1,7}\s*$/;
	if (!re_date.exec(num)) {
		return false;
	}
return true;	
}

function urlcheck(url)
{
     var u= /^http(s?):\/\/[-\w\.]{3,}\.[A-Za-z]{2,3}/;
     return u.test(url);
}

function emailcheck(email)
{      
   var e = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return e.test(email);
}

function phonecheck(phone)
{      
   //var p = /^[0-9]{1,3}[-\s]{1}[0-9]{1,3}[-\s]{1}[0-9]{6,}$/;
	var p = /^[0-9]+[-\s]{1}[0-9]+[-\s]{1}[0-9]+[-\s]*[0-9]*[-\s]*[0-9]*$/;
   return p.test(phone);
}

function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}


function create_keywords(string) 
{
	var text=string.replace(/\W/g," "); // Clean none alpha and none numeric
	text=text.replace(/\d/g," ");   // Clean numeric
	text=text.replace(/(\s\w{1,3}\s)/g," "); // Clean 1-3 letter words
	text=text.replace(/(\s\w{1,3}\s)/g," "); // Clean 1-3 letter words
	text=text.replace(/(\s\w{1,3}\s)/g," "); // Clean 1-3 letter words	
	text=text.replace(/^(\w{1,3}\s)|(\s\w{1,3})$/g," "); // Clean 1-3 letter words
	text=text.replace(/^(\s+)|(\s+)$/g,''); //Clean spaces at the beginning and the end
	text=text.replace(/\s+/g,',');
	return(text);
}
function prep_keywords(element,keywords) {
	keywords.value=create_keywords(element.value);
}

function kH(e) {
	var pK = document.all? window.event.keyCode:e.which;
	return (pK != 13);
}




function popup(url) {
	day = new Date();
	id = day.getTime();
	url=getBaseURL()+url;
	eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=900,height=900');");
}

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 8));

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);
        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

//so backspace doesn't go back
//document.onkeydown = checkForBackspace;
//function checkForBackspace() {
// //we can backspace in a textbox 
// if(window.event.srcElement.type.match("text") || window.event.target.type.match("text")) {
//	 return true;
// }
// 
// if(window.event && window.event.keyCode == 8) {
//	 // try to cancel the backspace
//	 window.event.cancelBubble = true;
//	 window.event.returnValue = false;
//	 return false;
// }
//}

//Every single key press action will call this function.
function shouldCancelbackspace(e) {
	var key;
	if(e){
		key = e.which? e.which : e.keyCode;
		if(key == null || ( key != 8 && key != 13)){ // return when the key is not backspace key.
			return false;
		}
	}
	else{
		return false;
	}

	if (e.srcElement) { // in IE
		tag = e.srcElement.tagName.toUpperCase();
		type = e.srcElement.type;
		readOnly =e.srcElement.readOnly;
		if( type == null){ // Type is null means the mouse focus on a non-form field. disable backspace button
			return true;
		}
		else{
			type = e.srcElement.type.toUpperCase();
		}

	} 
	else { // in FF
		tag = e.target.nodeName.toUpperCase();
		type = (e.target.type) ? e.target.type.toUpperCase() : "";
	}

	// we don't want to cancel the keypress (ever) if we are in an input/text area
	if ( tag == 'inPUT' || type == 'TEXT' || type == 'TEXTAREA' || type == 'PASSWORD') {
		if (e.srcElement) {
			if(readOnly == true ) // if the field has been dsabled, disbale the back space button
				return true;
		}
		if( ((tag == 'inPUT' && type == 'RADIO') || (tag == 'inPUT' && type == 'CHECKBOX'))
		&& (key == 8 || key == 13) ){
			return true; // the mouse is on the radio button/checkbox, disbale the backspace button
		}
		return false;
	}

	// if we are not in one of the above things, then we want to cancel (true) if backspace
	return (key == 8 || key == 13);
}

// check the browser type
function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';

	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0,agt.indexOf('\/'));
		}
		else
			return 'Netscape';
	}
	else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	else
		return navigator.userAgent;
}

// Global events (every key press)

//var browser = whichBrs();
//if(browser == 'internet Explorer'){
//	document.onkeydown = function() { return !shouldCancelbackspace(event); }
//}
//else if(browser == 'firefox'){
//	document.onkeypress = function(e) { return !shouldCancelbackspace(e); }
//}

function check_radio(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function CustomReady(src) {
	if ($("ul.tabs").length > 0) {
		//When page loads...
		$(".tab_content").hide(); //Hide all content
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab_content:first").show(); //Show first tab content
	
		//On Click Event
		AddTabsClick();
	}
	var expandObj = $("div.expand");
	expandObj.toggler();
	
	InitFeedback();
	
	if ($.browser.msie && ($.browser.version == 6))
		$('.fix-z-index').bgiframe(); // Fixes IE6 Z-index issue

	if ($.browser.msie) $(document).ready(OnlyOnReady);
	else OnlyOnReady();
}

function InitFeedback()
{
	$( "#feedback_tabs" ).tabs({
		select : 	function(event, ui) {
						$('#text_area_feedback').hide();
						$('#feedback_form').get(0).reset();
						$('#tabs_subject').val($(ui.tab).attr("value"));
					}
	});
	$(':radio','#feedback_form').click(function() {	$('#text_area_feedback').show(); });
	$( "button", ".feedback_form" ).button().click(function() {	FeedbackSubmit(); });
	
	$('.feedback_form').tabSlideOut({
	    tabHandle: '.handle',                     //class of the element that will become your tab
	    pathToTabImage: '/images/feedback_btn.png', //path to the image for the tab //Optionally can be set using css
	    imageHeight: '125px',                     //height of tab image           //Optionally can be set using css
	    imageWidth: '37px',                       //width of tab image            //Optionally can be set using css
	    tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
	    speed: 300,                               //speed of animation
	    action: 'click',                          //options: 'click' or 'hover', action to trigger animation
	    topPos: '0px',                          //position from the top/ use if tabLocation is left or right
	    //leftPos: '0px',                          //position from left/ use if tabLocation is bottom or top
	    fixedPosition: true                      //options: true makes it stick(fixed position) on scroll
	});
	$(".handle").css("top","255px");
	$('.feedback_form').show();
}

function FeedbackSubmit()
{
	$("#feedback_submit_btn").hide();
	$("#feedback_please_wait").show();
	if (!AjaxSubmitForm('feedback_form',FeedbackCallback)) {
		$("#feedback_please_wait").hide();
		$("#feedback_submit_btn").show();
	}
}

function CommentSubmit(reply)
{
	$("#comment_submit_btn"+reply).hide();
	$("#comment_please_wait"+reply).show();
	var call_back_func = ConfCommentCallback;
	if (!empty(reply)) call_back_func =  ConfCommentCallbackReply;
	if (!AjaxSubmitForm('conf_comments_form'+reply,call_back_func)) {
		$("#comment_please_wait"+reply).hide();
		$("#comment_submit_btn"+reply).show();
	}
}

function ActionsSubmit()
{
	$(".comment_submit_btn").hide();
	$(".comment_please_wait").show();
	var call_back_func = ConfActionsCallback;
	if (!AjaxSubmitForm('conf_actions_form',call_back_func)) {
		$(".comment_please_wait").hide();
		$(".comment_submit_btn").show();
	}
}

function AjaxSubmitForm(form_id, callback_function, ajax_script, disable_validate)
{
	// If diable validate flag is set, skip validation
	if (empty(disable_validate) || !disable_validate) {
		if (!ValidateForm(form_id)) return false;
	}
	if (empty(ajax_script)) ajax_script = "/ajx_submit.php";
	
	$.post(ajax_script, $("#"+form_id).serialize(),
		function(data){
			if (typeof callback_function === 'function') callback_function(data);
			else AjaxSubmitForm_callback(data);
		}, "json"
	);
	return true;
}

function ValidateForm(form_id)
{
	
	// Select all elements without button and hidden parts
	var form_elements = $("#" + form_id + " :input").not(":submit").filter(function() {
		return !($(this).parents(".ca_head").css('display') == 'none');
	});
	
	//Text elements
	var text_elements = form_elements.filter(":text, textarea");
	//console.debug(text_elements);
	for (var i = 0; i < text_elements.length; i++) {
		if (empty(text_elements[i])) continue;
		var cur_element = $(text_elements[i]);
		//Check Empty
		if (!cur_element.hasClass('field_allow_empty') && cur_element.val() === '') {
			alert (cur_element.siblings("label").html().slice(0, -1) + ' field is missing');
			return false;
		}
		if (cur_element.hasClass('field_email') && !empty(cur_element.val()) && !emailcheck(cur_element.val())) {
			alert (cur_element.siblings("label").html().slice(0, -1) + ' format is incorrect');
			return false;	
		}
		if (cur_element.hasClass('field_phone') && !empty(cur_element.val()) && !phonecheck(cur_element.val())) {
			alert (cur_element.siblings("label").html().slice(0, -1) + ' format is incorrect\n\r\n\rShould be:  [Country code]-[Area code]-[Local number]');
			return false;	
		}
		if (cur_element.hasClass('qdate') && !empty(cur_element.val()) && 
		!validate_date(cur_element.val(),cur_element.siblings("label").html().slice(0, -1))) {
			return false;	
		}
		
	}

	//Select elements
	var select_elements = form_elements.filter("select");
	//console.debug(select_elements[1]);
	for (var i = 0; i < select_elements.length; i++) {
		if (empty(select_elements[i])) continue;
		var cur_element = $(select_elements[i]);
		//Check Empty
		if (!cur_element.hasClass('field_allow_empty') && cur_element.get(0).value == 0) {
			alert (cur_element.siblings("label").html().slice(0, -1) + ' field is missing');
			return false;
		}
	}	
	
	//Radio
	var radio_elements = form_elements.filter(":radio");
	for (var i = 0; i < radio_elements.length; i++) {
		var cur_element = $(radio_elements[i]).attr('name');
		// TODO Check if checking is not mandatory
		if ($("input[@name="+cur_element+"]:checked").length) {
			radio_elements = radio_elements.not("input[name="+cur_element+"]:radio");
		}
		else {
			// TODO Return a proper text message
			alert ('Please select one of the options from ' + $("#radio_" + cur_element).siblings("label").html().slice(0, -1)); // A set of radio buttons should have a parent (brother to "Label") with an ID like "radio_"+name of radio button 
			return false;
		}
	}
	//Check boxes
	var checkbox_elements = form_elements.filter(":checkbox");
	for (var i = 0; i < checkbox_elements.length; i++) {
		var cur_element = $(checkbox_elements[i]).attr('name');
		
		if (!$("input[name="+cur_element+"]").hasClass('field_allow_empty') && $("input[@name="+cur_element+"]:checked").length == 0) {
			alert (cur_element.siblings("label").html().slice(0, -1) + ' field is missing');
			return false;
		}
	}

	// TODO Password
	
	
	return true;
}

function AjaxSubmitForm_callback(data,success_msg, error_msg)
{
	if (empty(success_msg)) success_msg = "Form Submitted successfuly, Thank you";
	if (empty(error_msg)) error_msg = "Error in submitting form, please try again later";
	
	if (!empty(data) && (typeof(data["bOK"]) != 'undefined')) {
		if (data["bOK"]) {
			alert(success_msg);
			return true;
		}
		else {
			alert(error_msg+"\n"+data["sMsg"]);
			return false;
		}
	}
	else {
		alert(error_msg);
		return false;
	}
}

function FeedbackCallback(data)
{
	if (AjaxSubmitForm_callback(data, "Thank you for sending us your feedback")) {
		$('#text_area_feedback').hide();
		$('#feedback_form').get(0).reset();
		if ($('.feedback_form.open').length > 0)
			$('.handle').click();
	}
	$("#feedback_please_wait").hide();
	$("#feedback_submit_btn").show();
}

function ConfCommentCallbackReply(data)
{
	ConfCommentCallback(data,"_reply");
}

function ConfCommentCallback(data,reply)
{
	if (empty(reply)) reply = '';
	if (AjaxSubmitForm_callback(data, "Thank you, Your comment will be reviewed and submitted.")) {
		var comments_conf_id = $('#conf_comments_id'+reply).val();
		$('#conf_comments_form'+reply).get(0).reset();
		$('#conf_comments_id'+reply).val(comments_conf_id);
	}
	$("#comment_please_wait"+reply).hide();
	$("#comment_submit_btn"+reply).show();
	if (!empty(reply)){
		$("#conf_comments_reply").dialog("close");
	}
}

function ConfActionsCallback(data)
{
	if (AjaxSubmitForm_callback(data, "Thank you. Your message will be reviewed and handled accordingly.")) {
		var conf_id = $('#conf_id').val();
		$('#conf_actions_form').get(0).reset();
		$('#conf_id').val(conf_id);
	}
	$("#actions_please_wait").hide();
	$("#actions_submit_btn").show();
	$("#conf_actions_form_container").dialog("close");
}

function ConfActionsDialog(type)
{
	var sTitle = "";
	var sContent = "";
	var sSubject = "Subject:";
	$("#conf_actions_form").get(0).reset();

	// Set the default for fields hide and show
	var bHideJobtitle = false;
	var bHideCompany = false;
	var bHideCountry = false;
	var bHideSubject = false;
	var bHideMessage = false;
	var bHidePhone = false;
	var bHideReminder = true;
	var bHideRating = true;
	var bHideLocation = true;
	var bHideRequest = true;
	var bHidePrice = true;
	var bHideCuisine = true;
	var bHideAttraction = true;
	var bHideUpdates = true;
	var bHideGeneralRemarks = true;
	
	$(".field_allow_empty").removeClass("field_allow_empty"); // clear all fields that were not mandatory in the previous form
	
	if ($(".mceEditor").length>0) { // if previous form included TinyMCE
		$('textarea.mceEditor').tinymce().remove(); // clear textarea field from TinyMCE
		$(".mceEditor").removeClass("mceEditor"); 
		$("#actions_content").width("320");
		$("#actions_content").height("80");
	}	
	
	var iDialogH = 400;
	var iDialogW = 490;
	
	switch (type) {

		case "contact_form":
			sTitle = "Contact the Event`s Organizer";
			sContent = "Message:";
			$(document.conf_actions_form.phone).addClass("field_allow_empty");
			$("#request_type").val("4"); // general message to organizer
			break;
	
		case "register_form":
			sTitle = "Request for Registration to the event";
			sContent = "Remarks:";
			bHideSubject = true;
			bHideRequest = false;
			bHideGeneralRemarks = false;
			$("#general_remark").html("Eligible registration requests will be transferred to the organizer");
			var bMandatoryContent = false;
			$(document.conf_actions_form.content).addClass("field_allow_empty");
			iDialogH = 450;
			break;
	
		case "reminder_form":
			sTitle = "Set a Reminder to the event / Recieve Event Updates";
			bHidePhone = true;
			bHideSubject = true;
			bHideMessage = true;
			bHideReminder = false;
			bHideUpdates = false;
			$(document.conf_actions_form.updates).addClass("field_allow_empty");
			iDialogH = 300;
			break;
	
		case "review_form":
			sTitle = "Post a Review to Previous Editions of the Event";
			sContent = "Review:";
			bHidePhone = true;
			bHideSubject = true;
			bHideRating = false;
			break;
	
		case "restaurant_form":
			$("#msg_type").val(1);
			sTitle = "Recommend a Restaurant in the City";
			sContent = "Description:";
			sSubject = "Restaurant Name:";
			bHideJobtitle = true;
			bHideCompany = true;
			bHidePhone = true;
			bHideCountry = true;
			bHideLocation = false;
			bHideRating = false;
			bHidePrice = false;
			bHideCuisine = false;
			iDialogH = 500;
			break;
	
		case "attraction_form":
			$("#msg_type").val(2);
			sTitle = "Recommend a Tourist Attraction around the City";
			sContent = "Description:";
			sSubject = "Attraction Name:";
			bHideJobtitle = true;
			bHideCompany = true;
			bHidePhone = true;
			bHideCountry = true;
			bHideLocation = false;
			bHideRating = false;
			bHideAttraction = false;
			iDialogH = 470;
			break;
	
		case "article_form":
			$("#msg_type").val(2);
			sTitle = "Post an Article";
			sContent = "Article:";
			sSubject = "Subject:";
			$("#actions_content").addClass("mceEditor");
			$("#actions_content").width("428");
			$("#actions_content").height("300");

			$(function() {
                $('textarea.mceEditor').tinymce({
                        // Location of TinyMCE script
                        script_url : '/tiny_mce/tiny_mce.js',

                        // General options
                        theme : "advanced",
                        plugins : "searchreplace",

                        // Theme options
                        theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,|,cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,",
                        theme_advanced_buttons2 : "undo,redo,|,link,unlink,|preview",
                        theme_advanced_buttons3 : "",
                        theme_advanced_toolbar_location : "top",
                        theme_advanced_toolbar_align : "left",
                        theme_advanced_statusbar_location : "none",
                        theme_advanced_resizing : false

                });
			});

			bHidePhone = true;
			bHideGeneralRemarks = false;
			$("#general_remark").html("The article should be original and unique.<br>" +
					"Approved articles are being published on Clocate.com and can be referenced from the conference page and other relevant pages.");
			iDialogH = 670;
			iDialogW = 600;
			break;
			
		default:
			return;
		
	}
	
	$("#conf_actions_form_name").val(type);
	$("#conf_actions_content").html(sContent);
	$("#conf_actions_subject_label").html(sSubject);
	
	$("#conf_actions_jobtitle").toggle(!bHideJobtitle);
	$("#conf_actions_company").toggle(!bHideCompany);
	$("#conf_actions_company").toggle(!bHideCompany);
	$("#conf_actions_country").toggle(!bHideCountry);
	$("#conf_actions_phone").toggle(!bHidePhone);
	$("#conf_actions_reminder").toggle(!bHideReminder);
	$("#conf_actions_subject").toggle(!bHideSubject);
	$("#conf_actions_message").toggle(!bHideMessage);
	$("#conf_actions_rating").toggle(!bHideRating);
	$("#conf_actions_location").toggle(!bHideLocation);
	$("#conf_actions_request").toggle(!bHideRequest);
	$("#conf_actions_price").toggle(!bHidePrice);
	$("#conf_actions_cuisine").toggle(!bHideCuisine);
	$("#conf_actions_attraction").toggle(!bHideAttraction);
	$("#conf_actions_updates").toggle(!bHideUpdates); 
	$("#conf_actions_general_remark").toggle(!bHideGeneralRemarks);
	
	if (!bHideCountry && $("#country option").length<=2) { // create the select options if they do not exist
		prep_select('country','countries',0,'','','Select');
	}
	if (!bHideLocation) {  // create the select options if they do not exist
		if ($("#ctry1 option").length<=2) prep_select('ctry1','countries',0,'',$("#country_code").val(),'Select');
		else $("#ctry1").val($("#country_code").val()).attr('selected',true);
		if ($("#country_code").val()=='US') {
			$("#stat1").removeAttr("disabled");
			if ($("#stat1 option").length<=2) prep_select('stat1','states',0,'',$("#state_code").val(),'Select');
			else $("#stat1").val($("#state_code").val()).attr('selected',true);
		}	
		else $("#stat1").attr("disabled",true);
		prep_select('city1','cities',0,$("#country_code").val()+','+$("#state_code").val(),$("#city_code").val(),'Select');
	}
	
	//if ($.browser.msie && $.browser.version < 8) commentDialogH += 23;
    $("#conf_actions_form_container").dialog({
		modal: true,
	    title: sTitle,
	    draggable: false,
	    resizable: false,
	    autoOpen: true,
	    width: iDialogW,
	    height: iDialogH,
	    open: function() 	{
	    						$(".ui-dialog-title").attr("style", "float: none; display: block; text-align: center;" );
	    					},
	    close: function() 	{ 	
	    						$(".ui-dialog-title").removeAttr("style");
	    					}
   });
}

function ConfCommentReplyDialog(conf, name, disc_id)
{
	var reply_title = (name == "") ? "New Comment" : 'Reply to '+name+"'s comment";
	var commentDialogH = 250;
	//if ($.browser.msie && $.browser.version < 8) commentDialogH += 23;
	
	if ($("#conf_comments_reply").length) {
		$("#conf_comments_reply").dialog("open");
		return;
	}

	$(function ()    {
        $('<div id="conf_comments_reply">').dialog({
		modal: true,
        title: reply_title,
        draggable: false,
        resizable: false,
        autoOpen: true,
        width: 490,
        height: commentDialogH,
        open: function() 	{ 
        						$(this).load('conf_comments_reply.php?conf='+conf, function() {
            						$("#conf_comments_discussion_reply").val(disc_id);
            						$("#conf_comments_form_reply").get(0).reset();
            						$(".ui-dialog-title").attr("style", "float: none; display: block; text-align: center;" );
            						$( "input:submit, a, :button", ".ButtonDiva" ).button();

        						});
        					},
        close: function() 	{ 	
        						$(".ui-dialog-title").removeAttr("style");
        					}
        });
	});
}

function InitMceEditor(buttons,wdt)
{
	buttons2 = "";
	if (buttons=="buttons-a") buttons="bold,italic,underline,|,justifyleft,justifycenter,|,bullist,numlist,|,outdent,indent,|,sub,sup,|,undo,redo,|,search,replace,|,cleanup,removeformat,|,code,help";
	if (buttons=="buttons-b") buttons="bold,italic,underline,|,justifyleft,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,sub,sup,|,help";
	if (buttons=="buttons-c") {
		buttons = "bold,italic,underline,|,justifyleft,justifycenter,|,bullist,numlist,|,outdent,indent,|,sub,sup,|,undo,redo,|,search,replace,|,cleanup,removeformat,|,code,help";
		buttons2 = "link,unlink,|preview";
	}

	tinyMCE.init({
        // General options
        mode : "specific_textareas",
        theme : "advanced",
        editor_selector :"mceEditor",
        gecko_spellcheck : true,
		width : wdt,
		plugins : "searchreplace",
		font_size_style_values : "large",
        // Theme options
        theme_advanced_buttons1 : buttons,
        theme_advanced_buttons2 : buttons2,
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "none"
      
        // Example content CSS (should be your site CSS)
        //content_css : "cnfs.css"

	});	
}

function OnlyOnReady()
{
	if ($(".qdate").length > 0) CreateDatePicker();	
	if ($("#org").length > 0) prep_autocomplete("org");
	if ($("#org_mother_company").length > 0) prep_autocomplete("org_mother_company");
	if ($("#ven").length > 0) prep_autocomplete("ven");
	if ($("#location").length > 0) prep_autocomplete("location");
	if ($("#category").length > 0) prep_autocomplete("category");
	if ($("#event").length > 0) prep_autocomplete("event");
	if ($(".ButtonDiv").length > 0) $("input:submit, a, :button", ".ButtonDiv" ).button();
	if ($(".ButtonDiva").length > 0) $( "input:submit, a, :button", ".ButtonDiva" ).button();
	if ($(".SubjectPicker").length > 0) {
		$(".SubjectPicker").click(function() { 
			var cat = this.id.split("-")[1];
			var count = $("#category-"+cat+"-container").find(":checked").length;
			$("#category-"+cat+"-counter").html("["+count+"]");
		});
	}
	if ($("#scroller_carousel").length > 0) {
		$('#scroller_carousel').carouFredSel({
			width: 985,
			align: false,
			height: 80,
			items: 1,
			scroll: {
				duration: 10000,
				pauseDuration: 0,
				easing: 'linear',
				pauseOnHover: 'immediate'
			}
		});	
	}
}

function setVal(attr,newId, newVal) {
	//alert ('attr='+attr+' newid='+newId+' newVal='+newVal);
	if (attr=="value") $("#"+newId+"_code").attr('value',newVal);
	if (attr=="") $("#"+newId).val(newVal);
}

function prep_autocomplete(pid) {
	var cache = {},
		lastXhr;
	
	$( "#"+pid).autocomplete({
		minLength: 2,
		source: function( request, response ) {
			var term = request.term;
			//var test_cache = term + "+" + pid;
			var params =   {
					term: request.term,
					id: pid
			};
			switch (pid) {
				case 'ven':
					if ($("#city").length > 0) var city = $("#city").val();
					if ($("#city1").length > 0) var city = $("#city1").val();
					params.city = city;
					//test_cache += "+" + city;
					break;
				
			}		

//			if ( test_cache in cache ) {
//				response( cache[ test_cache ] );
//				return;
//			}
						
			lastXhr = $.getJSON( "/ajx_autocomplete.php", params, function( data, status, xhr ) {
				$(this).removeClass("ui-autocomplete-loading");
				//cache[ test_cache ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
			});
		},
		select: function( event, ui ) {
			setVal( "value",pid, ui.item ? ui.item.code : '');
			if (pid=='ven') {
				//setVal( "","add", ui.item ? ui.item.address : '');
				if ($("#add").length > 0) $("#add").html(ui.item.address);
				$(this).data("ven_val",ui.item.label);
			}
			if (pid=='org') {
				setVal( "","oweb", ui.item ? ui.item.org_web : '');
				setVal( "","omail", ui.item ? ui.item.org_mail : '');
				setVal( "","org_mother_company", ui.item ? ui.item.org_mother_company : '');
				$(this).data("org_val",ui.item.label);
			}
			if (pid=='org_mother_company') {
				$(this).data("org_mother_company_val",ui.item.label);
				//alert ('aa='+$(this).val()+' bb='+$(this).data("org_mother_company_val"));
			}
		},
		change: function (event, ui) {
			if ((pid=='category' || pid=='location') && !ui.item) { // clear field if nothing was selected
				$(this).val('');
			}			
		}
	}).change(function(){
		if (pid=='ven' && ($(this).val() != $(this).data("ven_val"))){
			$("#add").html('');
			$(this).data("ven_val",'');
			setVal( "value",'ven', '');
		}
		if (pid=='org' && ($(this).val() != $(this).data("org_val"))) {
			$("#oweb").val('');
			$(this).data("org_val",'');
			setVal( "value",'org', '');
		}
		//if (pid=='org_mother_company') alert ('xx='+$(this).val()+' yy='+$(this).data("org_mother_company_val")+' zz='+$(this).data("org_mother_company_code"));
		if (pid=='org_mother_company' && ($(this).val() != $(this).data("org_mother_company_val"))) {
			$(this).data("org_mother_company_val",'');
			setVal( "value",'org_mother_company','');
		}

	});
}

function AddTabsClick() {
	$("ul.tabs li.clickable").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
	
		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).show(); //Fade in the active ID content
		return false;
	});
}

function gotoTab(level,scroll) {
	var liObj = $("#li_tab" + level);
	//liObj.addClass("clickable");
	//liObj.removeClass("unclickable");
	var labelObj = liObj.find("label");
	//labelObj.html('<a href="#tab' + level + '">' + labelObj.html() + "</a>");
	//AddTabsClick();
	$(".tab_content").hide();
	$("li.active").removeClass("active");
	liObj.addClass("active").show();
	$("#tab" + level).show();
	if (!empty(scroll) && scroll=='scroll') $('html, body').animate({scrollTop:0},'slow');
}

function NextTab(level,scroll)
{
	gotoTab(level,scroll);
	
	$("#tab_button"+level).hide();
	level = (level == 1) ? 2 : 1;
	$("#tab_button" + level).show();
}

function ProfileFinish() {
	if (validate_sub($("#frm_subscribe").get(0))) {
		gotoTab(2);
		var oldButton = $("#sub_btn");
	    var newButton = oldButton.clone();
	    newButton.attr("type", "submit");
	    newButton.attr("id", "sub_btn2");
	    newButton.attr("value","Save");
	    newButton.removeAttr("onclick");
	    newButton.insertBefore(oldButton);
	    oldButton.remove();
	    newButton.attr("id", "sub_btn");
	    $("#upcoming_events").css("height", document.getElementById("frame").offsetHeight);
		$("#frm_subscribe_btn").show();
	}
}

function CreateDatePicker()
{
	$(".qdate").datepicker({ 
			dateFormat: 'dd-mm-yy' ,
			changeMonth: true,
			changeYear: true
	});
}

function CreateYoutubeDialog(div_id)
{
	var youtube_html = '<script type="text/javascript" src="swfobject.js"></script>';
	youtube_html += '<div id="youtube_please_wait" style="text-align:center;padding-top:140px;">';
	youtube_html += '	<img src="images/ajax-loader.gif"><br>';
	youtube_html += '	<label>Loading Video</label>';	
	youtube_html += '</div>';
	youtube_html += '<div id="ytapiplayer">';
	youtube_html += 'You need Flash player 8+ and JavaScript enabled to view this video.';
	youtube_html += '  </div>';
	youtube_html += '  <script type="text/javascript">';
	youtube_html += '	var params = { allowScriptAccess: "always" };';
	youtube_html += '    var atts = { id: "myytplayer" };';
	youtube_html += '	    swfobject.embedSWF("http://www.youtube.com/v/XraGP9hnQJE?enablejsapi=1&playerapiid=ytplayer",'; 
	youtube_html += '	                       "ytapiplayer", "560", "340", "8", null, null, params, atts);';
	youtube_html += '  </script>';
	$("#"+div_id).html(youtube_html);
	$("#"+div_id).dialog({
		modal: true,
	        title: 'Clocate.com Video',
	        draggable: false,
	        resizable: false,
	        autoOpen: true,
	        width: 585,
	        height: 390,
	        open: function() 	{ 
	        						$(".ui-dialog-title").attr("style", "float: none; display: block; text-align: center;" );
	        					},
	        close: function() 	{ 	
	        						$(".ui-dialog-title").removeAttr("style");
	        						$("#"+div_id).html('&nbsp');
	        						//if (!empty(ytplayer)) ytplayer.stopVideo();
	        					}
	});
}

function onYouTubePlayerReady(playerId) {
	$("#youtube_please_wait").html("");
	$("#youtube_please_wait").removeAttr("style");
	var ytplayer = document.getElementById("myytplayer");
	if (!empty(ytplayer)) ytplayer.playVideo();
}

function empty (mixed_var) {
    var key;    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    } 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }        return true;
    }
 
    return false;
}

function checkArray(form, arrayName) {
	var retval = new Array();
	for(var i=0; i < form.elements.length; i++) {
		var el = form.elements[i]; 
		if(el.type == "checkbox" && el.name == arrayName && el.checked) {
			retval.push(el.value);
		}
	} 
	return retval; 
}

function searchArray(item, arrayName) {
	for (var i=0; i < arrayName.length; i++) {
		if (arrayName[i]==item) return i;
	} 
	return -1; 
}

function reverse(s){
    return s.split("").reverse().join("");
}

function xcode(str) {
	str=reverse(btoa(str));
	return str;
}
function ycode(str)
{
	str=atob(reverse(str)); 
	return str;
}

function passwordCheck() {
	var strength = document.getElementById('strength');
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");
	var pwd = document.getElementById("p");
	if (pwd.value.length==0) {
		strength.innerHTML = '';
	} else if (false == enoughRegex.test(pwd.value)) {
		strength.innerHTML = '';
	} else if (strongRegex.test(pwd.value)) {
		strength.innerHTML = '<span style="color:green;">Strong</span>';
	} else if (mediumRegex.test(pwd.value)) {
		strength.innerHTML = '<span style="color:orange;">Medium</span>';
	} else { 
		strength.innerHTML = '<span style="color:red;">Weak</span>';
	}
}

function event_exist(conf_name) {
	$.post("/ajx_chk_conf_name.php",{ cname: conf_name },function(data){data>0?alert ('Event "'+conf_name+'" already exists'):"";});
}

function prep_select(select_id,table_name,sql_code,sql_params,selected_item,option0) {
	//alert ('t='+table_name+' sql='+table_sql+' sel='+selected_item);
	$.post("/ajx_select.php",{ tab: table_name, sqlc: sql_code, sqlp: sql_params, sel: selected_item },
		function(data){
			if (!empty(data)){
				document.getElementById(select_id).options.length = 0; // clear options
				
				var array = data.split(";");
				
				prep_options(select_id,0,option0,0);
				
				for (var i = 0; i < array.length-1; i=i+3) {
			    	prep_options(select_id,array[i],array[i+1],array[i+2]);
			    }				
			}
		}
	);
}

function prep_options(select_id,value,text,selected) {
	var optn = document.createElement("OPTION");
	optn.value = value;
	optn.text = text;
	if (selected==1) optn.selected = true;
	document.getElementById(select_id).options.add(optn);
}

function display_description(conf_code,div_id,mod) {
	if ($("#desc"+div_id).css('display')=='none') {
		$("#show"+div_id).html("Close description");
		if ($("#desc"+div_id).html() == "") {
			$.post("/ajx_display_description.php",{ conf: conf_code, mod: mod },function(data){
				if (!empty(data)){
					$("#desc"+div_id).html(data);
					$("#desc"+div_id).slideToggle();
				}
			});
		}
		else{
			$("#desc"+div_id).slideToggle();
		}
	}
	else {
		$("#show"+div_id).html("Description");
		$("#desc"+div_id).slideToggle();
	}
}

// functions for location and ctegory dialog boxes
$(function() {
	
	var country = $( "#ctry" ),
		state = $( "#stat" ),
		city = $( "#city" ),
		allFields = $( [] ).add( country ).add( state ).add( city ),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}

	function checkValue( o, n) {
		if ( o.val() <= 0 ) {
			o.addClass( "ui-state-error" );
			updateTips( "Missing " + n + "." );
			return false;
		} else {
			return true;
		}
	}

	$( "#dialog-location" ).dialog({
		autoOpen: false,
		height: 280,
		width: 250,
		modal: true,
		resizable: false,
		buttons: {
			"Select": function() {
				allFields.removeClass( "ui-state-error" );

				var bValid = checkValue( country, "Country" );

				if ( bValid ) {
					var ci =  $("#city option:selected").text()!="All"?$("#city option:selected").text()+", ":"";
					var st = $("#stat option:selected").val()!="-1"?$("#stat option:selected").text()+", ":"";
					var co = $("#ctry option:selected").text()!=""?$("#ctry option:selected").text():"";
					$( "#location" ).val ( ci+st+co );
					//$( "#location_code" ).val ( $("#city option:selected").val()+","+$("#stat option:selected").val()+","+$("#ctry option:selected").val() ); 
					$( this ).dialog( "close" );
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
			tips.text("");
		}
	});

	var category = $( "#cat" ),
	subject = $( "#subj" ),
	allFields = $( [] ).add( category ).add( subject ),
	tips = $( ".validateTips" );

	$( "#dialog-category" ).dialog({
		autoOpen: false,
		height: 230,
		width: 250,
		modal: true,
		resizable: false,
		buttons: {
			"Select": function() {
				allFields.removeClass( "ui-state-error" );
				var bValid = checkValue( category, "Category" );

				if ( bValid ) {
					var ca = $("#cat option:selected").text();
					var su = $("#subj option:selected").val()!="" && $("#subj option:selected").text()!="All"?": " + $("#subj option:selected").text():"";
					$( "#category" ).val ( ca+su );
					link="category/"+ca+"+"+su;
					
					$( "#category_code" ).val ( $("#cat option:selected").val()+","+$("#subj option:selected").val() );
					$( this ).dialog( "close" );
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
			tips.text("");
		}
	});

});

function getresults(type) {
	//alert(' type='+type);
	// Check if at least one field was selected
	var fields = {
		"search_confs": ["category","event","location","fdate","tdate"],
		"search_orgs": ["orgz","category","location","fdate","tdate"],
		"search_venues": ["location","fdate","tdate","vnam"]
	};
	var str="";
	for (i in fields[type]) {
		str += $("#"+fields[type][i]).val();	
	}
	if (str=="") {
		alert("Please select, at least, one search parameter");
		return false;
	}

	// check dates
	if (!check_dates($("#fdate").val(),$("#tdate").val())) return false;
	
	// prepare url
	var Url="";
	if (type=="search_orgs") Url="organizer";
	if (type=="search_venues") Url="venue";
	
	for (i_fields in fields[type]) {
		//alert(i_fields+'='+fields[type][i_fields]);
		if (fields[type][i_fields]=="orgz") {
			var Organizer=prep_url($("#orgz option:selected").text(),'-');
			if (Organizer!="" && Organizer!="All") {
				if (Url!="") Url += '/';
				Url += Organizer;
			}
		}
	
		if (fields[type][i_fields]=="category") {
			var Category=$("#category").val().split(': ');
			if (Category.length>0 && !empty(Category[0])) {
				for (i=0;i<Category.length;i++) {
					Category[i] = prep_url(Category[i],'-');
				}
				if (Url!="") Url += '/';
				Url += "category/"+Category.join('+');
			}
		}
		
		if (fields[type][i_fields]=="location") {
			var Location=$("#location").val().split(', ');
			if (Location.length>0 && !empty(Location[0])) {
				for (i=0;i<Location.length;i++) {
					Location[i] = prep_url(Location[i],'-');
				}
				if (Url!="") Url += '/';
				Url += "country/"+Location.reverse().join('+');
				if (type=="search_confs" && $("#dist").val()>0) Url += "+" + ($("#dist").val());
			}
		}
		if (fields[type][i_fields]=="event") {
			var Search_text=prep_url($("#event").val(),'+');
			if (Search_text!="") {
				if (Url!="") Url += '/';
				Url += "text/"+Search_text;
			}
		}
		if (fields[type][i_fields]=="fdate" && $("#fdate").val()!="" && $("#tdate").val()!="") {
			if (Url!="") Url += '/';
			Url += $("#fdate").val()+"+"+$("#tdate").val();
		}
	
		if (fields[type][i_fields]=="vnam") {
			var Venue_name=prep_url($("#vnam").val(),'+');
			if (Venue_name!="") {
				if (Url!="") Url += '/';
				Url += "text/"+Venue_name;
			}
		}
		
	} // end of loop	
	
	Url += '/';
	alert('url='+Url);
	location.href=Url;
	
}

function prep_url(Url,delimiter) {
	Url=Url.replace(/&/g,'and');
	Url=Url.replace(/[^\w\/+]/g,' ');
	Url=Url.replace(/[^(\x20-\x7F)]*/g,''); // remove none ascii characters
	Url=Url.replace(/^\s+|\s+$/g,""); // trim
	Url=Url.replace(/\s+/g,delimiter);
	return(Url);
}

function check_dates(fdate,tdate) {
	if (fdate=="" && tdate!="") {
		alert("'From Date' is missing.");
		$("#fdate").focus();
		return false;
	}
	if (fdate!="" && tdate=="") {
		alert("'To Date' is missing.");
		$("#tdate").focus();
		return false;
	}	
	if (!validate_date(fdate,'From date')) {
		$("#fdate").focus();
		return false;
	}
	if (!validate_date(tdate,'To date')) {
		$("#tdate").focus();
		return false;
	}
	if (!compare_dates(tdate,fdate)) {
		alert("'To Date' must be later than 'From Date'.");
		return false;
	}
	return true;
}

function switch_search(type) {
	var button_html = '<input type="submit" value="SEARCH" style="height:28px;width:90px;font-size:14px;font-weight:bold;" onclick="getresults(';
	switch(type) {
	
		case 'search_confs':
			$('#orgz_div').hide();
			$('#vnam_div').hide();
			$('#category_div').show();
			$('#text_div').show();
			$('#location_div').show();
			$('#dist_div').show();
			$('#fdate_div').show();
			$('#tdate_div').show();
			$('#tdate').css('margin-right',10);
			$('#search_button').html(button_html+'\'search_confs\');">');
			break;

		case 'search_orgs':
			$('#orgz_div').show();
			$('#vnam_div').hide();
			$('#category_div').show();
			$('#text_div').hide();
			$('#location_div').show();
			$('#dist_div').hide();
			$('#fdate_div').show();
			$('#tdate_div').show();
			$('#tdate').css('margin-right',70);
			$('#search_button').html(button_html+'\'search_orgs\');">');
			break;

		case 'search_venues':
			$('#orgz_div').hide();
			$('#vnam_div').show();
			$('#category_div').hide();
			$('#text_div').hide();
			$('#location_div').show();
			$('#dist_div').hide();
			$('#fdate_div').show();
			$('#tdate_div').show();
			$('#tdate').css('margin-right',10);
			$('#search_button').html(button_html+'\'search_venues\');">');
			break;
	
	}
}

$(function(){
// Ignore backspace in a select field	
	var BACKSPACE_KEY = 8; 
    // Firefox backspace (select dropdown)
    $("select").keypress(function(e){
        if (e.which == BACKSPACE_KEY) return false;
   });

    // IE backspace
   $(document).keydown(function(){
        // Make sure it is ie
        if (typeof window.event != 'undefined'){
            skipBackspaceKey = false;
           // Lets first to check that it is a backspace key that was pushed
          if (event.keyCode == BACKSPACE_KEY)
           {
             // Now let's check to see if it is on a select dropdown
              if (event.srcElement.type == "select-one")
              {
                skipBackspaceKey = true;
              }
            }
            return (!skipBackspaceKey);
        } // end if
        });
});

// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 1000;
$(function() {
	$( "#dialog_description" ).dialog({
		autoOpen: false,
		width: 600,
		resizable: false
	});
	$( "#dialog_exhibit_fees" ).dialog({
		autoOpen: false,
		width: 700,
		resizable: false
	});
	$( "#dialog_visitor_fees" ).dialog({
		autoOpen: false,
		width: 700,
		resizable: false
	});
	$( "#dialog_floor_plan" ).dialog({
		autoOpen: false,
		width: 700,
		resizable: false
	});
	$( "#dialog_image_s" ).dialog({
		autoOpen: false,
		width: 520,
		resizable: false
	});
	$( "#dialog_image_a" ).dialog({
		autoOpen: false,
		width: 520,
		resizable: false
	});


	$( "#opener" ).click(function() {
		$.post("/ajx_display_description.php",{ conf: $("#conf_code").val(), mod: $("#desc_mod").val() },function(data){
			if (!empty(data)){
				$("#dialog_description").html(data);
			}
		});
		$( "#dialog_description" ).dialog( "open" );
		return false;
	});
	$( "#image_standard" ).click(function() {
		$.post("/ajx_display_image.php",{ img: $("#image_name").val() },function(data){
			if (!empty(data)){
				var pos = data.search('height="');
				var len = data.substr(pos+8).search('"');
				var height_div = data.substr(pos+8,len);
				$("#dialog_image_s").height(height_div);
				$("#dialog_image_s").html(data);
			}
		});
		$( "#dialog_image_s" ).dialog( "open" );
		return false;
	});
	$( "#image_advanced" ).click(function() {
		$.post("/ajx_display_image.php",{ img: $("#image_name").val() },function(data){
			if (!empty(data)){
				var pos = data.search('height="');
				var len = data.substr(pos+8).search('"');
				var height_div = data.substr(pos+8,len);
				$("#dialog_image_a").height(height_div);
				$("#dialog_image_a").html(data);
			}
		});
		$( "#dialog_image_a" ).dialog( "open" );
		return false;
	});
	$( "#exhibit_fees" ).click(function() {
		$.post("/ajx_popup.php",{ conf: $("#conf_code").val(), typ: 1 },function(data){
			if (!empty(data)){
				$("#dialog_exhibit_fees").html(data);
			}
		});
		$( "#dialog_exhibit_fees" ).dialog( "open" );
		return false;
	});
	$( "#visitor_fees" ).click(function() {
		$.post("/ajx_popup.php",{ conf: $("#conf_code").val(), typ: 2 },function(data){
			if (!empty(data)){
				$("#dialog_visitor_fees").html(data);
			}
		});
		$( "#dialog_visitor_fees" ).dialog( "open" );
		return false;
	});
	$( "#floor_plan" ).click(function() {
		$.post("/ajx_popup.php",{ conf: $("#conf_code").val(), typ: 3 },function(data){
			if (!empty(data)){
				$("#dialog_floor_plan").html(data);
			}
		});
		$( "#dialog_floor_plan" ).dialog( "open" );
		return false;
	});

});

function ArticleSlide(id)
{
	$("#" + id).slideToggle(null,function() {
		$("#content").css("height","");
		$("#upcoming_events").css("height","");
		
		var conHeight = document.getElementById("content").offsetHeight;
		var upHeight = document.getElementById("upcoming_events").offsetHeight;
		
		if (conHeight<upHeight) divHeight=upHeight;
		else divHeight=conHeight;
		
		strHeight=divHeight+"px";
		document.getElementById("content").style.height = strHeight;
		document.getElementById("upcoming_events").style.height = strHeight;		
	});

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* --- BoxOver ---
/* --- v 2.1 17th June 2006
By Oliver Bryant with help of Matthew Tagg
http://boxover.swazz.org */

if (typeof document.attachEvent!='undefined') {
   window.attachEvent('onload',init);
   document.attachEvent('onmousemove',moveMouse);
   document.attachEvent('onclick',checkMove); }
else {
   window.addEventListener('load',init,false);
   document.addEventListener('mousemove',moveMouse,false);
   document.addEventListener('click',checkMove,false);
}

var oDv=document.createElement("div");
var dvHdr=document.createElement("div");
var dvBdy=document.createElement("div");
var windowlock,boxMove,fixposx,fixposy,lockX,lockY,fixx,fixy,ox,oy,boxLeft,boxRight,boxTop,boxBottom,evt,mouseX,mouseY,boxOpen,totalScrollTop,totalScrollLeft;
boxOpen=false;
ox=10;
oy=10;
lockX=0;
lockY=0;

function init() {
	oDv.appendChild(dvHdr);
	oDv.appendChild(dvBdy);
	oDv.style.position="absolute";
	oDv.style.visibility='hidden';
	document.body.appendChild(oDv);	
}

function defHdrStyle() {
	dvHdr.innerHTML='<img  style="vertical-align:middle"  src="/images/info.gif">&nbsp;&nbsp;'+dvHdr.innerHTML;
	dvHdr.style.fontWeight='bold';
	dvHdr.style.width='150px';
	dvHdr.style.fontFamily='arial';
	dvHdr.style.border='1px solid #A5CFE9';
	dvHdr.style.padding='3px';
	dvHdr.style.fontSize='11px';
	dvHdr.style.color='#4B7A98';
	dvHdr.style.background='#D5EBF9';
	dvHdr.style.filter='alpha(opacity=100)'; // IE
	dvHdr.style.opacity='1'; // FF
}

function defBdyStyle() {
	dvBdy.style.borderBottom='1px solid #A5CFE9';
	dvBdy.style.borderLeft='1px solid #A5CFE9';
	dvBdy.style.borderRight='1px solid #A5CFE9';
	dvBdy.style.width='150px';
	dvBdy.style.fontFamily='arial';
	dvBdy.style.fontSize='11px';
	dvBdy.style.padding='3px';
	dvBdy.style.color='#1B4966';
	dvBdy.style.background='#FFFFFF';
	dvBdy.style.filter='alpha(opacity=100)'; // IE
	dvBdy.style.opacity='1'; // FF
}

function checkElemBO(txt) {
if (!txt || typeof(txt) != 'string') return false;
if ((txt.indexOf('header')>-1)&&(txt.indexOf('body')>-1)&&(txt.indexOf('[')>-1)&&(txt.indexOf('[')>-1)) 
   return true;
else
   return false;
}

function scanBO(curNode) {
	  if (checkElemBO(curNode.title)) {
         curNode.boHDR=getParam('header',curNode.title);
         curNode.boBDY=getParam('body',curNode.title);
			curNode.boCSSBDY=getParam('cssbody',curNode.title);			
			curNode.boCSSHDR=getParam('cssheader',curNode.title);
			curNode.IEbugfix=(getParam('hideselects',curNode.title)=='on')?true:false;
			curNode.fixX=parseInt(getParam('fixedrelx',curNode.title));
			curNode.fixY=parseInt(getParam('fixedrely',curNode.title));
			curNode.absX=parseInt(getParam('fixedabsx',curNode.title));
			curNode.absY=parseInt(getParam('fixedabsy',curNode.title));
			curNode.offY=(getParam('offsety',curNode.title)!='')?parseInt(getParam('offsety',curNode.title)):10;
			curNode.offX=(getParam('offsetx',curNode.title)!='')?parseInt(getParam('offsetx',curNode.title)):10;
			curNode.fade=(getParam('fade',curNode.title)=='on')?true:false;
			curNode.fadespeed=(getParam('fadespeed',curNode.title)!='')?getParam('fadespeed',curNode.title):0.04;
			curNode.delay=(getParam('delay',curNode.title)!='')?parseInt(getParam('delay',curNode.title)):0;
			if (getParam('requireclick',curNode.title)=='on') {
				curNode.requireclick=true;
				document.all?curNode.attachEvent('onclick',showHideBox):curNode.addEventListener('click',showHideBox,false);
				document.all?curNode.attachEvent('onmouseover',hideBox):curNode.addEventListener('mouseover',hideBox,false);
			}
			else {// Note : if requireclick is on the stop clicks are ignored   			
   			if (getParam('doubleclickstop',curNode.title)!='off') {
   				document.all?curNode.attachEvent('ondblclick',pauseBox):curNode.addEventListener('dblclick',pauseBox,false);
   			}	
   			if (getParam('singleclickstop',curNode.title)=='on') {
   				document.all?curNode.attachEvent('onclick',pauseBox):curNode.addEventListener('click',pauseBox,false);
   			}
   		}
			curNode.windowLock=getParam('windowlock',curNode.title).toLowerCase()=='off'?false:true;
			curNode.title='';
			curNode.hasbox=1;
	   }
	   else
	      curNode.hasbox=2;   
}


function getParam(param,list) {
	var reg = new RegExp('([^a-zA-Z]' + param + '|^' + param + ')\\s*=\\s*\\[\\s*(((\\[\\[)|(\\]\\])|([^\\]\\[]))*)\\s*\\]');
	var res = reg.exec(list);
	var returnvar;
	if(res)
		return res[2].replace('[[','[').replace(']]',']');
	else
		return '';
}

function Left(elem){	
	var x=0;
	if (elem.calcLeft)
		return elem.calcLeft;
	var oElem=elem;
	while(elem){
		 if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderLeftWidth)))&&(x!=0))
		 	x+=parseInt(elem.currentStyle.borderLeftWidth);
		 x+=elem.offsetLeft;
		 elem=elem.offsetParent;
	  } 
	oElem.calcLeft=x;
	return x;
	}

function Top(elem){
	 var x=0;
	 if (elem.calcTop)
	 	return elem.calcTop;
	 var oElem=elem;
	 while(elem){		
	 	 if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderTopWidth)))&&(x!=0))
		 	x+=parseInt(elem.currentStyle.borderTopWidth); 
		 x+=elem.offsetTop;
	         elem=elem.offsetParent;
 	 } 
 	 oElem.calcTop=x;
 	 return x;
 	 
}

var ah,ab;
function applyStyles() {
	if(ab)
		oDv.removeChild(dvBdy);
	if (ah)
		oDv.removeChild(dvHdr);
	dvHdr=document.createElement("div");
	dvBdy=document.createElement("div");
	CBE.boCSSBDY?dvBdy.className=CBE.boCSSBDY:defBdyStyle();
	CBE.boCSSHDR?dvHdr.className=CBE.boCSSHDR:defHdrStyle();
	dvHdr.innerHTML=CBE.boHDR;
	dvBdy.innerHTML=CBE.boBDY;
	ah=false;
	ab=false;
	if (CBE.boHDR!='') {		
		oDv.appendChild(dvHdr);
		ah=true;
	}	
	if (CBE.boBDY!=''){
		oDv.appendChild(dvBdy);
		ab=true;
	}	
}

var CSE,iterElem,LSE,CBE,LBE, totalScrollLeft, totalScrollTop, width, height ;
var ini=false;

// Customised function for inner window dimension
function SHW() {
   if (document.body && (document.body.clientWidth !=0)) {
      width=document.body.clientWidth;
      height=document.body.clientHeight;
   }
   if (document.documentElement && (document.documentElement.clientWidth!=0) && (document.body.clientWidth + 20 >= document.documentElement.clientWidth)) {
      width=document.documentElement.clientWidth;   
      height=document.documentElement.clientHeight;   
   }   
   return [width,height];
}


var ID=null;
function moveMouse(e) {
   //boxMove=true;
	e?evt=e:evt=event;
	
	CSE=evt.target?evt.target:evt.srcElement;
	
	if (!CSE.hasbox) {
	   // Note we need to scan up DOM here, some elements like TR don't get triggered as srcElement
	   iElem=CSE;
	   while ((iElem.parentNode) && (!iElem.hasbox)) {
	      scanBO(iElem);
	      iElem=iElem.parentNode;
	   }	   
	}
	
	if ((CSE!=LSE)&&(!isChild(CSE,dvHdr))&&(!isChild(CSE,dvBdy))){		
	   if (!CSE.boxItem) {
			iterElem=CSE;
			while ((iterElem.hasbox==2)&&(iterElem.parentNode))
					iterElem=iterElem.parentNode; 
			CSE.boxItem=iterElem;
			}
		iterElem=CSE.boxItem;
		if (CSE.boxItem&&(CSE.boxItem.hasbox==1))  {
			LBE=CBE;
			CBE=iterElem;
			if (CBE!=LBE) {
				applyStyles();
				if (!CBE.requireclick)
					if (CBE.fade) {
						if (ID!=null)
							clearTimeout(ID);
						ID=setTimeout("fadeIn("+CBE.fadespeed+")",CBE.delay);
					}
					else {
						if (ID!=null)
							clearTimeout(ID);
						COL=1;
						ID=setTimeout("oDv.style.visibility='visible';ID=null;",CBE.delay);						
					}
				if (CBE.IEbugfix) {hideSelects();} 
				fixposx=!isNaN(CBE.fixX)?Left(CBE)+CBE.fixX:CBE.absX;
				fixposy=!isNaN(CBE.fixY)?Top(CBE)+CBE.fixY:CBE.absY;			
				lockX=0;
				lockY=0;
				boxMove=true;
				ox=CBE.offX?CBE.offX:10;
				oy=CBE.offY?CBE.offY:10;
			}
		}
		else if (!isChild(CSE,dvHdr) && !isChild(CSE,dvBdy) && (boxMove))	{
			// The conditional here fixes flickering between tables cells.
			if ((!isChild(CBE,CSE)) || (CSE.tagName!='TABLE')) {   			
   			CBE=null;
   			if (ID!=null)
  					clearTimeout(ID);
   			fadeOut();
   			showSelects();
			}
		}
		LSE=CSE;
	}
	else if (((isChild(CSE,dvHdr) || isChild(CSE,dvBdy))&&(boxMove))) {
		totalScrollLeft=0;
		totalScrollTop=0;
		
		iterElem=CSE;
		while(iterElem) {
			if(!isNaN(parseInt(iterElem.scrollTop)))
				totalScrollTop+=parseInt(iterElem.scrollTop);
			if(!isNaN(parseInt(iterElem.scrollLeft)))
				totalScrollLeft+=parseInt(iterElem.scrollLeft);
			iterElem=iterElem.parentNode;			
		}
		if (CBE!=null) {
			boxLeft=Left(CBE)-totalScrollLeft;
			boxRight=parseInt(Left(CBE)+CBE.offsetWidth)-totalScrollLeft;
			boxTop=Top(CBE)-totalScrollTop;
			boxBottom=parseInt(Top(CBE)+CBE.offsetHeight)-totalScrollTop;
			doCheck();
		}
	}
	
	if (boxMove&&CBE) {
		// This added to alleviate bug in IE6 w.r.t DOCTYPE
		bodyScrollTop=document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;
		bodyScrollLet=document.documentElement&&document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft;
		mouseX=evt.pageX?evt.pageX-bodyScrollLet:evt.clientX-document.body.clientLeft;
		mouseY=evt.pageY?evt.pageY-bodyScrollTop:evt.clientY-document.body.clientTop;
		if ((CBE)&&(CBE.windowLock)) {
			mouseY < -oy?lockY=-mouseY-oy:lockY=0;
			mouseX < -ox?lockX=-mouseX-ox:lockX=0;
			mouseY > (SHW()[1]-oDv.offsetHeight-oy)?lockY=-mouseY+SHW()[1]-oDv.offsetHeight-oy:lockY=lockY;
			mouseX > (SHW()[0]-dvBdy.offsetWidth-ox)?lockX=-mouseX-ox+SHW()[0]-dvBdy.offsetWidth:lockX=lockX;			
		}
		oDv.style.left=((fixposx)||(fixposx==0))?fixposx:bodyScrollLet+mouseX+ox+lockX+"px";
		oDv.style.top=((fixposy)||(fixposy==0))?fixposy:bodyScrollTop+mouseY+oy+lockY+"px";		
		
	}
}

function doCheck() {	
	if (   (mouseX < boxLeft)    ||     (mouseX >boxRight)     || (mouseY < boxTop) || (mouseY > boxBottom)) {
		if (!CBE.requireclick)
			fadeOut();
		if (CBE.IEbugfix) {showSelects();}
		CBE=null;
	}
}

function pauseBox(e) {
   e?evt=e:evt=event;
	boxMove=false;
	evt.cancelBubble=true;
}

function showHideBox(e) {
	oDv.style.visibility=(oDv.style.visibility!='visible')?'visible':'hidden';
}

function hideBox(e) {
	oDv.style.visibility='hidden';
}

var COL=0;
var stopfade=false;
function fadeIn(fs) {
		ID=null;
		COL=0;
		oDv.style.visibility='visible';
		fadeIn2(fs);
}

function fadeIn2(fs) {
		COL=COL+fs;
		COL=(COL>1)?1:COL;
		oDv.style.filter='alpha(opacity='+parseInt(100*COL)+')';
		oDv.style.opacity=COL;
		if (COL<1)
		 setTimeout("fadeIn2("+fs+")",20);		
}


function fadeOut() {
	oDv.style.visibility='hidden';
	
}

function isChild(s,d) {
	while(s) {
		if (s==d) 
			return true;
		s=s.parentNode;
	}
	return false;
}

var cSrc;
function checkMove(e) {
	e?evt=e:evt=event;
	cSrc=evt.target?evt.target:evt.srcElement;
	if ((!boxMove)&&(!isChild(cSrc,oDv))) {
		fadeOut();
		if (CBE&&CBE.IEbugfix) {showSelects();}
		boxMove=true;
		CBE=null;
	}
}

function showSelects(){
   var elements = document.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
      elements[i].style.visibility='visible';
   }
}

function hideSelects(){
   var elements = document.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
   elements[i].style.visibility='hidden';
   }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//// slideToggle.js

/* ---------------------------------------------
expandAll v.1.3.8
http://www.adipalaz.com/experiments/jquery/expand.html
Requires: jQuery v1.3+
Copyright (c) 2009 Adriana Palazova
Dual licensed under the MIT (http://www.adipalaz.com/docs/mit-license.txt) and GPL (http://www.adipalaz.com/docs/gpl-license.txt) licenses
------------------------------------------------ */
(function($) {
$.fn.expandAll = function(options) {
    var o = $.extend({}, $.fn.expandAll.defaults, options);   
    
    return this.each(function(index) {
        var $$ = $(this), $referent, $sw, $cllps, $tr, container, toggleTxt, toggleClass;
               
        // --- functions:
       (o.switchPosition == 'before') ? ($.fn.findSibling = $.fn.prev, $.fn.insrt = $.fn.before) : ($.fn.findSibling = $.fn.next, $.fn.insrt = $.fn.after);
                    
        // --- var container 
        if (this.id.length) { container = '#' + this.id;
        } else if (this.className.length) { container = this.tagName.toLowerCase() + '.' + this.className.split(' ').join('.');
        } else { container = this.tagName.toLowerCase();}
        
        // --- var $referent
        if (o.ref && $$.find(o.ref).length) {
          (o.switchPosition == 'before') ? $referent = $$.find("'" + o.ref + ":first'") : $referent = $$.find("'" + o.ref + ":last'");
        } else { return; }
        
        // end the script if the length of the collapsible element isn't long enough.  
        if (o.cllpsLength && $$.closest(container).find(o.cllpsEl).text().length < o.cllpsLength) {$$.closest(container).find(o.cllpsEl).addClass('dont_touch'); return;}
    
        // --- if expandAll() claims initial state = hidden:
        (o.initTxt == 'show') ? (toggleTxt = o.expTxt, toggleClass='') : (toggleTxt = o.cllpsTxt, toggleClass='open');
        if (o.state == 'hidden') { 
          $$.find(o.cllpsEl + ':not(.shown, .dont_touch)').hide().findSibling().find('> a.open').removeClass('open'); 
        } else {
          $$.find(o.cllpsEl).show().findSibling().find('> a').addClass('open'); 
        }
        
        (o.oneSwitch) ? ($referent.insrt('<p class="switch"><a href="#" class="' + toggleClass + '">' + toggleTxt + '</a></p>')) :
          ($referent.insrt('<p class="switch"><a href="#" class="">' + o.expTxt + '</a>&nbsp;|&nbsp;<a href="#" class="open">' + o.cllpsTxt + '</a></p>'));

        // --- var $sw, $cllps, $tr :
        $sw = $referent.findSibling('p').find('a');
        $cllps = $$.closest(container).find(o.cllpsEl).not('.dont_touch');
        if (o.trigger) {$tr = $$.closest(container).find(o.trigger + ' > a');}
                
        if (o.child) {
          $$.find(o.cllpsEl + '.shown').show().findSibling().find('> a').addClass('open').text(o.cllpsTxt);
          window.$vrbls = { kt1 : o.expTxt, kt2 : o.cllpsTxt };
        }

        var scrollElem;
        (typeof scrollableElement == 'function') ? (scrollElem = scrollableElement('html', 'body')) : (scrollElem = 'html, body');
        
        $sw.click(function() {
            var $switch = $(this),
                $c = $switch.closest(container).find(o.cllpsEl +':first'),
                cOffset = $c.offset().top;
            if (o.parent) {
              var $swChildren = $switch.parent().nextAll().children('p.switch').find('a');
                  kidTxt1 = $vrbls.kt1, kidTxt2 = $vrbls.kt2,
                  kidTxt = ($switch.text() == o.expTxt) ? kidTxt2 : kidTxt1;
              $swChildren.text(kidTxt);
              if ($switch.text() == o.expTxt) {$swChildren.addClass('open');} else {$swChildren.removeClass('open');}
            }
            if ($switch.text() == o.expTxt) {
              if (o.oneSwitch) {$switch.text(o.cllpsTxt).attr('class', 'open');}
              $tr.addClass('open');
              $cllps[o.showMethod](o.speed);
            } else {
              if (o.oneSwitch) {$switch.text(o.expTxt).attr('class', '');}
              $tr.removeClass('open');
              if (o.speed == 0 || o.instantHide) {$cllps.hide();} else {$cllps[o.hideMethod](o.speed);}
              if (o.scroll && cOffset < $(window).scrollTop()) {$(scrollElem).animate({scrollTop: cOffset},600);}
          }
          return false;
        });
        /* -----------------------------------------------
        To save file size, feel free to remove the following code if you don't use the option: 'localLinks: true'
        -------------------------------------------------- */
        if (o.localLinks) { 
          var localLink = $(container).find(o.localLinks);
          if (localLink.length) {
            // based on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
            $(localLink).click(function() {
              var $target = $(this.hash);
              $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
              if ($target.length) {
                var tOffset = $target.offset().top;
                $(scrollElem).animate({scrollTop: tOffset},600);
                return false;
              }
            });
          }
        }
        /* -----------------------------------------------
        Feel free to remove the following function if you don't use the options: 'localLinks: true' or 'scroll: true'
        -------------------------------------------------- */
        //http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
        function scrollableElement(els) {
          for (var i = 0, argLength = arguments.length; i < argLength; i++) {
            var el = arguments[i],
                $scrollElement = $(el);
            if ($scrollElement.scrollTop() > 0) {
              return el;
            } else {
              $scrollElement.scrollTop(1);
              var isScrollable = $scrollElement.scrollTop() > 0;
              $scrollElement.scrollTop(0);
              if (isScrollable) {
                return el;
              }
            }
          };
          return [];
        }; 
      /* --- end of the optional code --- */
});};
$.fn.expandAll.defaults = {
        state : 'hidden', // If 'hidden', the collapsible elements are hidden by default, else they are expanded by default 
        initTxt : 'show', // 'show' - if the initial text of the switch is for expanding, 'hide' - if the initial text of the switch is for collapsing
        expTxt : '[Expand All]', // the text of the switch for expanding
        cllpsTxt : '[Collapse All]', // the text of the switch for collapsing
        oneSwitch : true, // true or false - whether both [Expand All] and [Collapse All] are shown, or they swap
        ref : '.expand', // the switch 'Expand All/Collapse All' is inserted in regards to the element specified by 'ref'
        switchPosition: 'before', //'before' or 'after' - specifies the position of the switch 'Expand All/Collapse All' - before or after the collapsible element
        scroll : false, // false or true. If true, the switch 'Expand All/Collapse All' will be dinamically repositioned to remain in view when the collapsible element closes
        showMethod : 'slideDown', // 'show', 'slideDown', 'fadeIn', or custom
        hideMethod : 'slideUp', // 'hide', 'slideUp', 'fadeOut', or custom
        speed : 600, // the speed of the animation in m.s. or 'slow', 'normal', 'fast'
        cllpsEl : '.collapse', // the collapsible element
        trigger : '.expand', // if expandAll() is used in conjunction with toggle() - the elements that contain the trigger of the toggle effect on the individual collapsible sections
        localLinks : null, // null or the selector of the same-page links to which we will apply a smooth-scroll function, e.g. 'a.to_top'
        parent : false, // true, false
        child : false, // true, false
        cllpsLength : null, //null, {Number}. If {Number} (e.g. cllpsLength: 200) - if the number of characters inside the "collapsible element" is less than the given {Number}, the element will be visible all the time
        instantHide : false // {true} fixes hiding content inside hidden elements
};

/* ---------------------------------------------
Toggler - http://www.adipalaz.com/experiments/jquery/expand.html
When using this script, please keep the above url intact.
*** Feel free to remove the Toggler script if you need only the plugin expandAll().
------------------------------------------------ */
$.fn.toggler = function(options) {
    var o = $.extend({}, $.fn.toggler.defaults, options);
    
    var $this = $(this);
    $this.wrapInner('<a style="display:block" href="#" title="Expand/Collapse" />');
    if (o.initShow) {$(o.initShow).addClass('shown');}
    $this.next(o.cllpsEl + ':not(.shown)').hide();
    return this.each(function() {
      var container;
      (o.container) ? container = o.container : container = 'html';
      if ($this.next('div.shown').length) { $this.closest(container).find('.shown').show().prev().find('a').addClass('open'); }
      $(this).click(function() {
        $(this).find('a').toggleClass('open').end().next(o.cllpsEl)[o.method](o.speed);
        return false;
    });
});};
$.fn.toggler.defaults = {
     cllpsEl : 'div.collapse',
     method : 'slideToggle',
     speed : 'slow',
     container : '', //the common container of all groups with collapsible content (optional)
     initShow : '.shown' //the initially expanded sections (optional)
};
/* ---------------------------------------------
Feel free to remove any of the following functions if you don't need it.
------------------------------------------------ */
$.fn.toggleHeight = function(speed, easing, callback) {
    return this.animate({height: 'toggle'}, speed, easing, callback);
};
//http://www.learningjquery.com/2008/02/simple-effects-plugins:
$.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
$.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};
/* --- end of the optional code --- */
})(jQuery);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// swfobject.js

/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
