
/**
 * Convert special chars to HTML entities
 * @addon
 * @return The string with chars encoded for HTML
 * @type String
 */
String.prototype.htmlEnc = function() {
  var str = this.replace(/&/g,"&amp;");
  str = str.replace(/</g,"&lt;");
  str = str.replace(/>/g,"&gt;");
  str = str.replace(/\"/g,"&quot;");
  str = str.replace(/\n/g,"<br />");
  return str;
};

String.prototype.htmlDec = function() {
	var str = this.replace( /&amp;/g, "&");
	str = str.replace(/&quot;/g,"\"" );
	str = str.replace(/&auml;/g,"ä" );
	str = str.replace(/&ouml;/g,"ö" );
	str = str.replace(/&aring;/g,"å" );
	str = str.replace(/&Auml;/g,"Ä" );
	str = str.replace(/&Ouml;/g,"Ö" );
	str = str.replace(/&Aring;/g,"Å" );
	return str;
}

var dpcal_current_event = 0;
var dpcal_state = {
  task : null,
  link : null,
  button : null,
  ide : 0,
  prefix : null
};

function runTask( link, button, prefix ) {
  /* Globaalit arvot jotka aina lahetetaan postdatassa */
  var gparam = { option: dpcalOption, Itemid: dpcalItemid, ajax: 1, prefix: prefix };
  gparam.categories = dpcal.display.getString('categories');
  gparam.sections = dpcal.display.getString('sections');
  gparam.organizers = dpcal.display.getString('organizers');
  
  var linkname = link.id;
  if ( typeof link.id == 'undefined' ) {
	linkname = link;
    link = dpcal.menu.links[ link ];
  }
	
  if ( typeof link == 'undefined' ) return;  

  if ( button != null && prefix != null )
    linkname = button;	
	
  var param = array_merge( gparam, dpcal.menu.links[ linkname ].param );
  var task = dpcal.menu.links[ linkname ].task;

  if ( typeof param.statechange == 'undefined' ) {
    /* save last task */
    dpcal_state.task = task;
    dpcal_state.link = link;
    dpcal_state.button = button;
    dpcal_state.prefix = prefix;
  } else {
    if ( param.statechange != 'ignore' ) {
      /* Tahan ne tehtavat jotka ajetaan javascriptilla ja joiden jalkeen ajetaan ed. suoritettu tehtava uudelleen */
      switch ( task ) {
      case 'change_selection_submit':
	$("#dpcal_change_selection" ).hide();
	break;
      }
      task = dpcal_state.task;
      link = dpcal_state.link;
      linkname = link.id;
      button = dpcal_state.button;
      prefix = dpcal_state.prefix;

      if ( button != null && prefix != null )
	linkname = button;
      param = array_merge( gparam, dpcal.menu.links[ linkname ].param );
    }
  }

  var dialog = $( link ).parents('div.jqmDialog').get(0);

  if ( typeof param.form != 'undefined'  )
    param = array_merge( param, getFormValues( param.form, false ) );

  if ( typeof param.year == 'undefined' ) param.year = dpcal.menu.year;
  if ( typeof param.month == 'undefined' ) param.month = dpcal.menu.month;
  if ( typeof param.day == 'undefined' ) param.day = dpcal.menu.day;

  dpcal.menu.setDate( param.year, param.month, param.day );

  if ( typeof param.task == 'undefined' ) param.task = task;

  if ( prefix == null && $(link).is('.dpcal_menu_link') ) {
    $('A.dpcal_menu_link').removeClass('current');
    $('#' + link.id ).addClass('current');
  }

  switch ( task ) {
  case 'open_add_category':    dialog_open( 'modCategory', param, dialog );    break;
  case 'open_add_section':     dialog_open( 'modSection', param, dialog );     break;
  case 'open_add_organizer':   dialog_open( 'modOrganizer', param, dialog );   break;

  case 'add_category':        dialog_exec( param, dialog, 'category', false, true ); break;
  case 'delete_category':     dialog_exec( param, dialog, 'category', _DPCAL_DELETE_CATEGORY_Q ); break;
  case 'rename_category':     dialog_exec( param, dialog, 'category', _DPCAL_RENAME_CATEGORY_Q ); break;

  case 'add_section':         dialog_exec( param, dialog, 'section', false, true ); break;
  case 'delete_section':      dialog_exec( param, dialog, 'section', _DPCAL_DELETE_SECTION_Q ); break;
  case 'rename_section':      dialog_exec( param, dialog, 'section', _DPCAL_RENAME_SECTION_Q ); break;

  case 'add_organizer':       dialog_exec( param, dialog, 'organizer', false, true ); break;
  case 'delete_organizer':    dialog_exec( param, dialog, 'organizer', _DPCAL_DELETE_ORGANIZER_Q ); break;
  case 'rename_organizer':    dialog_exec( param, dialog, 'organizer', _DPCAL_RENAME_ORGANIZER_Q ); break;

/*      case 'event_view':
       var ev = eval( '('+param.event+')' );
       dpcal_event.popup( ev );
       break; */

  case 'event':
    switch ( param.view ) {
    case 'add': dpcal_form_incomplete = true; getContent( task, param ); break;
    case 'save': dpcal_form_incomplete = false; getContent( task, param ); break;
    case 'publish':
      var ev_idlist = new Array();
      $("form[@name=dpcal_event_list] input[@type=checkbox]")
	.each( function() {
		 ev_idlist.push( "e["+this.value+"]=" + dpc_is_checked(this) );
	       });
      param['eventlist'] = ev_idlist.join('&');
      param['published'] = $("form[@name=dpcal_event_list] input[@name=published]").val();
      getContent( task, param );
      break;
    case 'mod':
      if ( dpcal_current_event == 0 ) {
		alert( _DPCAL_ERROR_SELECT_EVENT );
		// Ei piiloiteta tapahtumia, kun mitään ei ole valittu
		//$("#dpcal_content").html("");
      } else {
		param.eventid = dpcal_current_event;
		$("#dpcal_event_popup").hide();
        dpcal_form_incomplete = true;
		getContent( task, param );
      }
      break;
	case 'copy':
	  if ( dpcal_current_event == 0 ) {
		alert( _DPCAL_ERROR_SELECT_EVENT );
		// Ei piiloiteta tapahtumia, kun mitään ei ole valittu
		//$("#dpcal_content").html("");
      } else {
		param.eventid = dpcal_current_event;
		$("#dpcal_event_popup").hide();
        dpcal_form_incomplete = true;
		getContent( task, param );
      }
    }
    break;
  case 'toggle_selection':
    var selbox = $("#dpcal_change_selection");
    if ( selbox.css('display') == 'none' )
      selbox.show();
    else
      selbox.hide();
    break;
  default:
    getContent( task, param );
    break;
  }
  return false;
}

function dpcalList() {
  this.content = "";
  this.modified = -1;
  this.task = "";
  this.index = "";
  this.title = 'name';
  this.elements = new Array();
}

function getTotalHeight( elem ) {
  var ha = $.map( [
		   elem.height(),
		   elem.css( 'border-top-width' ),
		   elem.css( 'border-bottom-width' ),
		   elem.css( 'margin-top-width' ),
		   elem.css( 'margin-bottom-width' ),
		   ], function(n) {
		    var tmp = "" + n;
		    return Number( tmp.replace( /[^0-9]*/g, '' ) );
		  });
  var h = 0;
  for ( i in ha )
    h = h + ha[i];
  return h;
}

/* ##################### EVENT ########################## */

function addWithPostfix( mystring, mydelim ) {
	if ( mystring.length > 0 )
		return '' + mystring + mydelim;
	return '';
}
function addWithDelim( mydelim1, mystring, mydelim2 ) {
	if  (mystring.length > 0 )
		return mydelim1 + mystring + mydelim2;
	return '';
}


var dpcal_event = {
	popup : function ( ev ) {
		if ( $("#dpcal_event_popup").is( "DIV" ) )
			$("#dpcal_event_popup").hide().remove();

		$("#dpcalEditors").append("<div id='dpcal_event_popup'></div>");
		var popup = $("#dpcal_event_popup");
		var contentarea = $("#dpcal_content");
		var ppos = contentarea.offset();
		popup.css( { 'top': ppos.top + 10 + 'px', 'left': ppos.left + 8 + 'px', 'width': contentarea.width() - 28 + 'px', 'height':contentarea.height() - 28 + 'px' } );


		var appendstr = "<div id='dpcal_event_popup_titlebar'>"+ ev.e_date + " : " + ev.title + "</div><div id='dpcal_event_popup_content'>";
		for ( i in ev )
			appendstr = appendstr + i + ": " + ev[i] + "<br />";
		appendstr = appendstr + "</div>";
		popup.append( appendstr );
		$("#dpcal_event_popup_content", popup).height( popup.height() - $("#dpcal_event_popup_titlebar",popup).height() - 30 );
		popup.bind( 'click', function() { popup.hide().remove(); } );
		popup.show();
	},
	hover_show : function ( div ) {
		var link = $( div ).children( "A" )[0];
		var re = /([0-9]*):[0-9]*[^0-9]*([0-9]*):.*/;
		if ( $( link ).is( '.eventbox' ) ) {
			/* viikkonakyma */
			var links = $( div ).children( "A" );
			links.each( function() {
				var str = $(this).attr('title');
				var vars = str.match( re );
				if ( vars ) {
					var starth = vars[1];
					var endh = vars[2];

					$("#dpcalEditors").append( "<div id='dpcal_hover_"+this.id+"' style='display: none'></div>" );

					var popup = $( "#dpcal_hover_"+this.id );
					var alink = $( this );
					var adiv = $( div );
					var lpos = alink.offset();
					var rpos = adiv.offset();

					var tw = alink.width();
					var th = (adiv.height() + 1) * ( endh - starth ) + 3 ;

					if ( th <= adiv.height() )
					th = 0;

					popup.css( { 'position': 'absolute',
					     'border-style': 'solid',
					     'border-color': '#555',
					     'border-width': '0px 1px ' + ( th == 0 ? '0px' : '1px' ) + ' 1px',
					     'top':lpos.top + alink.height() - 1 + 'px',
					     'left': ( lpos.left - parseInt( alink.css('margin-left') ) ) + 'px',
					     'background-color': alink.css('background-color') ,
					     'padding':'0px 0px 0px 0px',
					     'margin':'0px 0px 0px 0px',
					     'border-color':'#555',
					     'width': tw + 'px',
					     'height': th + 'px'
					     });

					if ( $.browser.msie )
						popup.css( 'margin-left', '1px' );

					popup.show();
				}
			});

		} else {
			var str = $(link).attr('title');
			vars = str.match( re );
			if ( vars ) {
				var starth = vars[1];
				var endh = vars[2];

				$("#dpcalEditors").append( "<div id='dpcal_hover_"+link.id+"' class='dpcal_event_preview'></div>" );

				var popup = $( "#dpcal_hover_"+link.id );
				var alink = $( link );
				var adiv = $( div );
				var lpos = alink.offset();
				var rpos = adiv.offset();

				/* Paivanakyma */
				popup.css( { 'top': rpos.top + adiv.height()  + "px", 'left': rpos.left - 2 + "px" } );
				var th = adiv.height() * ( endh - starth - 1 ) ;
				if ( th < adiv.height() ) {
					th = 0;
					popup.css( 'border-bottom-width', '0px' );
				}
				popup.css( 'height', th + "px" );
			}
			popup.show();
		}	
	},
	hover_hide : function( div ) {
	    $( div ).children( "A" ).each( function() {
					     $("#dpcal_hover_" + this.id ).hide();
					     $("#dpcal_hover_" + this.id ).remove();
				});
	},
    destroy : function( link ) {
		var str = link.id;
		var re = /[a-zA-Z_]*-([0-9]*)/;
	    vars = str.match( re );
	    if ( vars && vars[1] > 0 ) {
			if ( confirm( _DPCAL_DELETE_EVENT_Q ) ) {
				var param = { option: dpcalOption, Itemid: dpcalItemid, ajax: 1, prefix: null, eventid: vars[1], task: 'event', view: 'destroy' };
				$.post( "index.php", param, function( reply ) {
					var data=$('dpcalresponse',reply);
					if ( data.children('status').text() == 'ok' ) {
						$(link).parent().parent().parent().hide().remove();
					} else {
						alert( _DPCAL_DELETE_EVENT_FAILED );
					}
				});
			}
		}
	},
	open : function( link ) {
	    var str = link.id;
	    var re = /[a-zA-Z_]*-([0-9]*)/;
	    varsnats = str.match( re );
	    if ( varsnats ) {
			var param = { option: dpcalOption, Itemid: dpcalItemid, ajax: 1, prefix: null, eventid: varsnats[1], task: 'getevent' };
			$.post( "index.php", param, function( reply ) {
				var data=$('dpcalresponse',reply);
				if ( data.children('status').text() == 'ok' ) {
				    var ev = data.children("event");
					var locs = ev.children("locations");
					var loc = locs.children("item");
					var sched = ev.children("schedule");

					if ( $("#dpcal_event_popup").is( "DIV" ) )
					    $("#dpcal_event_popup").hide().remove();					  
					var dpc = $("#dpcal_content");

					dpc.children().hide();
				    dpc.prepend( "<div id='dpcal_event_popup'></div>" );

				    var popup = $("#dpcal_event_popup");	
					dpcal_current_event = parseInt(  ev.children('id').text() );

					var shortTitle = ev.children('title').text().htmlDec();
					shortTitle = shortTitle.substr( 0,50 );
					
					$("A#dpcal_menu_event_mod" ).attr('title', ev.children('title').text().htmlDec() );
					$("A#dpcal_menu_event_mod" ).text( _DPCAL_MODIFY );

					var attlist = ev.children('attachments');
					var aimage = attlist.children('image');

					var dateStr = "";
					var timeStr = "";
				    
					if ( sched.children('type').text() == '1' ) { /*period*/
					    var startday = $('day:first', sched);
					    var endday = $('day:last', sched);
						
						startDateTxt = startday.children( "date" ).text();
						endDateTxt = endday.children("date").text();
						if ( startDateTxt != endDateTxt )
							dateStr = startDateTxt + " - " + endDateTxt;
						else
							dateStr = startDateTxt;
							
						startTime = startday.children("starttime").text();
						endTime = startday.children("endtime").text();
						if ( startTime != endTime ) {
							timeStr = startTime + " - " + endTime;
						} else if ( startTime != '00:00' ) {
							timeStr = startTime;
						}
					} else {
					    sched.children( 'day' ).each( function() {
								dateStr = $(this).children('date').text();
								startTime = $(this).children("starttime").text();
								endTime = $(this).children("endtime").text();
								if ( startTime != endTime ) {
									timeStr = startTime + " - " + endTime;
								} else if ( startTime != '00:00' ) {
									timeStr = startTime;
								}
						 });
					}

					var astr = "<a id='dpcal_event_popup_close' href='javascript:void(0)'>"+ _DPCAL_CLOSE + "</a>";
					astr = astr + "<div class='image'>" + aimage.children('embed').text() + "</div>";

					astr = astr + "<div class='event_border'></div><div class='event_date' id='dpcal_event_popup_date'>" + dateStr + "</div>" +
						"<div class='event_type'>" + ev.children('categoryname').text() +"</div>";
					var contactStr = addWithPostfix( ev.children('contact_name' ).text(), ', ' )
						+ ev.children('contact_phone' ).text();
					astr = astr + "<div id='dpcal_event_popup_titlebar'>" + ev.children( 'title' ).text() + "</div>";
					astr = astr + "<div id='dpcal_event_popup_content'>" +
						"<div class='graytext'><div class='addresstext'>" + addWithPostfix( timeStr , "</br>" ) + '</div>';

					var locStr = '<div class="addresstext">' + addWithPostfix( loc.children('location' ).text(), '<br />' )
						+ addWithPostfix( loc.children('address' ).text(), ', ' )
						+ addWithPostfix( loc.children('postnumber' ).text() , " " )
						+ addWithPostfix( loc.children('postaddress' ).text(), " " ) + "</div>";
					
					var orgStr = "" +
					addWithDelim( "<div class='participants gbtitle'><div class='dpcal_event_gbtitle'>" + _DPCAL_PARTICIPANTS_TITLE + "</div>" , ev.children( 'participants' ).text(), "</div>" ) +
					addWithDelim( "<div class='organizer gbtitle'><div class='dpcal_event_gbtitle'>" + _DPCAL_ORGANIZER_TITLE + "</div>" , ev.children( 'organizer_name' ).text() , "</div>" ) +
				    addWithDelim( "<a href='"+ev.children( 'url' ).text() + "' target='_blank'>", (ev.children('urltext' ).text() ?ev.children('urltext' ).text() : ev.children('url' ).text()) , "</a><br />") +
					addWithDelim( "<span class='contact'>" ,  contactStr , "</span><br />" ) +
				    addWithDelim( "<span class='contact'>" ,  ev.children('contact_email' ).text() ,"</span><br />" );

					astr = astr + locStr + orgStr + "</div>" +  
						"<div class='description'>" + ev.children('description' ).text() + "</div>";				
					astr = astr + loc.children('googlemap').text() + "</div>";

					popup.append( astr );
					$("#dpcal_event_popup_content", popup).height( popup.height() - $("#dpcal_event_popup_titlebar", popup).height() - 20 );
					$("#dpcal_event_popup_close", popup ).bind( 'click', function() { 
						popup.hide().remove(); $("#dpcal_content").children().show();
						});
					
					popup.show();		  
				}
			});
		}
	}
};

/* ######################### DPCAL MAIN ######################### */
function dpcal_MAIN_CLASS(){}
var dpcal = {
  open : {
	day : function( link ) {
		var str = link.id;
		var re = /[a-zA-Z_]*-([0-9]*)-([0-9]*)-([0-9]*)/;
		vars = str.match( re );
		if ( vars ) {
			dpcal.menu.setDate( vars[1], vars[2], vars[3] );
			$("#dpcal_menu_day").click();
		} /*else {
			runTask( link, null, null );
		}*/
	},
	week : function( link ) {
		var str = link.id;
		var re = /[a-zA-Z_]*-([0-9]*)-([0-9]*)-([0-9]*)/;
		vars = str.match( re );
		if ( vars ) {
			dpcal.menu.setDate( vars[1], vars[2], vars[3] );
			$("#dpcal_menu_week").click();
		}
	},
	month : function( link ) {
		var str = link.id;
		var re = /[a-zA-Z_]*-([0-9]*)-([0-9]*)-([0-9]*)/;
		vars = str.match( re );
		if ( vars ) {
			dpcal.menu.setDate( vars[1], vars[2], vars[3] );
			$("#dpcal_menu_month").click();
		}
	}
  },
  menu : {
    date : new Date(),
    day : new Date().getDate(),
    month : new Date().getMonth() + 1,
    year : new Date().getFullYear(),
    wday : new Date().getDay(),
    setDate : function( Lyear, Lmonth, Lday ) {
		dState = this.checkDate( Lyear, Lmonth, Lday );
		if ( dState == 0 ) {
			this.date.setYear( Lyear );
			this.date.setMonth( Lmonth - 1 , Lday );
			this.year = this.date.getFullYear();
			this.month = this.date.getMonth() + 1;
			this.day = this.date.getDate();
		} else {
			if ( dState & 1 ) Lyear = this.year;
			if ( dState & 2 ) Lmonth = this.month;
			if ( dState & 4 ) Lday = 1;
			this.setDate( Lyear, Lmonth, Lday );
		}
    },
	checkDate : function( Lyear, Lmonth, Lday ) {
		var errVal = 0;
		var defDate = new Date();

		if ( Lyear == 'NaN' || typeof Lyear == 'undefined' ) {
			errVal = errVal | 1;
			Lyear = defDate.getFullYear();
		}
		if ( Lmonth == 'NaN' || typeof Lmonth == 'undefined' || Lmonth < 1 || Lmonth > 12 ) {
			errVal = errVal | 2;
		    Lmonth = defDate.getMonth() + 1;
		}

		var mLen = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		if ( (Lyear % 4 == 0 && Lyear % 100 != 0 ) || Lyear % 400 ) mLen[1] = 29;
		if ( Lday > mLen[ Lmonth - 1 ] ) {
			errVal = errVal | 4;
		}
		return errVal;
	},
	bindThem : function ( linknames ) {
		for ( i in linknames ) {
			$("#" + i ).bind( 'click', function() {			    
			    runTask( dpcal.menu.links[i], null, null );			    
				return false;
			  });
		}
	},
    bind : function () {		
		for ( i in this.links )
			$("#" + i ).bind( 'click', function() {			    
			    runTask( this, null, null );			    
				return false;
			  });
		$("A.dpcal_menu_organizer").bind( 'click', function() {
				$("A.dpcal_menu_organizer").removeClass('selected');
				$(this).addClass('selected');

				var OID = Number( this.id.replace( /[^0-9]*/, '' ) );
				for ( i in dpcal.display.organizers ) {
					if ( OID == 0 || dpcal.display.organizers[i].value == OID )
						dpcal.display.organizers[i].selected = true;
					else
						dpcal.display.organizers[i].selected = false;
				}

				runTask( 'dpcal_menu_list_all' , null, null );

			});
    },
    links : {
      dpcal_menu_day :      { id: 'dpcal_menu_day',task : 'day',	param : {}    },
      dpcal_menu_month :    { id: 'dpcal_menu_month',task : 'month',	param : {}    },
      dpcal_menu_week :     { id: 'dpcal_menu_week',task : 'week',	param : {}    },
      dpcal_menu_year :     { id: 'dpcal_menu_year',task : 'year',	param : {}    },

	  dpcal_menu_search :     { id: 'dpcal_menu_search',task : 'search',	param : {}    },

      dpcal_menu_list_day : { id: 'dpcal_menu_list_day',		task : 'list', param : { view: 'day', published: 1 } },
      dpcal_menu_list_month : { id: 'dpcal_menu_list_month',   	task : 'list', param : { view: 'month', published: 1 } },
	  dpcal_menu_list_autumn : { id: 'dpcal_menu_list_autumn', 	task : 'list', param : { view: 'autumn', published: 1 } },
	  dpcal_menu_list_spring : { id: 'dpcal_menu_list_spring', 	task : 'list', param : { view: 'spring', published: 1 } },
	  dpcal_menu_list_all : { id: 'dpcal_menu_list_all', 		task : 'list', param : { view: 'all', published: 1 } },
	  dpcal_menu_list_past : { id: 'dpcal_menu_list_past', 		task : 'list', param : { view: 'past', published: 1 } },
	  dpcal_menu_list_complete : { id: 'dpcal_menu_list_complete',	task : 'list', param : { view: 'all', complete : 1, published: 1 } },

      dpcal_menu_event_add :     { task : 'event', param : { view: 'add' } },
	  dpcal_menu_event_suggest :     { task : 'event', param : { view: 'add' } },
      dpcal_menu_event_mod :     { task : 'event', param : { view: 'mod' } },
	  dpcal_menu_event_copy :     { task : 'event', param : { view: 'copy' } },

      dpcal_menu_event_list_unpublished : { task : 'list', param : { view: 'all', published: 0 } },

      dpcal_menu_toggle_selection : { task : 'toggle_selection', param : { statechange:'ignore' } },
      dpcal_change_selection_submit : { task : 'change_selection_submit', param : { statechange:'run'} },

      dpcal_menu_addcategory :  { task : 'open_add_category',  param : { width: 150, height: 230, top: 100, left: 300 } },
      dpcal_menu_addsection :   { task : 'open_add_section',   param : { width: 150, height: 230, top: 100, left: 300 } },
      dpcal_menu_addorganizer : { task : 'open_add_organizer', param : { width: 200, height: 310, top: 100, left: 300 } },

      add_category :    { task : 'add_category',    param : {} },
      delete_category : { task : 'delete_category', param : {} },
      rename_category : { task : 'rename_category', param : {} },
      add_section :    { task : 'add_section',    param : {} },
      delete_section : { task : 'delete_section', param : {} },
      rename_section : { task : 'rename_section', param : {} },
      add_organizer :    { task : 'add_organizer',    param : {} },
      delete_organizer : { task : 'delete_organizer', param : {} },
      rename_organizer : { task : 'rename_organizer', param : {} }
    },
    chksums : {},
    bindButton : function( prefix, button ) {
      $('#' + prefix + button ).bind('click', function() { runTask( this, button, prefix ); } );
    },
    addLink : function ( param ) {
      var newid = this.getGUID( param );
      this.links[ newid ] = { task : param.task, param : param };
      return newid;
    },
    getGUID : function (param) {
      if ( typeof this.chksums[ param.chksum ] != 'undefined' ) {
	return this.chksums[param.chksum];
      } else {
	var str = 'dpcal_link_';
	var num = Math.floor(Math.random() * 2000);
	while ( typeof this.links[ str + num ] != 'undefined' )
	  num++;
	this.chksums[ param.chksum ] = str + num;
	return str + num;
      }
    }
  },
  dialogs : {
    names : new Array(),
    reorder : function( name ) {
      var topdlg = true;
      for ( i in this.names ) {
	if ( this.names[i] == name && i < this.names.length - 1 ) {
	  topdlg = false;
	  this.names.splice( i, 1 );
	  this.names.push( name );
	}
	var dlg = $("#" + this.names[i] );
	dlg.css( "z-index", "" + (5000 + Number(i)) );
      }
    },
    hide : function( name ) {
      $("#" + name).fadeOut( "fast" );
      for ( i in this.names ) {
	if ( this.names[ i ] == name ) {
	  this.names.splice( i, 1 );
	}
      }
      $("#" + name ).remove();
    },
    getName : function() {
      var dnum = 0;
      var nameexists = false;
      do {
	nameexists = false;
	name = 'dpcalDialog' + (++dnum);
	for ( i in this.names )
	  if ( this.names[i] == name )
	    nameexists = true;
      } while ( nameexists );
      this.names.push( name );
      return name;
    },
    getTopZIndex : function() {
      var topzindex = 5000;
      for ( i in this.names ) {
	if ( $("#"+this.names[i]).css('z-index') == 'auto' )
	  $("#"+this.names[i]).css('z-index', 5000 );
	if ( topzindex < $("#"+this.names[i]).css('z-index') )
	  topzindex = $("#"+this.names[i]).css('z-index');
      }
      return topzindex + 1;
    },
    setStatus : function( dialogname, message ) {
      for ( i in this.names )
	if ( this.names[i] == dialogname )
	  $( "div.dpcalDStatusBar", $("#" + this.names[i] ) ).html( message.replace( /\{prefix\}/, $("#" + this.names[i] ).attr('id') ) );
    }
  },
  lists : {
    lists : new Object(),

    /* lisataan / haetaan select-listan nimi */
    addElementID : function( cat, name, update ) {
      if ( this.lists[ cat ] )
	this.lists[cat].elements.push( name );
      if ( this.lists[ cat ].modified < 0 ) {
	this.updateList( cat, this.updateElement, {cat:cat, name:name } );
      } else if ( update )
	this.updateElement( { cat:cat, name:name } );
    },
    getElementID : function( cat, index ) {
      return this.lists[cat].elements[index];
    },
    getElementList : function( cat ) {
      return this.lists[cat].elements;
    },
    updateElement : function( param ) {
      $( "#" + param.name ).empty().html( dpcal.lists.lists[param.cat].content );
    },

    /* lisataan dpcalList */
    addList : function( cat, task , index, title ) {
      if ( !this.lists[cat] ) {
	this.lists[cat] = new dpcalList();
	this.lists[cat].task = task;
	this.lists[cat].index = index;
	this.lists[cat].title = title;
      }
    },
    /* paivitetaan dpcalList */
    updateList : function( cat, callback, param ) {
      $.post("index.php",
	     { task: this.lists[cat].task, ajax: 1 , option: dpcalOption, Itemid: dpcalItemid },
	     function ( reply ) {
	       var tmpcontent = "";
	       var data = $('dpcalresponse', reply );
	       var status = $('status', data ).text();
	       if ( status == 'ok' ) {
		 $( 'row', data )
		   .each( function() {
			    tmpcontent = tmpcontent + "<option value='" + $( dpcal.lists.lists[cat].index , this).text() + "'>" +
			      $(  dpcal.lists.lists[cat].title , this).text() + "</option>";
			  }
			  );
		 tmpcontent = tmpcontent + "<option value=''></option>";
	       } else
		 alert( $( 'message', data ).text() );
	       dpcal.lists.lists[cat].content = tmpcontent;
	       dpcal.lists.lists[cat].modified = new Date().getTime();
	       if ( callback )
		 callback( param );
	     }
	     );
    },
    /* html-sisalto */
    getList : function( param ) {
      if ( param.time > dpcal.lists.lists[ param.cat ].modified && param.time <= new Date().getTime() ) {
	this.updateList( param.cat, this.getList, { cat: param.cat, time: param.time } );
      } else {
	elements = dpcal.lists.getElementList( param.cat );
	for ( i in elements )
	  dpcal.lists.updateElement( { cat: param.cat, name: elements[i] } );
      }
    }

  },
  display : {
    getString : function( which ) {
      var ml = this.categories;
      switch ( which ) {
      case 'sections':
	ml = this.sections;
	break;
      case 'organizers':
	ml = this.organizers;
	break;
      }

      var arr = new Array();
      for ( i in ml ) {
	if ( ml[i].selected == true && ml[i].value > 0 )
	  arr.push( ml[i].value );
      }
      return arr.toString();
    },
    categories : {},/* new Array(),*/
    sections : {},/*new Array(),*/
    organizers :{}/* new Array()*/
  }
};

dpcal.lists.addList( 'category', 'getcategories', 'id_c', 'name' );
dpcal.lists.addList( 'section', 'getsections', 'id_s', 'name' );
dpcal.lists.addList( 'organizer', 'getorganizers', 'id_o', 'name' );
dpcal.lists.addList( 'organizer_abbrev', 'getorganizers', 'id_o', 'abbrev'  );




function array_merge( a1, a2 ) {
  var combined = {};
  for ( i in a1 )
    combined[i] = a1[i];
  for ( i in a2 )
    combined[i] = a2[i];
  return combined;
}

function getContent( task, param ) {
  myparam = array_merge( param, { task: task } );
  $.post( "index.php", myparam, function( reply ) {
	    data = $('dpcalresponse', reply );
	    var tmp = $('dpcalcontent', data ).text();
	    var re = new RegExp( "class='dpcal_link(.*?)' href='.*?(.*?)'","gm" );
	    var qre = new RegExp("([^?=&]+)(=([^&]*))?", "g" );

	    tmp = tmp.replace( re, function( $0, $1, $2 ) {
				 var href = $2;
				 var moreclasses = $1;
				 var param = { chksum: href };
				 href.replace( qre, function( $0, $1, $2, $3 ) {
						 if ( $1 != 'index.php' )
						   param[ $1 ] = $3;
					       });
				 if ( param.popup ) {
				   returnstr = "class='dpcal_link"+moreclasses+" dpcal_hover' id='" + dpcal.menu.addLink( param ) + "' href='javascript:void(0)'";
				 } else {
				   returnstr = "class='dpcal_link"+moreclasses+"' id='" + dpcal.menu.addLink( param ) + "' href='javascript:void(0)'";
				 }
				 return returnstr;
			       });

	    $("#dpcal_content").html( tmp );
	    $("#dpcal_content .dpcal_link").bind( "click", function() { runTask( this, null, null ) } );
 	    $("#dpcal_content .dpcal_hover").parent().hover( function() { dpcal_event.hover_show( this ) }, function() { dpcal_event.hover_hide( this ) } );
	    $("#dpcal_content A.dpcal_target_day").bind( "click", function() { dpcal.open.day( this ) } );
		$("#dpcal_content A.dpcal_target_week").bind( "click", function() { dpcal.open.week( this ) } );
		$("#dpcal_content A.dpcal_target_month").bind( "click", function() { dpcal.open.month( this ) } );
		$("#dpcal_content A.dpcal_event_destroy").bind( "click", function() { dpcal_event.destroy( this ) } );

	    var script = $('dpcalscript', data ).text();
	    eval( script );

		if ( dpcal_state.ide > 0 ) {
			$("#dpcal_content/*").hide();
			$("#dpcal_target_event-" + dpcal_state.ide ).click();
			dpcal_state.ide = 0;
		}
	  });
}

function dialog_open( form, param, dialog ) {
  myparam = array_merge( param, { task: 'getform', formname: form } );
  $.post( "index.php", myparam , function(reply) {
	    checkReturn( reply, myparam, dialog );
	  });
}
function dialog_exec( param, dialog, taskname, confirmmsg, checkreturn ) {
  var goAhead = true;
  if ( confirmmsg ) {
    goAhead = confirm( confirmmsg );
  }
  if ( goAhead ) {
    param = array_merge( param, getFormValues( 'mod' + taskname , dialog ) );
    $.post( "index.php",
	    param ,
	    function( data ) {
	      if ( checkreturn )
		checkReturn( data, param, dialog );
	      else
		dpcal.dialogs.setStatus( dialog.id, $('message',data).text() );
	      $("#dpcalEditors" ).trigger( taskname + 'change', [ new Date().getTime() ] );
	    });
  }
}

function checkReturn( reply, param, dialog ) {
  data = $('dpcalresponse', reply );
  if ( $('status', data).text() == 'ok' ) {
    dpcal.dialogs.setStatus( dialog.id, $('message', data).text() );
  } else {
    var ndlg = initDialog( $('dpcaltitle',data).text(), $( 'dpcalform', data).text(), $('dpcalstatus', data ).text(), dialog, param );
    if ( ndlg ) {
      var scr = $('dpcalscript', reply ).text();
      scr = scr.replace( /\{prefix\}/g, ndlg.attr('id') );
      eval( scr );
    }
  }
}

function getFormValues( formname, dialog ) {
  var values = {};// task: formname };
  var formelem = 0;
  var attrib = 'id';
  if ( dialog )
    formelem = $( "#" + dialog.id + formname ).children();
  else {
    formelem = $( "form[@name=" + formname + "] :input" );
    attrib = 'name';
  }
  
  if ( $('#enddate').val() == "" ) $('#enddate').val( $('#startdate').val() );
  if ( typeof tinyMCE != 'undefined' ) {
	tinyMCE.triggerSave( true, true );
	$('#dpcal_ev_description').text( tinyMCE.getContent() );
	tinyMCE.execCommand( 'mceRemoveControl', false, 'dpcal_ev_description' );
  }

  formelem.each( function( i ) {
		   if ( $( this ).is( "input[@type=radio]" ) || $( this ).is( "input[@type=checkbox]" ) ) {
		     if ( this.checked )
		       values[ $(this).attr( attrib ) ] = $( this ).val();
		   } else {
		     if ( $( this ).is( "input" ) || ( $(this).is( "select" ) && $(this).attr('multiple') != 'multiple' ) )
		       values[ $(this).attr( attrib ) ] = $(this).val();
		     if ( $( this ).is( "textarea" ) )
		       values[ $(this).attr( attrib ) ] = $(this).val();
		     if ( $( this ).is( "select" ) && $(this).attr('multiple') == 'multiple' ) {
		       /*laitetaan multiselectin valitut arvot pilkulla erotettuina stringiks*/
		       var elem = new Array();
		       $(this).children('option')
			 .each( function() {
				  if ( $(this).attr('selected') == true )
				    elem.push( $(this).val() );
				});
		       values[ $(this).attr( attrib ) ] = elem.join(',');
		     }
		   }
		 });
	
  return values;
}

function initDialog( dpctitle, dpccontent, dpcstatus, dialogdiv, param ) {
  var editors = $("#dpcalEditors");
  var dnum = 0;
  var name = "dpcalDialog" + dnum;
  var nameexists = false;

  if ( !dialogdiv ) {
    name = dpcal.dialogs.getName();

    editors.append( "<div class='jqmDialog' id='" + name + "'></div>" );
    var dialog = $("#" + name );

    /* Replace {prefix} with dialog name */
    dpccontent = dpccontent.replace( /\{prefix\}/g, name );
    dpctitle = dpctitle.replace( /\{prefix\}/g, name );
    dpcstatus = dpcstatus.replace( /\{prefix\}/g, name );

    dialog.css( 'z-index', dpcal.dialogs.getTopZIndex() );

    dialog.append(
		  "<div class='dpcalAjaxStatus'></div>" +
		  "<input type='image' src='" + mosConfig_live_site +
		  "/components/com_dpcal/images/16-em-cross.png' class='dpcalDClose' />" +
		  "<div class='dpcalDHandle'>"  + dpctitle   + "</div>" +
		  "<div class='dpcalDContent'>" + dpccontent + "</div>" +
		  "<div class='dpcalDStatusBar'>"+dpcstatus  + "</div>" +
		  "<img src='" + mosConfig_live_site + "/components/com_dpcal/images/resize.gif' alt='resize' class='dpcalDResize' />"

		  );

    $("div.dpcalAjaxStatus", dialog)
      .ajaxError( function( request, settings ) {
		    $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-message-warn.png ) " );
		  })
      .ajaxSend( function( request, settings ) {
		   $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-ajaxloaderwhite.gif )" );
		 })
      .ajaxSuccess( function( request, settings ) {
		      $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-em-check.png )" );
		    });

    dialog
      .jqm( { autofire: true, overlay: 0 } )
      .jqDrag('div.dpcalDHandle')
      .click( function() { dpcal.dialogs.reorder( name ) } );
    $('div.dpcalDContent', dialog)
      .jqResize( $('img.dpcalDResize', dialog ) );
    $("div.dpcalDHandle", dialog )
      .mousedown( function() { dpcal.dialogs.reorder( name ); } );
    $('input.dpcalDClose', dialog )
      .click( function() { dpcal.dialogs.hide( name ); } )
      .hover(
	     function(){ $(this).addClass('jqmdXFocus'); },
	     function(){ $(this).removeClass('jqmdXFocus'); })
      .focus(
	     function(){ this.hideFocus=true; $(this).addClass('jqmdXFocus'); })
      .blur(
	    function(){ $(this).removeClass('jqmdXFocus'); });

    contentarea = $('div.dpcalDContent', dialog);
    cssparam = [ 'width', 'height' ];
    for ( i in cssparam ) {
      if ( param[ cssparam[i] ] )
	contentarea.css( cssparam[i], param[ cssparam[i] ] + "px" );
    }
    cssparam = ['top','left' ];
    for ( i in cssparam )
      if ( param[ cssparam[i] ] )
	dialog.css( cssparam[i], param[ cssparam[i] ] + "px" );

    dialog.fadeIn('fast');
    return dialog;
  } else {

    /* Replace {prefix} with dialog name */
    dpccontent = dpccontent.replace( /{prefix}/, dialogdiv.id );
    dpctitle = dpctitle.replace( /{prefix}/, dialogdiv.id );
    dpcstatus = dpcstatus.replace( /{prefix}/, dialogdiv.id );

    $( 'div.dpcalDHandle', dialogdiv ).html( dpctitle );
    /*$( 'div.dpcalDContent', dialogdiv ).html( dpccontent );*/
    $( 'div.dpcalDStatusBar', dialogdiv ).html( dpcstatus );
    /*return $(dialogdiv);*/
    return false; /*ei ajeta formin skriptia*/
  }
}

function bindListChange( list, textbox ) {
  $( list )
    .bind('change',
	  function() {
	    $( textbox ).val( $( $('option', this)[ $(this)[0].selectedIndex ] ).text() );
	  });
}

/* function remoteDay( target ) {
  var str = target;
  var re = /[a-zA-Z_]*-([0-9]*)-([0-9]*)-([0-9]*)/;
  vars = str.match( re );
  if ( vars ) {
    var param = { chksum: 'day' + vars[1] + vars[2] + vars[3], year: vars[1], month: vars[2], day: vars[3], task: 'day' };
    link = dpcal.menu.addLink( param );
    runTask( link, null, null );
  }
} */

function MAIN_APPLICATION () {}
$( function() {
     $("body").append( "<div id='dpcalEditors'><a id='dpcalDummyLink'></a></div>" );

     /*openLogWindow();

	init_uploader();*/

     $("#dpcalEditors")
       .bind( 'categorychange', function( event, time ) { dpcal.lists.getList( { cat:'category', time: time } );   })
       .bind( 'sectionchange',  function( event, time ) { dpcal.lists.getList( { cat:'section', time: time } );    })
       .bind( 'organizerchange', function( event, time ) {
		dpcal.lists.getList( { cat:'organizer', time: time } );
		dpcal.lists.getList( { cat:'organizer_abbrev', time: time } );
	      });

     /*$("#dpcalStatus").ajaxComplete( function( request, settings ) { $(this).empty(); $(this).append( "Complete" ); } );*/
     $("#dpcalStatus")
       .ajaxError(function( request, settings ) {
		    $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-message-warn.png ) " );
		  })
       .ajaxSend( function( request, settings ) {
		    $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-ajaxloaderwhite.gif )" );
		  })
       .ajaxSuccess( function( request, settings ) {
		       $(this).css( "background-image", "url(" + mosConfig_live_site + "/components/com_dpcal/images/16-em-check.png )" );
		     });

     dpcal.menu.bind();

	 $('#dpcal_archive_change').bind( 'click', archiveGetTerm );
     $('#dpcal_archive_alt_change').bind( 'click', archiveGetAlt );


     /* ladataan kategoria/osasto/jarjestaja muistiin - kaikki on alussa valittuna */
     var dpc_chg_cat = $("SELECT#dpcal_change_category")[0];
     var dpc_chg_sec = $("SELECT#dpcal_change_section")[0];
     var dpc_chg_org = $("SELECT#dpcal_change_organizer")[0];


    for ( var i = 0; i < dpc_chg_cat.options.length ; i++ )
		dpcal.display.categories[ i ] = { selected: true, value: dpc_chg_cat.options[i].value };
    for ( var i = 0; i < dpc_chg_sec.options.length ; i++ )
		dpcal.display.sections[ i ] = { selected:true, value: dpc_chg_sec.options[i].value };
    for ( var i = 0; i < dpc_chg_org.options.length ; i++ ) {
		if ( dpcalInitialOrganizer < 1 || dpc_chg_org.options[i].value == dpcalInitialOrganizer )
			dpcal.display.organizers[ i ] = { selected:true, value: dpc_chg_org.options[i].value };
		else
			dpcal.display.organizers[ i ] = { selected:false, value: dpc_chg_org.options[i].value };
     }

     $("SELECT.multiselect")
       .bind( 'change', function( event ) {
		var sbox =  $(event.target)[0];
		var slist = dpcal.display.categories;
		if ( sbox.id == 'dpcal_change_section' )
		  slist = dpcal.display.sections;
		else if ( sbox.id == 'dpcal_change_organizer' )
		  slist = dpcal.display.organizers;
		for ( var i = 0; i < sbox.options.length; i++ )
		  slist[i].selected = sbox.options[i].selected;
	      });


	remoteCall();
/* 	$( window.location.hash ).bind('change', 'remoteCall' );
     .attr('disabled', true );


     debug( "init ok" ); */
   });

function init_uploader() {
	$('#dpcalUploader').hide().remove();

	$("#dpcalEditors").append( "<div class='jqmDialog' id='dpcalUploader' style='display: none;'></div>" );
	$("#dpcalUploader").append(
				      "<input type='image' src='" + mosConfig_live_site +
				      "/components/com_dpcal/images/16-em-cross.png' class='dpcalDClose' />" +
				      "<div class='dpcalDHandle'>" + _DPCAL_UPLOAD_TITLE + "</div>" +
				      "<iframe class='dpcalDContent' style='background-color: #FFF' frameborder='0'></iframe>" +
				      "<div class='dpcalDStatusBar'></div>" +
				      "<img src='" + mosConfig_live_site +
				      "/components/com_dpcal/images/resize.gif' alt='resize' class='dpcalDResize' />"
					 );

    var t = $('#dpcalUploader .dpcalDContent');
	var dialog = $('#dpcalUploader');

	var tpos = $('#dpcupimg').offset();

	dialog.css('top', tpos.top );
	dialog.css('left', tpos.left );


	 $("A.dpcalUploadImage")
	   .bind("click", function() {
		   $("#dpcalUploader .dpcalDContent").attr( 'src', $(this).attr( 'href' ) );
		 });
	 dialog
	   .jqm( {
		 trigger: 'A.dpcalUploadImage',
		 target: t,
		 modal: true,
		 overlay: 0 } )
	   .jqDrag( 'div.dpcalDHandle' );
	 $('.dpcalDContent', dialog )
	   .jqResize( $('img.dpcalDResize', dialog ) );
	 $('input.dpcalDClose', dialog )
	   .click( function() { dialog.jqmHide(); } )
	   .hover(
		  function(){ $(this).addClass('jqmdXFocus'); },
		  function(){ $(this).removeClass('jqmdXFocus'); })
	   .focus(
		  function(){ this.hideFocus=true; $(this).addClass('jqmdXFocus'); })
	   .blur(
		 function(){ $(this).removeClass('jqmdXFocus'); });
}

function dpcal_image_uploaded( fname, img_src, img_w, img_h ) {
  var curdate = new Date();
  var elem = $( "#" + fname );
  $('input[@name='+fname+'_image]').val( img_src.replace( /^.*\//, '' ) );
  $('input[@name='+fname+'_image_width]').val( img_w );
  $('input[@name='+fname+'_image_height]').val( img_h );
  elem.attr("src", img_src+"?t="+curdate.getTime());
  elem.attr("width", img_w);
  elem.attr("height", img_h);
  $('#dpcalUploader').jqmHide();
  return false;
}

function remoteCall() {	
	if ( window.location.hash.substring(1).match( 'remote=' ) ) {
		var q = window.location.hash.substring(1).split( /[&;]/ );
		var retask = '';
		for ( var i = 0; i< q.length; i++ ) {
			var n = q[i].split( '=' );
			var varname = unescape( n[0] );
			if ( n.length == 2 )
				var varvalue = unescape( n[1] );
			switch ( varname ) {
				case 'task': dpcal_state.task = varvalue; break;
				case 'day': dpcal.menu.day = varvalue; break;
				case 'month': dpcal.menu.month = varvalue; break;
				case 'year': dpcal.menu.year = varvalue; break;
				case 'remote': retask = varvalue; break;
				case 'ide': dpcal_state.ide = varvalue; break;

				case 'date':
					var str = varvalue;
					var re = /([0-9]*)-([0-9]*)-([0-9]*)/;
					vars = str.match( re );
					if ( vars )
						dpcal.menu.setDate( vars[1], vars[2], vars[3] );
					break;
			}
		}

		runTask( retask, null, null );		
		var url = window.location.href.replace( /#.*/ , "#" );
		window.location.replace( url );
	} else if ( ! dpcal_state.task ) {
		/*dpcal_state.task = 'month';*/				
		
		runTask( dpcalDefaultTask, null, null );
	}
}

function archiveGetTerm(){
	var termstr = $("#dpcal_archive_select").val();
	var termyear = Number( termstr.substring( 0, 4 ) );
	var term = termstr.substring( 5, 7 ) ;

	dpcal.menu.setDate( termyear, dpcal.menu.month, dpcal.menu.day );
	if ( term == 1 ) {
		runTask( 'dpcal_menu_list_spring', null, null );
	} else if ( term == 2 ) {
		runTask( 'dpcal_menu_list_autumn', null, null );
	}
	return false;
}

function archiveGetAlt(){
	var termstr = $("#dpcal_archive_alt_select").val();

	if ( termstr == 'upcoming' )
		runTask( 'dpcal_menu_list_all', null, null );
	else if ( termstr == 'past' )
		runTask( 'dpcal_menu_list_past', null, null );
	return false;
}


/* function limitTimeInput( objname , hour ) {
  obj = document.getElementById( objname );

  if ( !obj.value.match( /^\d+$/ ) ) {
    obj.value = '';
  }
  if ( !obj.value.match( /^\d{1,2}$/ ) )
    obj.value = obj.value.substr(0,2);

  val = parseInt( obj.value, 10 );

  if ( ( val < 0 || val > 24 ) && hour )
    obj.value = '';
  if ( ( val < 0 || val > 59 ) && !hour )
    obj.value = '';
}

function isEmpty(elemId, fieldName) {
  var elem = document.getElementById(elemId);
  var messagestart = "Ole hyva ja tayta kentta: ";

  if (elem.value.length == 0) {
    elem.focus();
    alert(messagestart + fieldName + ".");
	return false;
  }

  return true;
} */

function openLogWindow() {
  if ( typeof console == 'undefined' ) {
    $("#dpcalEditors").append("<div id='datapolis_log' style='"+
			      "position:absolute; text-align:left; z-index:10000000;"+
			      "top:0; left:10px; width:900px; height:100px; "+
			      "padding:4px; overflow:auto; background-color:#fff; "+
			      "border:1px solid #226; border-top:none;'></div>");

    $("#datapolis_log").append("<pre></pre>");
    $("#datapolis_log").click( function() {
				 if ( $("#datapolis_log").height() < 10 )
				   $("#datapolis_log").height( 100 );
				 else
				   $("#datapolis_log").height( 6 );
			       });
  }
}


function debug( msg ) {
  if ( typeof console == 'undefined' ) {
    $("#datapolis_log > pre").prepend( msg + '<br />' );
  } else {
    console.log( msg );
  }
}
// From Joomla core

// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function dpcal_selected(cal, date) {
	cal.sel.focus();
	cal.sel.value = date; // just update the value of the input field	
	cal.sel.blur();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function dpcal_close_handler(cal) {
	cal.hide();			// hide the calendar

	// don't check mousedown on document anymore (used to be able to hide the
	// calendar when someone clicks outside it, see the showCalendar function).
	Calendar.removeEvent(document, "mousedown", dpcal_check_calendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function dpcal_check_calendar(ev) {
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null; el = el.parentNode)
	// FIXME: allow end-user to click some link without closing the
	// calendar.  Good to see real-time stylesheet change :)
	if (el == calendar.element || el.tagName == "A") break;
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		calendar.callCloseHandler(); Calendar.stopEvent(ev);
	}
}
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function dpcal_show_calendar(id) {
	var el = document.getElementById(id);
	if (calendar != null) {
		// we already have one created, so just update it.
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
	} else {
		// first-time call, create the calendar
		var cal = new Calendar(true, null, dpcal_selected, dpcal_close_handler);
		calendar = cal;		// remember the calendar in the global
		cal.setRange(1900, 2070);	// min/max year allowed
		calendar.create();		// create a popup calendar
		calendar.parseDate(el.value); // set it to a new date
	}
	calendar.sel = el;		// inform it about the input field in use
	calendar.showAtElement(el);	// show the calendar next to the input field

	// catch mousedown on the document
	Calendar.addEvent(document, "mousedown", dpcal_check_calendar);
	return false;
}

//omat
function showClock( ename ) {
  if ( $("#dpcal_clock").is( "DIV" ) ) {
    $("#dpcal_clock").remove();
    return false;
  }
  var element = $("#" + ename );
  var pos = element.offset();

  $("#dpcalEditors").append( "<div id='dpcal_clock'></div>" );
  clock = $("#dpcal_clock");
  clock.css( { 'top': pos.top + element.height() +3+ "px", 'left' : pos.left + "px" } );
  clock.width( element.width() - 8 );

  var appendstr = "<table border='0' cellspacing='0' cellpadding='0'><tr>"
	+ "<td><input type='text' id='dpcal_clock_hour'></td><td>:</td>" 
	+ "<td><input type='text' id='dpcal_clock_min'></td></tr>"
    + "<tr><td><ul id='dpcal_hour_select'>";
  for ( i = 6; i<24;i++)
    appendstr = appendstr + "<li>" + ( i < 10 ? '0' + i : i ) + "</li>";
  for ( i = 0; i<6;i++)
    appendstr = appendstr + "<li>" + ( i < 10 ? '0' + i : i ) + "</li>";
  appendstr = appendstr + "</ul></td><td></td>"
    + "<td><ul id='dpcal_min_select'><li>00</li><li>15</li><li>30</li><li>45</li></ul></td></tr></table>";

  clock.append( appendstr );

  var hour = $("#dpcal_clock_hour", clock );
  var min = $("#dpcal_clock_min", clock );

  var hoursel = $("#dpcal_hour_select", clock );
  var minsel = $("#dpcal_min_select", clock );

  hour.bind( "mouseover",
	     function() {
	       minsel.hide();
	       hoursel.show();
	     });
  min.bind( "mouseover",
	    function() {
	      hoursel.hide();
	      minsel.show();
	    });
  $( "li", hoursel )
    .bind( "click", function() {
	     hour.val( $(this).text() );
	     hoursel.hide();
	     if ( hour.val() != '' && min.val() != '' ) {
	       element.val( hour.val() + ":" + min.val() );
	       clock.remove();
	     }
	   });
  $( "li", minsel )
    .bind( "click", function() {
	     min.val( $(this).text() );
	     minsel.hide();
	     if ( hour.val() != '' && min.val() != '' ) {
	       element.val( hour.val() + ":" + min.val() );
	       clock.remove();
	     }
	   });

  clock.show();
}

function updateScheduleType() {
	var sdval = $("#startdate").val();
	var edval = $("#enddate").val();
	parseSD = sdval;
	parseED = edval;
		
	if ( parseSD.indexOf('.') > 0 ) {
		parts = parseSD.split('.');
		parseSD = parts[2] + "/" + parts[1] + "/" + parts[0];
	}	
	if ( parseED.indexOf('.') > 0 ) {
		parts = parseED.split('.');
		parseED = parts[2] + "/" + parts[1] + "/" + parts[0];
	}
		
	$("#e_date").val( sdval );		
	
	mysdt = Date.parse( parseSD );
	myedt = Date.parse( parseED );	
	
	if ( $.trim( edval ) == "" || myedt < mysdt || myedt == mysdt) 
		$("#enddate").val( sdval );
	
	if ( mysdt == myedt ) 
		$("#scheduletype").val( dpcalScheduleDay );
	else
		$("#scheduletype").val( dpcalSchedulePeriod );
}

function bindEventForm() {
	$("#startdate").get(0).onblur = updateScheduleType;
	$("#enddate").get(0).onblur = updateScheduleType;		
}
function changeScheduleDisplay( source ) {
  $( "DIV.scheduletype" ).removeClass('visible');
  $( "#scheduletype_" + source.value ).addClass('visible');
}

/* ##################################### Generic Functions */

function rselect( myradio, which ) {
  var radio = $( "input[@name=" + myradio + "]" ).get( which );
  $( radio ).attr('checked','checked').trigger( 'click' );
}

function dpc_is_checked( mycheckbox ) {
  return ( typeof $(mycheckbox).attr('checked') != 'undefined' ) ? 1 : 0;
}

