//// BOF

function applyPopup() {
	consoleLog(getElementsByClass("photo"));
}

function popupImg(evt, id_image) {
	var pop = new SinglePopup();
	if (evt.type === 'mouseover') {
//		consoleLog("mouseOVER: "+pop);
		pop.show(evt, id_image);
	} else if (evt.type === 'mouseout' || evt.type === 'mousedown') {
//		consoleLog(evt);
		pop.hide();
	}
}

function SinglePopup() {
	if (SinglePopup.instance == null) {
		SinglePopup.instance = this;
		SinglePopup.instance.initialize();
//		consoleLog("creating new SinglePopup instance!");
	} else {
//		delete this; // fails in IE6, stops the js
		this == null;
	}
	return SinglePopup.instance;
}

// wrapper for finding event target in ff and ie
//foo.onbar = function (e) { e = e || window.event; var elt =
//                   e.target || e.srcElement; ... }

SinglePopup.prototype = {
	instance: null,
	popup: null,
	id_image: null,
	timer: 0,
	initialize: function() {
	  // Actual constructor for your one instance
		this.popup = document.createElement("div");
		this.popup.id = "popup";
		// done in css now with a IE6 special case
//		this.popup.style.position = "fixed"; // 'fixed' relative to viewport
		this.popup.style.visibility = "hidden";
//		this.popup.style.backgroundColor = "black"; // FIXME: black stripe
		this.popup.style.color = "white";
//		document.body.appendChild(this.popup);
		document.getElementById('page_wrapper').appendChild(this.popup);
	},
	show: function(evt, id_image) {
//		consoleLog("popup initialized: " + this.popup);
		var popup = this.popup;
		if (this.popup.style.visibility === "visible" || this.timer != 0) {
			return;
		} else if (id_image !== this.id_image) {
			popup.innerHTML = '';
			applyURLContent('/util/img_caption.md?id_image='+id_image, popup);
			this.id_image = id_image;
		}
		// only load URL if new id_image
//		consoleLog("this: " + this);
		// for closure in setTimeout callback function
//		this.timer = setTimeout(function() {
//			var obj = new SinglePopup();
			popup.style.left = (evt.clientX + 5)+'px'; // no offset == flicker
			popup.style.top = (evt.clientY + 5) +'px'; // no offset == flicker
			popup.style.visibility = "visible";
//		}, 500);
	},
	hide: function() {
//		if (this.timer != 0) {
//			var a = clearTimeout(this.timer);
//			consoleLog("clearTimeout returns: " + a);
//			this.timer = 0;
//		}
		if (this.popup.style.visibility === "hidden") {
			return;
		}
		this.popup.style.visibility = "hidden";
	}
}

function applyURLContent(url, elem) {
	var req = getXmlHttpRequestObject();
	req.open('GET', url);
	req.onreadystatechange = function () {
//		consoleLog("response: ^" + req.responseText + "$");
		if (req.readyState == 4) {
//			consoleLog("url: " + url);
			elem.innerHTML = req.responseText;
		}
	};
	req.send(null);
}

//var IE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;

function appendColonToIE6Labels() {
	var label_list=document.getElementsByTagName("label");
	for(var i = 0; i < label_list.length; i++) {
		var label=label_list[i]; //document.getElementById('div'+i);
		if(label.className !== "regular" && label.innerHTML.slice(-1) !== ':') {
			label.innerHTML += ':';
		}
	}
}

function searchSuggest(input) {
	var req = getXmlHttpRequestObject();
	if (req.readyState == 4 || req.readyState == 0 && input.value.length > 1) {
//	if (input.value.length > 2) { // at least two chars typed
		req.open('GET', '/suggest.md?q='+escape(input.value));
//		req.setRequestHeader ("Charset", "ISO-8859-15");
//		req.open('GET', '/'); // animation testing
		req.onreadystatechange = function() {handleSearchSuggest(input, req);};
		req.send(null);
	} else {
		var sg = document.getElementById('searchdiv');
		sg.style.display = "none";
//		sg.innerHTML = "";
		sg.options.length = 0;
	}
//	consoleLog("baseURI: " + document.baseURI);
//	consoleLog("location: " + window.location);
}

function handleSearchSuggest(input, req) {
	if (req.readyState == 4) {
//		var str = req.responseText.split("\n");
		var str = eval('('+req.responseText+')');
//		consoleLog(document.activeElement);
//		consoleLog("response: ^" + req.responseText + "$");
//		ta.value = str;
		setTimeout(function () { // delay animation end
//			clearInterval(req.timer);
//			input.nextSibling.style.visibility = 'hidden';
//			input.style.background = '';
			input.className = "";
		}, 1000);
//		sg.style.display = "block";
//		lb.style.display = "block";
//		var sg = getSelectList(input);

		var sg = document.getElementById('searchdiv');
		sg.options.length = 0;
		if (str.length == 0) {
			sg.style.display = "none";
		} else {
			sg.style.display = "block";
		}

//		var sg = document.getElementById('searchdiv');
//		sg.innerHTML = "";

//		consoleLog("str.length is :" + str.length);
		for(var i = 0; i < str.length; i++) {
//			var opt = str[i].split(",");
//			sg.options[i] = new Option(opt[1], opt[0]);
			sg.options[i] = new Option(str[i][1], str[i][0]);

//			var a = document.createElement("a");
//			a.href = str[i][0];
//			a.innerHTML = str[i][1];
//			a.className = "suggestlink";
//			sg.appendChild(a);

//			opt.text = str[i];
//			addEvent(div, "mouseover", suggestOver);
//			addEvent(div, "mouseout", suggestOut);
//			addEvent(div, "click", setSearch);
//			div.className = "suggest_link";
//			div.innerHTML = str[i];
//			sg.options[i] = opt;
		}
//		console.log("result is :" + str.length);
////			document.getElementById('personform').removeChild(sg.parentNode);
////			sg.innerHTML = "";
//			sg.style.display = "none";
//			sg.options.length = 0;
////			sg.parentNode.parentNode.removeChild(sg.parentNode);
//		}
//		alert("Search results:" + str);
//	} else if (req.timer == null) {
	} else {
		// store timer id for later termination
//		req.timer = animate(input.nextSibling);
//		input.style.background = "transparent url('/img/ajax-loader.gif') no-repeat scroll right";
		input.className = "animator";
//		alert("request object is NULL!");
//		ta.value = "request object state is: " + req.readyState;
	}
}

// only submit() the form if the keypress is an <ENTER>
function submitIfReturn(event, element) {
//	console.log('THIS: ' + this);
	if (event.keyCode === event.DOM_VK_RETURN) {
		element.form.submit();
	} else {
		console.log('keycode: ' + event.keyCode);
	}
	return true;
}

function removeSearchSuggest() {
	var sg = document.getElementById('searchdiv');
	sg.innerHTML = "";
	sg.style.display = "none";
}

function getSelectList(input) {
	var sg = document.getElementById('person_to_event__id_person');
	if (sg == null) {
		var sg = document.createElement("select");
		sg.name = "person_to_event__id_person";
		sg.id = "person_to_event__id_person";
		addEvent(sg, "change", function () {document.personform.submit();});
		sg.size = 5;

		var lb = document.createElement('label');
		lb.innerHTML = "Suggestions";

		var li = document.createElement('li');
		li.appendChild(lb);
		li.appendChild(sg);
		document.getElementById('personform').insertBefore(li,
				input.parentNode.nextSibling);
	} else {
		sg.options.length = 0;
	}
	return sg;
}

function suggestOver() {
	this.className = 'suggest_link_over';
}

function suggestOut() {
	this.className = 'suggest_link';
}

function setSearch() {
	document.getElementById('lastname').value = this.innerHTML;
	this.parentNode.innerHTML = '';
}

function animate(obj) {
	obj.style.visibility = 'visible';
	return setInterval(function() {
		obj.innerHTML = {
//		'': '-',
		'[-]': '[\\]',
		'[\\]': '[|]',
		'[|]': '[/]',
		'[/]': '[-]'
		}[obj.innerHTML] },
		 100);
//						clearInterval(timer);
}

function showWholeImg(obj, size) {
	obj.style.overflow = 'visible';
	if (obj.firstChild.clientHeight > (size + 20)) {
		obj.parentNode.lastChild.style.color = 'white';
	}
}

function showImgCaption(obj) {
	obj.style.overflow = 'hidden';
	obj.parentNode.lastChild.style.color = 'black';
}

//var formdb = {};

//function store_form() {
//	var r = {};
//	for (var i = 0, g = window.document.forms, n = g.length; i < n; i++) {
//		if (g[i].name) {
////			if (r[g[i].name] != undefined) {
////				alert("two forms on the same page!!");
////				return null;
////			}
//			r[g[i].name] = {};
//			for (var j = 0, f = g[i].elements, m = f.length; j < m; j++) {
//				if (f[j].name) {
//					r[g[i].name][f[j].name] = f[j].value;
//				}
//			}
//		}
//	}
//	return r;
////	alert("formdb is: " + formdb["lform:start_day"]);
//}

function treedate(obj) {
	if (obj.nextSibling.style.display != 'none') {
		obj.nextSibling.style.display = 'none';
		obj.firstChild.src = '/img/nav_plus.gif';
		obj.firstChild.alt = '+';
	} else {
		obj.nextSibling.style.display = 'block';
		obj.firstChild.src = '/img/nav_minus.gif';
		obj.firstChild.alt = '-';
	};
	return false; // ignore href
}

function scrolldate(obj) {
	var div = document.getElementById("datediv");
	var prev = document.getElementById("prevdate");
	var next = document.getElementById("nextdate");
	for (var i = 0, c = div.childNodes, n = c.length; i < n; i++) {
		if (c[i].style.display == 'block') {
			if (obj.id == "prevdate" && i > 0) {
				c[i].style.display = 'none';
				c[i - 1].style.display = 'block';
				prev.textContent = '[ '+ (i - 1) +' <<]';
				next.textContent = '[>>'+ (n - i) +']';
			} else if (obj.id == "nextdate" && i < n - 1) {
				c[i].style.display = 'none';
				c[i + 1].style.display = 'block';
				prev.textContent = '['+(i + 1)+'<<]';
				next.textContent = '[>>'+(n - (i+2))+']';
			}
			return false;
		}
	}
	return false;
}

function countdown(obj) {
	for (var i = 5; i > 0; i--) {
		obj.innerHTML = i;
	}
}

function countdown2(obj, destination) {
	var n = 5, timer = setInterval(
			function() {
				if (n >= 0) {
					obj.innerHTML = n.toFixed(2);
					n -= 0.01;
				} else {
					clearInterval(timer);
					window.location = destination;
				}
			}, 10);
}

//function other_events(id) {
function other_events(obj) {
//	var div = document.getElementById(id);
	var ul = obj.nextSibling;
	if (ul.style.display == 'none') {
		ul.style.display = 'block';
		console.log("showing ul " + ul.style.display);
	} else {
		ul.style.display = 'none';
		console.log("hiding ul");
	}
//	alert(obj);
	return false;
}

//// suggested on ##javascript
//function formToObject(frm) {
//  for(var r = {}, f = frm.elements, i = f.length - 1, n; i >= 0; --i)
//    if(f[i].name && (typeof f[i].checked !== "boolean" || f[i].checked))
//      if(r[f[i].name])
//        if(r[f[i].name] instanceof Array)
//          r[f[i].name].push(f[i].value);
//        else
//          r[f[i].name] = [r[f[i].name], f[i].value];
//      else
//        r[f[i].name] = f[i].value;

//  return r;
//}

//function formsToObjects() {
//  for(var i = arguments.length - 1, r = []; i >= 0; --i)
//    r[i] = formToObject(arguments[i]);

//  return r;
//}

//var formdb = formsToObjects.apply(null, window.document.forms);

// usage: javascript:void(favoris());

function favoris() {
	if(navigator.appName!='Microsoft Internet Explorer') {
		window.sidebar.addPanel(document.title,location.href,"");
	}
	else {
		window.external.AddFavorite(location.href,document.title);
	}
}

//function today() {document.write(new Date());:

function setupDatepicker(ids) {
$(function() {
	$.datepicker.setDefaults(
		$.extend({
			showMonthAfterYear: false,
			showOn: "both",
			changeMonth: true,
			buttonImage: "/img/calendar.gif",
			buttonImageOnly: true,
			appendText: " [jj/mm/aaaa]",
			changeMonth: true,
			changeYear: true
			},
			$.datepicker.regional['fr']
	));
//	consoleLog("DATEPICKER: "+ids);
	for (var i = 0, n = ids.length; i < n; i++) {
		//// must reinit opt or it keeps its previous value!
		var opt = {};
		//// var scope is function, not loop
		switch (ids[i]) {
			case "datepicker":
				opt = {
				maxDate: "-9y",
				minDate: "-100y",
	//			yearRange: "1890:2000",
				defaultDate: "-9y",
				yearRange: "-100:0" // 2nd part of range must be > 0
				};
				break;
			case "start_date":
				opt = {
				onClose: function(dateText, inst) {
//					console.log("onClose CALLED", inst);
	//				$("#end_date").datepicker('setDate', this.getDate());
					$("#end_date").datepicker('option', 'defaultDate', 
							$("#start_date").datepicker('getDate'));
				}
				};
				break;
		};
		var dp = $("#"+ids[i]).datepicker(opt);
//		console.log("DatePicker configured", opt);
	}

});
}

function setupSearchSuggestJQ() {
$(function() {
	$("#lastname").autocomplete('/suggest-jq.md', {
		minChars: 2,
		selectFirst: false, // don't submit() on TAB
		formatItem: function(item) {
//			consoleLog(typeof item[0]);
//			consoleLog(item[0].match(/:(.+)$/));
			return /:(.+)$/.exec(item[0])[1];
		},
		formatResult: function(item) {
			return /:(.+)$/.exec(item[0])[1];
		}
	})
	.result(function(event, item) {
//		consoleLog("IN RESULT");
		location.href = item.url;
		var hidden = document.getElementsByName("person_to_event__id_person")[0];
		hidden.value = /^(.+):/.exec(item[0])[1];
		document.forms['personform'].submit();
	})
	;
});
}

function moveImage(evt) {
	consoleLog("moveImage called with event: " + evt);
}

function setupDragImage(id, id_image) {
	$(function() {
//		if 'id' is undefined use empty string	
		var elm = $("#drag" + (id || ''));
//		console.log("ELM: %o", elm);
		var prt = elm.parent();
//		console.log("PRT: %o", prt);
		var h = elm.height() - prt.height()
		var w = elm.width() - prt.width()
		var o = prt.offset();
//		consoleLog("HxW: "+h+'x'+prt.height());
		elm.draggable({
//			containment: 'parent',
			containment: [o.left-w, o.top-h, o.left, o.top],
			stop: function(event, ui) {
//				consoleLog("DRAG STOP: " + ui.position.left);
				jQuery.post("/util/image_offset.md", {
					id_image: id_image,
					geometry: prt.width() + 'x' + prt.height() + '+' + -ui.position.left + '+' + -ui.position.top
//					xoffset: -ui.position.left, 
//					yoffset: -ui.position.top
					});
			},
			cursor: 'move'
//			axis: 'y',
		});
	});
}

//// EOF
