/* * * * * * * * * * * * * * * * * * * * * 
 *
 * Envisage International Corporation
 * JavaScript Library for the Web
 * 
 */

function popup( mylink, windowname )
{
	if (! window.focus)
	{
		return true;
	}
	
	var href;
	
	if (typeof(mylink) == 'string')
	{
   		href=mylink;
	}
	else
	{
		href=mylink.href;
	}
	
	window.open(href, windowname, 'width=1024,height=600,scrollbars=yes');	
	return false;
}

/**
 *	for some crazy reason the regular JavaScript escape and serialization
 *	cannot work together nicely, so I made this escaping function for now
 *
 */
function envii_encode( str )
{
	escapes = new Array(
							Array(
								  	"\\n", "XXXnewlineXXX"
								  ),
							
							Array(
								  	"&", "XXXandXXX"
								  ),
							
							Array(
								  	"#", "XXXnrXXX"
								  ),
							
							Array(
								  	'\"', "XXXquotemarkXXX"
								  )							
						);

	for( i=0; i< escapes.length; i++ )
	{
		replace_from 	= escapes[i][0];
		replace_to		= escapes[i][1];
		
		str=str.replace( new RegExp( replace_from, "g" ), replace_to );
	}	
	
	return str;
}

/**
 *	this loads at the beginning, so we have the default values  
 *	for the ADMIN table
 *
 */
function loadDefaultSettings()
{
	TableKit.options.editAjaxURI = 'ajax/updateformfield.php';
	TableKit.Editable.multiLineInput( 'provider_address' );

	TableKit.Editable.selectInput('provider_type', {}, [
			['doctor','doc'],
			['urgent care','urge'],
			['hospital','hosp']																												
		]);
	
	TableKit.Editable.selectInput('provider_active', {}, [
			['active','1'],
			['not active','0']
		]);
}

function loadDefultsForLocations()
{
		TableKit.options.editAjaxURI = 'ajax/updatelocationformfield.php';
		TableKit.Editable.multiLineInput( 'location_comments' );	
		
		TableKit.Editable.selectInput('location_active', {}, [
			['active','1'],
			['not active','0']
		]);	
}

/**
 *
 *
 */
function listenOnZipField( input_field_name, form_name )
{
	// the form field object
	form_obj = $(input_field_name);
	if( form_obj.value.length > 2 )
	{
		var url='./ajax/findzip.php?form=' + form_name + '&zip=' + form_obj.value;
		
		new Ajax.Request
		(
		 	url,
			{
				method: 'get',
				onSuccess: function(transport)
				{
					$('zips_display').style.display = 'block';
					$('zips_display').innerHTML = transport.responseText;
				}
			}
		);
	}
	else
	{
		$('zips_display').style.display = 'none';
		
		$('new_provider_state_display').innerHTML = '';
		$('new_location_state_display').innerHTML = '';
		
		$('new_provider_city_display').innerHTML = '';
		$('new_location_city_display').innerHTML = '';
		
		$('new_provider_state').value = '';
		$('new_location_state').value = '';
		
		$('new_provider_city').value = '';
		$('new_location_city').value = '';
	}
}

/**
 * updates the information that show for the user and the hidden 
 * form field as well
 *
 */ 
function updateProviderCityDisplay( zip, state, city, population )
{
	$('new_provider_zip').value = zip;
	$('new_provider_state').value = state;
	$('new_provider_city').value = city;
	$('new_provider_population').value = population;	
	$('new_provider_state_display').innerHTML = state;
	$('new_provider_city_display').innerHTML = city;	
}

/**
 * updates the information that show for the user and the hidden 
 * form field as well
 *
 */ 
function updateLocationCityDisplay( zip, state, city, population )
{
	$('new_location_zip').value = zip;
	$('new_location_state').value = state;
	$('new_location_city').value = city;
	$('new_provider_population').value = 0;	
	$('new_location_state_display').innerHTML = state;
	$('new_location_city_display').innerHTML = city;	
}

/**
 * resets all the NEW PROVIDER FORM fields
 * 
 */
function resetFormFields()
{
	$('new_provider_zip').value = '';
	$('new_provider_state').value = '';
	$('new_provider_city').value = '';
	$('new_provider_address').value = '';	
	$('new_provider_phone').value = '';
	$('new_provider_name').value = '';	
	$('new_provider_state_display').innerHTML = '';
	$('new_provider_city_display').innerHTML = '';
	$('zips_display').hide();
	$('error_display').hide();
}

/**
 *
 *
 */
function resetLocationFormFields()
{
	$('new_location_zip').value = '';
	$('new_location_state').value = '';
	$('new_location_city').value = '';
	$('transportation_url').value = '';	
	$('travel_url').value = '';
	
	$('new_location_state_display').innerHTML = '';
	$('new_location_city_display').innerHTML = '';
	
	$('zips_display').hide();
	
	$('location_error_display').hide();
}

/**
 * this form submit is for a NEW PROVIDER
 *
 */
function submitForm( form_obj )
{
	clearErrorDisplay( 'error_display' );
	$('zips_display').style.display='none';
	
	if( simpleProviderValidation( form_obj ) )
	{		
		// so everything seems OK so far, let's process
//		alert( form_obj['new_provider_name'].value );
		$('ajax_loader_display').style.display='block';
		
		// we'll need this for the JSON version
		
//		var name 	= form_obj['new_provider_name'].value.replace(/&/, "and" );
//		var address = form_obj['new_provider_address'].value.replace( new RegExp( "\\n", "g" ), "\n" );
//		alert( address ); return false;
		
		var data_for_json = {
						name: 		envii_encode( form_obj['new_provider_name'].value ),
						tel: 		form_obj['new_provider_phone'].value, 
						address:	envii_encode( form_obj['new_provider_address'].value ),
						zip:		form_obj['new_provider_zip'].value,
						type:		form_obj['new_provider_type'].value,
						active:		form_obj['new_provider_active'].value,
						state:		form_obj['new_provider_state'].value,
						city:		form_obj['new_provider_city'].value,
						population: form_obj['new_provider_population'].value
					};
//		alert( Object.toJSON(data) );
//		var url='./ajax/addnewprovider.php?data=' + Object.toJSON( data );	
		
//		data = Object.toJSON( data_for_json );	
		var url = './ajax/addnewprovider.php?data=' + serialize( data_for_json );
		
		new Ajax.Request
		(
		 	url,
			{
				method: 'get',
				onSuccess: function(transport)
				{					
					if( transport.responseText == 'success' )
					{
						$('ajax_loader_display').style.display = 'none';
						$('status_display').innerHTML = 'new provider saved';
						$('status_display').style.display = 'block';
						$('status_display').fade({duration: 5.0});
						resetFormFields();
					}
					else
					{
						$('ajax_loader_display').style.display = 'none';						
						updateErrorDisplay( 'error_display', 'invalid character in one of the form fields' );
					}
				}
			}
		);
	}
}

/**
 *
 *
 */
function submitLocationForm( form_obj )
{
	clearErrorDisplay( 'location_error_display' );
	$('zips_display').style.display='none';
	
	if( simpleLocationValidation( form_obj ) )
	{		
		// so everything seems OK so far, let's process
//		alert( form_obj['new_provider_name'].value );
		$('ajax_location_loader_display').style.display='block';

		// we'll need this for the JSON version
		
//		var name 	= form_obj['new_provider_name'].value.replace(/&/, "and" );
//		var address = form_obj['new_provider_address'].value.replace( new RegExp( "\\n", "g" ), "\n" );
//		alert( address ); return false;
		
		// first let's get the CLIENTS, put them into a nice string
		var clients = "";
		for( i=0; i < form_obj['new_location_client'].options.length; i++ )
		{
			// if this client is selected ...
			if( form_obj['new_location_client'].options[i].selected )
			{
				clients = clients + form_obj['new_location_client'].options[i].value + ',';									
			}
		}
		
		var data_for_json = {
						city:		envii_encode( form_obj['new_location_city'].value ),
						zip:		envii_encode( form_obj['new_location_zip'].value ),
						state:		envii_encode( form_obj['new_location_state'].value ),
						transport:	envii_encode( form_obj['transportation_url'].value ),
						travel:		envii_encode( form_obj['travel_url'].value ),
						clients:	clients
					};
//		alert( Object.toJSON(data) );
//		var url='./ajax/addnewprovider.php?data=' + Object.toJSON( data );	
		
//		data = Object.toJSON( data_for_json );	
		var url = './ajax/addnewlocation.php?data=' + serialize( data_for_json );

		new Ajax.Request
		(
		 	url,
			{
				method: 'get',
				onSuccess: function(transport)
				{					
					if( transport.responseText == 'success' )
					{
						$('ajax_location_loader_display').style.display 	= 'none';
						$('location_status_display').innerHTML 				= 'new location saved';
						$('location_status_display').style.display 			= 'block';
						$('location_status_display').fade({duration: 5.0});
						resetLocationFormFields();
					}
				}
			}
		);
	}
}

/**
 *
 *
 */
function simpleProviderValidation( form_obj )
{
	var pass = true;
	
	if( form_obj[ 'new_provider_name' ].value.length == 0 )
	{
		pass = false;
		updateErrorDisplay( 'error_display', 'provider name is required' );
	}
	
	if( form_obj[ 'new_provider_city' ].value.length == 0 )
	{
		pass = false;
		updateErrorDisplay( 'error_display', 'a valid zip and city is required' );
	}
	
	if( pass )
	{
		return true;
	}
	else
	{
		return false;
	}
}

/**
 *
 *
 */
function simpleLocationValidation( form_obj )
{
	var pass = true;
	
	/*
	if( form_obj[ 'new_location_zip' ].value.length == 0 )
	{
		pass = false;
		updateErrorDisplay( 'location_error_display', 'location name is required' );
	}
	*/
	
	if( form_obj[ 'new_location_zip' ].value.length == 0 || form_obj[ 'new_location_city' ].value.length == 0 )
	{
		pass = false;
		updateErrorDisplay( 'location_error_display', 'a valid zip and city is required' );
	}
	
	if( pass )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function updateErrorDisplay( field, text )
{
	$(field).innerHTML = $(field).innerHTML + '<li>' + text + '</li>';
	$(field).style.display = 'block';
}

function clearErrorDisplay( field )
{
	$(field).innerHTML = '';
}

/*
 *	we need this function for now, becuase we don't have php5.2.x 
 *  on the server so we don't have JSON support in PHP :(
 *
 */
function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}
