function $(elementId)
{
	return(document.getElementById(elementId));
}

function el_show(elementId)
{
	var element = $(elementId);
	
	if (typeof(element.style) != "undefined")
	{
		element.style.display = "block";
		element.style.visibility = "visible";
	}
}

function el_hide(elementId)
{
	var element = $(elementId);
	
	if (typeof(element.style) != "undefined")
	{
		element.style.display = "none";
		element.style.visibility = "hidden";
	}
}

function el_update(elementId, text)
{
	var element = $(elementId);
	
	if (typeof(element.innerHTML) != "undefined")
	{
		element.innerHTML = text;
	}
}

function el_new_id(elementId, elementNewId)
{
	var element = $(elementId);
	
	if (typeof(element.id) != "undefined")
	{
		element.id = elementNewId;
	}
}

function img_src(image, newsrc)
{
	var img = document[image];
	
	if (typeof(img.src) != "undefined")
	{
		img.src = newsrc;
	}
}

function pop_window(mypage, myname, w, h, props) {

	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+','+props
	win = window.open(mypage, myname, winprops)
	
	if (parseInt(navigator.appVersion) >= 4) { 
		win.window.focus(); 
	}
	
	return(win);
	
}

function do_check_uncheck(field, value)
{
	if (value == true)
	{
		check_all(field);
	}
	else
	{
		uncheck_all(field);
	}
}

function check_all(field)
{
	if (typeof(field.length) == 'undefined')
	{
		field.checked = true;
	}
	else
	{
		for(i = 0; i < field.length; i++)
		{
			field[i].checked = true;
		}
	}
}

function uncheck_all(field)
{
	if (typeof(field.length) == 'undefined')
	{
		field.checked = false;
	}
	else
	{
		for(i = 0; i < field.length; i++)
		{
			field[i].checked = false;
		}
	}
}

function empty_select(field)
{
	var length = field.length;
	
	for (i = 0; i < length; i++)
	{
		field.options[0] = null;
	}
}

function add_option(field, text, value, selected)
{
	if (selected)
	{
		field.options.add(new Option(text, value, true, true));
	}
	else
	{
		field.options.add(new Option(text, value));
	}
}

function radio_hook(field, eventfunction)
{
	for(i = 0; i < field.length; i++)
	{
		field[i].onclick = eventfunction;
	}
}

function radio_value(field)
{
	for(i = 0; i < field.length; i++)
	{
		if (field[i].checked)
		{
			return(field[i].value);
		}
	}
	
	return('');
}

/*function switchlang()
{
	var currentpage = document.location.href;
//	currentpage = currentpage.toLowerCase();
	var position = currentpage.indexOf('lang=');
	
	if (position == -1)
	{
		if (currentpage.indexOf('?') != -1)
		{
			document.location = currentpage + '&lang=en';
		}
		else
		{
			document.location = currentpage + '?lang=en';
		}
	}
	else
	{
		var lang = currentpage.substr(position + 5, 2);	
		var newlocation = currentpage.substr(0, position + 5);
		
		if (lang == 'fr')
		{
			newlocation += 'en' + currentpage.substr(position + 7);
		}
		else
		{
			newlocation += 'fr' + currentpage.substr(position + 7);
		}
		
		document.location = newlocation;
	}
	
}*/

function str_replace (search, replace, subject, count) 
{
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function switchlang()
{
      	var currentpage = 	document.location.href;
      	var urlquery	=	currentpage.split("#") ;
      	
      	var url_without_anchor 	= 	urlquery[0];
      	var anchor_bloc			=	currentpage.substr(url_without_anchor.length);
      	
      	
		
      	var position = url_without_anchor.indexOf('lang=');
		
		var position_en= currentpage.indexOf('recettes/en');
		var position_fr= currentpage.indexOf('recettes/fr');
		
		var lang_position_fr 	=	currentpage.indexOf('/fr/');
		var lang_position_en	= 	currentpage.indexOf('/en/');
		
		
		
		if(position_fr !=-1)
		{
			document.location = str_replace("recettes/fr","recettes/en",currentpage);
		}
		else if(position_en !=-1)
		{
			document.location = str_replace("recettes/en","recettes/fr",currentpage);
		}
		else if(lang_position_fr != -1)
		{
			document.location = str_replace("/fr/","/en/",currentpage);
		}
		else if(lang_position_en != -1)
		{
			document.location = str_replace("/en/","/fr/",currentpage);
		}
		else if (position == -1)
      	{
      		if (url_without_anchor.indexOf('?') != -1)
      		{
      			document.location = url_without_anchor + '&lang=en'+anchor_bloc;
      		}
      		else
      		{
      			document.location = url_without_anchor + '?lang=en'+anchor_bloc;
      		}
      	}
      	else
      	{
      		var lang = url_without_anchor.substr(position + 5, 2);	
      		var newlocation = url_without_anchor.substr(0, position + 5);
      		
      		if (lang == 'fr')
      		{
      			newlocation += 'en' + url_without_anchor.substr(position + 7);
      		}
      		else
      		{
      			newlocation += 'fr' + url_without_anchor.substr(position + 7);
      		}
      		
      		document.location = newlocation+anchor_bloc;
      	}
		
		
}

function validate_captcha(hash, value)
{
	makePostRequest('captcha.php',  'hash=' + escape(hash) + '&value=' + escape(value), 'validate_captcha_handler');
}

function validate_captcha_handler()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			var response = http_request.responseXML.documentElement;
			var valid = response.getElementsByTagName('valid')[0].firstChild.data;
			
			if (Number(valid) == 1)
			{
				// captcha is valid
				captcha_validator(true);
			}
			else
			{
				// captcha is invalid
				captcha_validator(false);
			}
		}
	}
}

function generate_captcha()
{
	makePostRequest('captcha.php?action=generate',  '', 'generate_captcha_handler');
}

function generate_captcha_handler()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			var response 	= http_request.responseXML.documentElement;
			var newhash 	= response.getElementsByTagName('hash')[0].firstChild.data;
			//console.log('Before captcha_reload: ');
			captcha_reload(newhash);
		}
	}
}

function recherche_top()
{
	var currentpage = document.location.href.toLowerCase();
	var longueur = currentpage.length;
	var where_is=currentpage.indexOf('q=')+2;
	var longueur = longueur - where_is;
	var extraction = currentpage.substr(where_is,longueur);
	for (var x = 1; x <= 6; x++) {
		var extraction = extraction.replace("+"," ");
				}
	if (where_is!=-1) document.getElementById('q').value = decodeURIComponent(extraction);
	/*
	if (extraction.indexOf('%')!=-1) return false;
	else if (where_is!=-1) document.getElementById('q').value = extraction;
	*/
}

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, prec = decimals;
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
    if (s.indexOf(dec) === -1 && prec > 1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

window.track_events=true;

function stop_event_tracking(){
    window.track_events=false;
}

function redirect( url, target, event) {
    // Trigger an optional GA event and then redirect 
    var event = event || false
    if (event){
        //using the GA async queue to make sure the redirect happens after the event has been logged
        _gaq.push(function() {
            track_event(event.category, event.action, event.opt_label, event.opt_value);
        });
    }
    _gaq.push(function() {
        window.location.href=url;
    });
}

function track_event(category, action, opt_label, opt_value) {
    // ASync Google Analytics event tracking
    // doc : http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
    if (track_events) {
        var label = opt_label || "";
        var value = opt_value || 1;
        _gaq.push(['_trackEvent', category, action, label, value]); 
    }
}


setTimeout(function(){stop_event_tracking();}, 60000);
