Object.extend(scal.prototype,
{
    toggleCalendar: function()
    {
        var element = $(this.options.wrapper) || this.element;
        this.options[element.visible() ? 'onclose' : 'onopen'](element);
        this.options[element.visible() ? 'closeeffect' : 'openeffect'](element, {duration: 0.5});
	//line added by ray to remove the select boxes that remain visible in ie6-
	element.visible() ? $$('.mediumInput')[0].style.visibility = 'visible' : $$('.mediumInput')[0].style.visibility = 'hidden';
    },

    isOpen: function()
    { 
        return ( $(this.options.wrapper) || this.element).visible();
    }
});

//this is a global variable to have only one instance of the calendar
var calendar = null;

//element   => is the <div> where the calender will be rendered by Scal.
//input     => is the <input> where the date will be updated.
//container => is the <div> for dragging.
//source    => is the img/button which raises up the calender, the script will locate the calenar over this control.
function showCalendar(element, input, container, source)            
{
    if (!calendar)
    {
        container = $(container);
        //the Draggable handle is hard coded to "rtop" to avoid other parameter.
        //new Draggable(container, {handle: "rtop", starteffect: Prototype.emptyFunction, endeffect: Prototype.emptyFunction});
        
	container.innerHTML = '<div class="floating" id="calendar"></div>';
	
        //The singleton calendar is created.
        calendar = new scal(element, $(input),
        {
            updateformat: 'dd/mm/yyyy',
            closebutton: 'X',
            wrapper: container
        });
   }
    else
    {
        calendar.updateelement = $(input);
    }

    
/*    calendar.options.updateformat.split("/").each(function(w){
		    alert(w);
    });*/
    
    var day = $F(input).substr(calendar.options.updateformat.indexOf("d"), 2);
    var month = $F(input).substr(calendar.options.updateformat.indexOf("m"), 2);
    var year = $F(input).substr(calendar.options.updateformat.indexOf("y"), 4);
    
    var date = new Date(month + "/" + day + "/" + year);
    
    calendar.setCurrentDate(isNaN(date) ? new Date() : date);
    
    //Locates the calendar over the calling control  (in this example the "img").
    if (source = $(source))
    {
        Position.clone($(source), container, {setWidth: false, setHeight: false, offsetLeft: source.getWidth() + 2});
    }
    
    //finally show the calendar =)
    calendar.openCalendar();
};

var imgCalendar_Click = function(e, input){
	calendar = null;
	showCalendar("calendar", input, "calendar-container", Event.element(e));
};

var applyCalendarEvent = function() {
	Event.observe("imgPrefDate", "click", imgCalendar_Click.bindAsEventListener(window, $$("input.myDateInput")[0].id));
	Event.observe("textPrefDate", "click", imgCalendar_Click.bindAsEventListener(window, $$("input.myDateInput")[0].id));
};
