/*
 * AnchorMen jQuery Support Pack™ 1.0.0 - Ajax Extensions
 * Tested and compatible with jQuery 1.2.6
 *
 * Takes care of some basic ajax calls in short and easy to use functions!
 * 
 * Copyright (c) 2009 Nico Schouten
 *
 * $Date: 2009-01-12$
 *
 */

// 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)
{
	//browsercache voorkomen:
	if ( urlStr.indexOf('&dummy=') == -1 )
	{
		if ( urlStr.indexOf('?') > -1 )
			urlStr += '&';
		else
			urlStr += '?';
		urlStr += 'dummy='+getRandomString(6);
	}
	
  $.ajax({
    url: urlStr,
    type: 'GET',
    dataType: 'html',
    timeout: 5000,
    error: function(){
        alert('Error loading document. [ajaxGet='+urlStr+']');
    },
    success: function(html){
        // do something with html
        $('#'+idStr).html(html);
    }
  });
}

// 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)
{ 
  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);
  
  $.ajax({
    type: "POST",
    dataType: 'html',
    url: urlStr,
    data: params,
    success: function(html){
       // do something with html
        $('#'+idStr).html(html);
    },
    error: function(error){
        alert('Error loading document. [ajaxPost='+urlStr+']');
    }
  });
}


// ======================================================================================
// = 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;
}

