/*
OBLONGTECH JAVASCRIPT CALENDAR CODE VERSION3 UPDATED AUG2010
REQUIRES =>JQUERY 1.4.2 + OBLONGTECH-CORE-3
Edited By Dustin 20100820438
*/

//DEFAULT CAL INPUT
function init_cal(ji,jb,oncomplete){
jb.eq(0)
.bind('click',{i:ji,c:ji.prev(),fn:oncomplete},Calendar3).prev().bind('click',function(event){ return false; });
}
function init_cal2(ji,jb,oncomplete){
jb.eq(0)
.bind('click',{i:ji,c:ji.prev(),fn:oncomplete},Calendar3_2).prev().bind('click',function(event){ return false; });
}
function init_cal3(ji,jb,oncomplete){
jb.eq(0).bind('focus',{i:ji,c:ji.next(),fn:oncomplete},Calendar3_2);
ji.eq(0).bind('click',function(event){ return false; });
}
function init_cal_backup(ji,jb){
jb.eq(0)
.bind('click',{i:ji,c:ji.prev(),fn:function(event){

d = event.data.date;//[yyyy,mm]
D = jQuery(this).find('span').html();//dd
p = jQuery(this).parents('.calendar-placeholder').eq(0).html('').css({'display':'none'});
i = p.next();
v = d[0]+'-'+d[1]+'-'+D;//yyyy-mm-dd
//v = d[1]+'/'+D+'/'+d[0];//mm/dd/yyyy
//v = D+'/'+d[1]+'/'+d[0];//dd/mm/yyyy
//v = D+'.'+d[1]+'.'+d[0];//dd.mm.yyyy

i.val(v).trigger('focus').trigger('blur');

 }},Calendar3).prev().bind('click',function(event){ return false; });
}

/*#########################################################################################*/
//SORT OBJECT
function sortObject(o){
 var sorted = {}, key, a = [];
 for(key in o){ a.push(key); }
 a.sort();
 for(key=0;key<a.length;key++){ sorted[a[key]] = o[a[key]]; }
 return sorted;
 }
//Object.prototype.sort = function(){ return sortObject(this); }
 
/*#########################################################################################*/
//SIMULATES PHP DATE FUNCTION - USAGE = (new Date()).format('Ymd')
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

/*#########################################################################################*/
//RETURN DATE ARRAY [YYYY,MM,DD]
function parseDate2(date){
 if(typeof(date)=='undefined'||date==''){ return false; }
 date = (typeof(date)=='string' ? date.split(/\/|\.|\-/g) : date );
 var y = parseInt(date[2]);
 var m = (parseInt(date[1])==0 && date[1].toString().length==2 ? parseInt(date[1].toString().substr(1)) : parseInt(date[1]) );
 var d = (parseInt(date[0])==0 && date[0].toString().length==2 ? parseInt(date[0].toString().substr(1)) : parseInt(date[0]) );
 /* y = (isNaN(y) || y == null) ? (new Date()).getFullYear() : y ; m = (isNaN(m) || m == null) ? (new Date()).getMonth()+1 : m ; d = (isNaN(d) || d == null) ? (new Date()).getDate() : d ; */
 return [y,m,d];
 }
function parseDate(date){
 if(typeof(date)=='undefined'||date==''){ return false; }
 date = (typeof(date)=='string' ? date.split(/\/|\.|\-/g) : date );
 var y = parseInt(date[0]);
 var m = (parseInt(date[1])==0 && date[1].toString().length==2 ? parseInt(date[1].toString().substr(1)) : parseInt(date[1]) );
 var d = (parseInt(date[2])==0 && date[2].toString().length==2 ? parseInt(date[2].toString().substr(1)) : parseInt(date[2]) );
 /* y = (isNaN(y) || y == null) ? (new Date()).getFullYear() : y ; m = (isNaN(m) || m == null) ? (new Date()).getMonth()+1 : m ; d = (isNaN(d) || d == null) ? (new Date()).getDate() : d ; */
 return [y,m,d];
 }
/*#########################################################################################*/
//GET DAYS IN MONTH FUNCTION
function daysInMonth(m,y){
 m--;if(m<0){m=11;y--;}else if(m>11){m=0;y++;}
 var l = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m];
 //COMPENSATE FOR LEAP YEAR
 if(m==1){/*FEB ONLY*/
  y=(typeof(y)=='undefined' ? (new Date()).getFullYear() : y );
  if((y%4==0 && y%100!=0) || y%400==0){ l=29; }
  }
 return l;
 }
/*#########################################################################################*/
//HIDE CALENDARS ON CLICK DOCUMENT EVENT
jQuery(document).bind('click',function(event){
 event = ( window.event || event );
 var target = ( event.target || event.srcElement );
 jQuery('.calendar').each(function(i){
  if(
  jQuery(this.parentNode).parent().find('.btn-datepicker').get(0)!=target
 &&
  !jQuery.contains(jQuery(this.parentNode).get(0),target)
  ){
   jQuery(this.parentNode).html('').css({'display':'none'});
   }
  });
 });
/*#########################################################################################*/
//INITIATE CALENDAR
function initCalendar(trigger,input){
 if(typeof(input)=='string'){ input = document.getElementById(input); }
 else if(typeof(input)=='undefined'){ input = jQuery(trigger).before('<input type="hidden" />').prev().get(0); };
 
 id = unique_id(); trigger.id = 'btn_'+id; input.id = 'val_'+id;
 
 var n = document.createElement('div');
 jQuery(trigger).before(n).get(0).onclick = function(event){ refreshCalendar(this.id.substring(4)); };
 jQuery(n).addClass('calendar-placeholder').attr('id','cal_'+id).bind('click',function(event){ return false; });
 
 refreshCalendar(id);
 }

/*#########################################################################################*/
//SET DATE FUNCTION
function dateSelect(d,id){
 d = parseDate(d);
 m = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'][d[1]-1];
 c = jQuery('#cal_'+id).css({'display':'none'});
 c.next().find('.calmonth').html(m);
 c.next().find('.calday').html(d[2]);
 c.next().find('.calyear').html(d[0]);
 jQuery('#val_'+id).val( (is_array(d) ? d.join('-') : d ) );
 }

/*#########################################################################################*/
//SELECT MONTH NEW CALENDAR
function refreshCalendar(id,d){
 
 if(typeof(d)=='undefined') d = jQuery('#val_'+id).val();
 if(typeof(d)=='string') d = parseDate(d);
 
 if(is_array(d)){
  y = parseInt(d[0]); m = parseInt(d[1]);
  if(m<1){m=12;y--;}else if(m>12){m=1;y++;}
  day=(typeof(d[2])=='undefined'?1:parseInt(d[2]));
  d = [y,m,day];
  }
 
 var cal = new Calendar(d,id);
 
 jQuery('#cal_'+id).html(cal.html).css({'display':'block'})
 .find('.calendar-day a')
 .bind('click',function(event){
  dateSelect(
  jQuery('#'+this.name+' .calendar-year').val()+'-'+jQuery('#'+this.name+' .calendar-month').val()+'-'+jQuery('span',this).html()
  ,this.name);
  });
 
 }

/*#########################################################################################*/
//DEFINE CALENDAR OBJECT
Calendar = function(date,id){//
 
 this.id = id;
 
 var today = new Date();
 
 if(typeof(date)=='undefined') date = [today.getFullYear(),today.getMonth()+1,today.getDate()];
 this.year = date[0]; this.month = date[1]; this.day = date[2];
 
 var days_mapped = [6,0,1,2,3,4,5];
 var days_labels = ['MON','TUE','WED','THU','FRI','SAT','SUN'];
 var months_labels = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
 
	var firstDay = new Date(this.year, this.month-1, 1);
	var startingDay = days_mapped[firstDay.getDay()];
	var monthLength = daysInMonth(this.month,this.year);

 var Mselect = '';
 for(var m=1;m<=12;m++){ var sel = (m==this.month) ? ' selected' : '' ; Mselect += '<option value="'+m+'"'+sel+'>'+months_labels[m-1]+'</option>'; }
 var Yselect = '';
 for(var y=this.year-6;y<this.year+6;y++){ var sel = (y==this.year) ? ' selected' : '' ; Yselect += '<option value="'+y+'"'+sel+'>'+y+'</option>'; }

//START WRITING CALENDAR HTML
var html = ''
+'<div class="calendar" id="'+this.id+'">'
+'<table class="calendar-table">'
+'<tr>'

+'<td class="calendar-prev-month" style="cursor:pointer;cursor:hand;" onclick="refreshCalendar('+'\''+this.id+'\''+',['+this.year+','+(this.month-1)+']);">&lt;&lt;</td>'
+'<td colspan="5">'
+'<select class="calendar-month" onchange="refreshCalendar('+'\''+this.id+'\''+',nextSib(this).value+\'-\'+this.value)">'+Mselect+'</select>'
+'<select class="calendar-year" onchange="refreshCalendar('+'\''+this.id+'\''+',this.value+\'-\'+prevSib(this).value)">'+Yselect+'</select>'
+'</td>'
+'<td class="calendar-next-month" style="cursor:pointer;cursor:hand;" onclick="refreshCalendar('+'\''+this.id+'\''+',['+this.year+','+(this.month+1)+']);">&gt;&gt;</td>'

+'</tr>'

+'<tr class="calendar-header">';

//FILL IN WEEDAY LABELS
for(var i=0;i<=6;i++){ html += '<th>'+ days_labels[i]+ '</th>'; }
html += '</tr><tr>';

//FILL IN DAYS
var n = daysInMonth(this.month-1,this.year)-days_mapped[firstDay.getDay()]+1;
var day = 1;

//LOOP FOR WEEKS/ROWS
for(var i=0;i<6;i++){
//LOOP FOR WEEK DAYS/CELLS
 for(var j=0;j<=6;j++){
  html += '<td class="calendar-day';
  if(day<=monthLength && (i>0 || j>=startingDay)){
   n = 1;
   if((f=parseDate(jQuery('#val_'+this.id).val())) && f[2]==day && f[1]==this.month && f[0]==this.year)html+=' calendar-day-selected';
   if(day==today.getDate() && this.month==today.getMonth()+1 && this.year==today.getFullYear())html+=' calendar-day-today';
html+='"><a href="javascript:;" class="btn-default-med" name="'+this.id+'">'
+' <span>'+ day + '</span></a>';
   day++;
   }
  else{
   html += ' calendar-day-disabled"><div class="btn-default-med"><span>'+n+'</span></div>';
   n++;
   }
  html += '</td>';
  }

//STOP MAKING ROWS IF RUN OUT OF DAYS
 if(day>monthLength){ break; }
 else {
  html += '</tr><tr>';
  }
 }
html += '</tr></table>'
+'</div>'
;
 
 this.html = html;
 
 }

function Calendar4(event){ Calendar3(event); return false; }
function Calendar3_2(event){
 event.data.date = parseDate2(event.data.i.val());
 Calendar3(event);
 return false;
 }
function Calendar3(event){
  
 var undefined;
 var today = new Date();
 
 var i = event.data.c.data('input') || event.data.i;
 var f = (i&&parseDate(i.val())?parseDate(i.val()):undefined);
 
 var date = event.data.date || event.data.c.data('last_date') || f;
 if(date==undefined) date = [today.getFullYear(),today.getMonth()+1,today.getDate()];
 
 y = parseInt(date[0]); m = parseInt(date[1]);
 if(m<1){m=12;y--;}else if(m>12){m=1;y++;}
 d = (typeof(date[2])=='undefined'?1:parseInt(date[2]));
 date = [y,m,d]; 
 
 event.data.c.data('last_date',date);
 event.data.c.data('input',i);
 
 year = date[0]; month = date[1]; day = date[2];
 
 var days_mapped = [6,0,1,2,3,4,5];
 var days_labels = ['MON','TUE','WED','THU','FRI','SAT','SUN'];
 var months_labels = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
 
	var firstDay = new Date(year, month-1,1);
	var startingDay = days_mapped[firstDay.getDay()];
	var monthLength = daysInMonth(month,year);

 var Mselect = ''; for(var m=1;m<=12;m++){ var sel = (m==month) ? ' selected' : '' ; Mselect += '<option value="'+m+'"'+sel+'>'+months_labels[m-1]+'</option>'; }
 var Yselect = ''; for(var y=year-10;y<=year+10;y++){ var sel = (y==year) ? ' selected' : '' ; Yselect += '<option value="'+y+'"'+sel+'>'+y+'</option>'; }

//START WRITING CALENDAR HTML
var html = ''
+'<div class="calendar">'
+'<table class="calendar-table">'

+'<tr>'
+'<td colspan="7">'
+'<table style="width:100%;">'
+'<tr class="cols6">'

+'<td class="calendar-prev-month" style="cursor:pointer;cursor:hand;">&lt;&lt;</td>'
+'<td>'
+'<select class="calendar-month" style="width:50px">'+Mselect+'</select>'
+'</td>'
+'<td class="calendar-next-month" style="cursor:pointer;cursor:hand;">&gt;&gt;</td>'

+'<td class="calendar-prev-year" style="cursor:pointer;cursor:hand;">&lt;&lt;</td>'
+'<td>'
+'<select class="calendar-year" style="width:50px">'+Yselect+'</select>'
+'</td>'
+'<td class="calendar-next-year" style="cursor:pointer;cursor:hand;">&gt;&gt;</td>'

+'</tr>'
+'</table>'

+'</td>'
+'</tr>'

+'<tr class="calendar-header">';

//FILL IN WEEDAY LABELS
for(var i=0;i<=6;i++){ html += '<th>'+ days_labels[i]+ '</th>'; }
html += '</tr><tr>';

//FILL IN DAYS
var n = daysInMonth(month-1,year)-days_mapped[firstDay.getDay()]+1;
var day = 1;

//LOOP FOR WEEKS/ROWS
for(var i=0;i<6;i++){
//LOOP FOR WEEK DAYS/CELLS
 for(var j=0;j<=6;j++){
  html += '<td class="calendar-day';
  if(day<=monthLength && (i>0 || j>=startingDay)){
   n = 1;
   if(typeof(f)!='undefined' && is_array(f) && f[2]==day && f[1]==month && f[0]==year)html+=' calendar-day-selected';
   if(day==today.getDate() && month==today.getMonth()+1 && year==today.getFullYear())html+=' calendar-day-today';
html+='"><a href="javascript:;">'
+' <span>'+ day + '</span></a>';
   day++;
   }
  else{
   html += ' calendar-day-disabled"><div><span>'+n+'</span></div>';
   n++;
   }
  html += '</td>';
  }

//STOP MAKING ROWS IF RUN OUT OF DAYS
 if(day>monthLength){ break; }
 else {
  html += '</tr><tr>';
  }
 }
html += '</tr></table>'
+'</div>'
;

c = event.data.c
c.html(html)
.css({'display':'block'}).find('.calendar-day a').bind('click',{'date':[year,month]},event.data.fn)
;

jQuery('.calendar-prev-month',c.get(0)).eq(0).bind('click',{'c':c,'fn':event.data.fn,'date':[year,month-1]},Calendar4);
jQuery('.calendar-next-month',c.get(0)).eq(0).bind('click',{'c':c,'fn':event.data.fn,'date':[year,month+1]},Calendar4);

jQuery('.calendar-prev-year',c.get(0)).eq(0).bind('click',{'c':c,'fn':event.data.fn,'date':[year-1,month]},Calendar4);
jQuery('.calendar-next-year',c.get(0)).eq(0).bind('click',{'c':c,'fn':event.data.fn,'date':[year+1,month]},Calendar4);

jQuery('select.calendar-month',c.get(0)).eq(0).bind('change',{'c':c,'fn':event.data.fn,'year':year},function(event){ event.data.date = [event.data.year,jQuery(this).val()]; Calendar3(event); });
jQuery('select.calendar-year',c.get(0)).eq(0).bind('change',{'c':c,'fn':event.data.fn,'month':month},function(event){ event.data.date = [jQuery(this).val(),event.data.month]; Calendar3(event); });

//return false;

 }

