<!--
// This calls our function ClearInput, and the two variables we
// will need for it to function the original value and the id.
function ClearInput(value, element){ 
	if(value == element.value) element.value = '';
} 
function ResetInput(value, element){ 
	if (element.value== '') element.value = value;
} 

// AJAX function
function ajax_call(url, params, targetdiv) {
	if(targetdiv === undefined)
	{
		new Ajax.Request(url, {
			parameters: params,
			evalScripts: true
		});	
	} else {
		new Ajax.Updater(targetdiv,url, {
			parameters: params,
			evalScripts: true
		});	
	}
}

function formHandler(formid, fieldvalue )
{
	if (fieldvalue!='')
	{
		document.getElementById(formid).deleteid.value = fieldvalue;
	}
	document.getElementById(formid).submit();
} 

function polaroid_focus(polaroid)
{
	polaroid.className = "polaroid_focus clickable";
}

function polaroid_blur(polaroid)
{
	polaroid.className = "polaroid_blur clickable";
}

function keep_scrolling(id, width, startnr, maxnr, duration, time) {
	new Effect.Move(id, { x: (-1*width*startnr), y: 0, mode: 'absolute', duration: duration}); 
	setTimeout("keep_scrolling('"+id+"',"+width+","+((startnr+1)%maxnr)+","+maxnr+","+duration+","+time+");", time);
	return false;
}


// CALL WAKEUP.PHP TO MAKE SURE THE USER DOESN'T GET LOGGED OUT WHILE WEBSITE IS STILL OPEN
function wakeup() {
    new Ajax.Updater('wakeup', '/wakeup.php');
    setTimeout("wakeup();",3300000); // an hour
}

function removeAnchorFromURL(theURL) {
	//if no # is found in the url return the url...
	if (theURL.search('#') < 0) return theURL; 
	//remove the # and the text at the right of it!
	charIndex = theURL.search('#');
	return(theURL.substring(0, charIndex));
}

//removes a forced language in the url (e.g. '/en/search/user' (used for SEO purposes) is turned to '/search/user)'
function removeURLLanguage(theURL) {
	var languages = ['en', 'nl'];
	var newURL = theURL;
	for(var i in languages)
	{
		newURL = newURL.replace('/'+languages[i]+'/', '/');
	}		
	return newURL;
}

//change language
function change_user_lang(user_lang)
{	
	// change lang in user profile
  new Ajax.Request('/change_lang.php', {
    method: 'post',
    parameters:{ lang : user_lang},
    onSuccess: function () { window.location = removeURLLanguage(removeAnchorFromURL(window.location.href)); },
    onFailure: function (err) { alert(err.responseText); }
  });
}

// google map api function for address.
var obj_result = [];
var geocoder;
var blind_down = false;
var location_changed=false;

function initialize_googlemap()
{ 
	location_changed=false;
	geocoder = new google.maps.Geocoder();
	obj_result = new Object();

	document.getElementById("selected_address").innerHTML='';
	document.getElementById("validate_selected_address").innerHTML='';
	document.getElementById("address_search_result").innerHTML ='';
	document.getElementById("city").value='';
	document.getElementById("latitude").value='';
	document.getElementById("longitude").value='';
	document.getElementById("formatted_address").value='';
	search_address();	
}	

function search_address() 
{
	$('address_search_result').hide();
	var address = $('address').value + ', ' + $('country').value;
	var allowed_address_component_types=['locality','sublocality','administrative_area_level_3', 'administrative_area_level_2', 'administrative_area_level_1'];
	if (geocoder) 
	{
	  var user_country = $('country').value;

	  geocoder.geocode( { 'address': address, 'language' : CURRENT_LANG, 'region': user_country}, function(results, status) 
		{	
		  	if($('submit_btn') != undefined)$('submit_btn').onclick = function() { $('register').submit(); hideAndShowLoading(this); };//this is used in the registration
			if (status==google.maps.GeocoderStatus.OK) 
			{		
				obj_result = [];
				var number_result = 0;
				$('address_search_result').innerHTML = MAP_MORE_RESULTS + '<br>';				
				last_index = results.length;

				results.each(function(result, index) {
					//Check if addres is really in the users country (sometimes google gives back results not from the country)
					var in_user_country = false;
					for(var j=0; (j<result.address_components.length); j++)
					{
						if (result.address_components[j].types.indexOf('country')!=-1) {
							if ((result.address_components[j].short_name == user_country)) in_user_country = true;
						}
					}
					
					var not_found_yet = true;
					for(var j=0; not_found_yet && in_user_country && (j<allowed_address_component_types.length); j++)
					{	
						(result.address_components).each(function(address_component) {														  
							if (not_found_yet && (address_component.types).indexOf(allowed_address_component_types[j])!=-1) {
								result_object = new Object();
								result_object.formatted_address = result.formatted_address;
								result_object.city = address_component.short_name;
								result_object.latitude = result.geometry.location.lat();
								result_object.longitude = result.geometry.location.lng();

								obj_result.push(result_object);
								$('address_search_result').innerHTML +=
									'<br/><div class="address_search_result"  readonly="readonly" onclick="select_address('+number_result+');">'+
									result_object.formatted_address+'</div>';								
								number_result++;
								not_found_yet = false;
							}
						});
					}
				});
				
				if(number_result==0)
				{
					$('address_search_result').innerHTML='';
					$('selected_address').innerHTML = MAP_NO_RESULTS;
					validatecity('validate_selected_address');
				}
				else if(number_result==1)
				{
					$('address_search_result').innerHTML='';
					select_address(0);
				}
				else
				{
					var result_height = (last_index*35+75);
					$('address_search_result').style.height = result_height;
					new Effect.BlindDown("address_search_result");
					blind_down = true;
				}
			}
			else
			{	
				$('address_search_result').innerHTML='';
				$('selected_address').innerHTML = MAP_NO_RESULTS;
				validatecity('validate_selected_address');
			}			
		}
	  );
	}
}
  
function select_address(index)
{
	$('selected_address').innerHTML = obj_result[index].formatted_address;
	$('formatted_address').value = obj_result[index].formatted_address;
	$('city').value = obj_result[index].city;
	$('latitude').value = obj_result[index].latitude;
	$('longitude').value = obj_result[index].longitude;	
	
	validatecity('validate_selected_address');

	if(blind_down) {
		new Effect.BlindUp('address_search_result');
	}
		
}
// google map api function.
 
 /**
* Window popup
*/
function popup(url, width, height, name)
{
	if (!name)
	{
		name = '_popup';
	}

	window.open(url.replace(/&amp;/g, '&'), name, 'height=' + height + ',resizable=yes,scrollbars=yes, width=' + width);
	return false;
}

//Cancel a click event
function cancelClickEvent(e) {
	//make sure that only this onclick function is called, so the getExerciseInfo() is not called	
	if (!e) var e = window.event;
	if(e != undefined) {
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
}
 
//Hides for example a button and shows the loading animation instead
function hideAndShowLoading(element) {
	$(element).insert({'after' : '<img src="/images/loading.gif" />'});
	$(element).hide();
}

/*
	This class takes care of calling an ajax call at a submit.
	Requires a div with id="<result_div>"
	
	This class allows you to validate a page without a page refresh because ajax is used. You can use an alert message to show the validation errors.
	Example php code: print('<script>alert("'.$error_string.'");</script>'); 
	
	Example call from HTML: onclick="new FormSubmit('input_form', 'result'); return false;"
		
	@params	string form_id (ID of the form), 
			string result_div (ID of the result div), 
			boolean show_loader (Set to true if you want to show a loading icon) optional, 
			string show_loader_div (ID of a div where the loading icon should be placed) optional,
			int loader_type (0 for big loader, 1 for small loader, 2 for wide loader) optional

*/
var FormSubmit = Class.create(
{
	initialize: function(form_id, result_div, show_loader, show_loader_div, loader_type) 
	{
		this.result_div = result_div;
		if(show_loader == true){
			var loader_location = this.result_div;
			if(show_loader_div){
				loader_location = show_loader_div;
			}
			if(loader_type == undefined || loader_type == 0){
				$(loader_location).update('<img src="/images/loading.gif" alt="loading..." style="width: 32px; height: 32px; margin: 5px auto; display: block;" />');
			}else if(loader_type == 1){
				$(loader_location).update('<img src="/images/loaders/ajax-loader_snake.gif" alt="loading..." style="width: 16px; height: 16px; margin: 0px auto; display: block;" />');
			}else{
				$(loader_location).update('<img src="/images/loaders/loading_bert2_orange.gif" alt="loading..." style="width: 128px; height: 15px; margin: 5px auto; display: block;" />');
			}
		}
		$(form_id).request({
			onSuccess: function(t) {
				$(this.result_div).update(t.responseText);
			}.bind(this)			
		});
	}
});

function show_tooltip(event) {			
	var element = event.element();
	var cnt = 0;
	while(cnt<10){		
		if(element.readAttribute('tooltip') == null){
			element = element.up();			
		}else{
			break;
		}	
		cnt++;
	}	
	var text = element.readAttribute('tooltip');
	var postionFix = parseInt(element.getStyle('width').replace('px', ''));
	$('tooltip_text').update(text);	
	$('tooltip_holder').setStyle({ width:'250px'});		
	$('tooltip_holder').show();
	Element.clonePosition($('tooltip_holder'), $(element), {setWidth: false, setHeight: false});	
	$('tooltip_holder').setStyle({ top: ($('tooltip_holder').getStyle('top').replace('px', '') - ($('tooltip_text').getHeight()+35)) + 'px'});
	$('tooltip_holder').setStyle({ left: ($('tooltip_holder').getStyle('left').replace('px', '') - (27-(Math.floor(postionFix/2)))) + 'px'});
}

function scanForTooltips(){
	var elements = $$("[tooltip]");
	elements.each(	
		function(e) {
			var childs = e.childElements();
			var numC = childs.length;
			Event.observe(e, "mouseover", show_tooltip);
			Event.observe(e, "mouseout", function(event) { $('tooltip_holder').hide(); });
			childs.each(
				function(a) {
					Event.stopObserving(a);
					Event.observe(a, "mouseover", show_tooltip);
					Event.observe(a, "mouseout", function(event) { $('tooltip_holder').hide(); });
				}
			);
		}
	);
}

Event.observe(window, 'load', function() {
	scanForTooltips();
});

function outside_click_handler(e) {
	if (!e) var e = window.event;
	var src = e.target;

	if(!$(src).descendantOf('menu_dropdown') && src.id != 'menu_dropdown' && 
	   !$(src).descendantOf('show_menu_dropdown') && src.id != 'show_menu_dropdown') {
		$('menu_dropdown').hide();
		document.stopObserving('click', outside_click_handler);
	}
}

function load_graph(graphtype1, graphtype2, period, user_link, user_id, width, height, advanced_input, page) {
	$('graph_container').update('<img style="margin: 75px 50% 0px 50%;" id="loading_image" src="/images/loading.gif" />');
	new Ajax.Updater('graph_container', user_link+'/ajax', {
		parameters: { 	
						action : 'get_graph_data',
						graphtype1 : graphtype1,
						graphtype2 : graphtype2,	
						u : user_id,
						period: period,
						width: width,
						height: height,
						advanced_input : advanced_input,
						page_graph_data : page
					},
		evalScripts: true
	});	
}

function connect_social(network_name, ach_url) {
	new Ajax.Updater('result', '/user/ajax', 
		{
		method:	'get',
		parameters: {
						action : 'connect_social',	
					  	message : $F('message'),
					  	network : network_name,
					  	ach_url_id : ach_url
					},
		evalScripts: true
		}
	);
}

function send_social_message(ach_url){
	new Ajax.Updater('result', '/user/ajax', {
		method:	'get',
		parameters: {
			action : 'send_social_message',
			message : $F('ach_popup_message'),
			ach_url_id : ach_url
		},
		evalScripts: true
	}
	);
}

//-->
