/**
 * Library of javascript functions
 * 
 * @version 1.0
 */

// ----------------------------------------------------------------------------
// general show/hide
// ----------------------------------------------------------------------------

var timerHide = new Array();
var timerTrans = null;

// requires JQuery
function show(el) {
	// parameters can be speed, effect or just speed
	var sp = '';
	var ty = '';
	if (show.arguments.length == 3) {
		sp = show.arguments[1];
		ty = show.arguments[2];
	} else if (show.arguments.length == 2) {
		sp = show.arguments[1];
	}
	if (ty == 'slide')
		$(el+":hidden").slideDown(sp);
	else if (ty == 'fade')
		$(el+":hidden").fadeIn(sp);
	else
		$(el+":hidden").show(sp);
}

// requires JQuery
function hide(el) {
	// parameters can be speed, effect or just speed
	var sp = '';
	var ty = '';
	if (hide.arguments.length == 3) {
		sp = hide.arguments[1];
		ty = hide.arguments[2];
	} else if (hide.arguments.length == 2) {
		sp = hide.arguments[1];
	}
	if (ty == 'slide')
		$(el+":visible").slideUp(sp);
	else if (ty == 'fade')
		$(el+":visible").fadeOut(sp);
	else
		$(el+":visible").hide(sp);
}

// requires JQuery
function toggle(el) {
	sp = ty = null;
	if (toggle.arguments.length == 3) {
		sp = toggle.arguments[1];
		ty = toggle.arguments[2];
	} else if (toggle.arguments.length == 2) {
		sp = toggle.arguments[1];
	}
	if ($(el+":visible").size() > 0) {
		hide(el, sp, ty);
	} else {
		show(el, sp, ty);
	}
}

// hide all div matching an expression
function hideAll(exp, except) {
	sp = ty = null;
	if (hideAll.arguments.length == 4) {
		sp = hideAll.arguments[2];
		ty = hideAll.arguments[3];
	} else if (hideAll.arguments.length == 3) {
		sp = hideAll.arguments[2];
	}
	if (ty == 'slide')
		$(exp+":visible").filter(function(index) {return this.id != except;}).slideUp(sp);
	else if (ty == 'fade')
		$(exp+":visible").fadeOut(sp);
	else
		$(exp+":visible").hide(sp);
}

// hide a div after x seconds, return the timer
function hideAfter(id, sec) {
	timerHide[id] = setTimeout("hideAfterReal('"+id+"')", sec*1000);
}
// hide a div after x seconds
function cancelHideAfter(id) {
	if (timerHide[id] != null) {
		clearTimeout(timerHide[id]);
		timerHide[id] = null;
	}
}
// hide a div after x seconds
function hideAfterReal(id) {
	hide(id);
}

// ----------------------------------------------------------------------------
// general pictures
// ----------------------------------------------------------------------------

// define a new function for jquery to preload images
if (jQuery) {
	jQuery.preloadImages = function() {
		for(var i = 0; i<arguments.length; i++) {
			jQuery("<img>").attr("src", arguments[i]);
		}
	}
}

// show a picture 
function showPicture(id, href) {
	if (href != '')
		$(id).attr('src', href);
}

// ----------------------------------------------------------------------------
// general url
// ----------------------------------------------------------------------------

// goto an url
function gotoUrl(u) {
	document.location=u;
}

// open the link in a new window
// return false if the popup is shown, true otherwise
function openWindow(oLink, name, width, height, params) {
	var href = '';
	if (oLink.getAttribute) href = oLink.getAttribute('href');
	if (href=='') href = oLink.href;
	if (!href || href=='') href = oLink;
	var all_params = '';
	all_params += 'width=' + width + ',height=' + height;
	if (params && params!='') all_params += ','+params;
	// all is ready, open the popup and focus on it
	var oPopup = window.open(href, (name && name!='' ? name : 'popup'), all_params);
	if (oPopup) oPopup.focus();
	return (oPopup?false:true);
}

// ----------------------------------------------------------------------------
// general string
// ----------------------------------------------------------------------------

// trim the left and right spaces of a string
function trim(str) {
	return str.replace(/^\s+|\s+$/, '');
};

// returns true if the string is empty
function isEmpty(str) {
	return (str == null) || (str.length == 0);
}

// returns true if the string is a valid email
function isEmail(str) {
	if (isEmpty(str)) return false;
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return re.test(str);
}

// transform new lines to BR tags
function nl2br(s) {
	return s.replace(/\n|\r|\r\n/g,'<br />');
}

// limit a field to the number of chars
function limitChars(f, n) {
	if (f.value.length > n) {
		f.value = f.value.substr(0,n);
	}
}

// copy the content of a form field to an html element
function updateDivWithFieldContent(f, id) {
	$("#"+id).html(nl2br(f.value));
}

// ----------------------------------------------------------------------------
// general form
// ----------------------------------------------------------------------------

// confirm and submit the form
function confirmSubmit(theformname, theaction, thefield, theid, theconfirmation) {
	if (confirm(theconfirmation)) {
		if (document.forms[theformname]) {
			document.forms[theformname].elements[thefield].value = theid;
			document.forms[theformname].elements['act'].value = theaction;
			document.forms[theformname].submit();
		}
	}
}

// confirm the delete and submit the form
function doubleConfirmSubmit(theformname, theaction, thefield, theid, theconfirmation) {
	if (confirm("Warning!\n\nPlease read the following screen carefuly.\n\nYou will not be able to undo your action\nafter your confirmation in the next screen.\n\nIf your are not sure, please cancel now!\n")) {
		confirmSubmit(theformname, theaction, thefield, theid, theconfirmation);
	}
}

// change the text of the button and disable it
function waitSubmit(form, btn, div) {
	if (form && form.elements[btn]) {
		form.elements[btn].disabled = true;
	}
	if (div != "") {
		show(div);
	}
	return true;
}

// submit the form 
function submitForm(theformname, theaction) {
	if (document.forms[theformname]) {
		document.forms[theformname].elements['act'].value = theaction;
		document.forms[theformname].submit();
		return true;
	}
	return false;
}

// submit the form with a new value
function submitFormField(theformname, theaction, thefield, thevalue) {
	if (document.forms[theformname]) {
		document.forms[theformname].elements[thefield].value = thevalue;
		document.forms[theformname].act.value = theaction;
		document.forms[theformname].submit();
	}
}

// get basename of file
function basename(path) {
    var slash = (path.indexOf('/') > -1) ? '/' : '\\';
    var filename = path.substring(path.lastIndexOf(slash)+1,path.length);
	return filename.substring(0,filename.lastIndexOf('.'));
}

// copy the filename of a field to another field
function copyFilename(theform, thefile, thefield) {
	// copy only if field empty
	if (theform[thefield].value=="")
		theform[thefield].value = basename(theform[thefile].value);
}

// ----------------------------------------------------------------------------
// general scroll
// ----------------------------------------------------------------------------

// get xy scroll position
function getScrollXY() {
	var pos = [];
	pos[0] = self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
	pos[1] = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
	return pos;
}

// set xy scroll position
function setScrollXY(px, py) {
	window.scrollTo(px, py);
}

// ----------------------------------------------------------------------------
// general ajax test
// ----------------------------------------------------------------------------

// test if ajax is available on the browser
// borrowed from http://www.jibbering.com/2002/4/httprequest.html
function ajaxAvailable() {
	var xmlhttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	@end @*/
	// if we have no xmlhttp object, try to create it in a standard way
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	// still no xmlhttp object, maybe this is IceBrowser (java)
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	// return result
	return !xmlhttp ? false : true;
}

// test for ajax
var ajax_available = ajaxAvailable();

// ----------------------------------------------------------------------------
// newsletter
// ----------------------------------------------------------------------------

// init the form with default values
function initNewsletterSubscr(formname) {
	var f = document.forms[formname];
	if (f) {
		var defs = "FIRSTNAME_FIELD,LASTNAME_FIELD,ADRESSE_FIELD,CP_FIELD,VILLE_FIELD".split(',');
		for (var i = 0; i < defs.length; i++) {
			if (f.elements[defs[i]].value == '')
				f.elements[defs[i]].value = f.elements[defs[i]].title;
		}
	}
}

// check if the form is correctly filled
function checkNewsletterSubscr(f) {
	if (f) {
		var defs = "ffirstname,flastname,faddress,fnumber,fbox,fzipcode,fcity".split(',');
		var mand = "ftitle,ffirstname,flastname,femail".split(',');
		for (var i = 0; i < defs.length; i++) {
			if (f.elements[defs[i]].value == f.elements[defs[i]].title)
				f.elements[defs[i]].value = '';
			f.elements[defs[i]].value = trim(f.elements[defs[i]].value);
		}
		for (var i = 0; i < mand.length; i++) {
			if (f.elements[mand[i]].type == 'select-one') {
				if (f.elements[mand[i]].selectedIndex <= 0) {
					f.elements[mand[i]].focus();
					return false;
				}
			} else {
				if (f.elements[mand[i]].value.length < 2) {
					f.elements[mand[i]].focus();
					return false;
				}
			}
		}
		waitSubmit(f, "send", ""); // disable the send button
		return true;
	}
	return false;
}

//
// hide a div after x seconds, return the timer
function callTransAfter(f, sec) {
	timerTrans = setTimeout(f, sec*1000);
}
// hide a div after x seconds
function cancelCallTransAfter() {
	if (timerTrans != null) {
		clearTimeout(timerTrans);
		timerTrans = null;
	}
}

// choose a category on finder page
function chooseCat(el) {
	if (el && el.selectedIndex > -1) {
		document.location = el.form.action+'?ca='+el.options[el.selectedIndex].value;
	}
}
