/**
 * @author bdolmar
 * Updates elements with the 'date_select' class to display YUI Widget
 * Relies on: jquery 1.1.4, jquery dimensions ,YUI 2.3.0
 * 
 */

SB = {};

SB.DateSelect = function (element){
	this.textInput = element;
	this.calID = "calContainer" + this.getNextID();
	$("body").append("<div id=\"" + this.calID + "\">Hello World</div>");
	this.calContainer = $("#"+this.calID);
	this.positionCalContainer();
	this.initYUICalendar();
};
p = SB.DateSelect.prototype;
p.currentID = 0;

p.getNextID = function(){
	p.currentID += 1;
	return this.currentID;
}
p.positionCalContainer = function(){
	var offset = $(this.textInput).offset();
	$(this.calContainer).css("position", "absolute");
	$(this.calContainer).css("top", offset.top + $(this.textInput).height()+5);
	$(this.calContainer).css("left", offset.left);
}
p.initYUICalendar = function(){
	this.calendar = new YAHOO.widget.Calendar("yui_cal-"+this.calID,this.calID);
	this.calendar.render();
	this.calendar.selectEvent.subscribe(this.onDateSelect, this, true);
	var container = this.calContainer;
	this.textInput.calendar = this.calendar;
	this.textInput.calContainer = this.calContainer;
	this.textInput.activeContainer = this.activeContainer;
	this.textInput.dateSelect = this;
	$(this.textInput).click(function(){
		if($(this).val()!=""){
			firstDate = new Date($(this).val());
//			this.calendar.select((firstDate.getMonth()+1) + "/" + firstDate.getDate() + "/" + firstDate.getFullYear())
			this.calendar.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear()); 
			//this.calendar.render();
		}
		if(SB.DateSelect.activeContainer){
			$(SB.DateSelect.activeContainer).hide();
		}
		if(SB.DateSelect.activeContainer == this.calContainer){
			SB.DateSelect.activeContainer = "";
		}else{
			this.dateSelect.positionCalContainer();			
			$(this.calContainer).show();
			SB.DateSelect.activeContainer = this.calContainer;
					
		}
	});	
	$(this.textInput).keydown(function (e) {
      if(e.which == 9 && SB.DateSelect.activeContainer){
			$(SB.DateSelect.activeContainer).hide();
      }
      return this;
    });
}
p.onDateSelect = function(evt, info, target){
//	console.log("Hello World");
//	console.log("this = %o,evt = %o, info = %o, target = %o", this, evt, info, target);
	$(this.calContainer).hide();
    $(this.textInput).val( info[0][0][1] 
                           + '/'
                           + info[0][0][2]
                           + '/'
                           + info[0][0][0]);
}

var cal_attach = function(){
    dateSelects = $(".date_picker");
    for(i = 0; i < dateSelects.length; i++){
        new SB.DateSelect(dateSelects[i]);
    }
};

$(cal_attach);

