Basis of rails-driven app for local business
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

442 lines
21 KiB

  1. // CalendarDateSelect version 1.15 - a prototype based date picker
  2. // Questions, comments, bugs? - see the project page: http://code.google.com/p/calendardateselect
  3. if (typeof Prototype == 'undefined') alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (.g. <%= javascript_include_tag :defaults %>) *before* it includes calendar_date_select.js (.g. <%= calendar_date_select_includes %>).");
  4. if (Prototype.Version < "1.6") alert("Prototype 1.6.0 is required. If using earlier version of prototype, please use calendar_date_select version 1.8.3");
  5. Element.addMethods({
  6. purgeChildren: function(element) { $A(element.childNodes).each(function(e){$(e).remove();}); },
  7. build: function(element, type, options, style) {
  8. var newElement = Element.buildAndAppend(type, options, style);
  9. element.appendChild(newElement);
  10. return newElement;
  11. }
  12. });
  13. Element.buildAndAppend = function(type, options, style)
  14. {
  15. var e = $(document.createElement(type));
  16. $H(options).each(function(pair) { e[pair.key] = pair.value });
  17. if (style) e.setStyle(style);
  18. return e;
  19. };
  20. nil = null;
  21. Date.one_day = 24*60*60*1000;
  22. Date.weekdays = $w("S M T W T F S");
  23. Date.first_day_of_week = 0;
  24. Date.months = $w("January February March April May June July August September October November December" );
  25. Date.padded2 = function(hour) { var padded2 = parseInt(hour, 10); if (hour < 10) padded2 = "0" + padded2; return padded2; }
  26. Date.prototype.getPaddedMinutes = function() { return Date.padded2(this.getMinutes()); }
  27. Date.prototype.getAMPMHour = function() { var hour = this.getHours(); return (hour == 0) ? 12 : (hour > 12 ? hour - 12 : hour ) }
  28. Date.prototype.getAMPM = function() { return (this.getHours() < 12) ? "AM" : "PM"; }
  29. Date.prototype.stripTime = function() { return new Date(this.getFullYear(), this.getMonth(), this.getDate());};
  30. Date.prototype.daysDistance = function(compare_date) { return Math.round((compare_date - this) / Date.one_day); };
  31. Date.prototype.toFormattedString = function(include_time){
  32. var hour, str;
  33. str = Date.months[this.getMonth()] + " " + this.getDate() + ", " + this.getFullYear();
  34. if (include_time) { hour = this.getHours(); str += " " + this.getAMPMHour() + ":" + this.getPaddedMinutes() + " " + this.getAMPM() }
  35. return str;
  36. }
  37. Date.parseFormattedString = function(string) { return new Date(string);}
  38. Math.floor_to_interval = function(n, i) { return Math.floor(n/i) * i;}
  39. window.f_height = function() { return( [window.innerHeight ? window.innerHeight : null, document.documentElement ? document.documentElement.clientHeight : null, document.body ? document.body.clientHeight : null].select(function(x){return x>0}).first()||0); }
  40. window.f_scrollTop = function() { return ([window.pageYOffset ? window.pageYOffset : null, document.documentElement ? document.documentElement.scrollTop : null, document.body ? document.body.scrollTop : null].select(function(x){return x>0}).first()||0 ); }
  41. _translations = {
  42. "OK": "OK",
  43. "Now": "Now",
  44. "Today": "Today",
  45. "Clear": "Clear"
  46. }
  47. SelectBox = Class.create();
  48. SelectBox.prototype = {
  49. initialize: function(parent_element, values, html_options, style_options) {
  50. this.element = $(parent_element).build("select", html_options, style_options);
  51. this.populate(values);
  52. },
  53. populate: function(values) {
  54. this.element.purgeChildren();
  55. var that = this; $A(values).each(function(pair) { if (typeof(pair)!="object") {pair = [pair, pair]}; that.element.build("option", { value: pair[1], innerHTML: pair[0]}) });
  56. },
  57. setValue: function(value) {
  58. var e = this.element;
  59. var matched = false;
  60. $R(0, e.options.length - 1 ).each(function(i) { if(e.options[i].value==value.toString()) {e.selectedIndex = i; matched = true;}; } );
  61. return matched;
  62. },
  63. getValue: function() { return $F(this.element)}
  64. }
  65. CalendarDateSelect = Class.create();
  66. CalendarDateSelect.prototype = {
  67. initialize: function(target_element, options) {
  68. this.target_element = $(target_element); // make sure it's an element, not a string
  69. if (!this.target_element) { alert("Target element " + target_element + " not found!"); return false;}
  70. if (this.target_element.tagName != "INPUT") this.target_element = this.target_element.down("INPUT")
  71. this.target_element.calendar_date_select = this;
  72. this.last_click_at = 0;
  73. // initialize the date control
  74. this.options = $H({
  75. embedded: false,
  76. popup: nil,
  77. time: false,
  78. buttons: true,
  79. clear_button: true,
  80. year_range: 10,
  81. close_on_click: nil,
  82. minute_interval: 5,
  83. popup_by: this.target_element,
  84. month_year: "dropdowns",
  85. onchange: this.target_element.onchange,
  86. valid_date_check: nil
  87. }).merge(options || {});
  88. this.use_time = this.options.get("time");
  89. this.parseDate();
  90. this.callback("before_show")
  91. this.initCalendarDiv();
  92. if(!this.options.get("embedded")) {
  93. this.positionCalendarDiv()
  94. // set the click handler to check if a user has clicked away from the document
  95. Event.observe(document, "mousedown", this.closeIfClickedOut_handler = this.closeIfClickedOut.bindAsEventListener(this));
  96. Event.observe(document, "keypress", this.keyPress_handler = this.keyPress.bindAsEventListener(this));
  97. }
  98. this.callback("after_show")
  99. },
  100. positionCalendarDiv: function() {
  101. var above = false;
  102. var c_pos = this.calendar_div.cumulativeOffset(), c_left = c_pos[0], c_top = c_pos[1], c_dim = this.calendar_div.getDimensions(), c_height = c_dim.height, c_width = c_dim.width;
  103. var w_top = window.f_scrollTop(), w_height = window.f_height();
  104. var e_dim = $(this.options.get("popup_by")).cumulativeOffset(), e_top = e_dim[1], e_left = e_dim[0], e_height = $(this.options.get("popup_by")).getDimensions().height, e_bottom = e_top + e_height;
  105. if ( (( e_bottom + c_height ) > (w_top + w_height)) && ( e_bottom - c_height > w_top )) above = true;
  106. var left_px = e_left.toString() + "px", top_px = (above ? (e_top - c_height ) : ( e_top + e_height )).toString() + "px";
  107. this.calendar_div.style.left = left_px; this.calendar_div.style.top = top_px;
  108. this.calendar_div.setStyle({visibility:""});
  109. // draw an iframe behind the calendar -- ugly hack to make IE 6 happy
  110. if(navigator.appName=="Microsoft Internet Explorer") this.iframe = $(document.body).build("iframe", {src: "javascript:false", className: "ie6_blocker"}, { left: left_px, top: top_px, height: c_height.toString()+"px", width: c_width.toString()+"px", border: "0px"})
  111. },
  112. initCalendarDiv: function() {
  113. if (this.options.get("embedded")) {
  114. var parent = this.target_element.parentNode;
  115. var style = {}
  116. } else {
  117. var parent = document.body
  118. var style = { position:"absolute", visibility: "hidden", left:0, top:0 }
  119. }
  120. this.calendar_div = $(parent).build('div', {className: "calendar_date_select"}, style);
  121. var that = this;
  122. // create the divs
  123. $w("top header body buttons footer bottom").each(function(name) {
  124. eval("var " + name + "_div = that." + name + "_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ");
  125. });
  126. this.initHeaderDiv();
  127. this.initButtonsDiv();
  128. this.initCalendarGrid();
  129. this.updateFooter("&#160;");
  130. this.refresh();
  131. this.setUseTime(this.use_time);
  132. },
  133. initHeaderDiv: function() {
  134. var header_div = this.header_div;
  135. this.close_button = header_div.build("a", { innerHTML: "x", href:"#", onclick:function () { this.close(); return false; }.bindAsEventListener(this), className: "close" });
  136. this.next_month_button = header_div.build("a", { innerHTML: "&gt;", href:"#", onclick:function () { this.navMonth(this.date.getMonth() + 1 ); return false; }.bindAsEventListener(this), className: "next" });
  137. this.prev_month_button = header_div.build("a", { innerHTML: "&lt;", href:"#", onclick:function () { this.navMonth(this.date.getMonth() - 1 ); return false; }.bindAsEventListener(this), className: "prev" });
  138. if (this.options.get("month_year")=="dropdowns") {
  139. this.month_select = new SelectBox(header_div, $R(0,11).map(function(m){return [Date.months[m], m]}), {className: "month", onchange: function () { this.navMonth(this.month_select.getValue()) }.bindAsEventListener(this)});
  140. this.year_select = new SelectBox(header_div, [], {className: "year", onchange: function () { this.navYear(this.year_select.getValue()) }.bindAsEventListener(this)});
  141. this.populateYearRange();
  142. } else {
  143. this.month_year_label = header_div.build("span")
  144. }
  145. },
  146. initCalendarGrid: function() {
  147. var body_div = this.body_div;
  148. this.calendar_day_grid = [];
  149. var days_table = body_div.build("table", { cellPadding: "0px", cellSpacing: "0px", width: "100%" })
  150. // make the weekdays!
  151. var weekdays_row = days_table.build("thead").build("tr");
  152. Date.weekdays.each( function(weekday) {
  153. weekdays_row.build("th", {innerHTML: weekday});
  154. });
  155. var days_tbody = days_table.build("tbody")
  156. // Make the days!
  157. var row_number = 0, weekday;
  158. for(var cell_index = 0; cell_index<42; cell_index++)
  159. {
  160. weekday = (cell_index+Date.first_day_of_week ) % 7;
  161. if ( cell_index % 7==0 ) days_row = days_tbody.build("tr", {className: 'row_'+row_number++});
  162. (this.calendar_day_grid[cell_index] = days_row.build("td", {
  163. calendar_date_select: this,
  164. onmouseover: function () { this.calendar_date_select.dayHover(this); },
  165. onmouseout: function () { this.calendar_date_select.dayHoverOut(this) },
  166. onclick: function() { this.calendar_date_select.updateSelectedDate(this, true); },
  167. className: (weekday==0) || (weekday==6) ? " weekend" : "" //clear the class
  168. },
  169. { cursor: "pointer" }
  170. )).build("div");
  171. this.calendar_day_grid[cell_index];
  172. }
  173. },
  174. initButtonsDiv: function()
  175. {
  176. var buttons_div = this.buttons_div;
  177. if (this.options.get("time"))
  178. {
  179. var blank_time = $A(this.options.get("time")=="mixed" ? [[" - ", ""]] : []);
  180. buttons_div.build("span", {innerHTML:"@", className: "at_sign"});
  181. var t = new Date();
  182. this.hour_select = new SelectBox(buttons_div,
  183. blank_time.concat($R(0,23).map(function(x) {t.setHours(x); return $A([t.getAMPMHour()+ " " + t.getAMPM(),x])} )),
  184. {
  185. calendar_date_select: this,
  186. onchange: function() { this.calendar_date_select.updateSelectedDate( { hour: this.value });},
  187. className: "hour"
  188. }
  189. );
  190. buttons_div.build("span", {innerHTML:":", className: "seperator"});
  191. var that = this;
  192. this.minute_select = new SelectBox(buttons_div,
  193. blank_time.concat($R(0,59).select(function(x){return (x % that.options.get('minute_interval')==0)}).map(function(x){ return $A([ Date.padded2(x), x]); } ) ),
  194. {
  195. calendar_date_select: this,
  196. onchange: function() { this.calendar_date_select.updateSelectedDate( {minute: this.value }) },
  197. className: "minute"
  198. }
  199. );
  200. } else if (! this.options.get("buttons")) buttons_div.remove();
  201. if (this.options.get("buttons")) {
  202. buttons_div.build("span", {innerHTML: "&#160;"});
  203. if (this.options.get("time")=="mixed" || !this.options.get("time")) b = buttons_div.build("a", {
  204. innerHTML: _translations["Today"],
  205. href: "#",
  206. onclick: function() {this.today(false); return false;}.bindAsEventListener(this)
  207. });
  208. if (this.options.get("time")=="mixed") buttons_div.build("span", {innerHTML: "&#160;|&#160;", className:"button_seperator"})
  209. if (this.options.get("time")) b = buttons_div.build("a", {
  210. innerHTML: _translations["Now"],
  211. href: "#",
  212. onclick: function() {this.today(true); return false}.bindAsEventListener(this)
  213. });
  214. if (!this.options.get("embedded") && !this.closeOnClick())
  215. {
  216. buttons_div.build("span", {innerHTML: "&#160;|&#160;", className:"button_seperator"})
  217. buttons_div.build("a", { innerHTML: _translations["OK"], href: "#", onclick: function() {this.close(); return false;}.bindAsEventListener(this) });
  218. }
  219. if (this.options.get('clear_button')) {
  220. buttons_div.build("span", {innerHTML: "&#160;|&#160;", className:"button_seperator"})
  221. buttons_div.build("a", { innerHTML: _translations["Clear"], href: "#", onclick: function() {this.clearDate(); if (!this.options.get("embedded")) this.close(); return false;}.bindAsEventListener(this) });
  222. }
  223. }
  224. },
  225. refresh: function ()
  226. {
  227. this.refreshMonthYear();
  228. this.refreshCalendarGrid();
  229. this.setSelectedClass();
  230. this.updateFooter();
  231. },
  232. refreshCalendarGrid: function () {
  233. this.beginning_date = new Date(this.date).stripTime();
  234. this.beginning_date.setDate(1);
  235. this.beginning_date.setHours(12); // Prevent daylight savings time boundaries from showing a duplicate day
  236. var pre_days = this.beginning_date.getDay() // draw some days before the fact
  237. if (pre_days < 3) pre_days += 7;
  238. this.beginning_date.setDate(1 - pre_days + Date.first_day_of_week);
  239. var iterator = new Date(this.beginning_date);
  240. var today = new Date().stripTime();
  241. var this_month = this.date.getMonth();
  242. vdc = this.options.get("valid_date_check");
  243. for (var cell_index = 0;cell_index<42; cell_index++)
  244. {
  245. day = iterator.getDate(); month = iterator.getMonth();
  246. cell = this.calendar_day_grid[cell_index];
  247. Element.remove(cell.childNodes[0]); div = cell.build("div", {innerHTML:day});
  248. if (month!=this_month) div.className = "other";
  249. cell.day = day; cell.month = month; cell.year = iterator.getFullYear();
  250. if (vdc) { if (vdc(iterator.stripTime())) cell.removeClassName("disabled"); else cell.addClassName("disabled") };
  251. iterator.setDate( day + 1);
  252. }
  253. if (this.today_cell) this.today_cell.removeClassName("today");
  254. if ( $R( 0, 41 ).include(days_until = this.beginning_date.stripTime().daysDistance(today)) ) {
  255. this.today_cell = this.calendar_day_grid[days_until];
  256. this.today_cell.addClassName("today");
  257. }
  258. },
  259. refreshMonthYear: function() {
  260. var m = this.date.getMonth();
  261. var y = this.date.getFullYear();
  262. // set the month
  263. if (this.options.get("month_year") == "dropdowns")
  264. {
  265. this.month_select.setValue(m, false);
  266. var e = this.year_select.element;
  267. if (this.flexibleYearRange() && (!(this.year_select.setValue(y, false)) || e.selectedIndex <= 1 || e.selectedIndex >= e.options.length - 2 )) this.populateYearRange();
  268. this.year_select.setValue(y);
  269. } else {
  270. this.month_year_label.update( Date.months[m] + " " + y.toString() );
  271. }
  272. },
  273. populateYearRange: function() {
  274. this.year_select.populate(this.yearRange().toArray());
  275. },
  276. yearRange: function() {
  277. if (!this.flexibleYearRange())
  278. return $R(this.options.get("year_range")[0], this.options.get("year_range")[1]);
  279. var y = this.date.getFullYear();
  280. return $R(y - this.options.get("year_range"), y + this.options.get("year_range"));
  281. },
  282. flexibleYearRange: function() { return (typeof(this.options.get("year_range")) == "number"); },
  283. validYear: function(year) { if (this.flexibleYearRange()) { return true;} else { return this.yearRange().include(year);} },
  284. dayHover: function(element) {
  285. var hover_date = new Date(this.selected_date);
  286. hover_date.setYear(element.year); hover_date.setMonth(element.month); hover_date.setDate(element.day);
  287. this.updateFooter(hover_date.toFormattedString(this.use_time));
  288. },
  289. dayHoverOut: function(element) { this.updateFooter(); },
  290. clearSelectedClass: function() {if (this.selected_cell) this.selected_cell.removeClassName("selected");},
  291. setSelectedClass: function() {
  292. if (!this.selection_made) return;
  293. this.clearSelectedClass()
  294. if ($R(0,42).include( days_until = this.beginning_date.stripTime().daysDistance(this.selected_date.stripTime()) )) {
  295. this.selected_cell = this.calendar_day_grid[days_until];
  296. this.selected_cell.addClassName("selected");
  297. }
  298. },
  299. reparse: function() { this.parseDate(); this.refresh(); },
  300. dateString: function() {
  301. return (this.selection_made) ? this.selected_date.toFormattedString(this.use_time) : "&#160;";
  302. },
  303. parseDate: function()
  304. {
  305. var value = $F(this.target_element).strip()
  306. this.selection_made = (value != "");
  307. this.date = value=="" ? NaN : Date.parseFormattedString(this.options.get("date") || value);
  308. if (isNaN(this.date)) this.date = new Date();
  309. if (!this.validYear(this.date.getFullYear())) this.date.setYear( (this.date.getFullYear() < this.yearRange().start) ? this.yearRange().start : this.yearRange().end);
  310. this.selected_date = new Date(this.date);
  311. this.use_time = /[0-9]:[0-9]{2}/.exec(value) ? true : false;
  312. this.date.setDate(1);
  313. },
  314. updateFooter:function(text) { if (!text) text = this.dateString(); this.footer_div.purgeChildren(); this.footer_div.build("span", {innerHTML: text }); },
  315. clearDate:function() {
  316. if ((this.target_element.disabled || this.target_element.readOnly) && this.options.get("popup") != "force") return false;
  317. var last_value = this.target_element.value;
  318. this.target_element.value = "";
  319. this.clearSelectedClass();
  320. this.updateFooter('&#160;');
  321. if (last_value!=this.target_element.value) this.callback("onchange");
  322. },
  323. updateSelectedDate:function(partsOrElement, via_click) {
  324. var parts = $H(partsOrElement);
  325. if ((this.target_element.disabled || this.target_element.readOnly) && this.options.get("popup") != "force") return false;
  326. if (parts.get("day")) {
  327. var t_selected_date = this.selected_date, vdc = this.options.get("valid_date_check");
  328. for (var x = 0; x<=3; x++) t_selected_date.setDate(parts.get("day"));
  329. t_selected_date.setYear(parts.get("year"));
  330. t_selected_date.setMonth(parts.get("month"));
  331. if (vdc && ! vdc(t_selected_date.stripTime())) { return false; }
  332. this.selected_date = t_selected_date;
  333. this.selection_made = true;
  334. }
  335. if (!isNaN(parts.get("hour"))) this.selected_date.setHours(parts.get("hour"));
  336. if (!isNaN(parts.get("minute"))) this.selected_date.setMinutes( Math.floor_to_interval(parts.get("minute"), this.options.get("minute_interval")) );
  337. if (parts.get("hour") === "" || parts.get("minute") === "")
  338. this.setUseTime(false);
  339. else if (!isNaN(parts.get("hour")) || !isNaN(parts.get("minute")))
  340. this.setUseTime(true);
  341. this.updateFooter();
  342. this.setSelectedClass();
  343. if (this.selection_made) this.updateValue();
  344. if (this.closeOnClick()) { this.close(); }
  345. if (via_click && !this.options.get("embedded")) {
  346. if ((new Date() - this.last_click_at) < 333) this.close();
  347. this.last_click_at = new Date();
  348. }
  349. },
  350. closeOnClick: function() {
  351. if (this.options.get("embedded")) return false;
  352. if (this.options.get("close_on_click")===nil )
  353. return (this.options.get("time")) ? false : true
  354. else
  355. return (this.options.get("close_on_click"))
  356. },
  357. navMonth: function(month) { (target_date = new Date(this.date)).setMonth(month); return (this.navTo(target_date)); },
  358. navYear: function(year) { (target_date = new Date(this.date)).setYear(year); return (this.navTo(target_date)); },
  359. navTo: function(date) {
  360. if (!this.validYear(date.getFullYear())) return false;
  361. this.date = date;
  362. this.date.setDate(1);
  363. this.refresh();
  364. this.callback("after_navigate", this.date);
  365. return true;
  366. },
  367. setUseTime: function(turn_on) {
  368. this.use_time = this.options.get("time") && (this.options.get("time")=="mixed" ? turn_on : true) // force use_time to true if time==true && time!="mixed"
  369. if (this.use_time && this.selected_date) { // only set hour/minute if a date is already selected
  370. var minute = Math.floor_to_interval(this.selected_date.getMinutes(), this.options.get("minute_interval"));
  371. var hour = this.selected_date.getHours();
  372. this.hour_select.setValue(hour);
  373. this.minute_select.setValue(minute)
  374. } else if (this.options.get("time")=="mixed") {
  375. this.hour_select.setValue(""); this.minute_select.setValue("");
  376. }
  377. },
  378. updateValue: function() {
  379. var last_value = this.target_element.value;
  380. this.target_element.value = this.dateString();
  381. if (last_value!=this.target_element.value) this.callback("onchange");
  382. },
  383. today: function(now) {
  384. var d = new Date(); this.date = new Date();
  385. var o = $H({ day: d.getDate(), month: d.getMonth(), year: d.getFullYear(), hour: d.getHours(), minute: d.getMinutes()});
  386. if ( ! now ) o = o.merge({hour: "", minute:""});
  387. this.updateSelectedDate(o, true);
  388. this.refresh();
  389. },
  390. close: function() {
  391. if (this.closed) return false;
  392. this.callback("before_close");
  393. this.target_element.calendar_date_select = nil;
  394. Event.stopObserving(document, "mousedown", this.closeIfClickedOut_handler);
  395. Event.stopObserving(document, "keypress", this.keyPress_handler);
  396. this.calendar_div.remove(); this.closed = true;
  397. if (this.iframe) this.iframe.remove();
  398. if (this.target_element.type != "hidden" && ! this.target_element.disabled) this.target_element.focus();
  399. this.callback("after_close");
  400. },
  401. closeIfClickedOut: function(e) {
  402. if (! $(Event.element(e)).descendantOf(this.calendar_div) ) this.close();
  403. },
  404. keyPress: function(e) {
  405. if (e.keyCode==Event.KEY_ESC) this.close();
  406. },
  407. callback: function(name, param) { if (this.options.get(name)) { this.options.get(name).bind(this.target_element)(param); } }
  408. }