// JavaScript Document

/*
This is a calendar service.
Params:

Key             |       Value
--------------------------------------------------------
calendar                REQUIRED
  						flat       ---- Flat Calendar
						popup      ---- Popup Calendar

calendarTime            OPTIONAL
                        true       ---- Calendar with time
						false      ---- Calendar without time

calendarName            OPTIONAL
                        Will be setted to input field as it name attribute. Needed in popup calendar.

calendarId              OPTIONAL
                        Will be setted to input field as it id attribute. Needed in popup calendar.

handler                 OPTIONAL
                        Handler function name which will be called when user clicks on calendar. Needed in flat calendar
						If this attribute didn't set, program will cal standart handler.

format                  OPTIONAL
                        %a         ---- Abbreviated weekday name
						%A         ---- Full weekday name
						%b         ---- Abbreviated monthday name
						%B         ---- Full monthday name
						%C         ---- Century number
						%d         ---- The day of the month (00 ... 31)
						%e         ---- The day of the month (0 ... 31)
						%H         ---- Hour (00 ... 23)
						%k         ---- Hour (0 ... 23)
						%I         ---- Hour (01 ... 12)
						%l         ---- Hour (1 ... 12)
						%j         ---- The day of the year (000 ... 366)
						%m         ---- Month (01 ... 12)
						%n         ---- A new line character
						%p         ---- PM or AM
						%P         ---- pm or am
						%S         ---- Second (00 .. 59)
						%s         ---- Number of seconds since Epoch
						%t         ---- A tab character
						%W         ---- The week number (as per ISO 8601)
						%u         ---- The day of week (1 .. 7, 1 = Monday)
						%w         ---- The day of week (0 .. 6, 0 = Sunday)
						%y         ---- Year without the century (00 .. 99)
						%Y         ---- Year including the century ( ex. 1979)
						%%         ---- A literal % character
--------------------------------------------------------

*/

if(navigator.appName != "Microsoft Internet Explorer")
{
 Node.prototype.replaceNode=function(Node) {
   this.parentNode.replaceChild(Node,this);
 }
}

function attachEvent_( eventName , element , handler )
{
	if( eventName.substr(0,2).toLowerCase() == "on" )
		eventName = eventName.substr(2);

	if(window.addEventListener)
	{ 
		// Mozilla, Netscape, Firefox
		element.addEventListener( eventName , handler, false);
	} 
	else 
	{
		 // IE
		element.attachEvent('on' + eventName, handler);
	}
}
function animateCalendar( calendar )
{
		var obj;
		if( typeof(calendar) == "string" )
			obj = document.getElementById( calendar );
		else
			obj = calendar;

		var popupCalImg = document.getElementById("CalendarImagePath").value;

		var calendarType   = obj.getAttribute( "calendar" );
		var calendarTime   = obj.getAttribute( "calendarTime" );
		var format         = obj.getAttribute( "format" );
		var calendarName   = obj.getAttribute("calendarName");
		var calendarId     = obj.getAttribute( "calendarId" );
		var calendarValue  = obj.getAttribute( "calendarValue" );
		var handler        = obj.getAttribute("handler");

		if( calendarType == null )
			return;

		if( !(calendarType == "flat" || calendarType == "popup") )
			return;

		if( calendarTime == "true" )
			calendarTime = true;
		else if( calendarTime == "false" )
			calendarTime = false;
		if( !(obj.tagName == "DIV" || (obj.tagName == "INPUT" && obj.type == "text")) )
			return;


		var img = document.createElement( "img" )
		img.setAttribute( "src" , popupCalImg );
		img.setAttribute( "id" , getValidID( "calendarbutton_" ) );
		img.style.cursor = "pointer";

		if(handler == null || handler =="")
			handler = flatCalendarCallback;
		try{eval( handler );}catch( ex ){handler = flatCalendarCallback}


		var input, div;
		if( obj.tagName == "DIV" )
		{
			input = document.createElement( "INPUT" );
			input.setAttribute( "name" , calendarName );
			input.setAttribute( "id" ,  (calendarId != null)? (calendarId): (getValidID("calendarinput_")) );
			input.setAttribute( "type" , "text" );
			div = obj;
			div.innerHTML = "";
			div.setAttribute( "id",  getValidID("calendar_") );

			if( calendarType == "popup" )
			{
				div.appendChild( input );
				div.appendChild( img );
			}
		}
		else
		{
			if( calendarType == "flat" )
				return;

			div = document.createElement( "DIV" );
			if( obj.id == null || obj.id == "")
				obj.setAttribute( "id" , getValidID("calendarinput_") );

			input = obj.cloneNode(true);
			div.appendChild( input );
			div.appendChild( img );
			obj.replaceNode( div );
		}

		/// Making calendar visible
		if( calendarType == "flat" )
		{
				Zapatec.Calendar.setup
				({
					firstDay          : 1,
					weekNumbers       : true,
					showOthers        : true,
					showsTime         : calendarTime,
					timeFormat        : "24",
					step              : 2,
					range             : [1900.01, 2999.12],
					flat              : div.getAttribute("id"),
					flatCallback      : eval( handler )
				});
		}

		if( calendarType == "popup" )
		{

			if( calendarValue != null )
				input.setAttribute( "value" , calendarValue );

			if( calendarTime == true )
				ifFormatV = "%Y/%m/%d %l:%M %P";
			else
				ifFormatV = "%d/%m/%Y";

			if( format != null )
				ifFormatV = format;

			Zapatec.Calendar.setup({
				firstDay          : 1,
				weekNumbers       : true,
				showOthers        : true,
				showsTime         : calendarTime,
				timeFormat        : "24",
				step              : 2,
				range             : [1900.01, 2999.12],
				electric          : false,
				doubleClick       : true,
				inputField        : input.getAttribute("id"),
				button            : img.getAttribute("id"),
				ifFormat          : ifFormatV,
				daFormat          : "%d/%m/%Y",
				align             : "Br"
			  });
		}
}

function animateCalendars()
{
	if( Zapatec == null )
		return;
	var popupCalImg = "../../gui/clientside/img/calendar.gif";

	var divs = document.getElementsByTagName( "DIV" );
	var size = divs.length;
	for( var i=0; i<size; i++ )
		animateCalendar( divs[i] );

	var inputs = document.getElementsByTagName( "INPUT" );
	var size = inputs.length;
	for( var i=0; i<size; i++ )
	{
		if( inputs[i] == null || inputs[i].getAttribute("calendar") == null )
			continue;
		animateCalendar( inputs[i] );
	}
}

function flatCalendarCallback(cal)
{

	if (cal.dateClicked)
	{
		alert( cal.date.print("%Y")+ "/" + cal.date.print("%m")+ "/" + cal.date.print("%d") )
	}
}

// Returns valid id which starts with startId
function getValidID( startId )
{
	var obj = document.getElementById( startId );
	while( obj != null )
	{
		startId += String.fromCharCode(97 + Math.round(Math.random() * 25));;
		obj = document.getElementById( startId );
	}
	return startId;
}