/**
 * Usage of this ajax class
 * 
 * All ajax methods will have the same resultset as json output.
 * 
 * json.html		Html output of the json call used to update 'div'
 * json.notice		Displays a notice to the user 
 * json.type		Type of display alert (javascript alert) or default ('div'+error)
 * json.redirect	Will redirect a user to this page
 * 
 * I want to GET an update for a div
 * sendRequest(methode, functioncall, div);
 * 
 * I want to post my form from div, make sure the form has the 'div' id like <form id='div'>
 * postRequest(methode, functioncall, div);
 * 
 * I want to update a div with this image
 * imageRequest(methode, functioncall, imagename, div);
 * 
 * I want to delete stuff and update div (optional)
 * confirmation(item, itemname, id, div);
 * Will do a javascript confirm box and then execute sendRequest() with method delete+'methode'
 */

/**
 * Register responders
 */ 
Ajax.Responders.register(
{
	onCreate: function() {
		Ajax.activeRequestCount++;
	},
	onComplete: function() {
		Ajax.activeRequestCount--;
	}	
});

/**
 * Show the ajax loader
 */
function showLoader(div) {
	//TODO: If onComplete make sure timeout is cancelled!
	window.setTimeout("startloader('" + div + "')", 650);
}

/**
 * Start the ajax loader
 */
function startloader(div) {
	if(!Ajax.activeRequestCount)
	{
		return false;
	}
	// Show the loader
	var loader = div + 'loader';
	var error = div + 'error';
	$(loader).show();
	$(error).hide();
}

/**
 * Stop the ajax loader
 */
function stopLoader(div) {
	// Hide the loader
	var loader = div + 'loader';
	$(loader).hide();
}

function sendRequestP(methode, functioncall, callback) {
	//If this call is already running stop!
	if(Ajax.activeRequestCount) {	
		return false;
	}

	//showLoader(div);	
	
	// Prepare the request url
	var url = basepath + 'account/' + methode + '/' + functioncall;

	// Do the ajax request
	new Ajax.Request(url, {
		method: 'post',
		parameters: { requestitem: functioncall, method: methode },
		onSuccess: function(transport, json) {
			//Always stop the loader
			//stopLoader(div);
			// Super annoying fix.... leave me be!
			if(!json) {
				json = eval('(' + transport.responseText + ')');
			}

			//If error is set, stop!
			if(json.error) {
				//errorMessage(json.error,json.etype,div);
			}
			//If notice is set, continue!
			else {
				if(json.notice){
					//errorMessage(json.notice,json.ntype);
				}
				if(json){
					//$(div).innerHTML = json.html;
					callback(json);
				}				
				redirect(json);
				
			}
		},
		onFailure: function(transport) {
			alert('method ' + methode + ' failed');
		}
	});
	return false;
}

/**
 * Show the ajax loader
 */
function sendRequest(methode, functioncall, div) {
	//If this call is already running stop!
	if(Ajax.activeRequestCount || !div) {	
		return false;
	}

	showLoader(div);	
	
	// Prepare the request url
	var url = basepath + 'ajax/' + methode + '/' + functioncall;

	// Do the ajax request
	new Ajax.Request(url, {
		method: 'post',
		parameters: { requestitem: functioncall, method: methode },
		onSuccess: function(transport, json) {
			//Always stop the loader
			stopLoader(div);
			// Super annoying fix.... leave me be!
			if(!json) {
				json = eval('(' + transport.responseText + ')');
			}
				
			//If error is set, stop!
			if(json.error) {
				errorMessage(json.error,json.etype,div);
			}
			//If notice is set, continue!
			else {
				if(json.notice){
					errorMessage(json.notice,json.ntype, div);
				}
				if(div && json.html){
					$(div).innerHTML = json.html;
				}				
				redirect(json);
				
			}
		},
		onFailure: function(transport) {
			alert('method ' + methode + ' failed');
		}
	});
	return false;
}

/**
 * Show the ajax loader
 */
function postRequest(methode, functioncall, div, div2) {
	//If this call is already running stop!
	if(Ajax.activeRequestCount || !div) {
		return false;		
	}

	showLoader(div);	
	
	// Prepare the request url
	var url = basepath + 'ajax/' + methode + '/' + functioncall;
	var params = $(div).serialize(true);

	// Do the ajax request
	new Ajax.Request(url, {
		method: 'post',
		parameters: params,	
		onSuccess: function(transport, json) {
			//Always stop the loader
			stopLoader(div);			
			// Super annoying fix.... leave me be!
			if(!json) {
				json = eval('(' + transport.responseText + ')');
			}	

			//If error is set, stop!
			if(json.error) {
				errorMessage(json.error,json.etype, div);
			}
			//If notice is set, continue!
			else {
				if(json.notice){
					errorMessage(json.notice,json.ntype, div);
				}
				if(div2 && json.html){
					$(div2).innerHTML = json.html;
				}				
				redirect(json);
			}
		},
		onFailure: function(transport) {
			alert('method ' + methode + ' failed');
		}
	});
	return false;
}

/**
 * Show the ajax loader
 */
function imageRequest(methode, functioncall, imagename, div) {
	//If this call is already running stop!
	if(Ajax.activeRequestCount || !div) {	
		return false;		
	}

	showLoader(div);
	
	// Prepare the request url
	var url = basepath + 'ajax/' + methode + '/' + functioncall;

	// Do the ajax request
	new Ajax.Request(url, {
		method: 'post',
		parameters: { image: imagename, method: methode },
		onCreate: function() {
			showLoader(div);
		},		
		onSuccess: function(transport, json) {
			//If error is set, stop!
			if(json.error) {
				errorMessage(json.error,json.etype, div);
			}
			//If notice is set, continue!
			else {
				if(json.notice) {
					errorMessage(json.notice,json.ntype, div);
				}
				//If theres a notice, update the admin_list frame with method X
				$(div).innerHTML = json.html;
			}
		},
		onFailure: function(transport) {
			stopLoader(div);
			alert('method ' + methode + ' failed');
		}
	});
	return false;
}

/**
 * Show the ajax loader
 */
function redirect(json) {
	if(!json.redirect) {
		return false;
	}
	//TODO: make a config item?
	window.location = basepath + json.redirect;
}

/**
 * Show the ajax loader
 */
function errorMessage(message,type, div) {
	if(type) {
		return alert(message);
	}
	var elem = $(div + 'error');
	elem.show();
	elem.innerHTML=message;
}

/**
 * Show the ajax loader
 */
function confirmation(methode, functioncall, id, div) {
	var test = confirm("Wilt u dit item verwijderen?");
	if(test) {
		sendRequest(methode, functioncall + '/' + id, div);
		return true;
	}
	return false;
}

function showDiv(name) {
	$(name).show();
}

function hideDiv(name) {
	$(name).hide();
}

function mooRequest(methode, functioncall, div) {
	//If this call is already running stop!
	if(Ajax.activeRequestCount || !div) {	
		return false;
	}

	showLoader(div);	
	
	// Prepare the request url
	var url = basepath + 'ajax/' + methode + '/' + functioncall;

	// Do the ajax request
	new Ajax.Request(url, {
		method: 'post',
		parameters: { requestitem: functioncall, method: methode },
		onSuccess: function(transport, json) {
			//Always stop the loader
			stopLoader(div);
			// Super annoying fix.... leave me be!
			if(!json) {
				json = eval('(' + transport.responseText + ')');
			}
				
			//If error is set, stop!
			if(json.error) {
				errorMessage(json.error,json.etype,div);
			}
			//If notice is set, continue!
			else {
				if(json.notice) {
					errorMessage(json.notice,json.ntype,div);
				}
				$(div).innerHTML = json.html;
				fAccordion();
			}
		},
		onFailure: function(transport) {
			alert('method ' + methode + ' failed');
		}
	});
	return false;
}

window.onload = function()
{
	var elem;
	
	if(elem = $('product-scroll'))
	{
	
		var child = elem.childNodes[1];
		child.counter = 1;
		child.scroller = function(elem)
		{
			elem.style.marginLeft = '-' + (elem.counter++ * 3)  + 'px';
			
			if (elem.counter * 3 >= elem.offsetWidth) 
			{
				elem.counter = 1;
				elem.style.marginLeft = '0px';
			}
		}
		child.interval = setInterval(function()
		{
			child.scroller(child);
		} , 50); 
	}
	
	if (elem = $$('.formpanel')) 
	{
		if (typeof elem[0] != 'undefined') 
		{
		
			elem[0].onsubmit = function()
			{
				fields = elem[0].getElementsBySelector('input')
				for (i = 0; i < fields.length; i++) 
				{
					//console.log();
					if (!fields[i].valid && (fields[i].type == 'text' || fields[i].type == 'password')) 
					{
						if (fields[i].validate) 
							if(fields[i].validate('true'))
								continue;
						
						return false;
					}
					
				}
				return true;
			}
			
			fields = elem[0].getElementsBySelector('input')
			//var_dump(elem);
			
			for (i = 0; i < fields.length; i++) 
			{
				if (fields[i].type != 'text' && fields[i].type != 'password') 
					continue;
				
				if ($(fields[i]).hasClassName('form-input-valid')) 
					$(fields[i]).valid = true;
				
				fields[i].validate = function(force)
				{
					if (/*(this.value == '' && force != 'true') ||*/ this.readOnly) 
						return;
						
					if ($(this).hasClassName('blankAllowed')) 
					{
						$(this).removeClassName('form-input-load');
						$(this).removeClassName('form-input-error');
						$(this).removeClassName('form-input-empty');
						$(this).addClassName('form-input-valid');
						return (this.valid = true);
					}	
						
					$(this).removeClassName('form-input-empty');
					$(this).removeClassName('form-input-error');
					$(this).addClassName('form-input-load');
					
					if (!$(this).formpanel) 
					{
						var form = this;
						while (!((form = form.parentNode).tagName == 'FORM'));
						$(this).formpanel = $(form);
					}
					
					//console.log($(this).formpanel.serialize(true));	
					
					this.ajaxCall = new Ajax.Request(basepath + 'account/validation/', {
						method: 'post',
						parameters: {
							value	: this.value,
							id		: $(this).id,
							fields	: $(this).formpanel.serialize(true)
						},
						onSuccess: function(transport, json)
						{
							if (!json) 
								json = eval('(' + transport.responseText + ')');
							UnTip();
							
							if (json.notification) 
							{
							
								//$('form-notification').hide();
								$('form-notification').innerHTML = json.notification;
								if ($('form-notification')) 
								{
									$('form-notification').innerHTML = json.notification;
									$('form-notification').style.display = 'block';
								}
								
							//alert(json.notification);
							//$('form-notification').show();
							}
							
							if (json.error || (json.equal && $(json.id).value != $(json.equal).value)) 
							{
							
								if (!json.error) 
									json.error = json.equalmessage;
								
								$(json.id).removeClassName('form-input-load');
								$(json.id).removeClassName('form-input-valid');
								$(json.id).addClassName('form-input-error');
								if (json.transform) 
									$(json.id).value = json.transform;
								$(json.id).valid = false;
								$(json.id).style.cursor = 'help';
								
								$(json.id).onmouseover = function()
								{
									Tip(json.error);
								};
								
								$(json.id).onmouseout = function()
								{
									UnTip();
								};
							}
							else 
								if (json.valid) 
								{
									$(json.id).valid = true;
									
									$(json.id).onmouseover = null;
									$(json.id).onmouseout = null;
									$(json.id).style.cursor = 'text';
									
									$(json.id).removeClassName('form-input-load');
									$(json.id).removeClassName('form-input-error');
									$(json.id).addClassName('form-input-valid');
									if (json.transform) 
										$(json.id).value = json.transform;
									if (json.readonly) 
										for(i=0; i < json.readonly.length; i++)
											$(json.readonly[i]).readOnly = true;
								
									if (json.show) 
									{
										$(json.show).show();
										if (first = $(json.show).getElementsBySelector('input')) 
											first[0].focus();
									}
										
									if (json.hide) 
										for(i=0; i < json.hide.length; i++)
											$(json.hide[i]).hide();	
									
									if (json.disable) 
										$(json.id).disabled = true;
									
									if (json.clear && $(json.clear)) 
										$(json.clear).value = '';
									
									
								}
						},
						onFailure: function(transport)
						{
							alert('Error with call');
						}
					});
					
					
				//var errorMessage = document.createElement('div');
				//errorMessage.className = 'error';
				
				}
				//fields[i].onblur = fields[i].validate;
				fields[i].onchange = fields[i].validate;
			//alert('yes');
			}
		}
		
	}	
	
	var charity;
	if(charity = $('charities'))
	{
		var charities = charity.getElementsByClassName('charity-hidden'); 
		for(i=0;i < charities.length; i++)
		{
			charities[i].onclick = function()
			{
				var elements = $('charities').getElementsByClassName('charity-visible');
				for (x = 0; x < elements.length; x++) 
					if(this != elements[x])
						elements[x].className = 'charity-hidden';
				
				this.className = 'charity-visible';
			}
		}
	}
	
}


function charityButtonHandler(button, id)
{
	var elements = button.parentNode.getElementsByClassName('charity-form');
	var form = elements[0];
	if(form.style.display == 'block')
	{
		if(validateCharityForm($('charity-form-' + id)))
			$('charity-form-' + id).submit();
	}
	else
	{
		form.style.display = 'block';
		$('charity-form-' + id).onsubmit = validateCharityForm; 
	}
	
}

function validateCharityForm(form)
{
	var fields = form.getElements(); 
	var error = false;
	var values = {};
	for(i=0;  i < fields.length; i++)
		if((fields[i].type == 'radio' && fields[i].checked) || fields[i].type != 'radio')
			values[fields[i].name] = fields[i].value;
	
	var id = values['charity-id'];	
	if(values['type['+id+']'] == 'periodic')
	{
		if (!values['amount-periodic'] || parseInt(values['amount-periodic']) < 250 || isNaN(parseInt(values['amount-periodic']))) {
			error = 'Vul minimaal 250 values in.';
		}
	}
	else if(values['type['+id+']'] == 'once')
	{
		if (
			(
				!values['amount-once'] || 
				parseInt(values['amount-once']) < 250 || 
				parseInt(values['amount-once']) > 10000000 ||
				isNaN(parseInt(values['amount-once']))
			)
			
		) {
			error = 'Vul minimaal 250 en maximaal 10000000 values in.';
		}
	}
	else
	{
		error = 'Selecteer een periodieke of eenmalige betaling.';
	}	

	if (error) 
	{
		alert(error);	
		return false;
	}
	
	return true;	
}

function scroller(element, el2)
{
	var_dump(this);
}


function var_dump(element, limit, depth)
{
	depth =	depth?depth:0;
	limit = limit?limit:1;

	returnString = '<ol>';

	for(property in element)
	{
		//Property domConfig isn't accessable
		if (property != 'domConfig')
		{
			returnString += '<li><strong>'+ property + '</strong> <small>(' + (typeof element[property]) +')</small>';

			if (typeof element[property] == 'number' || typeof element[property] == 'boolean')
				returnString += ' : <em>' + element[property] + '</em>';
			if (typeof element[property] == 'string' && element[property])
				returnString += ': <div style="background:#C9C9C9;border:1px solid black; overflow:auto;"><code>' +
									element[property].replace(/</g, '&amp;lt;').replace(/>/g, '&amp;gt;') + '</code></div>';

			if ((typeof element[property] == 'object') && (depth < limit))
				returnString += var_dump(element[property], limit, (depth + 1));

			returnString += '</li>';
		}
	}
	returnString += '</ol>';

	if(depth == 0)
	{
		winpop = window.open("", "","width=800,height=600,scrollbars,resizable");
		winpop.document.write('<pre>'+returnString+ '</pre>');
		winpop.document.close();
	}	

	return returnString;
}


