
function init_menu() {
	$('table.menu td').hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
	$('table.menu td:first').css("border-width", 0);

$("*.ui-state-default").hover(
	function(){ 
		$(this).addClass("ui-state-hover"); 
	},
	function(){ 
		$(this).removeClass("ui-state-hover"); 
	});


}

function init_dt() {
	
	var editor = $('#dt_editor');
	//var dt_editor_hovering = false;

	var edit_dt = function() {
		//alert('edit');
	};

	var edit_dt = function(event) {
		var div = $(this);
		editor.appendTo(div);
		var pos = div.offset();
		var height = div.height();
		var width = div.width();
		editor.css('left', pos.left + 20);
		editor.css('top', pos.top + height + 1);
		editor.css('width', width-60);
		editor.show();
	}



	$('div.dt').hover(
		function() {
			var div = $(this);
			div.addClass('hover');
			div.click(edit_dt);
		},
		function() {
			//if(dt_editor_hovering)
			//	return;
			var div = $(this);
			div.removeClass('hover');
			div.unbind("click", edit_dt);
			editor.hide();
		}
	);

	$('#dt_editor').hover(
		function() {
			//dt_editor_hovering = true;
		},
		function() {
			//dt_editor_hovering = false;
		}
	);
}


function init_list(cont) {
	var tabs = $('table.list:not(.nohover)', get(cont));
	var tbodies = tabs.children('tbody');
	var rows = tbodies.children('tr').not('.nohover');
	rows.hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	).filter("[onclick]").css('cursor', 'pointer');

	rows.children("td").children("input").click(
		function(event) {
			//debug.profile();
			//$(this.parentNode.parentNode).toggleClass('selected', this.checked);
			//clog("click on cb");
			event.stopPropagation();
			//debug.profileEnd();
		}
	).closest('td').css('cursor', 'auto').click(
		function(event) {
			//clog("click on td");
			event.stopPropagation() ;
		}
	);

	//$("table.list>thead>tr>th[onclick]").css('cursor', 'pointer');
	tabs.find("thead>tr>th.sortable").hover(
		function() {
			$(this).css("color", '#dd2222');
		},
		function() {
			$(this).css("color", '');
		}
	);
}


function er(url) {
	redirect(url);
}

function onchange_dep(main, sec, url) {
	
	var val = $(main).val();

	var func = function(data) {
		set_options(document.getElementById(sec), data);
	}

	set_options(document.getElementById(sec), [{"value":"", "label": "loading.."}]);
	$.getJSON(window.location.pathname + '/' + url + val, func);
}


function init_sections(id) {

	$("#" + id + " > h3 > a").append(' <span>(click to open)</span>');

	$('#' + id).addClass("ui-accordion ui-widget ui-helper-reset")
		.find("h3")
		.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
		.prepend('<span class="ui-icon ui-icon-triangle-1-e"/>')
		.click(function() {
			$(this).toggleClass("ui-accordion-header-active").toggleClass("ui-state-active")
			.toggleClass("ui-state-default").toggleClass("ui-corner-bottom")
			.find("> .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s")
			.end().next().toggleClass("ui-accordion-content-active").toggle();
			return false;
		})
		.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide();

	$("#" + id + " > h3.open").trigger("click");
}

function swap() {
	jQuery.fn.swap = function(b) {
		b = jQuery(b)[0];
    	var a = this[0];

    	var t = a.parentNode.insertBefore(document.createTextNode(""), a);
		b.parentNode.insertBefore(a, b);
		t.parentNode.insertBefore(b, t);
		t.parentNode.removeChild(t);

	    return this;
	};
}


function open_dialog(url, name, save_callback, dialogOptions) {
	id = name+'_dialog';
	var dialog = get(id);
	var first = !dialog;
	var time = $time();
	//console.log(time);
	if(dialog && dialog.loading && time-dialog.loading<5000) { // timeout 5 seconds
		//console.log("REJECTED. dif: " + (time-dialog.loading));
		//alert("dialog already loading");
		return false;
	}

	if(first) {
		dialog = document.createElement('div');
		dialog.id = id;
		dialog.loading = 0;
	}
	else {
		dialog.loading = time;
	}
	
	var load_func = function(data) {
		
		if(data["errors"]) {
			alert_errors(data["errors"]);
			if(dialog)
				dialog.loading = 0;
			return;
		}

		var options = data["options"];
		if(dialogOptions) {
			for(var k in dialogOptions)
				options[k] = dialogOptions[k];
		}

		if(data["buttons"]) {
			var buttons = {};
			for(var b in data["buttons"]) {
				/*
				var func;
				switch(b) {
				case 'cancel':
				case 'close':
					func = function() {
						//console.log(this);
						$(this).dialog('close');
					};
					break;
				case 'delete':
					func = function() {
						if(!confirm('Are you sure you want to delete this item?')) return false;
						$(this).dialog('close');
						submit_dialog(this.id, 'delete', save_callback);
					};
					break;
				default:
					func = function() {
						if(typeof(validate) == "function") {
							if(!validate())	return false;
						}
						//submit_dialog(this.id, 'x', save_callback);
					};
				}

				*/
								

				var func;
				var func_code =
					"func = function(event) { " +
					"if('"+b+"'=='delete') {"+
					"	if(!confirm('Are you sure you want to delete this item?'))"+
					"		return;"+
					"}\n";
				if(b!="cancel" && b!="close" && b!="delete") {
					func_code +=
					"if(typeof(validate_"+name+") == 'function')\n"+
					"    if(!validate_"+name+"()) return false;";
				}
					
				func_code += "$(this).dialog('close');"+
					"if('"+b+"'!='close' && '"+b+"' != 'cancel') submit_dialog('"+id+"', '"+b+"', save_callback);" +
					"}";
				// submit_dialog(id, event.target.innerHTML, save_callback);
				
				//clog(func_code);

				buttons[data["buttons"][b]] = eval(func_code);
				
			}
			options["buttons"] = buttons;
		}
		
		var d;

		if(first) {
			document.body.appendChild(dialog);
			d = $(dialog);
			options["bgiframe"] = true;
			//options["open"] = function() { this.loading=0; };
			d.dialog(options);
			d.bind("dialogopen", function() { this.loading=0; });
		}
		else {
			d = $(dialog);
			for(var opt in options)
				d.dialog("option", opt, options[opt]);
		}

		dialog.innerHTML = data["html"];
		if(data["title"])
				dialog.title = data["title"];
	

		d.dialog("open");
		init_dates(d);
		init_list(dialog);
	};

	if(typeof url == "string") {
		$.getJSON(url, { init: first?1:0 }, load_func);
	}
	else {
		var postData = url['post'];
		postData['init'] = first?1:0;
		$.post(url['url'], postData, load_func, "json");
	}
}

function submit_dialog(id, action, callback) {
	var err = false;
	//alert("submit id="+id+" action="+action);
	$('#' + id + " form").each(function() {
		//alert('fount form: id='+this.id);
		var act = "&" + encodeURIComponent("act["+action+"]") + "=1";
		$.post(this.action, $(this).serialize()+act, function(data) {
			//alert(data);
			data = eval("("+data+")");
			if(data["errors"]) {
				alert_errors(data["errors"]);
			}
			else {
				callback(data);
			}
		});
	});
	return "id="+id+" action="+action;
}

function close_dialog(name) {
	var id = name+'_dialog';
	var dialog = get(id);
	$(dialog).dialog("close");
	//var dialog = $(x).closest("div.ui-dialog-content");
	//dialog.dialog("close");
}

function load_section(id) {
	var section = id;
	var callback = null;
	var args = {};
	var state = '';

	var url = window.location.href;
	if(window.location.hash)
		url = substr(url, 0, -window.location.hash.length);

	for(var i = 1; i<arguments.length; i++) {
		switch(typeof(arguments[i])) {
		case 'string':
			if(arguments[i][0]==='#')
				state = arguments[i].substring(1);
			else if(arguments[i][0]==='/')
				url = arguments[i];
			else
				section = arguments[i];
			break;
		case 'function':
			callback = arguments[i];
			break;
		case 'object':
			args = arguments[i];
			break;
		}
	}
	args['__sect__'] = section;
	if(state) {
		url += window.location.search? '&': '?';
		url += state; //.substring(1);
	}
	//alert("section url="+url);
	$.get(url, args, function(html) {
		$('#'+id).html(html);
		if(callback)
			callback(html);
	});
}

function open_field_help(id) {
	open_dialog('/misc/fieldhelp?id=' + id, 'field_help');
}

function get_json(url, data, callback) {
	$.getJSON(url, data, function(data, textStatus) {
		if(data["errors"]) {
			text = "";
			for(k in data["errors"]) {
				text += data["errors"][k]["message"] + "\n\n";
			}
			alert(text);
			callback(data, "error");
		}
		else {
			callback(data, textStatus);
		}
	});
}


function df_count_completed(cont) {
	var nc = 0;
	var nn = 0;

	cont = get(cont);

	$("input.required:text,textarea.required,select.required,input.required:radio:checked", cont).each(function() {
		var self = $(this);
		if(this.df_hidden || self.hasClass("disabled") || self.hasClass("_disabled2"))
			return;
		if(getval(this)!='')
			nc++;
		else
			nn++;
	});
	$("input.required:checkbox", cont).each(function() {
		var self = $(this);
		if(this.df_hidden || self.hasClass("disabled") || self.hasClass("_disabled2"))
			return;
		nc++;		
	});
	
	var nt = nc+nn;
	
	return { "nc" : nc, "nn" : nn, "nt" : nt};
}

function df_init_completion(containerId, reportId) {
	var cont = $("#"+containerId);
	if(!cont.length)
		return;

	var f = function() {

		window.document.body.style.backgroundColor = 'green';
	
		var c = df_count_completed(cont);
		var nn = c.nn;
		var nc = c.nc;
		var nt = c.nt;

		var df_inc = function(message) {
			return df_incomplete(message, cont);
		};

		var report = get(reportId);
		if(report) {
			var percent = nt?Math.floor(100*nc/nt):100;
			var color = nn>0?'red':'green';
			report.innerHTML = '<span style="color: '+color+'">Complete: '+percent+"%&nbsp;</span>";
			report.innerHTML += '<span style="color: gray">(' + nc+' out of '+nt+')&nbsp;</span>';
			report.testCompletion = nn>0? df_inc: df_complete;
		}
		else {
			//alert('cant find '+reportId);
		}

		window.document.body.style.backgroundColor = '';

	}

	var f2 = function() {
		if(typeof(this.lastValue)=="undefined") {
			f();
		}
		else if(this.lastValue!=this.value) {
			f();
		}
		this.lastValue = this.value;
	};

	$("input.required:text,textarea.required", cont).unbind(".compl").bind("keyup.compl", f2);
	$("input.required:text,select.required,textarea.required", cont).unbind(".compl").bind("change.compl", f);
	$("input.required:checkbox,input.required:radio", cont).unbind(".compl").bind("click.compl", f);

	cont.data("df_completion", f);
	f();
}

function df_refresh_completion(contId) {
	var cont = get(contId);
	var x = $("select.required", cont);
	if(x.length)
		x.eq(0).change();
	else {
		x = $("input.required:radio", cont);
		if(x.length)
			x.eq(0).click();
		else {
			// other fields
		}
	}
}

function df_recalculate_completion(contSel) {
	f = $(contSel).data("df_completion");
	if(f) f();
}

function df_incomplete(message, cont) {
	if(typeof(message)=="undefined")
		message = "You have not completed all the required fields.";

	$("input.required:text:visible,textarea.required:visible,select.required:visible,input.required:radio:checked:visible", cont).not(".disabled,._disabled2").each(function() {
		//$(this).css('border', getval(this)!=''? '0 none': '1px solid red');
		$(this).css('background-color', getval(this)!=''? '': '#ff4444');
	});
	
	alert(message);


	return false;
}

function df_complete() {
	return true;
}

function df_dep_options(idbase, supFid, supVal, depFids) {
	for(var k=0; k<depFids.length; k++) {
		try {	
			df_dep_options_load(depFids[k], idbase+depFids[k], supFid, supVal);
		}
		catch(ex) {
			clog('*** EXCEPTION2 ***');
			clog(ex);
		}
	}
}

function df_dep_options_load(fid, domId, supFid, supVal) {

	if(!get(domId))
		return;

	if(rate_options && typeof(rate_options[fid]) != 'undefined') {
		//rate options field
		//alert("fid="+fid+" domId="+domId+" supFid="+supFid+" supVal="+supVal);
		var rate = rate_options[fid];

		if(supVal == rate.values[supFid])
			return;

		//set_options(domId, {"": "loading..."});
		rate.values[supFid] = supVal;
		var opts = rate.options;
		var anyAll = false;
		for(var k=0; k<rate.filters.length; k++) {
			var filterFid = rate.filters[k];
			var filterValue = rate.values[filterFid];
			if(filterValue=='*')
				anyAll = true;
			opts = opts[filterValue];
		}

		if(rate['allvalues']=='1') {
			if(opts)
				opts['*'] = 'All'; //'All (rate options)';
			else if(anyAll)
				opts = {'*': 'All'}; //'All (rate options empty)'};
		}

		if(!opts || opts.length==0) {
			set_options(domId, {'n/a': 'N/A'});
			hide("_df_container_"  + fid);
		} else {
			set_options(domId, opts, '', '');
			show("_df_container_" + fid);
		}
		
	}
	else { // tag field

		var args = {"f": fid, "t": supVal};
		//var sel = get(domId);
		//sel.options[sel.options.length] = new Option("loading...", "@@loading...@@")
		var oldval = getval(domId);
		set_options(domId, {"": "loading..."});
		$.getJSON("/mod/field_options", args, function(data) {
			var sel = get(domId);
			set_options(sel, data);
			setval(sel, oldval);
			$(sel).change();
			if(!data || data.length==0 || (data.length==1 && data[0].value=='n/a')) {
				hide("_df_container_"  + fid);
			}
			else {
				show("_df_container_" + fid);
			}
		});
	}
}


function dyn_fields_percentage(nc, nn, compl, but) {

		if(but) {
			but.unbind("click.required_fields");
			if(nn) {
				but.bind("click.required_fields", function(event) {
					event.stopImmediatePropagation();
					return false;
				});
			}
		}

}

function alert_errors(errors) {
			text = "";
			for(k in errors) {
				text += errors[k]["message"] + "\n\n";
			}
			alert(text);
	return text;
}

function df_show(elem, really) {
	if(!elem)
		return;
	if(typeof(really)=="undefined") really = true;
	elem.parentNode.parentNode.style.display = really? '': 'none';
	elem.df_hidden = !really;
}

function init_dates(context) {

	$.datepicker.setDefaults({
		dateFormat: 'dd/mm/yy',
		showOn: 'button',
		buttonText: 'click to select date',
		//appendText: ' dd/mm/yyyy',
		buttonImage: '/media/date.png',
		buttonImageOnly: true,
		changeMonth: true,
		changeYear: true,
		//constrainInput: true,
		gotoCurrent: true,
		duration: ''
	});

	/*
	$('input.date_dob', context).datepicker({
		"minDate": "-80y",
		"maxDate": "+0d",
		"yearRange": "1910:2030"
	});

	$('input.date_renewal', context).datepicker({
		"yearRange": "2000:2030",
		"minDate": "-3y",
		"maxDate": "+3m"
	});
	*/
	

	$('input.date', context)
		.filter(".date_dob").datepicker({
			"minDate": "-80y",
			"maxDate": "+0d",
			"yearRange": "1910:2030"
		})
		.end()
		.filter(".date_renewal").datepicker({
			"yearRange": "2000:2030",
			"minDate": "-3y",
			"maxDate": "+3m"
		})
		.end()
		.filter(".field_date")
			.after('<img src="/media/date.png" class="ui-datepicker-trigger"> dd/mm/yyyy')
			.datepicker({
			//"appendText": ' dd/mm/yyyy'
		})
		.end()
		.filter(".date_activity").datepicker({
			"minDate": "-1y",
			"maxDate": "+1m"
		})
		.end();

		//.filter("input.date_dob")
		////.datepicker("option", "minDate", "01/01/1920")
		//.datepicker("option", "maxDate", "+1")
		//.datepicker("option", "yearRange", "1920:2010")
		//.end()
		//.filter("input.date_renewal")
		////.datepicker("option", "minDate", "-1m")
		//.datepicker("option", "maxDate", "+3m")
		//.datepicker("option", "yearRange", "2009:2010")
		//;

}

function validate_renewal(renewal) {
	renewal.style.backgroundColor = '';
	var a = renewal.value.split('/');
	if(a.length!=3 || (a[0]<1 || a[0]>31 || a[1]<1 || a[1]>12 || a[2]<2009 || a[2]>2030)) {
		renewal.style.backgroundColor = 'red';
		alert('Renewal Date ('+renewal.value+') not valid.\nPlease use dd/mm/yyyy format.');
		return false;
	}
	var ren_date = new Date(a[2], a[1]-1, a[0]);
	var today = new Date();
	var days = Math.round((ren_date-today)/(1000*60*60*24));

	//alert(days);

	if(days<-31) {
		alert('Renewal Date ('+renewal.value+') cannot go more than 1 month in the past.');
		return false;
	}

	if(days>92) {
		alert('Renewal Date ('+renewal.value+') cannot go more than 3 months in the future.');
		return false;
	}

	return true;
}

function calculate_age(dob, ref) {
	switch(typeof(ref)) {
	case 'undefined':
		var today = new Date();
		ref = [today.getDate(), today.getMonth()+1, today.getFullYear()];
		break;
	case 'string':
		ref = ref.split('/');
		break;
	}

	if(typeof(dob)=='string')
		dob = dob.split('/');

	var age = parseInt(ref[2])-parseInt(dob[2]) - (parseInt(dob[1])*100+parseInt(dob[0]) > parseInt(ref[1])*100 + parseInt(ref[0]) ? 1 : 0);
	return age;
}

function validate_dob(dob, renewal, type, type_descr) {
	if(typeof(renewal)=="string")
		renewal = renewal.split('/');

	dob.style.backgroundColor = '';
	var a = dob.value.split('/');
	if(a.length!=3 || (a[0]<1 || a[0]>31 || a[1]<1 || a[1]>12 || a[2]<1800 || a[2]>2030)) {
		dob.style.backgroundColor = 'red';
		alert('Date of Birth (' + dob.value + ') not valid.\nPlease use dd/mm/yyyy format.');
		return false;
	}

	//var age = renewal[2]-a[2] - (a[1]*100+a[0] > renewal[1]*100 + renewal[0] ? 1 : 0);
	var age = calculate_age(a, renewal);
	var err = '';

	switch(type) {
	case 'member':
		if(age<16)
			err = 'at least 16';
		else if(age>100)
			err = 'at most 100';
		break;
	case 'spouse':
		if(age<16)
			err = 'at least 16';
		else if(age>100)
			err = 'at most 100';
		break;
	case 'child':
		if(age<0)
			err = 'at least 0';
		else if(age>25)
			err = 'at most 25';
		break;
	default:
		if(age<0)
			err = 'at least 0';
		else if(age>100)
			err = 'at most 100';
	}
	if(err) {
		dob.style.backgroundColor = 'red';
		alert('The age of ' + type_descr + ' must be ' + err + '.');
		return false;
	}

	return true;
}

function toggle_datepicker(img) {
	//var dp = $(img).prevAll("img.ui-datepicker-trigger:last");
	var trig = img.previousSibling;
	$(trig).click();
	//console.log(dp);
	/*
	if(dp.datepicker._datepickerShowing)
		dp.datepicker('hide');
	else
		dp.datepicker('show');
	*/
}

function preview_richtext(ta, id) {
	/*
	var x = get("preview_richtext_buffer");
	if(!x) {
		x = $('<span style="xdisplay: none" id="preview_richtext_buffer"></span');
		$('body').append(x);
	}
	else {
		x = $(x);
	}
	x.text(ta.value);
	*/

	if(typeof ta == "string")
		ta = get(ta);

	var url = {
		url: "/mod/preview_richtext"+ (id?"?id="+id:""),
		post: { t: ta.value}
	};
	//arg = "t=" + encodeURIComponent(ta.value);
	open_dialog(url, "preview_richtext");
}

function edit_page_intro(id) {
	open_dialog("/mod/page_intro?id=" + id, "page_intro", function() {
		window.location.reload();
	});
}

function edit_cms_text(h) {
	open_dialog("/mod/cms_text?h=" + h, "cms_text", function() {
		window.location.reload();
	});
}

function init_page() {
	$("body").ajaxSend(function(event, http) {
		http.setRequestHeader('X-Ajax-Call', '1');
	})
	.ajaxStart(function() {
		$('#loading').show();
	})
	.ajaxComplete(function(event, http) {
		$('#loading').hide();
		var val = http.getResponseHeader('X-Ajax-Error');
		if(val) {
			alert(val);
		}
		val = http.getResponseHeader('X-Ajax-Redirect');
		if(val) {
			window.location.href = val;
		}
		val = http.getResponseHeader('X-Ajax-Reload-Page');
		if(val) {
			window.location.reload(true);
		}
	});


	init_menu();
	init_dt();
	init_list();

	init_dates();

	$("#header-menu tr.menu-items a").hover(
		function() {
			var k = (this.parentNode.cellIndex-1)/2;
			$("#menu-item-"+k).addClass('hover');
		},
		function() {
			var k = (this.parentNode.cellIndex-1)/2;
			$("#menu-item-"+k).removeClass('hover');
		}
	);

//$.datepicker.dialog( 'dialog' , '22/10/2009' , function(d) { alert(d); } , { } , [100,50] );
}

var timeout_ms = null;

function test_timeout(s) {
	//get('tt').innerHTML = s;
	setTimeout("get_timeout()", 1000*s);
	timeout_ms = new Date(new Date().getTime() + s*1000).getTime();
}

function show_timeout() {
	if(!timeout_ms)
		return;
	var ms = new Date().getTime();
	var s = Math.round((timeout_ms - ms)/1000);
	if(s<0) s=0;
	get('tt').innerHTML = ' - test in ' + s + 's'; //timeout_ms +  ' ' + ms;
}

function get_timeout() {
	$.getJSON('/mod/user/remain', function(data) {
		if(data['m'])
			alert('Your session is going to expire in ' + data['m'] + '.');
		else if(data['w'])
			test_timeout(data['w']);
		else
			clog('no data');
	});
}

