/*
 * AnchorMen jQuery Support Pack™ 1.0.3 - Ajax Extensions
 *
 * 1.0.0 - (2009-01-12) initial release. 
 * 1.0.1 - (2010-03-17) ajaxGet now has a callback option.
 * 1.0.2 - (2010-03-18) instead of giving an alert errors are now displayed in the html element to fill.
 * 1.0.3 - (2010-04-22) ajaxPost now has an optional slideTime parameter that allows the div to slide in and out so the client is aware of changes if the call is too fast to notice.
 *
 * Tested and compatible with jQuery 1.2.6, 1.3.2 and 1.4.2
 *
 * Takes care of some basic ajax calls in short and easy to use functions!
 * 
 * Copyright (c) 2010 Nico Schouten
 *
 * $Date: 2010-04-22$
 *
 */
 
// parameters:
// - urlStr: Url to be requested by the ajax call
// - idStr: Id of the element to write the resulting html into
function ajaxGet(urlStr, idStr, callback)
{
	//browsercache voorkomen:
	if ( urlStr.indexOf('&dummy=') == -1 )
	{
		if ( urlStr.indexOf('?') > -1 )
			urlStr += '&';
		else
			urlStr += '?';
		urlStr += 'dummy='+getRandomString(6);
	}
	
  $.ajax({
		async: true,
    url: urlStr,
    type: 'GET',
    dataType: 'html',
/*
    error: function()
		{
			if ( idStr )
				$('#'+idStr).html('Error loading document. [ajaxGet='+urlStr+']. Please refresh the page to try again.');
			else
				alert('Error loading document. [ajaxGet='+urlStr+']');
    },*/
    success: function(html) 
		{
        // do something with html
				if ( idStr )
					$('#'+idStr).html(html);
					
				if ( callback )
					callback();
    }
  });
	
}

// parameters:
// - formIdStr: Id of the form that should be posted bu the ajax call
// - idStr: Id of the element to write the resulting html into
function ajaxPost(formIdStr, idStr, fadeTime)
{ 
  var form = document.getElementById(formIdStr);
  if ( !form )
    alert('ajaxPost: form '+formIdStr+' not found!');
  
  var urlStr = form.attributes.action.value;
  var params = parseFormDataToUri(form);
  //alert('params:'+params);
  
	var doPost = function (){
		$.ajax({
			type: "POST",
			dataType: 'html',
			url: urlStr,
			data: params,
			success: function(html){
				 // do something with html
					$('#'+idStr).html(html);
					if ( fadeTime )
						$('#'+idStr).slideToggle(fadeTime);
			},
			error: function(error){
				if ( idStr )
					$('#'+idStr).html('Error loading document. [ajaxPost='+urlStr+']. Please refresh the page to try again.');
				else
					alert('Error loading document. [ajaxPost='+urlStr+']');
					
				if ( fadeTime )
						$('#'+idStr).slideToggle(fadeTime);
			}
		});
	};
	
	if ( fadeTime )
		$('#'+idStr).slideToggle(fadeTime, doPost);
	else
		doPost();
}


// ======================================================================================
// = Support functions for parsing form data to strings usable by ajax calls
// ======================================================================================

// parameters:
// - form: a form object acquired by a document.getElementById call
// resultaat:
// - an uri with all names and values of the form data (for example: 'Name=John&Company=MyCompany')
function parseFormDataToUri(form)
{
  return parseArrayToUrlAttributeString( parseFormDataToNamedArray(form) );
}

// parameters:
// - form: a form object acquired by a document.getElementById call
// resultaat:
// - an array with all names and values of the form data (for example: array['Name'] = 'John', array['Company'] = 'MyCompany')
function parseFormDataToNamedArray(form)
{
  if(!form.elements)
  	alert('parseFormDataToNamedArray: Object is not a form');
  var params = [];
  for(var i=0; i<form.elements.length; i++)
  {
  	var element = form.elements[i];
  	if(element && element.type /*&& (element.nodeName == 'INPUT' || element.nodeName == 'TEXTAREA' || element.nodeName == 'SELECT')*/)
  	{
  		if(element.type == 'checkbox') // enable checkbox support even when not checked (and not in request)
  		{
  		  if (element.checked) // alleen checked items meenemen, doet html ook standaard, dus daar houden we rekening mee!
        {
          //als er meerdere checkboxen zijn met dezelfde name, dan doen we dat komma gescheiden, net als de html standaard.
          if (params[element.name])
            params[element.name] += ','+element.value;
          else
            params[element.name] = element.value;
        }
  		    
  			//params[element.name] = element.checked?'on':'off';
  		}
  		else if( element.type == 'radio') // only save the selected option, and not all options!
      {
  		  if(element.checked)
  		  {
  				params[element.name] = element.value;
  			}
  		}
  		else
  		{
  			params[element.name] = element.value;
  		}
  	}
  } //end for
  return params;
}

// parameters:
// - an array with all names and values of the form data (for example: array['Name'] = 'John', array['Company'] = 'MyCompany')
// resultaat:
// - an uri with all names and values of the form data (for example: 'Name=John&Company=MyCompany')
function parseArrayToUrlAttributeString(namedArray)
{
  var data = '';
  var first = true;
  
  if ( !namedArray )
    return data;
  
  for ( var name in namedArray )
  {
    if ( !first )
      data += '&';
    else
      first = false;
      
    data += name+'='+namedArray[name];
  }
  return data;
}

//for the dummy to be used in the get function to prevent browser cache.
function getRandomString(length) 
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<length; i++) 
	{
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

