//-----------------------------------------------------------------------------
// CORE2 Javacript Utility Functions and Classes
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Detect client browser and its version
//-----------------------------------------------------------------------------
var agt			= navigator.userAgent.toLowerCase();
var is_major	= parseInt(navigator.appVersion);
var is_minor	= parseFloat(navigator.appVersion);
var is_nav		= ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
					&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
					&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav2		= (is_nav && (is_major == 2));
var is_nav3		= (is_nav && (is_major == 3));
var is_nav4		= (is_nav && (is_major == 4));
var is_nav4up	= (is_nav && (is_major >= 4));
var is_navonly	= (is_nav && ((agt.indexOf(";nav") != -1) || (agt.indexOf("; nav") != -1)) );
var is_nav6		= (is_nav && (is_major == 5));
var is_nav6up	= (is_nav && (is_major >= 5));
var is_gecko	= (agt.indexOf('gecko') != -1);
var is_ie		= ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3		= (is_ie && (is_major < 4));
var is_ie4		= (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up	= (is_ie && (is_major >= 4));
var is_ie5		= (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5	= (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up	= (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up	= (is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6		= (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie6up	= (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);
var is_opera	= (agt.indexOf("opera") != -1);
var is_opera2	= (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
var is_opera3	= (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
var is_opera4	= (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
var is_opera5	= (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4);

//-----------------------------------------------------------------------------
// Key values for use in onkey... handlers, returned by the get_event() function
//-----------------------------------------------------------------------------
var KEY_BACKSPACE	= 8;
var KEY_TAB			= 9;
var KEY_RETURN		= 13;
var KEY_ESC			= 27;
var KEY_LEFT		= 37;
var KEY_UP			= 38;
var KEY_RIGHT		= 39;
var KEY_DOWN		= 40;
var KEY_DELETE		= 46;
var KEY_HOME		= 36;
var KEY_END			= 35;
var KEY_PAGEUP		= 33;
var KEY_PAGEDOWN	= 34;

//-----------------------------------------------------------------------------
// Mouse button values returned by the get_event() function
//-----------------------------------------------------------------------------
var MOUSE_BUTTON_LEFT	= 1;
var MOUSE_BUTTON_RIGHT	= 2;
var MOUSE_BUTTON_MIDDLE = 4;

//-----------------------------------------------------------------------------
// Various constants
//-----------------------------------------------------------------------------
var g_cScrollBarWidth = 0;
var GOLDEN_RATIO = 1.6180339887;

//-----------------------------------------------------------------------------
// Utilitarian functions
//-----------------------------------------------------------------------------

//! Get the object with the specified id
function $( id )
{
	return document.getElementById( id );
}

//! Get left property in pixel units of object
function get_x( obj )
{
	return obj.offsetLeft;
}

//! Get top property in pixel units of object
function get_y( obj )
{
	return obj.offsetTop;
}

//! Get width property in pixel units of object
function get_width( obj )
{
	return obj.offsetWidth;
}

//! Get height property in pixel units of object
function get_height( obj )
{
	return obj.offsetHeight;
}

//! Set left property in pixel units of object
function set_x( obj, x )
{
	obj.style.left = x + "px";
}

//! Set top property in pixel units of object
function set_y( obj, y )
{
	obj.style.top = y + "px";
}

//! Set width property in pixel units of object
function set_width( obj, w )
{
	obj.style.width = w + "px";
}

//! Set height property in pixel units of object
function set_height( obj, h )
{
	obj.style.height = h + "px";
}

//! Set left and top properties in pixel units of object
function set_position( obj, x, y )
{
	obj.style.left = x + "px";
	obj.style.top = y + "px";
}

//! Set width and height properties in pixel units of object
function set_size( obj, w, h )
{
	obj.style.width = w + "px";
	obj.style.height = h + "px";
}

//! Set left,top,width,height properties in pixel units of object
function set_coords( obj, x, y, w, h )
{
	obj.style.left = x + "px";
	obj.style.top = y + "px";
	obj.style.width = w + "px";
	obj.style.height = h + "px";
}

//! Show or hide object, if do_show = undefine, it will show the object by default
function show_element( obj, do_show )
{
	if( do_show == undefined )
		do_show = true;

	if( obj == undefined || obj == null )
		return;

	obj.style.display = ( do_show ? "block" : "none" );
	obj.style.visibility = ( do_show ? "visible" : "hidden" );
}

//! Hide element object
function hide_element( obj )
{
	if( obj == undefined || obj == null )
		return;

	obj.style.display = "none";
	obj.style.visibility = "hidden";
}

//! Get page width
function get_page_width()
{
	return document.body.offsetWidth;
}

//! Get page height
function get_page_height()
{
	return document.body.offsetHeight;
}

//! Center element on page
function center_element( element )
{
	element.style.left = ( document.body.offsetWidth - element.getAttribute( "width" ) ) / 2 + "px";
	element.style.top = ( document.body.offsetHeight - element.getAttribute( "height" ) ) / 2 + "px";
}

//! Get frame inner HTML
function get_frame_contents( frame )
{
	return frame.contentWindow.document.body.innerHTML;
}

//! Set frame inner HTML
function set_frame_contents( frame, html )
{
	frame.contentWindow.document.body.innerHTML = html;
}

//! Get event with cross browser extracted info
//! \param e is the event coming from the event handler
//! \return an object with custom event info
function get_event( e )
{
	var code;

	if( !e && window.event ) 
		e = window.event;
	
	if( !e || e == "undefined" ) 
		return null;

	var keyCode = 0;

	if( e.keyCode != undefined )
		keyCode = e.keyCode;
	else
	if( e.which != undefined )
		keyCode = e.which;

	var character = String.fromCharCode( keyCode );
	var tgt = null;

	if( e.target )
		tgt = e.target;
	else
	if( e.srcElement )
		tgt = e.srcElement;

	// Safari fix
	if( tgt.nodeType == 3 )
		tgt = tgt.parentNode;

	if( !tgt )
		return null;

	var mousex = 0;
	var mousey = 0;
	
	if( e.pageX || e.pageY )
	{
		mousex = e.pageX;
		mousey = e.pageY;
	}
	else
	if( e.clientX || e.clientY )
	{
		mousex = e.clientX + document.body.scrollLeft
				 + document.documentElement.scrollLeft;
		mousey = e.clientY + document.body.scrollTop
				 + document.documentElement.scrollTop;
	}

	var mbutton = 0;

	if( e.button != undefined && e.button != null )
	{
		if( is_ie )
		{
			if( e.button == 1 )
				mbutton = MOUSE_BUTTON_LEFT;
			else
			if( e.button == 4 )
				mbutton = MOUSE_BUTTON_RIGHT;
			else
			if( e.button == 2 )
				mbutton = MOUSE_BUTTON_MIDDLE;
		}
		else
		if( is_gecko )
		{
			if( e.button == 0 )
				mbutton = MOUSE_BUTTON_LEFT;
			else
			if( e.button == 1 )
				mbutton = MOUSE_BUTTON_RIGHT;
			else
			if( e.button == 2 )
				mbutton = MOUSE_BUTTON_MIDDLE;
		}
	}

	// mouse wheel delta
	var delta = 0;

	if( e.wheelDelta )
	{ 
		/* IE/Opera. */
		delta = e.wheelDelta / 120;
		/** In Opera 9, delta differs in sign as compared to IE. */
		if( window.opera )
			delta = -delta;
	}
	else 
	if( e.detail )
	{
		/** Mozilla case. */
		/** In Mozilla, sign of delta is different than in IE.
		 * Also, delta is multiple of 3.
		 */
		delta = -e.detail / 3;
	}

	return	{
				target_node: tgt,
				parent_node: tgt.parentNode,
				key_code: keyCode,
				key_char: character,
				x: mousex,
				y: mousey,
				client_x: mousex - get_x( tgt ),
				client_y: mousey - get_y( tgt ),
				mouse_button: mbutton,
				wheel_delta: delta
			};
}

//! This function is used to be assigned to event hooks and cancel the event bubble
function do_cancel_event( e )
{
	var source;

	if( !e )
		e = event;

	if( e.target )
		source = e.target;
	else
	if( e.srcElement )
		source = e.srcElement;
	
	if( source.nodeType == 3 ) // defeat Safari bug
		source = source.parentNode;
					
	if( source.tagName && source.tagName.toLowerCase() == 'input' ) 
		return true;

	return false;
}

//! Navigate to specified URL address
function navigate_to( url )
{
	document.location = url;
}

//! Go back to previous page
function go_back()
{
	document.history.back();
}

//! Sleep milliseconds
function sleep( millisecondi )
{
    var now = new Date();
    var exitTime = now.getTime() + millisecondi;

    while( true )
    {
        now = new Date();
        if( now.getTime() > exitTime )
			return;
    }
}

//! Get time as text
function get_time()
{
	var today = new Date();
	var h = today.getHours();
	var m = today.getMinutes();
	var s = today.getSeconds();

	if( h < 10 )
		h = "0" + h;
	if( m < 10 )
		m = "0" + m;
	if( s < 10 )
		s = "0" + s;

	return h + ":" + m + ":" + s;
}

//! Get an element's attribute value, or some default value if the attribute is not specified
function get_attr_value( element, attr_name, default_value, append_value )
{
	if( default_value == undefined )
		default_value = "";

	if( append_value == undefined )
		append_value = "";
	
	if( element == undefined || element == null )
		return default_value;

	var val = element.getAttribute( attr_name );

	if( val != "undefined" && val != "" && val != null )
	{
		return ( val ) + append_value;
	}

	return default_value + append_value;
}

//! Set the cursor to the pointer cursor over the element definied by the parameter
//! \param the_id The id of the element over which to set the cursor to pointer
function div_mouse_over( the_id )
{
    my_div = $( the_id );
    my_div.style.cursor = "pointer";
}

//! Set the cursor to the normal cursor over the element definied by the parameter
//! \param the_id The id of the element over which to set the cursor to normal
function div_mouse_out( the_id )
{
    my_div = $( the_id );
    my_div.style.cursor = "";
}

//! Include a JS file from another .js file
function include( file )
{
	var script  = document.createElement( "script" );
	script.src  = file;
	script.type = "text/javascript";
	script.defer = true;
	document.getElementsByTagName( "head" ).item(0).appendChild( script );
}

//! Returns the scrollbar width
function get_scrollbar_width()
{
	if( is_ie )
	{
		document.body.innerHTML += "<form action=\"#\" id=\"f\"><div><textarea cols=\"20\" rows=\"2\" name=\"t\"></textarea></div></form>";
		var a, t = document.forms.f.elements.t;
		t.wrap = 'off'; a = t.offsetHeight;
		t.wrap = 'soft'; a -= t.offsetHeight;
		document.body.removeChild( document.forms.f );
		return a;
	}

	var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    
	// Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    
	// Add the scrollbar
    scr.style.overflow = 'auto';

	// Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild( document.body.lastChild );

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}


//! Resize width and height to match a view size, ignore width / height to
//! unconstrain the size to the specified dimension of the viewport
//! \param the_image_width the original image width
//! \param the_image_height the original image height
//! \param the_view_width the viewport width
//! \param the_view_height the viewport height
//! \param the_ignore_height if true then will ignore viewport height as constrain
//! \param the_ignore_width if true then will ignore viewport width as constrain
//! \return structure { new_width : the new width, new_height : the new height }
function resize_box_to_viewport( the_image_width, the_image_height,
								 the_view_width, the_view_height,
								 the_ignore_height,
								 the_ignore_width )
{
    var the_new_width = the_image_width;
    var the_new_height = the_image_height;

    if( the_image_width <= the_view_width &&
        the_image_height <= the_view_height )
    {
        return { new_width : the_new_width, new_height : the_new_height };
    }

    if( the_new_width >= the_view_width && !the_ignore_width )
    {
        var aspect_ratio = the_view_width / the_new_width;
        the_new_width = the_view_width;
        the_new_height *= aspect_ratio;
    }

    if( the_new_height >= the_view_height && !the_ignore_height )
    {
        var aspect_ratio = the_view_height / the_new_height;
        the_new_height = the_view_height;
        the_new_width *= aspect_ratio;
    }

    return { new_width : the_new_width, new_height : the_new_height };
}

//! Create cookie
//! \param name the name of the cookie
//! \param value the value of the cookie
//! \param days the number of days to keep the cookie
function create_cookie( name, value, days )
{
	if( days )
	{
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		var expires = "; expires=" + date.toGMTString();
	}
	else
	{
		var expires = "";
	}

	document.cookie = name + "=" + value + expires + "; path=/";
}

//! Read cookie contents
//! \param name the cookie's name
function read_cookie( name )
{
	var nameEQ = name + "=";
	var ca = document.cookie.split( ';' );

	for( var i = 0; i < ca.length; i++ )
	{
		var c = ca[i];
	
		while( c.charAt( 0 ) == ' ' )
			c = c.substring( 1, c.length );

		if( c.indexOf( nameEQ ) == 0 )
			return c.substring( nameEQ.length, c.length );
	}

	return null;
}

//! Erase cookie
//! \param name the cookie's name
function erase_cookie( name )
{
	create_cookie( name, "", -1 );
}

//! Save the document's events to itself
function save_document_events()
{
	document.savedEvents = new Array();
	document.savedEvents[0] = document.onmousedown;
	document.savedEvents[1] = document.onmousemove;
	document.savedEvents[2] = document.onmouseup;
	document.savedEvents[3] = document.onselectstart;
}

//! Restore document's events from itself
function restore_document_events()
{
	if( document.savedEvents && document.savedEvents.length )
	{
		document.onmousedown	= document.savedEvents[0];
		document.onmousemove	= document.savedEvents[1];
		document.onmouseup		= document.savedEvents[2];
		document.onselectstart	= document.savedEvents[3];
	}
}

//! Reload the current page
function reload_page()
{
	document.location.reload();
}

//! Move / relocate children of one element to another
function relocate_children( source, destination )
{
	if( !source.hasChildNodes() )
		return;

	while( source.childNodes.length )
	{
		destination.appendChild( source.childNodes[0] );
	}
}

//! Create new element
function create( name )
{
	return document.createElement( name );
}

//! Return true if function name exists (passed as string)
function function_exists( funcName )
{
	return eval( "typeof " + funcName + " == 'function'" );
}

//! Validate date
//! \param day The day
//! \param month The month
//! \param year The year
//! Displays alerts from date_alerts JS array in this order: \n
//!   0 - Day is wrong \n
//!   1 - Month is wrong \n
//!   2 - Year is wrong \n
//!   3 - Date is wrong \n
function check_date( day, month, year )
{
	
	var the_day   = day.toString();
	var the_month = month.toString();
	var the_year  = year.toString();
	
	var day_month_pattern =	/^(\d{1,2})$/;
	var year_pattern = /^(\d{4})$/;

	var regex = new RegExp(day_month_pattern)
	var matchArray = the_day.match(regex);

	error = "";

	if ( ( matchArray == null ) || ( day < 1 ) || ( day > 31 ) )
	{
		error = day + date_alerts[0];
	}
	
	var regex = new RegExp( day_month_pattern )
	var matchArray = the_month.match( regex );
	
	if ( ( matchArray == null ) || ( month < 1) || ( month > 12 ) )
	{
		error = month + date_alerts[1];
	}
	
	var regex = new RegExp( year_pattern );
	var matchArray = the_year.match( regex );

	if( matchArray == null )
	{
		error = year + date_alerts[2];
	}

	// is date valid for month
	if( month == 2 )
	{
		if( ( ( year%4 == 0 ) && ( year%100 != 0 ) ) || ( year%400 == 0 ) )
		{
			// leap year
			if( day > 29 )
			{
				error = date_alerts[3];
			}
		}
		else
		{
			if( day > 28 )
			{
				error = date_alerts[3];
			}
		}
	}
	
	if( ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) )
	{
		if( day > 30 )
		{
			error = date_alerts[3];
		}
	}

	return error;
}

//! forces input to accept only numbers
function numbers_only_field( the_input, the_length, the_length_alert, the_event )
{
	var keycode;

	if( window.event )
	{
		keycode = window.event.keyCode;
	}
	else 
	if( the_event )
	{ 
		keycode = the_event.which;
	}
	else
	{
		return true;
	}

	if( keycode == 13 )
	{
		return false;
	}


    if ( the_input.value.length > the_length )
    {
        alert( the_length_alert );
        the_input.value = the_input.value.substring( 0, the_length );
    }


    var field_value = the_input.value.substring( the_input.value.length - 1, the_input.value.length );

    var allowed_chars = /[0-9]+/;
    var regex = new RegExp( allowed_chars );

    if ( !field_value.match( regex ) )
    {
        the_input.value = the_input.value.substring( 0, the_input.value.length - 1 );
        return false;
    }
    return true;
}

function change_color( the_input )
{
	var input = document.getElementById( the_input );
		input.value = "";
		input.style.color = "black";
		input.style.fontWeight = "bold";
}