// ---------------------------------------------------------------------------- //
/*	Parts of this library were built assuming the availability of jQuery v1.3.2.
*/
// ---------------------------------------------------------------------------- //

if( typeof( LZ_LANGUAGE ) == 'undefined' )
	LZ_LANGUAGE = 'en';

// ---------------------------------------------------------------------------- //
/*	lz_validate_ids
*/
// ---------------------------------------------------------------------------- //

function lz_validate_ids( ids )
{
	var			inputs = [];
	var			id_count = ids.length;
	
	for( var i = 0; i < id_count; i++ )
	{
		var		elem = document.getElementById( ids[i] );
		
		if( elem != undefined )
			inputs[inputs.length] = elem;
		else
			alert( ids[i] );
	}
	
	return validate_inputs( inputs );
}


// ---------------------------------------------------------------------------- //
/*	lz_validate_inputs
	
	This function accepts a series of HTML objects and checks their value.
	
	It assumes these fields will have <label>s with ids that are the same as 
	the field + "_req" (e.g., f_name & f_name_req) if that field is required.
	
	It also assumes any email address in the form will end with '_email'.
	
	In the case of radio buttons, the first element should have an id the same
	as the name, but no others should have ids. Other input types should have
	the same name and id.
	
	Any field that does not contain data will have its label's class changed
	to "required". The class name is cleared every time data is found in a 
	required fields, so class names shouldn't carry class names of their own.
*/
// ---------------------------------------------------------------------------- //

function lz_validate_inputs( inputs )
{
	var			form_ok = true;
	var			all_fields_ok = true;
	try
	{
		var			n = inputs.length;
		
		for( var i = 0; i < n; i++ )
		{
			if( inputs[i].type == 'text' )
				all_fields_ok &= lz_filter_field( inputs[i], 'alert' );
			
			var		id = '';
			var		value = '';
			
			if( inputs[i].type == 'radio' )	// Note: Radio Group name must be same as id.
			{
				value = lz_form_get_radio( inputs[i].name );
				id = inputs[i].name;
			}
			
			else if( inputs[i].type == 'checkbox' )
			{
				value = inputs[i].checked ? inputs[i].value : '';
				id = inputs[i].id;
			}
			else
			{
				value = inputs[i].value;
				id = inputs[i].id;
			}
				
			var		req = $( '#' + id + "_req" );
			
			if( req.length )
			{
				if( value == '' )
				{
					req.addClass( 'required' );
					form_ok = false;
				}
				else
				{
					var		type = id.charAt( 0 );
					
					if( type == 'e' ) // Email
					{
						if( value.search( /^[A-Za-z0-9._\-]+@[A-Za-z0-9._\-]+\.[A-Za-z]{2,6}$/ ) == -1 )
						{
							req.addClass( 'required' );
							form_ok = false;
						}
						else
							req.removeClass( 'required' );
					}

					else if( type == 'd' ) // Decimal: #.#
					{
						if( value.search( /^[\d]+\.[\d]+$/ ) == -1 )
						{
							req.addClass( 'required' );
							form_ok = false;
						}
						else
							req.removeClass( 'required' );
					}
					
					else
						req.removeClass( 'required' );
				}
			}
		}
		
		if( typeof( 'LZ_LANGUAGE' ) == 'string' && LZ_LANGUAGE == 'fr' )
		{
			if( !form_ok )
				alert( "Veuillez remplir les champs obligatoires marqués en rouge." );
			
			else if( !all_fields_ok )
			{
				alert( "Les caractères non acceptés ont été supprimés. Veuillez confirmer ou modifier, puis soumettre." );
				form_ok = false;
			}
		}
		
		if( typeof( 'LZ_LANGUAGE' ) == 'undefined' || LZ_LANGUAGE == 'en' )
		{
			if( !form_ok )
				alert( "Please complete the required fields, highlighted in red." );
			
			else if( !all_fields_ok )
			{
				alert( "Certain unallowable symbols (e.g. < >) were removed from some responses. Please review your responses and re-submit. Thanks." );
				form_ok = false;
			}
		}
	}
	catch( e )
	{
		alert( e );
		return false;
	}
	
	return form_ok;
}


// -------------------------------------------------------------------------- //
/*	lz_filter_field

*/
// -------------------------------------------------------------------------- //

function lz_filter_field( field, notify, type )
{
	if( type == undefined )
		type = field.id.toString().charAt(0);
	type = field.id.toString().charAt(0);
	
	field.value = field.value.trim();	// If we're just removing whitespace, we won't say anything.
	var		cleaned_value = field.value;
	var		regex = '';
	var		msg = 'This field can only contain ';
	var		msg_fr = 'Ce champ ne peut contenir que ';
	var		field_ok = true;
	
	switch( type )
	{
		case 'i': // Integer
			regex = /[^0-9\-]+/g;
			msg += "numbers";
			msg_fr += "des chiffres";
			break;

		case 'd': // Decimal
			regex = /[^0-9.]+/g;
			msg += "numbers and decimals";
			msg_fr += "des chiffres";		// +++ Needs to include 'decimals'
			break;

		case 'a': // Just letters, spaces, apostrophes and dashes
			regex = /[^a-zA-Z '\-]+/g;
			msg += "letters, spaces and dashes";
			msg_fr = "Certains symboles ne sont pas autorisés"
			break;

		case 's': // A-Z, 0-9, space, comma, +, -, _, (, ), 
			regex = /[^a-zA-Z0-9 '",+\-_().]+/g;
			msg = "Some symbols are not allowed in this field";
			msg_fr = "Certains symboles ne sont pas autorisés"
			break;

		case 'p': // Phone Number
			regex = /[^0-9 +\-()x,]+/g;
			msg = "Expected characters are, for example:\r   +1 (321) 555-1212, x234";
			msg_fr = "Les caractères acceptés sont, par exemple:\r   +1 (321) 555-1212, x234"
			break;

		case 'e': // Email
		case 'x': // No XSS chars
			regex = /[<>();&]+/g;
			msg = "Some symbols are not allowed in this field";
			msg_fr = "Certains symboles ne sont pas autorisés"
			break;
		
		case '<': // No html open bracket
			regex = /[<]+/g;
			msg = "This field cannot contain the &lt; character";
			msg_fr = "Certains symboles ne sont pas autorisés"
			break;
		
		case 'z': // Anything goes
			break;
	}
	
	if( regex != '' )
	{
		cleaned_value = field.value.replace( regex, '' );
		cleaned_value = cleaned_value.trim();	// Did end spaces appear after bad chars removed?
		
		if( field.value != cleaned_value )
		{
			field_ok = false;
			field.value = cleaned_value.trim();
			
			if( typeof( 'LZ_LANGUAGE' ) == 'string' && LZ_LANGUAGE == 'fr' )
			{
				msg = msg_fr + ".\rLes caractères non acceptés ont été supprimés."
			}
	
			if( typeof( 'LZ_LANGUAGE' ) == 'undefined' || LZ_LANGUAGE == 'en' )
			{
				msg += ".\rUnexpected characters have been removed."
			}
			
			if( notify == 'alert' )
			{
				$(field).addClass('changed');
				alert( msg );
				$(field).removeClass('changed');
			}
			
			else if( $('#' + notify).length > 0 )
			{
				$('#' + alert).show().html(msg);
				setTimeout( function(){$('#' + alert).hide();}, 4000 );
			}
		}
	}
	
	return field_ok;
}


// -------------------------------------------------------------------------- //
/*	lz_cookies_enabled

*/
// -------------------------------------------------------------------------- //

function lz_cookies_enabled()
{
	lz_set_cookie( 'cookie_test', 'xyzzy' );
	var result = lz_get_cookie( 'cookie_test' );
	
	if( result !== 'xyzzy' )
	{
		lz_delete_cookie( 'cookie_test' );
		return true;
	}
	
	return false;
}
	

// -------------------------------------------------------------------------- //
/*	lz_get_cookie

*/
// -------------------------------------------------------------------------- //

function lz_get_cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;

	if( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
		return null;

	if( start == -1 )
		return null;

	var end = document.cookie.indexOf( ";", len );
	if( end == -1 )
		end = document.cookie.length;

	return unescape( document.cookie.substring( len, end ) );
}
	
// -------------------------------------------------------------------------- //
/*	lz_set_cookie

*/
// -------------------------------------------------------------------------- //

function lz_set_cookie( name, value, expires, path, domain, secure )
{
	var today = new Date();

	today.setTime( today.getTime() );
	if( expires )
		expires = expires * 1000 * 60 * 60 * 24;
	
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" + escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// -------------------------------------------------------------------------- //
/*	lz_delete_cookie
*/
// -------------------------------------------------------------------------- //

function lz_delete_cookie( name, path, domain )
{
	if( lz_get_cookie( name ) )
	{
		document.cookie = name + "=" + 
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +	
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}


// ---------------------------------------------------------------------------- //
/*	lz_go_to
	
	Takes the window base into consideration for browsers that 
	don't think to (i.e., IE).
*/
// ---------------------------------------------------------------------------- //

function lz_go_to( relative_path )
{
	var		base_tags = $( 'base' );
	var		base = '';
	
	if( base_tags.length )
		base = base_tags[0].attr( 'href' );
	
	window.location.href = base + relative_path
}



// -------------------------------------------------------------------------- //
/*	lz_form_get_float

*/
// -------------------------------------------------------------------------- //

function lz_form_get_float( id, reset_value )
{
	var			id_elem = document.getElementById( id );
	var			id_value = 0;
	
	if( id_elem !== undefined )
	{
		id_value = parseFloat( id_elem.value );

		if( isNaN( id_value ) || (id_value < 0) )
		{
			id_value = 0;
			id_elem.value = reset_value;
			try{ id_elem.focus(); } catch (e) {} 
		}
		else
			id_elem.value = id_value; // Send back the parsed data to clean the field.
	}
	
	return id_value;
}

// -------------------------------------------------------------------------- //
/*	lz_form_get_int

*/
// -------------------------------------------------------------------------- //

function lz_form_get_int( id, reset_value )
{
	var			id_elem = document.getElementById( id );
	var			id_value = 0;
	
	if( id_elem !== undefined )
	{
		id_value = parseInt( id_elem.value );

		if( isNaN( id_value ) || (id_value < 0) )
		{
			id_value = reset_value;
			id_elem.value = reset_value;
			try{ id_elem.focus(); } catch (e) {} 
		}
		else
			id_elem.value = id_value; // Send back the parsed data to clean the field.
	}
	
	return id_value;
}


//	-----------------------------------------------------------------------	//
//	lz_form_get_radio
//	
//	Get the value of a radio button by element name.
//	-----------------------------------------------------------------------	//

function lz_form_get_radio( element_name )
{
	var		elem = document.getElementsByName( element_name );
	
	for( var i=0; i < elem.length; i++)
	{
		if( elem.item(i).checked )
			return elem.item(i).value;
	}
	
	return '';
}

//	-----------------------------------------------------------------------	//
//	lz_form_set_radio
//	
//	Set the value of a radio button by element name.
//	-----------------------------------------------------------------------	//

function lz_form_set_radio( element_name, element_value )
{
	var		elems = document.getElementsByName( element_name );
	var		len = elems.length;
	
	for( var i=0; i < len; i++)
	{
		if( elems.item(i).value == element_value )
			elems.item(i).checked = true;
		else
			elems.item(i).checked = false;
	}
}

//	-----------------------------------------------------------------------	//
//	lz_form_disable_radio
//	
//	Set the value of a radio button by element name.
//	-----------------------------------------------------------------------	//

function lz_form_disable_radio( element_name, state )
{
	var		elem = document.getElementsByName( element_name );
	var		len = elem.length;
	
	for( var i=0; i < len; i++)
	{
		if( state == true )
			elem.item(i).checked = false;
		elem.item(i).disabled = state;
	}
}


//	-----------------------------------------------------------------------	//
//	lz_enable_forms
//	
//	Called on page-load to enable the forms on the page by moving the value
//	of $('#FORM_ID_action).
//
//	This assumes forms have been created without actions to prevent them
//	from being submitted if js isn't enabled. 
//
//	TO DO: Optional parameter with ids of forms to enable.
//	TO DO: Optional parameter to check cookies first.
//	-----------------------------------------------------------------------	//

function lz_enable_forms()
{
	var			forms = $('form');
	var			n_forms = forms.length;
	
	for( var i = 0; i < n_forms; i++ )
	{
		var		form_action = $('#' + forms.eq(i).attr('id') + '_action' );
		
		if( form_action.length )
			forms.eq(i).attr('action', form_action.attr( 'value' ) );
	}
	
	forms.removeClass( 'disabled' );
}


// -------------------------------------------------------------------------- //
/*	lz_json_to_form
	
	Given a json data block and a form id, it does its best to pull data out
	of the json block to fill out the form based on matching up the form field
	id with the json variable name.
	
	In the case of radio buttons, the radio group name is used instead of the
	individual id.
*/
// -------------------------------------------------------------------------- //

function lz_json_to_form( data, form_id )
{
	var		form = document.getElementById( form_id );
	
	if( form == undefined )
		return;
	
	var		elems = form.elements;
	var		n = elems.length;

	for( var i = 0; i < n; i++ )
	{
		var		elem = elems[i];
		var		json_id = elem.id;
		
		if( elem.type == 'radio' )
			json_id = elem.name;
		
		var		json_value = data[ json_id ];
		
		if( json_value != undefined )
		{
			if( elem.type == 'radio' )
				lz_form_set_radio( json_id, json_value );
			else if( elem.type == 'checkbox' )
				; //lz_set_checkbox( json_id, json_value );
			else
				elem.value = json_value;
		}
	}
}


// ---------------------------------------------------------------------------- //
/*	News_Editor Class
	
	
*/
// ---------------------------------------------------------------------------- //

function NewsEditor( tbl_name )
{
	
	this.base_id = "#lz_" + tbl_name;
	this.current_menu = this.base_id + "_index_" + ($( this.base_id + '_start_year' ).get(0).value);
	
	this.edit = function( msg_id )
	{
		var id = msg_id.substr( msg_id.lastIndexOf("_") + 1, 6 );
		
		$( this.base_id + "_form_" + id ).get(0).style.display = "block";
		$( this.base_id + "_" + id ).get(0).style.display = "none";
	}
	
	this.cancel_edit = function( msg_id )
	{
		var id = msg_id.substr( msg_id.lastIndexOf("_") + 1, 6 );
		
		$( this.base_id + "_form_" + id ).get(0).style.display = "none";
		$( this.base_id + "_" + id ).get(0).style.display = "block";
	}
	
	this.toggle_menu = function( toggle_id )
	{
		if( toggle_id != this.current_menu )
		{
			if( this.current_menu )
			{
				$( this.current_menu + "_box" ).get(0).style.display='none';
				$( this.current_menu ).get(0).className = "toggle_menu_box";
			}
			
			$( toggle_id + "_box" ).get(0).style.display='block';
			$( toggle_id ).get(0).className = "toggle_menu_box selected";
			
			this.current_menu = toggle_id;
		}
	}
}


// ---------------------------------------------------------------------------- //
/*	lz_change_image
*/
// ---------------------------------------------------------------------------- //

function lz_change_image( id, value )
{
	var			img = $(id);
	
	if( (img.length > 0) && (value != '') )
	{
		var		path = img.attr( 'src' );
		var		pos = path.lastIndexOf( '/' );
		
		if( pos < 0 )
			path = '';
		else
			path = path.substr( 0, pos + 1 );
		
		img.attr( 'src', path + value );
	}
}


// -------------------------------------------------------------------------- //
/*	MESSAGE CLASS (PHP)

	These functions are used in conjuction with the PHP Message class.
*/
// -------------------------------------------------------------------------- //

var		lz_ids_to_clear = [];

function lz_add_id_to_clear( id )
{
	if( _lz_ids_to_clear.length == 0 )
		setTimeout( clear_ids, 3000 );
	
	_lz_ids_to_clear[ _lz_ids_to_clear.length ] = id;
}

function lz_clear_ids()
{
	var	n = _lz_ids_to_clear.length;
	
	for( var i = 0; i < n; i++ )
	{
		var elem = document.getElementById( _lz_ids_to_clear[i] );
		if( elem != undefined )
			elem.style.display='none';
	}
}

// -------------------------------------------------------------------------- //
/*	lz_draw_eml

*/
// -------------------------------------------------------------------------- //

function lz_draw_eml( to )
{
	document.write("<a href='javascript:lz_send_eml(\"" + to + "\");'>Click to Email</a>" );
}


// -------------------------------------------------------------------------- //
/*	lz_send_eml

*/
// -------------------------------------------------------------------------- //

function lz_send_eml( to )
{
	document.location = "mai" + "lt" + "o:" + to;
}


// -------------------------------------------------------------------------- //
/*	lz_draw_ml

*/
// -------------------------------------------------------------------------- //

function lz_draw_ml( to )
{
	document.write("<a href='javascript:lz_send_ml(\"" + to + "\");'>" + to + "@accessmy" + "id.com</a>" );
}


// -------------------------------------------------------------------------- //
/*	lz_send_ml

*/
// -------------------------------------------------------------------------- //

function lz_send_ml( to )
{
	document.location = "mai" + "lt" + "o:" + to + "@accessmy" + "id.com";
}


// -------------------------------------------------------------------------- //
/*	lz_connect_tabs
	
	Call this to connect tabs to tabbed content.
	Assumptions:
	- The tab structures are the first children of tab_area_id and classed
	  .lz_tab. (This classing may be removed in the future but I'm not sure
	  how often I'll have first children in the same area that aren't tabs.
	- The tab content is surrounded by a structure with id=tab_area_id + _content.
	- CSS styles the tabs with a 'selected' class.
	- The default state of content is hidden and then shown when .selected.
*/
// -------------------------------------------------------------------------- //

function lz_connect_tabs( tab_area_id )
{
	var		tab_content_area_id = tab_area_id + '_content';
	var		tabs = $(tab_area_id + ' > .lz_tab');
	var		contents = $(tab_content_area_id + ' > .lz_tab_content');
	
	tabs.click( function ()
	{
		tabs.removeClass('selected');
		contents.removeClass('selected');
		tabs.eq( tabs.index(this) ).addClass('selected');
		contents.eq( tabs.index(this) ).addClass('selected');
	} );
	
	tabs.eq(0).trigger('click');
}


// -------------------------------------------------------------------------- //
/*	show_dialog / hide_dialog

*/
// -------------------------------------------------------------------------- //

function show_dialog( id )
{
	var		item = $('#' +  id );
	
	if( item.length )
	{
		item.fadeIn('slow');
		$('#modal_block').fadeIn('fast');
		
		if( $(document).height() != $('#modal_block').height() )
			$('#modal_block').height( $(document).height() );
	}
}

function hide_dialog( id )
{
	var		item = $('#' +  id );
	
	if( item.length )
	{
		item.fadeOut('fast');
		$('#modal_block').fadeOut('slow');
	}
}


// ===============================================
/*
	The following code is from:
	http://javascript.crockford.com/remedial.html
*/
// ===============================================

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length')) &&
                    typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}


function isEmpty(o) {
    var i, v;
    if (typeOf(o) === 'object') {
        for (i in o) {
            v = o[i];
            if (v !== undefined && typeOf(v) !== 'function') {
                return false;
            }
        }
    }
    return true;
}

String.prototype.entityify = function () {
    return this.replace(/&/g, "&amp;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;");
};

String.prototype.quote = function () {
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}; 

