Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Mon, Feb 10, 8:03 PM

in-portal

Index: branches/RC/core/admin_templates/js/script.js
===================================================================
--- branches/RC/core/admin_templates/js/script.js (revision 11931)
+++ branches/RC/core/admin_templates/js/script.js (revision 11932)
@@ -1,1759 +1,1759 @@
if ( !( isset($init_made) && $init_made ) ) {
var Application = new kApplication();
var Grids = new Array();
var GridScrollers = new Array ();
var Toolbars = new Array();
var $Menus = new Array();
var $ViewMenus = new Array();
var $nls_menus = new Array();
var $MenuNames = new Array();
var $form_name = 'kernel_form';
if(!$fw_menus) var $fw_menus = new Array();
var $env = '';
var submitted = false;
var unload_legal = false;
var $edit_mode = false;
var $init_made = true; // in case of double inclusion of script.js :)
// hook processing
var hBEFORE = 1; // this is const, but including this twice causes errors
var hAFTER = 2; // this is const, but including this twice causes errors
replaceFireBug();
}
function use_popups($prefix_special, $event) {
return $use_popups;
}
function getArrayValue()
{
var $value = arguments[0];
var $current_key = 0;
$i = 1;
while ($i < arguments.length) {
$current_key = arguments[$i];
if (isset($value[$current_key])) {
$value = $value[$current_key];
}
else {
return false;
}
$i++;
}
return $value;
}
function setArrayValue()
{
// first argument - array, other arguments - keys (arrays too), last argument - value
var $array = arguments[0];
var $current_key = 0;
$i = 1;
while ($i < arguments.length - 1) {
$current_key = arguments[$i];
if (!isset($array[$current_key])) {
$array[$current_key] = new Array();
}
$array = $array[$current_key];
$i++;
}
$array[$array.length] = arguments[arguments.length - 1];
}
function resort_grid($prefix_special, $field, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_Sort1', $field);
submit_event($prefix_special, 'OnSetSorting', null, null, $ajax);
}
function direct_sort_grid($prefix_special, $field, $direction, $field_pos, $ajax)
{
if(!isset($field_pos)) $field_pos = 1;
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special+'_Sort'+$field_pos,$field);
set_hidden_field($prefix_special+'_Sort'+$field_pos+'_Dir',$direction);
set_hidden_field($prefix_special+'_SortPos',$field_pos);
submit_event($prefix_special,'OnSetSortingDirect', null, null, $ajax);
}
function reset_sorting($prefix_special, $ajax)
{
submit_event($prefix_special,'OnResetSorting', null, null, $ajax);
}
function set_per_page($prefix_special, $per_page, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_PerPage', $per_page);
submit_event($prefix_special, 'OnSetPerPage', null, null, $ajax);
}
function set_refresh_interval($prefix_special, $refresh_interval, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('refresh_interval', $refresh_interval);
submit_event($prefix_special, 'OnSetAutoRefreshInterval', null, null, $ajax);
}
function submit_event(prefix_special, event, t, form_action, $ajax)
{
if (!Application.processHooks(prefix_special + ':' + event)) {
return false;
}
if ($ajax) {
return $Catalog.submit_event(prefix_special, event, t);
}
if (event) {
set_hidden_field('events[' + prefix_special + ']', event);
}
if (t) set_hidden_field('t', t);
if (form_action) {
var old_env = '';
if (!form_action.match(/\?/)) {
document.getElementById($form_name).action.match(/.*(\?.*)/);
old_env = RegExp.$1;
}
document.getElementById($form_name).action = form_action + old_env;
}
submit_kernel_form();
// reset remove special mark (otherwise all future events will have special removed too)
set_hidden_field('remove_specials[' + prefix_special + ']', null);
}
function submit_action($url, $action)
{
$form = document.getElementById($form_name);
$form.action = $url;
set_hidden_field('Action', $action);
submit_kernel_form();
}
function show_form_data()
{
var $kf = document.getElementById($form_name);
$ret = '';
for(var i in $kf.elements)
{
$elem = $kf.elements[i];
$ret += $elem.id + ' = ' + $elem.value + "\n";
}
alert($ret);
}
function submit_kernel_form()
{
if (submitted) {
return;
}
submitted = true;
unload_legal = true; // bug: when opening new popup from this window, then this window is not refreshed and this mark stays forever
var $form = document.getElementById($form_name);
if (typeof $form.onsubmit == 'function') {
$form.onsubmit();
}
$form.submit();
$form.target = '';
set_hidden_field('t', t);
// window.setTimeout(function() {submitted = false}, 500);
}
function set_event(prefix_special, event)
{
var event_field=document.getElementById('events[' + prefix_special + ']');
if(isset(event_field))
{
event_field.value = event;
}
}
function isset(variable)
{
if(variable==null) return false;
return (typeof(variable)=='undefined')?false:true;
}
function in_array(needle, haystack)
{
return array_search(needle, haystack) != -1;
}
function array_search(needle, haystack)
{
for (var i=0; i<haystack.length; i++)
{
if (haystack[i] == needle) return i;
}
return -1;
}
function print_pre(variable, msg)
{
if (!isset(msg)) msg = '';
var s = msg;
for (prop in variable) {
s += prop+" => "+variable[prop] + "\n";
}
alert(s);
}
function go_to_page($prefix_special, $page, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_Page', $page);
submit_event($prefix_special, 'OnSetPage', null, null, $ajax);
}
function go_to_list(prefix_special, tab)
{
set_hidden_field(prefix_special+'_GoTab', tab);
submit_event(prefix_special,'OnUpdateAndGoToTab',null);
}
function go_to_tab(prefix_special, tab)
{
set_hidden_field(prefix_special+'_GoTab', tab);
submit_event(prefix_special,'OnPreSaveAndGoToTab',null);
}
function go_to_id(prefix_special, id)
{
set_hidden_field(prefix_special+'_GoId', id);
submit_event(prefix_special,'OnPreSaveAndGo')
}
// in-portal compatibility functions: begin
function getScriptURL($script_name, tpl)
{
tpl = tpl ? '-'+tpl : '';
var $asid = get_hidden_field('sid');
return base_url+$script_name+'?env='+( isset($env)&&$env?$env:$asid )+tpl+'&en=0';
}
function OpenEditor(extra_env,TargetForm,TargetField)
{
var $url = getScriptURL('admin/index.php', 'popups/editor');
$url = $url+'&TargetForm='+TargetForm+'&TargetField='+TargetField+'&destform=popup';
if(extra_env.length>0) $url += extra_env;
openwin($url,'html_edit',800,575);
}
// in-portal compatibility functions: end
function InitTranslator(prefix, field, t, multi_line, $before_callback)
{
var $window_name = 'select_' + t.replace(/(\/|-)/g, '_');
var $options = {
onAfterShow: function ($popup_window) {
if ($modal_windows) {
getFrame('main').initTranslatorOnAfterShow(prefix, field, t, multi_line, $before_callback);
}
else {
initTranslatorOnAfterShow(prefix, field, t, multi_line, $before_callback, $popup_window);
}
}
};
openwin('', $window_name, 750, 400, $options);
}
function initTranslatorOnAfterShow(prefix, field, t, multi_line, $before_callback, $popup_window) {
var $window_name = 'select_' + t.replace(/(\/|-)/g, '_');
$popup_window = onAfterWindowOpen($window_name, undefined, $popup_window);
if ($popup_window === false) {
// iframe onload happens on frame content change too -> don't react on it
return ;
}
var $opener = getWindowOpener($popup_window);
var $prev_opener = get_hidden_field('m_opener');
$opener.set_hidden_field('m_opener', 'p');
$opener.set_hidden_field('translator_wnd_name', $window_name);
$opener.set_hidden_field('translator_field', field);
$opener.set_hidden_field('translator_t', t);
$opener.set_hidden_field('translator_prefixes', prefix);
$opener.set_hidden_field('translator_multi_line', isset(multi_line) ? multi_line : 0);
if ($.isFunction($before_callback)) {
$before_callback($opener);
}
$opener.document.getElementById($opener.$form_name).target = $window_name;
var split_prefix = prefix.split(',');
$opener.submit_event(split_prefix[0], 'OnPreSaveAndOpenTranslator');
$opener.set_hidden_field('m_opener', $prev_opener);
$opener.submitted = false;
}
function PreSaveAndOpenTranslator(prefix, field, t, multi_line)
{
InitTranslator(prefix, field, t, multi_line);
}
function PreSaveAndOpenTranslatorCV(prefix, field, t, resource_id, multi_line)
{
InitTranslator(
prefix, field, t, multi_line,
function ($opener) {
$opener.set_hidden_field('translator_resource_id', resource_id);
}
);
}
function openTranslator(prefix,field,url,wnd)
{
var $kf = document.getElementById($form_name);
set_hidden_field('trans_prefix', prefix);
set_hidden_field('trans_field', field);
set_hidden_field('events[trans]', 'OnLoad');
var $regex = new RegExp('(.*)\?env=(' + document.getElementById('sid').value + ')?-(.*?):(.*)');
var $t = $regex.exec(url)[3];
$kf.target = wnd;
submit_event(prefix,'',$t,url);
submitted = false;
}
function openwin($url, $name, $width, $height, $options)
{
var $settings = {
url: base_url + 'core/admin_templates/blank.html?width=' + $width + '&height=' + $height + '&TB_iframe=true&modal=true',
caption: 'Loading ...',
onAfterShow: function ($popup_window) {
if ($modal_windows) {
getFrame('main').onAfterWindowOpen($name, $url);
}
else {
onAfterWindowOpen($name, $url, $popup_window);
}
}
};
if ($options !== undefined) {
$.extend($settings, $options);
}
if ($modal_windows) {
if (window.name != 'main') {
// all popups are opened based on main frame
return getFrame('main').TB.show($settings);
}
TB.show($settings);
return ;
}
// prevent window from opening larger, then screen resolution on user's computer (to Kostja)
var left = Math.round((screen.width - $width) / 2);
var top = Math.round((screen.height - $height) / 2);
var cur_x = document.all ? window.screenLeft : window.screenX;
var cur_y = document.all ? window.screenTop : window.screenY;
var $window_params = 'left='+left+',top='+top+',width='+$width+',height='+$height+',status=yes,resizable=yes,menubar=no,scrollbars=yes,toolbar=no';
var $popup_window = window.open($url, $name, $window_params);
if ( $.isFunction($settings.onAfterShow) ) {
$settings.onAfterShow($popup_window);
}
return $popup_window;
}
function onAfterWindowOpen($window_name, $url, $popup_window) {
// this is always invoked from "main" frame
if ($popup_window === undefined) {
var $popup_window = $('#' + TB.getId('TB_iframeContent')).get(0).contentWindow;
if (!$.isFunction($popup_window.onLoad)) {
// iframe onload happens on frame content change too -> don't react on it
return false;
}
$popup_window.onLoad();
}
$popup_window.name = $window_name;
if ($url !== undefined) {
$popup_window.location.href = $url;
}
if ($modal_windows) {
TB.setWindowMetaData('window_name', $window_name); // used to simulate window.opener functionality
}
return $popup_window;
}
function OnResizePopup(e) {
if (!document.all) {
var $winW = window.innerWidth;
var $winH = window.innerHeight;
}
else {
var $winW = window.document.body.offsetWidth;
var $winH = window.document.body.offsetHeight;
}
window.status = '[width: ' + $winW + '; height: ' + $winH + ']';
}
function opener_action(new_action)
{
var $prev_opener = get_hidden_field('m_opener');
set_hidden_field('m_opener', new_action);
return $prev_opener;
}
function open_popup($prefix_special, $event, $t, $window_size, $onAfterOpenPopup) {
if (!$window_size) {
// if no size given, then query it from ajax
var $default_size = '750x400';
var $pm = getFrame('head').$popup_manager;
if ($pm) {
// popup manager was found in head frame
$pm.ResponceFunction = function ($responce) {
if (!$responce.match(/([\d]+)x([\d]+)/)) {
// invalid responce was received, may be php fatal error during AJAX request
$responce = $default_size;
}
open_popup($prefix_special, $event, $t, $responce, $onAfterOpenPopup);
}
$pm.GetSize($t);
return ;
}
$window_size = $default_size;
}
$window_size = $window_size.split('x');
var $window_name = $t.replace(/(\/|-)/g, '_'); // replace "/" and "-" with "_"
var $options = {
onAfterShow: function ($popup_window) {
if ($modal_windows) {
getFrame('main').onAfterOpenPopup($prefix_special, $event, $t);
}
else {
onAfterOpenPopup($prefix_special, $event, $t, $popup_window);
}
if ($onAfterOpenPopup !== undefined && $.isFunction($onAfterOpenPopup)) {
$onAfterOpenPopup($popup_window);
}
}
};
openwin('', $window_name, $window_size[0], $window_size[1], $options);
}
function onAfterOpenPopup($prefix_special, $event, $t, $popup_window) {
// this is always invoked from "main" frame
var $window_name = $t.replace(/(\/|-)/g, '_'); // replace "/" and "-" with "_"
$popup_window = onAfterWindowOpen($window_name, undefined, $popup_window);
if ($popup_window === false) {
// iframe onload happens on frame content change too -> don't react on it
return ;
}
var $opener = getWindowOpener($popup_window);
if ($opener === null) {
// we are already in main window
$opener = window;
}
$opener.document.getElementById($opener.$form_name).target = $window_name;
var $prev_opener = $opener.opener_action('p');
event_bak = $opener.get_hidden_field('events[' + $prefix_special + ']')
if (!event_bak) {
event_bak = '';
}
$opener.submit_event($prefix_special, $event, $t);
$opener.opener_action($prev_opener); // restore opener in parent window
$opener.set_hidden_field('events[' + $prefix_special + ']', event_bak); // restore event
// AJAX popup size respoce is received after std_edit_item/std_precreate_item function exit
$opener.set_hidden_field($prefix_special + '_mode', null);
$opener.submitted = false;
$opener.Application.processHooks($prefix_special + ':OnAfterOpenPopup');
}
function openSelector($prefix, $url, $dst_field, $window_size, $event)
{
// get template name from url
var $regex = new RegExp('(.*)\?env=(' + document.getElementById('sid').value + ')?-(.*?):(m[^:]+)');
$regex = $regex.exec($url);
var $t = $regex[3];
// substitute form action with selector's url
var $kf = document.getElementById($form_name);
var $prev_action = $kf.action;
$kf.action = $url;
// check parameter values
if (!isset($event)) {
$event = '';
}
Application.processHooks($prefix + ':OnBeforeOpenSelector');
// set variables need for selector to work
set_hidden_field('main_prefix', $prefix);
set_hidden_field('dst_field', $dst_field);
// alert('openSelector(' + $prefix + ', ' + $event + ', ' + $t + ', ' + $window_size + ')');
open_popup(
$prefix, $event, $t, $window_size,
function() {
// restore form action back
$kf.action = $prev_action;
}
);
}
function translate_phrase($label, $template) {
set_hidden_field('phrases_label', $label);
open_popup('phrases', 'OnNew', $template);
}
function direct_edit($prefix_special, $url) {
if (use_popups($prefix_special, '')) {
openSelector($prefix_special, $url);
}
else {
redirect($url);
}
return false;
}
function std_precreate_item(prefix_special, edit_template, $onAfterOpenPopup)
{
set_hidden_field(prefix_special+'_mode', 't');
if (use_popups(prefix_special, 'OnPreCreate')) {
open_popup(prefix_special, 'OnPreCreate', edit_template, null, $onAfterOpenPopup);
}
else {
opener_action('d');
submit_event(prefix_special,'OnPreCreate', edit_template);
}
// set_hidden_field(prefix_special+'_mode', '');
}
function std_new_item(prefix_special, edit_template, $onAfterOpenPopup)
{
if (use_popups(prefix_special, 'OnNew')) {
open_popup(prefix_special, 'OnNew', edit_template, null, $onAfterOpenPopup);
}
else {
opener_action('d');
submit_event(prefix_special,'OnNew', edit_template);
}
}
function std_edit_item(prefix_special, edit_template, $onAfterOpenPopup)
{
set_hidden_field(prefix_special+'_mode', 't');
if (use_popups(prefix_special, 'OnEdit')) {
open_popup(prefix_special, 'OnEdit', edit_template, null, $onAfterOpenPopup);
}
else {
opener_action('d');
submit_event(prefix_special,'OnEdit',edit_template);
}
// set_hidden_field(prefix_special+'_mode', '');
}
function std_edit_temp_item(prefix_special, edit_template, $onAfterOpenPopup)
{
if (use_popups(prefix_special, '')) {
open_popup(prefix_special, '', edit_template, null, $onAfterOpenPopup);
}
else {
opener_action('d');
submit_event(prefix_special,'',edit_template);
}
}
function std_delete_items(prefix_special, t, $ajax)
{
var phrase = phrases['la_Delete_Confirm'] ? phrases['la_Delete_Confirm'] : 'Are you sure you want to delete selected items?';
if (inpConfirm(phrase)) {
submit_event(prefix_special, 'OnMassDelete', t, null, $ajax);
}
}
function std_csv_export(prefix_special, grid, template)
{
set_hidden_field('PrefixSpecial', prefix_special);
set_hidden_field('grid', grid);
open_popup(prefix_special, '', template);
}
function std_csv_import(prefix_special, grid, template)
{
set_hidden_field('PrefixSpecial', prefix_special);
set_hidden_field('grid', grid);
if (use_popups(prefix_special, '')) {
open_popup(prefix_special, '', template);
}
else {
submit_event(prefix_special, '', template);
}
}
// set current form base on ajax
function set_form($prefix_special, $ajax)
{
if ($ajax) {
$form_name = $Catalog.queryTabRegistry('prefix', $prefix_special, 'tab_id') + '_form';
}
}
// sets hidden field value
// if the field does not exist - creates it
function set_hidden_field($field_id, $value, $has_id)
{
var $kf = document.getElementById($form_name);
var $field = $kf.elements[$field_id];
if ($value === null) {
if ($field) {
// alert('tag name on remove: ' + $field.parentNode.tagName);
$field.parentNode.removeChild($field); // bug: sometimes hidden fields are inside BODY tag in DOM model, why?
}
return true;
}
if ($field) {
$field.value = $value;
return true;
}
$field = document.createElement('INPUT');
$field.type = 'hidden';
$field.name = $field_id;
if (!isset($has_id) || $has_id) {
$field.id = $field_id;
}
$field.value = $value;
$kf.appendChild($field);
return false;
}
// sets hidden field value
// if the field does not exist - creates it
function setInnerHTML($field_id, $value) {
$( jq('#' + $field_id) ).html($value);
}
function get_hidden_field($field)
{
var $kf = document.getElementById($form_name);
return $kf.elements[$field] ? $kf.elements[$field].value : false;
}
function search($prefix_special, $grid_name, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('grid_name', $grid_name);
submit_event($prefix_special, 'OnSearch', null, null, $ajax);
}
function search_reset($prefix_special, $grid_name, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('grid_name', $grid_name);
submit_event($prefix_special, 'OnSearchReset', null, null, $ajax);
}
function search_keydown($event, $prefix_special, $grid, $ajax)
{
if ($prefix_special !== undefined) {
// if $prefix_special is passed, then keydown event was not assigned by jQuery
$event = $event ? $event : event;
if (window.event) {// IE
var $key_code = $event.keyCode;
}
else if($event.which) { // Netscape/Firefox/Opera
var $key_code = $event.which;
}
}
else {
// event bind with jQuery, so always use which
var $key_code = $event.which;
$prefix_special = $(this).attr('PrefixSpecial');
$grid = $(this).attr('Grid');
$ajax = $(this).attr('ajax');
}
switch ($key_code) {
case 13:
search($prefix_special, $grid, parseInt($ajax));
break;
case 27:
search_reset($prefix_special, $grid, parseInt($ajax));
break;
}
}
function getRealLeft(el)
{
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
xPos = el.offsetLeft;
tempEl = el.offsetParent;
while (tempEl != null)
{
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
// if (obj.x) return obj.x;
return xPos;
}
function getRealTop(el)
{
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
yPos = el.offsetTop;
tempEl = el.offsetParent;
while (tempEl != null)
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
// if (obj.y) return obj.y;
return yPos;
}
function show_viewmenu_old($toolbar, $button_id)
{
var $img = $toolbar.GetButtonImage($button_id);
var $pos_x = getRealLeft($img) - ((document.all) ? 6 : -2);
var $pos_y = getRealTop($img) + 32;
var $prefix_special = '';
window.triedToWriteMenus = false;
if($ViewMenus.length == 1)
{
$prefix_special = $ViewMenus[$ViewMenus.length-1];
$fw_menus[$prefix_special+'_view_menu']();
$Menus[$prefix_special+'_view_menu'].writeMenus('MenuContainers['+$prefix_special+']');
window.FW_showMenu($Menus[$prefix_special+'_view_menu'], $pos_x, $pos_y);
}
else
{
// prepare menus
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
$fw_menus[$prefix_special+'_view_menu']();
}
$Menus['mixed'] = new Menu('ViewMenu_mixed');
// merge menus into new one
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
$Menus['mixed'].addMenuItem( $Menus[$prefix_special+'_view_menu'] );
}
$Menus['mixed'].writeMenus('MenuContainers[mixed]');
window.FW_showMenu($Menus['mixed'], $pos_x, $pos_y);
}
}
var nlsMenuRendered = false;
function show_viewmenu($toolbar, $button_id)
{
if($ViewMenus.length == 1) {
$prefix_special = $ViewMenus[$ViewMenus.length-1];
menu_to_show = $prefix_special+'_view_menu';
}
else
{
mixed_menu = menuMgr.createMenu(rs('mixed_menu'));
mixed_menu.applyBorder(false, false, false, false);
mixed_menu.dropShadow("none");
mixed_menu.showIcon = true;
// merge menus into new one
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
mixed_menu.addItem( rs($prefix_special+'.view.menu.mixed'),
$MenuNames[$prefix_special+'_view_menu'],
'javascript:void()', null, true, null,
rs($prefix_special+'.view.menu'),$MenuNames[$prefix_special+'_view_menu'] );
}
menu_to_show = 'mixed_menu';
}
renderMenus();
nls_showMenu(rs(menu_to_show), $toolbar.GetButtonImage($button_id))
}
function renderMenus()
{
menuMgr.renderMenus('nlsMenuPlace');
nlsMenuRendered = true;
}
function set_window_title($title)
{
var $window = window;
if ($window.name != 'main') {
// traverse through real popups
$window = getFrame('main');
}
$window.top.document.title = (main_title.length ? main_title + ' - ' : '') + $title;
if ($modal_windows) {
$window.TB.setWindowTitle($title);
}
}
function set_filter($prefix_special, $filter_id, $filter_value, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('filter_id', $filter_id);
set_hidden_field('filter_value', $filter_value);
submit_event($prefix_special, 'OnSetFilter', null, null, $ajax);
}
function filters_remove_all($prefix_special, $ajax)
{
set_form($prefix_special, $ajax);
submit_event($prefix_special,'OnRemoveFilters', null, null, $ajax);
}
function filters_apply_all($prefix_special, $ajax)
{
set_form($prefix_special, $ajax);
submit_event($prefix_special,'OnApplyFilters', null, null, $ajax);
}
function filter_toggle($row_id, $prefix) {
// var $row = $('#' + jq($row_id));
var $row = $('tr.to-range-filter');
var $hidden = $row.hasClass('hidden-filter');
if ($hidden) {
$('td', $row).show();
$row.removeClass('hidden-filter');
}
else {
$('td', $row).hide();
$row.addClass('hidden-filter');
}
// recalculate filter row heights/widths
var $grid = GridScrollers[$prefix];
$grid.UpdateColWidths();
if ($hidden && $grid.FiltersExpanded !== true) {
$grid.AdjustInputWidths();
$grid.FiltersExpanded = true;
}
// $grid.SetLeftHeights();
// $grid.UpdateTotalDimensions();
// $grid.SyncScroll();
// $grid.Resize( $grid.GetAutoSize() );
}
function RemoveTranslationLink($string, $escaped)
{
if (!isset($escaped)) $escaped = true;
if ($escaped) {
return $string.replace(/&lt;a href=&quot;(.*?)&quot;&gt;(.*?)&lt;\/a&gt;/g, '$2');
}
return $string.replace(/<a href="(.*?)">(.*?)<\/a>/g, '$2');
}
function redirect($url)
{
window.location.href = $url;
}
function update_checkbox_options($cb_mask, $hidden_id)
{
var $kf = document.getElementById($form_name);
var $tmp = '';
for (var i = 0; i < $kf.elements.length; i++)
{
if ( $kf.elements[i].id.match($cb_mask) )
{
if ($kf.elements[i].checked) $tmp += '|'+$kf.elements[i].value;
}
}
if($tmp.length > 0) $tmp += '|';
document.getElementById($hidden_id).value = $tmp.replace(/,$/, '');
}
function update_multiple_options($hidden_id) {
var $select = document.getElementById($hidden_id + '_select');
var $result = '';
for (var $i = 0; $i < $select.options.length; $i++) {
if ($select.options[$i].selected) {
$result += $select.options[$i].value + '|';
}
}
document.getElementById($hidden_id).value = $result ? '|' + $result : '';
}
// related to lists operations (moving)
function move_selected($from_list, $to_list, $error_msg)
{
if (typeof($from_list) != 'object') $from_list = document.getElementById($from_list);
if (typeof($to_list) != 'object') $to_list = document.getElementById($to_list);
if (has_selected_options($from_list))
{
var $from_array = select_to_array($from_list);
var $to_array = select_to_array($to_list);
var $new_from = Array();
var $cur = null;
for (var $i = 0; $i < $from_array.length; $i++)
{
$cur = $from_array[$i];
if ($cur[2]) // If selected - add to To array
{
$to_array[$to_array.length] = $cur;
}
else //Else - keep in new From
{
$new_from[$new_from.length] = $cur;
}
}
$from_list = array_to_select($new_from, $from_list);
$to_list = array_to_select($to_array, $to_list);
}
else
{
alert(isset($error_msg) ? $error_msg : 'Please select items to perform moving!');
}
}
function select_to_array($aSelect)
{
var $an_array = new Array();
var $cur = null;
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
$an_array[$an_array.length] = new Array($cur.text, $cur.value, $cur.selected);
}
return $an_array;
}
function array_to_select($anArray, $aSelect)
{
var $initial_length = $aSelect.length;
for (var $i = $initial_length - 1; $i >= 0; $i--)
{
$aSelect.options[$i] = null;
}
for (var $i = 0; $i < $anArray.length; $i++)
{
$cur = $anArray[$i];
$aSelect.options[$aSelect.length] = new Option($cur[0], $cur[1]);
}
}
function select_compare($a, $b)
{
if ($a[0] < $b[0])
return -1;
if ($a[0] > $b[0])
return 1;
return 0;
}
function select_to_string($aSelect)
{
var $result = '';
var $cur = null;
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
for (var $i = 0; $i < $aSelect.length; $i++)
{
$result += $aSelect.options[$i].value + '|';
}
return $result.length ? '|' + $result : '';
}
function selected_to_string($aSelect)
{
var $result = '';
var $cur = null;
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
if ($cur.selected && $cur.value != '')
{
$result += $cur.value + '|';
}
}
return $result.length ? '|' + $result : '';
}
function string_to_selected($str, $aSelect)
{
var $cur = null;
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
$aSelect.options[$i].selected = $str.match('\\|' + $cur.value + '\\|') ? true : false;
}
}
function set_selected($selected_options, $aSelect)
{
if (!$selected_options.length) return false;
for (var $i = 0; $i < $aSelect.length; $i++)
{
for (var $k = 0; $k < $selected_options.length; $k++)
{
if ($aSelect.options[$i].value == $selected_options[$k])
{
$aSelect.options[$i].selected = true;
}
}
}
}
function get_selected_count($theList)
{
var $count = 0;
var $cur = null;
for (var $i = 0; $i < $theList.length; $i++)
{
$cur = $theList.options[$i];
if ($cur.selected) $count++;
}
return $count;
}
function get_selected_index($aSelect, $typeIndex)
{
var $index = 0;
for (var $i = 0; $i < $aSelect.length; $i++)
{
if ($aSelect.options[$i].selected)
{
$index = $i;
if ($typeIndex == 'firstSelected') break;
}
}
return $index;
}
function has_selected_options($theList)
{
var $ret = false;
var $cur = null;
for (var $i = 0; $i < $theList.length; $i++)
{
$cur = $theList.options[$i];
if ($cur.selected) {
$ret = true;
break;
}
}
return $ret;
}
function select_sort($aSelect)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
var $to_array = select_to_array($aSelect);
$to_array.sort(select_compare);
array_to_select($to_array, $aSelect);
}
function move_options_up($aSelect, $interval)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
if (has_selected_options($aSelect))
{
var $selected_options = Array();
var $first_selected = get_selected_index($aSelect, 'firstSelected');
for (var $i = 0; $i < $aSelect.length; $i++)
{
if ($aSelect.options[$i].selected && ($first_selected > 0) )
{
swap_options($aSelect, $i, $i - $interval);
$selected_options[$selected_options.length] = $aSelect.options[$i - $interval].value;
}
else if ($first_selected == 0)
{
//alert('Begin of list');
break;
}
}
set_selected($selected_options, $aSelect);
}
else
{
//alert('Check items from moving');
}
}
function move_options_down($aSelect, $interval)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
if (has_selected_options($aSelect))
{
var $last_selected = get_selected_index($aSelect, 'lastSelected');
var $selected_options = Array();
for (var $i = $aSelect.length - 1; $i >= 0; $i--)
{
if ($aSelect.options[$i].selected && ($aSelect.length - ($last_selected + 1) > 0))
{
swap_options($aSelect, $i, $i + $interval);
$selected_options[$selected_options.length] = $aSelect.options[$i + $interval].value;
}
else if ($last_selected + 1 == $aSelect.length)
{
//alert('End of list');
break;
}
}
set_selected($selected_options, $aSelect);
}
else
{
//alert('Check items from moving');
}
}
function swap_options($aSelect, $src_num, $dst_num)
{
var $src_html = $aSelect.options[$src_num].innerHTML;
var $dst_html = $aSelect.options[$dst_num].innerHTML;
var $src_value = $aSelect.options[$src_num].value;
var $dst_value = $aSelect.options[$dst_num].value;
var $src_option = document.createElement('OPTION');
var $dst_option = document.createElement('OPTION');
$aSelect.remove($src_num);
$aSelect.options.add($dst_option, $src_num);
$dst_option.innerText = $dst_html;
$dst_option.value = $dst_value;
$dst_option.innerHTML = $dst_html;
$aSelect.remove($dst_num);
$aSelect.options.add($src_option, $dst_num);
$src_option.innerText = $src_html;
$src_option.value = $src_value;
$src_option.innerHTML = $src_html;
}
function getXMLHTTPObject(content_type)
{
if (!isset(content_type)) content_type = 'text/plain';
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType(content_type);
// See note below about this line
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}
function str_repeat($symbol, $count)
{
var $i = 0;
var $ret = '';
while($i < $count) {
$ret += $symbol;
$i++;
}
return $ret;
}
function getDocumentFromXML(xml)
{
if (window.ActiveXObject) {
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async=false;
doc.loadXML(xml);
}
else {
var parser = new DOMParser();
var doc = parser.parseFromString(xml,"text/xml");
}
return doc;
}
function set_persistant_var($var_name, $var_value, $t, $form_action)
{
set_hidden_field('field', $var_name);
set_hidden_field('value', $var_value);
submit_event('u', 'OnSetPersistantVariable', $t, $form_action);
}
function setCookie($Name, $Value)
{
// set cookie
if (getCookie($Name) != $Value) {
document.cookie = $Name+'='+escape($Value);
}
}
function getCookie($Name)
{
// get cookie
var $cookieString = document.cookie;
var $index = $cookieString.indexOf($Name+'=');
if ($index == -1) {
return null;
}
$index = $cookieString.indexOf('=',$index)+1;
var $endstr = $cookieString.indexOf(';',$index);
if($endstr == -1) $endstr = $cookieString.length;
return unescape($cookieString.substring($index, $endstr));
}
function deleteCookie($Name)
{
// deletes cookie
if (getCookie($Name)) {
var d = new Date();
document.cookie = $Name + '=;expires=' + d.toGMTString() + ';' + ';';
}
}
function addElement($dst_element, $tag_name) {
var $new_element = document.createElement($tag_name.toUpperCase());
$dst_element.appendChild($new_element);
return $new_element;
}
Math.sum = function($array) {
var $i = 0;
var $total = 0;
while ($i < $array.length) {
$total += $array[$i];
$i++;
}
return $total;
}
Math.average = function($array) {
return Math.sum($array) / $array.length;
}
// remove spaces and underscores from a string, used for nls_menu
function rs(str, is_phrase)
{
if (isset(is_phrase) && is_phrase) {
str = RemoveTranslationLink(str, false);
}
return str.replace(/[ _\']+/g, '.');
}
function getFrame($name)
{
var $main_window = window;
// 1. cycle through popups to get main window
try {
// will be error, when other site is opened in parent window
var $i = 0;
var $opener;
do {
if ($i == 10) {
break;
}
// get popup opener
$opener = $main_window.opener;
if (!$opener) {
// when no opener found, then try parent window
$opener = $main_window.parent;
}
if ($opener) {
$main_window = $opener;
}
$i++;
} while ($opener);
}
catch (err) {
// catch Access/Permission Denied error
// alert('getFrame.Error: [' + err.description + ']');
return window;
}
var $frameset = $main_window.parent.frames;
for ($i = 0; $i < $frameset.length; $i++) {
if ($frameset[$i].name == $name) {
return $frameset[$i];
}
}
return $main_window.parent;
}
function ClearBrowserSelection()
{
if (window.getSelection) {
// removeAllRanges will be supported by Opera from v 9+, do nothing by now
var selection = window.getSelection();
if (selection.removeAllRanges) { // Mozilla & Opera 9+
// alert('clearing FF')
window.getSelection().removeAllRanges();
}
} else if (document.selection && !is.opera) { // IE
// alert('clearing IE')
document.selection.empty();
}
}
function reset_form(prefix, event, msg)
{
if (confirm(RemoveTranslationLink(msg, true))) {
submit_event(prefix, event)
}
}
function cancel_edit(prefix, cancel_ev, save_ev, msg)
{
if ((!Form || (Form && Form.HasChanged)) && confirm(RemoveTranslationLink(msg, true))) {
submit_event(prefix, save_ev)
}
else {
submit_event(prefix, cancel_ev)
}
}
function execJS(node)
{
var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
var bMoz = (navigator.appName == 'Netscape');
if (!node) return;
/* IE wants it uppercase */
var st = node.getElementsByTagName('SCRIPT');
var strExec;
for(var i=0;i<st.length; i++)
{
if (bSaf) {
strExec = st[i].innerHTML;
st[i].innerHTML = "";
} else if (bOpera) {
strExec = st[i].text;
st[i].text = "";
} else if (bMoz) {
strExec = st[i].textContent;
st[i].textContent = "";
} else {
strExec = st[i].text;
st[i].text = "";
}
try {
var x = document.createElement("script");
x.type = "text/javascript";
/* In IE we must use .text! */
if ((bSaf) || (bOpera) || (bMoz))
x.innerHTML = strExec;
else x.text = strExec;
document.getElementsByTagName("head")[0].appendChild(x);
} catch(e) {
alert(e);
}
}
};
function NumberFormatter() {}
NumberFormatter.ThousandsSep = '\'';
NumberFormatter.DecimalSep = '.';
NumberFormatter.Parse = function(num)
{
if (num == '') return 0;
return parseFloat( num.toString().replace(this.ThousandsSep, '').replace(this.DecimalSep, '.') );
}
NumberFormatter.Format = function(num)
{
num += '';
x = num.split('.');
x1 = x[0];
x2 = x.length > 1 ? this.DecimalSep + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + this.ThousandsSep + '$2');
}
return x1 + x2;
}
function getDimensions(obj) {
var style
if (obj.currentStyle) {
style = obj.currentStyle;
}
else {
style = getComputedStyle(obj,'');
}
padding = [parseInt(style.paddingTop), parseInt(style.paddingRight), parseInt(style.paddingBottom), parseInt(style.paddingLeft)]
border = [parseInt(style.borderTopWidth), parseInt(style.borderRightWidth), parseInt(style.borderBottomWidth), parseInt(style.borderLeftWidth)]
- for (var i in padding) if ( isNaN( padding[i] ) ) padding[i] = 0
- for (var i in border) if ( isNaN( border[i] ) ) border[i] = 0
+ for (var i = 0; i < padding.length; i++) if ( isNaN( padding[i] ) ) padding[i] = 0
+ for (var i = 0; i < border.length; i++) if ( isNaN( border[i] ) ) border[i] = 0
var result = new Object();
result.innerHeight = obj.clientHeight - padding[0] - padding[2];
result.innerWidth = obj.clientWidth - padding[1] - padding[3];
result.padding = padding;
result.borders = border;
result.outerHeight = obj.clientHeight + border[0] + border[2];
result.outerWidth = obj.clientHeight + border[1] + border[3];
return result;
}
function findPos(obj, with_scroll) {
/*var $offset = $(obj).offset();
return [$offset.left, $offset.top];*/
if (!with_scroll) var with_scroll = false;
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft - (with_scroll ? obj.scrollLeft : 0)
curtop = obj.offsetTop - (with_scroll ? obj.scrollTop : 0)
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft - (with_scroll ? obj.scrollLeft : 0)
curtop += obj.offsetTop - (with_scroll ? obj.scrollTop : 0)
}
}
return [curleft,curtop];
}
function scrollbarWidth() {
// Scrollbalken im Body ausschalten
var $overflow_backup = document.body.style.overflow;
document.body.style.overflow = 'hidden';
var width = document.body.clientWidth;
// Scrollbalken
document.body.style.overflow = 'scroll';
width -= document.body.clientWidth;
// Der IE im Standardmode
if (!width) {
width = document.body.offsetWidth - document.body.clientWidth;
}
// urspr?ngliche Einstellungen
document.body.style.overflow = $overflow_backup;
return width;
}
function maximizeElement($selector, $max_height) {
if ($max_height === undefined) {
$max_height = false;
}
var $element = $($selector);
if ($element.length == 0) {
return ;
}
$element.width('100%');
var $container_id = $element.attr('id') + '_container';
var $container = $( jq('#' + $container_id) );
if ($container.length == 0) {
// don't create same container twice
// all <script> tags will be executed again after wrap method is called, so remove them to prevent that
$('script', $element).remove();
$element.wrap('<div id="' + $container_id + '" style="position: relative; overflow: auto; width: 100%;"></div>');
$container = $( jq('#' + $container_id) );
$(window).resize(
function() {
maximizeElement($selector, $max_height);
}
);
}
var $offset_top = $container.offset().top;
var $window_height = $(window).height();
var $height_left = $window_height - $offset_top;
if (($max_height !== false) && ($max_height < $height_left)) {
$height_left = $max_height;
}
$height_left -= ($element.outerHeight() - $element.height());
$container.height($height_left);
var $element_width = $(window).width() - ($element.outerWidth() - $element.width());
if ( $height_left < $element.height() ) {
// needs vertical scrolling, so substract vertical scrollbar width
$element_width -= scrollbarWidth();
}
$element.width($element_width);
}
function addEvent(el, evname, func, traditional) {
if (traditional) {
eval('el.on'+evname+'='+func);
return;
}
if (evname.match(/mousedown|mousemove|mouseup/)) {
$(el)
.unbind(evname) // don't allow more then one
.bind(evname, func);
return ;
}
if (is.ie) {
el.attachEvent("on" + evname, func);
} else {
el.addEventListener(evname, func, true);
}
};
/*function removeEvent(el, evname, func) {
if (is.ie) {
el.detachEvent('on' + evname, func);
} else {
el.removeEventListener(evname, func, true);
}
}*/
function addLoadEvent(func, wnd)
{
Application.setHook('m:OnAfterWindowLoad', func);
}
function replaceFireBug() {
if (window.console === undefined || !console.firebug) {
var names = [
'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml',
'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'
];
if (window.top.console !== undefined || window.top.firebug) {
// console is not defined in iframes, so define it here
window.console = window.top.console;
window._getFirebugConsoleElement = window.top._getFirebugConsoleElement;
}
else {
window.console = {};
for (var i = 0; i < names.length; ++i) {
window.console[names[i]] = function($msg) {
alert('FireBug console object methods are not available outside Firefox!' + "\n" + $msg);
}
}
}
}
}
function runOnChange(elId) {
var evt;
var el = typeof(elId) == 'string' ? document.getElementById(elId) : elId
if (document.createEvent) {
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", true, false);
(evt) ? el.dispatchEvent(evt) : (el.onchange && el.onchange());
return;
}
if (el.fireEvent) {
el.fireEvent('onchange');
}
}
function WatchClosing(win, $url)
{
window.setTimeout(function() {
if (win.closed) {
var req = Request.getRequest();
var $ajax_mark = ($url.indexOf('?') ? '&' : '?') + 'ajax=yes';
req.open('GET', $url + $ajax_mark, false); //!!!SYNCRONIOUS!!! REQUEST (3rd param = false!!!)
req.send(null);
}
},
2000
)
}
function IterateUploaders($method) {
if (typeof UploadsManager != 'undefined') {
UploadsManager.iterate($method);
}
}
String.prototype.trim = function () {
return this.replace(/\s*((\S+\s*)*)/, "$1").replace(/((\s*\S+)*)\s*/, "$1");
}
String.prototype.toNumeric = function () {
return parseInt( this.replace(/(auto|medium)/, '0px').replace(/[a-z]/gi,'') );
}
function jq($selector) {
return $selector.replace(/(\[|\]|\.)/g, '\\$1');
}
function setHelpLink($user_docs_url, $title_preset) {
if (!$user_docs_url) {
return ;
}
$('#help_link', getFrame('head').document).attr('href', $user_docs_url + '/' + $title_preset);
}
// window management functions:
function getWindowOpener($window) {
// use this intead of "window.opener"
if (!$modal_windows) {
return $window.opener;
}
if ($window.name == 'main' || $window.name == 'main_frame') {
return null;
}
return getFrame('main').TB.findWindow($window.name, -1);
}
function window_close($close_callback) {
// use this instead of "window.close();"
if (!$modal_windows) {
if ($.isFunction($close_callback)) {
// use close callback, because iframe will be removed later in this method
$close_callback();
}
window.close();
return ;
}
if (window.name == 'main') {
return ;
}
if ($close_callback !== undefined) {
return getFrame('main').TB.remove(null, $close_callback);
}
return getFrame('main').TB.remove();
}
Array.prototype.each = function($callback) {
var $result = null;
for (var $i = 0; $i < this.length; $i++) {
$result = $callback.call(this[$i], $i);
if ($result === false) {
break;
}
}
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/ajax.js
===================================================================
--- branches/RC/core/admin_templates/js/ajax.js (revision 11931)
+++ branches/RC/core/admin_templates/js/ajax.js (revision 11932)
@@ -1,484 +1,484 @@
function preg_print_pre(obj, reg)
{
if (!reg) reg = /.*/;
var p = ''
for (var prop in obj) {
if (prop.match(reg) ) {
p += prop + ': '+obj[prop] + '\n'
}
}
alert(p)
}
// Main AJAX classs
function Request() {}
Request.timeout = 60000; //60 seconds
Request.method = 'GET';
-Request.headers = new Array();
+Request.headers = {};
Request.params = null;
Request.progressText = 'Loading ...';
Request.makeRequest = function(p_url, p_busyReq, p_progId, p_successCallBack, p_errorCallBack, p_pass, p_object) {
//p_url: the web service url
//p_busyReq: is a request for this object currently in progress?
//p_progId: element id where progress HTML should be shown
//p_successCallBack: callback function for successful response
//p_errorCallBack: callback function for erroneous response
//p_pass: string of params to pass to callback functions
//p_object: object of params to pass to callback functions
if (p_busyReq) return;
var req = Request.getRequest();
if (req != null) {
p_busyReq = true;
Request.showProgress(p_progId);
req.onreadystatechange = function() {
if (req.readyState == 4) {
p_busyReq = false;
window.clearTimeout(toId);
try {
if (req.status == 200) {
// preg_print_pre(req)
p_successCallBack(req, p_pass, p_object);
} else {
p_errorCallBack(req, p_pass, p_object);
}
Request.hideProgress(p_progId);
}
catch (e) {
// alert('AJAX error')
}
}
}
var $ajax_mark = (p_url.indexOf('?') ? '&' : '?') + 'ajax=yes';
req.open(Request.method, p_url + $ajax_mark, true);
if (Request.method == 'POST') {
Request.headers['Content-type'] = 'application/x-www-form-urlencoded';
Request.headers['referer'] = p_url;
}
else {
Request.headers['If-Modified-Since'] = 'Sat, 1 Jan 2000 00:00:00 GMT';
}
Request.sendHeaders(req);
if (Request.method == 'POST') {
req.send(Request.params);
Request.method = 'GET'; // restore method back to GET
}
else {
req.send(null);
}
var toId = window.setTimeout( function() {if (p_busyReq) req.abort();}, Request.timeout );
}
}
Request.processRedirect = function($request) {
var $match_redirect = new RegExp('^#redirect#(.*)').exec($request.responseText);
if ($match_redirect != null) {
// redirect to external template requested
window.location.href = $match_redirect[1];
return true;
}
return false;
}
Request.sendHeaders = function($request) {
for (var $header_name in Request.headers) {
if (typeof Request.headers[$header_name] == 'function') {
continue;
}
$request.setRequestHeader($header_name, Request.headers[$header_name]);
}
- Request.headers = new Array(); // reset header afterwards
+ Request.headers = {}; // reset header afterwards
}
Request.getRequest = function() {
var xmlHttp;
try { xmlHttp = new ActiveXObject('MSXML2.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new XMLHttpRequest(); return xmlHttp; } catch(e) {}
return null;
}
Request.showProgress = function(p_id) {
if (p_id != '') {
var $content_div = $( jq('#' + p_id) );
var $content_offset = $content_div.offset();
var $content_width = $content_div.width();
var $content_height = $content_div.height();
// alert('id: ' + p_id + '; ch: ' + $content_div.get(0).clientHeight + '; sh: ' + $content_div.get(0).style.height);
var $parent_div = $content_div.parents(':first');
// use parent height, when own height is larger, then parent's
$content_width = Math.min($content_width, $parent_div.width());
$content_height = Math.min($content_height, $parent_div.height());
var $progress_overlay = $( jq('#' + p_id + '_progress') );
if ($progress_overlay.length == 0) {
$progress_overlay = $('<div id="' + p_id + '_progress"></div>');
var $maximal_height = $(window).height() - $content_offset.top;
$progress_overlay.css(
{
width: $content_div.width(),
height: $content_height > 0 ? $content_height : $maximal_height,
left: $content_offset.left,
top: $content_offset.top + $parent_div.scrollTop(),
position: 'absolute',
zIndex: 30,
opacity: 0.5,
backgroundColor: '#2D79D6',
// don't show progress overlay, when target div is hidden
display: $content_offset.top /*$content_height*/ > 0 ? 'block' : 'none'
}
);
$('body').append($progress_overlay);
$progress_overlay.html( Request.getProgressHtml() );
}
else {
if ($content_height > 0) {
// show progress, only when target div is visible
$progress_overlay.css(
{
width: $content_width,
height: $content_height,
top: $content_offset.top + $parent_div.scrollTop()
}
);
}
$progress_overlay.show();
}
}
}
Request.hideProgress = function(p_id) {
if (p_id != '') {
$( jq('#' + p_id + '_progress') ).hide();
}
}
Request.setOpacity = function (opacity, id) {
var $element = $( typeof(id) == 'string' ? jq('#' + id) : id );
$element.css('opacity', opacity / 100);
}
Request.getProgressHtml = function() {
return "<div class='progress' style='position: relative; top: 50%; text-align: center; color: white;'>" + Request.progressText + "<br /><img src='img/ajax_progress.gif' align='absmiddle' width='100' height='7' alt='" + Request.progressText + "' title='" + Request.progressText + "'/></div>";
}
Request.getErrorHtml = function(p_req) {
//TODO: implement accepted way to handle request error
return '[status: ' + p_req.status + '; status_text: ' + p_req.statusText + '; responce_text: ' + p_req.responseText + ']';
}
Request.serializeForm = function(theform) {
if (typeof(theform) == 'string') {
theform = document.getElementById(theform);
}
var els = theform.elements;
var len = els.length;
var queryString = '';
Request.addField = function(name, value) {
if (queryString.length > 0) queryString += '&';
queryString += encodeURIComponent(name) + '=' + encodeURIComponent(value);
};
for (var i = 0; i<len; i++) {
var el = els[i];
if (el.disabled) continue;
switch(el.type) {
case 'text':
case 'password':
case 'hidden':
case 'textarea':
Request.addField(el.name, el.value);
break;
case 'select-one':
if (el.selectedIndex >= 0) {
Request.addField(el.name, el.options[el.selectedIndex].value);
}
break;
case 'select-multiple':
for (var j = 0; j < el.options.length; j++) {
if (!el.options[j].selected) continue;
Request.addField(el.name, el.options[j].value);
}
break;
case 'checkbox':
case 'radio':
if (!el.checked) continue;
Request.addField(el.name,el.value);
break;
}
}
return queryString;
};
// AJAX ProgressBar class
function AjaxProgressBar($url) {
this.WindowTitle = this.GetWindow().document.title;
this.URL = $url;
this.BusyRequest = false;
this.LastResponceTime = this.GetMicroTime();
this.ProgressPercent = 0; // progress percent
this.ProgressTime = new Array();
this.Query();
}
AjaxProgressBar.prototype.GetWindow = function() {
return window.parent ? window.parent : window;
}
AjaxProgressBar.prototype.GetMicroTime = function() {
var $now = new Date();
return Math.round($now.getTime() / 1000); // because miliseconds are returned too
}
AjaxProgressBar.prototype.Query = function() {
// prompt('requestinng', this.URL);
Request.makeRequest(this.URL, this.BusyRequest, '', this.successCallback, this.errorCallback, '', this);
}
// return time needed for progress to finish
AjaxProgressBar.prototype.GetEstimatedTime = function() {
return Math.ceil((100 - this.ProgressPercent) * Math.sum(this.ProgressTime) / this.ProgressPercent);
}
AjaxProgressBar.prototype.successCallback = function($request, $params, $object) {
var $responce = $request.responseText;
var $match_redirect = new RegExp('^#redirect#(.*)').exec($responce);
if ($match_redirect != null) {
$object.showProgress(100);
// redirect to external template requested
window.location.href = $match_redirect[1];
return false;
}
if (isNaN(parseFloat($responce))) {
// error message received, otherwise $responce should be number
alert($responce);
return ;
}
if ($object.showProgress($responce)) {
$object.Query();
}
}
AjaxProgressBar.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX Error; class: AjaxProgressBar; ' + Request.getErrorHtml($request));
}
AjaxProgressBar.prototype.FormatTime = function ($seconds) {
$seconds = parseInt($seconds);
var $minutes = Math.floor($seconds / 60);
if ($minutes < 10) $minutes = '0' + $minutes;
$seconds = $seconds % 60;
if ($seconds < 10) $seconds = '0' + $seconds;
return $minutes + ':' + $seconds;
}
AjaxProgressBar.prototype.showProgress = function ($percent) {
this.ProgressPercent = $percent;
var $now = this.GetMicroTime();
this.ProgressTime[this.ProgressTime.length] = $now - this.LastResponceTime;
this.LastResponceTime = $now;
var $display_progress = parseInt(this.ProgressPercent);
this.GetWindow().document.title = $display_progress + '% - ' + this.WindowTitle;
document.getElementById('progress_display[percents_completed]').innerHTML = $display_progress + '%';
document.getElementById('progress_display[elapsed_time]').innerHTML = this.FormatTime( Math.sum(this.ProgressTime) );
document.getElementById('progress_display[Estimated_time]').innerHTML = this.FormatTime( this.GetEstimatedTime() );
document.getElementById('progress_bar[done]').style.width = $display_progress + '%';
document.getElementById('progress_bar[left]').style.width = (100 - $display_progress) + '%';
return $percent < 100 ? true : false;
}
// AJAX PopupManager class
function AjaxPopupManager($url) {
this.URL = $url;
this.ResponceFunction = null;
this.PopupSizes = new Array();
}
AjaxPopupManager.prototype.GetSize = function ($template) {
if (this.ResponceFunction == null) {
alert ('Please define responce function first (type: '+typeof(this.ResponceFunction)+')');
}
if (!isset(this.PopupSizes[$template])) {
var $url = this.URL + '&type=GetPopupSize&template_name=' + $template;
// alert('from ajax: '+$url);
Request.makeRequest($url, this.BusyRequest, '', this.successCallback, this.errorCallback, ['GetSize', $template], this);
}
else {
// alert('from cache');
this.ResponceFunction(this.PopupSizes[$template]);
}
}
AjaxPopupManager.prototype.successCallback = function($request, $params, $object) {
var $responce = $request.responseText;
/*var $match_redirect = new RegExp('^#redirect#(.*)').exec($responce);
if ($match_redirect != null) {
alert('AJAX REDIRECT!!!')
// redirect to external template requested
window.location.href = $match_redirect[1];
return false;
}*/
switch ($params[0]) {
case 'GetSize':
// store responce to cache for future use
$object.PopupSizes[ $params[1] ] = $responce;
break;
}
$object.ResponceFunction($responce);
$object.ResponceFunction = null; // reset responce function
}
AjaxPopupManager.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX Error; class: AjaxPopupManager; ' + Request.getErrorHtml($request));
}
// AJAX DropdownPreloader class
function AjaxDropdownPreloader($url, $input_mask, $filter_field, $dependend_field, value) {
this.URL = $url;
this.InputMask = $input_mask;
this.FilterField = $filter_field;
this.DependendField = $dependend_field;
this.Titles = this.prepareTitles();
this.Value = value;
this.BusyRequest = false;
}
AjaxDropdownPreloader.prototype.prepareURL = function()
{
return this.URL.replace('#DEPENDEND#', this.Dependend).replace('#FILTER_VALUE#', this.getValue(this.FilterField));
}
AjaxDropdownPreloader.prototype.prepareTitles = function() {
var $control = this.getControl(this.DependendField);
var $i = 0;
var $ret = new Array ();
while ($i < $control.options.length) {
$ret[$control.options[$i].value] = $control.options[$i].innerHTML;
$i++;
}
return $ret;
}
AjaxDropdownPreloader.prototype.getValue = function($field_name) {
var $control = this.getControl($field_name);
if ($control.tagName == 'INPUT') return $control.value;
return $control.selectedIndex > 0 ? $control.options[$control.selectedIndex].value : '';
}
AjaxDropdownPreloader.prototype.Query = function () {
var $url = this.prepareURL();
var $selected_value = this.Value || this.getValue(this.DependendField);
// remove all existing options
this.removeOptions();
Request.makeRequest($url, this.BusyRequest, '', this.successCallback, this.errorCallback, $selected_value, this);
}
AjaxDropdownPreloader.prototype.getControl = function($field) {
var $id = this.InputMask.replace('#FIELD#', $field);
return document.getElementById($id);
}
AjaxDropdownPreloader.prototype.successCallback = function($request, $params, $object) {
if (Request.processRedirect($request) === true) {
return ;
}
var control = $object.getControl($object.DependendField)
$object.ProcessXMLNode($request.responseXML, control, $params);
runOnChange(control);
$object.AfterProcess();
}
AjaxDropdownPreloader.prototype.ProcessXMLNode = function($node, $dst_field, $selected_value) {
for (var i = 0; i < $node.childNodes.length; i++) {
var $child = $node.childNodes.item(i);
switch ($child.tagName) {
case 'option':
var opt_value = $child.getAttribute('value');
var title;
if (opt_value) { // value is passed explicically
title = $child.firstChild.nodeValue
}
else {
opt_value = $child.firstChild.nodeValue;
title = this.Titles[$child.firstChild.nodeValue];
}
this.addOption($dst_field, opt_value, title, $child.attributes);
if (!$dst_field.multiple && (opt_value == $selected_value)) {
$dst_field.options[$dst_field.options.length - 1].selected = true;
}
break;
case 'field_options':
if (!$dst_field.multiple) {
this.addOption($dst_field, '', '');
}
// add new states
this.ProcessXMLNode($child, $dst_field, $selected_value);
if ($dst_field.options.length == 0 || $dst_field.options.length == 2) {
$dst_field.value = $dst_field.options[$dst_field.options.length - 1].value;
}
break;
}
}
}
AjaxDropdownPreloader.prototype.AfterProcess = function() {
}
AjaxDropdownPreloader.prototype.removeOptions = function($object) {
if (!$object) $object = this.getControl(this.DependendField);
if ($object.options.length > 0) {
while ($object.options.length > 0) {
$object.remove(0);
}
}
}
AjaxDropdownPreloader.prototype.addOption = function($object, $value, $title, attributes) {
var $option = document.createElement('OPTION');
$object.options.add($option, $object.options.length);
$option.innerText = $title;
$option.innerHTML = $title;
$option.value = $value;
if (attributes) {
for (var i=0; i<attributes.length; i++) {
if (attributes[i].nodeName == 'value') continue;
$option.setAttribute(attributes[i].nodeName, attributes[i].nodeValue);
}
}
}
AjaxDropdownPreloader.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX Error; class: AjaxDropdownPreloader; ' + Request.getErrorHtml($request));
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/grid.js
===================================================================
--- branches/RC/core/admin_templates/js/grid.js (revision 11931)
+++ branches/RC/core/admin_templates/js/grid.js (revision 11932)
@@ -1,550 +1,550 @@
var $GridManager = new GridManager();
function GridManager () {
this.Grids = Grids; // get all from global variable, in future replace all references to it with $GridManager.Grids
this.AlternativeGrids = new Array();
}
GridManager.prototype.AddAlternativeGrid = function ($source_grid, $destination_grid, $reciprocal)
{
if ($source_grid == $destination_grid) {
return false;
}
if (typeof(this.AlternativeGrids[$source_grid]) == 'undefined') {
// alternative grids not found, create empty list
this.AlternativeGrids[$source_grid] = new Array();
}
if (!in_array($destination_grid, this.AlternativeGrids[$source_grid])) {
// alternative grids found, check if not added already
this.AlternativeGrids[$source_grid].push($destination_grid);
}
if ($reciprocal) {
this.AddAlternativeGrid($destination_grid, $source_grid);
}
}
GridManager.prototype.ClearAlternativeGridsSelection = function ($source_prefix)
{
if (!this.AlternativeGrids[$source_prefix]) return false;
var $i = 0;
var $destination_prefix = '';
while ($i < this.AlternativeGrids[$source_prefix].length) {
$destination_prefix = this.AlternativeGrids[$source_prefix][$i];
if (this.Grids[$destination_prefix]) {
// alternative grid set, but not yet loaded by ajax
this.Grids[$destination_prefix].ClearSelection();
}
$i++;
}
}
GridManager.prototype.CheckDependencies = function ($prefix) {
if (typeof(this.Grids[$prefix]) != 'undefined') {
this.Grids[$prefix].CheckDependencies('GridManager.CheckDependencies');
}
}
function GridItem(grid, an_element, cb, item_id, class_on, class_off)
{
this.Grid = grid;
this.selected = false;
this.id = an_element.id;
this.ItemId = item_id;
this.sequence = parseInt(an_element.getAttribute('sequence'));
// this.class_on = class_on;
if (class_off == ':original') {
this.class_off = an_element.className;
}
else
this.class_off = class_off;
if (class_on.match(/(.*):(.*)/)) {
var even = RegExp.$2;
var odd = RegExp.$1;
this.class_on = this.class_off.match(/even/) ? even : odd
}
else {
this.class_on = class_on
}
this.HTMLelement = an_element;
if (document.getElementById('left_'+an_element.id)) {
this.LeftElement = document.getElementById('left_'+an_element.id);
}
else {
this.LeftElement = false;
}
this.CheckBox = cb;
this.value = this.ItemId;
this.ItemType = 11;
}
GridItem.prototype.Init = function ()
{
this.HTMLelement.GridItem = this;
this.HTMLelement.onclick = function(ev) {
this.GridItem.Click(ev);
};
this.HTMLelement.ondblclick = function(ev) {
this.GridItem.DblClick(ev);
}
if ( this.LeftElement ) {
this.LeftElement.GridItem = this;
this.LeftElement.onclick = function(ev) {
this.GridItem.Click(ev);
};
this.LeftElement.ondblclick = function(ev) {
this.GridItem.DblClick(ev);
}
}
if ( isset(this.CheckBox) ) {
this.CheckBox.GridItem = this;
this.CheckBox.onclick = function(ev) {
this.GridItem.cbClick(ev);
};
this.CheckBox.ondblclick = function(ev) {
this.GridItem.DblClick(ev);
}
}
// if ( this.Grid.MouseOverClass ) {
addEvent(this.HTMLelement, 'mouseover', function(ev) { this.GridItem.MouseOver(ev)}, true); // true for traditional event model
addEvent(this.HTMLelement, 'mouseout', function(ev) { this.GridItem.MouseOut(ev)}, true);
if ( this.LeftElement ) {
addEvent(this.LeftElement, 'mouseover', function(ev) { this.GridItem.MouseOver(ev)}, true);
addEvent(this.LeftElement, 'mouseout', function(ev) { this.GridItem.MouseOut(ev)}, true);
}
// }
}
GridItem.prototype.AddClass = function(elem, class_name)
{
var cur_classes = elem.className;
// if (cur_classes.match(class_name)) return;
elem.className = cur_classes+' '+class_name;
// console.log('added %s to %s resulted %s', class_name, elem.id, elem.className)
}
GridItem.prototype.RemoveClass = function(elem, class_name)
{
var cur_classes = elem.className;
// console.log('looking for %s in %s', class_name, cur_classes)
if (!cur_classes.match(class_name)) return;
cur_classes = cur_classes.replace(class_name, '');
cur_classes = cur_classes.replace(/[ ]+/, ' ');
elem.className = cur_classes;
// console.log('removed %s from %s resulted %s', class_name, elem.id, elem.className)
}
GridItem.prototype.DisableClicking = function ()
{
this.HTMLelement.onclick = function(ev) {
return false;
};
this.HTMLelement.ondblclick = function(ev) {
return false;
}
if ( this.LeftElement ) {
this.LeftElement.onclick = function(ev) {
return false;
};
this.LeftElement.ondblclick = function(ev) {
return false;
}
}
if ( isset(this.CheckBox) ) {
this.CheckBox.onclick = function(ev) {
return false;
};
}
}
GridItem.prototype.Select = function ()
{
if (this.selected) return;
this.selected = true;
this.HTMLelement.setAttribute('_row_selected', 1)
this.AddClass(this.HTMLelement, this.class_on);
if ( this.LeftElement ) {
this.LeftElement.setAttribute('_row_selected', 1)
this.AddClass(this.LeftElement, this.class_on);
}
if ( isset(this.CheckBox) ) {
this.CheckBox.checked = true;
}
this.Grid.LastSelectedId = this.ItemId;
this.Grid.SelectedCount++;
// this is for in-portal only (used in relation select)
LastCheckedItem = this;
if (typeof (this.Grid.OnSelect) == 'function' ) {
this.Grid.OnSelect(this.ItemId);
}
}
GridItem.prototype.UnSelect = function ( force )
{
if ( !this.selected && !force) return;
this.selected = false;
this.HTMLelement.removeAttribute('_row_selected')
this.RemoveClass(this.HTMLelement, this.class_on);
if ( this.LeftElement ) {
this.LeftElement.removeAttribute('_row_selected')
this.RemoveClass(this.LeftElement, this.class_on);
}
if ( isset(this.CheckBox) ) {
this.CheckBox.checked = false;
}
this.Grid.SelectedCount--;
if (typeof (this.Grid.OnUnSelect) == 'function' ) {
this.Grid.OnUnSelect(this.ItemId);
}
this.Grid.LastSelectedId = null;
}
GridItem.prototype.ClearBrowserSelection = function() {
ClearBrowserSelection();
}
GridItem.prototype.Click = function (ev)
{
//this.ClearBrowserSelection();
this.Grid.ClearAlternativeGridsSelection('GridItem.Click');
var e = !is.ie ? ev : window.event;
if (e.shiftKey && !this.Grid.RadioMode) {
this.ClearBrowserSelection();
this.Grid.SelectRangeUpTo(this.sequence);
}
else {
if (e.ctrlKey && !this.Grid.RadioMode) {
this.Toggle()
}
else {
if (!(this.Grid.RadioMode && this.Grid.LastSelectedId == this.ItemId && this.selected)) {
// don't clear selection if item same as current is selected
if (!this.Grid.StickySelection) {
this.Grid.ClearSelection(null,'GridItem.Click');
}
else {
if (this.Grid.LastSelectedId == this.ItemId) {
return;
}
}
this.Toggle();
}
}
}
this.Grid.CheckDependencies('GridItem.Click');
e.cancelBubble = true;
}
GridItem.prototype.cbClick = function (ev)
{
var e = is.ie ? window.event : ev;
if (this.Grid.RadioMode) this.Grid.ClearSelection(null,'GridItem.cbClick');
this.Grid.ClearAlternativeGridsSelection('GridItem.cbClick');
this.Toggle();
this.Grid.CheckDependencies('GridItem.cbClick');
e.cancelBubble = true;
}
GridItem.prototype.DblClick = function (ev)
{
var e = is.ie ? window.event : ev;
this.Grid.Edit();
}
GridItem.prototype.MouseOver = function (ev)
{
this.HTMLelement.setAttribute('_row_highlighted', 1)
this.AddClass(this.HTMLelement, this.Grid.MouseOverClass);
// if (this.Grid.MouseOverClass) {this.HTMLelement.className = this.Grid.MouseOverClass;}
if ( this.LeftElement ) {
this.LeftElement.setAttribute('_row_highlighted', 1)
// if (this.Grid.MouseOverClass) this.LeftElement.className = this.Grid.MouseOverClass;
this.AddClass(this.LeftElement, this.Grid.MouseOverClass);
// this.LeftElement.className = this.LeftElement.className; // this is to make IE re-render the element
}
}
GridItem.prototype.MouseOut = function (ev)
{
this.HTMLelement.removeAttribute('_row_highlighted')
this.RemoveClass(this.HTMLelement, this.Grid.MouseOverClass);
// if (this.Grid.MouseOverClass) {this.HTMLelement.className = this.selected ? this.class_on : this.class_off;}
if ( this.LeftElement ) {
this.LeftElement.removeAttribute('_row_highlighted')
this.RemoveClass(this.LeftElement, this.Grid.MouseOverClass);
// if (this.Grid.MouseOverClass) this.LeftElement.className = this.selected ? this.class_on : this.class_off;
// this.LeftElement.className = this.LeftElement.className; // this is to make IE re-render the element
}
}
GridItem.prototype.Toggle = function ()
{
if (this.selected) this.UnSelect()
else {
this.Grid.LastSelectedSequence = this.sequence;
this.Select();
}
}
GridItem.prototype.FallsInRange = function (from, to)
{
return (from <= to) ?
(this.sequence >= from && this.sequence <= to) :
(this.sequence >= to && this.sequence <= from);
}
function Grid(prefix, class_on, class_off, dbl_click, toolbar)
{
this.prefix = prefix;
this.class_on = class_on;
this.class_off = class_off;
- this.Items = new Array();
+ this.Items = {};
this.LastSelectedSequence = 1;
this.LastSelectedId = null;
this.DblClick = dbl_click;
this.ToolBar = toolbar;
this.SelectedCount = 0;
this.AlternativeGrids = new Array();
this.DependantButtons = new Array();
this.RadioMode = false;
this.MouseOverClass = false;
// K3-style sticky selection, selection an item does not unselect currently selected
// even w/o Ctrl key pressed
this.StickySelection = false;
}
Grid.prototype.EnableRadioMode = function() {
this.RadioMode = true;
this.StickySelection = false;
}
Grid.prototype.AddItem = function( an_item ) {
this.Items[an_item.id] = an_item;
}
Grid.prototype.AddItemsByIdMask = function ( tag, mask, cb_mask ) {
var $item_id=0;
elements = document.getElementsByTagName(tag.toUpperCase());
for (var i=0; i < elements.length; i++) {
if ( typeof(elements[i].id) == 'undefined') {
continue;
}
if ( !elements[i].id.match(mask)) continue;
$item_id=RegExp.$1;
cb_name = cb_mask.replace('$$ID$$',$item_id);
cb = document.getElementById(cb_name);
if (typeof(cb) == 'undefined') alert ('No Checkbox defined for item '+elements[i].id);
this.AddItem( new GridItem( this, elements[i], cb, $item_id, this.class_on, this.class_off ) );
}
}
Grid.prototype.InitItems = function() {
for (var i in this.Items) {
this.Items[i].Init();
}
this.ClearSelection( true,'Grid.InitItems' );
var a_Grid = this;
addEvent(document, 'keyup', function(ev) {
var e = !is.ie ? ev : window.event;
switch (e.keyCode) {
case 65:
if (!e.ctrlKey) break;
a_Grid.SelectAll();
ClearBrowserSelection()
// window.setTimeout(ClearBrowserSelection, 500);
break;
case 27:
a_Grid.ClearSelection();
break;
case 33:
case 37:
//alert('<-') // go to prev page here
break;
case 34:
case 39:
// alert('->') // go to next page here
break;
case 88:
ClearBrowserSelection();
break;
}
});
}
Grid.prototype.DisableClicking = function() {
for (var i in this.Items) {
this.Items[i].DisableClicking();
}
this.ClearSelection( true, 'Grid.DisableClicking' );
}
Grid.prototype.ClearSelection = function( force, called_from ) {
// alert('selection clear. force: '+force+'; called_from: '+called_from);
if (typeof(force) == 'undefined') force = false;
if (this.CountSelected() == 0 && !force) return;
for (var i in this.Items) {
this.Items[i].UnSelect(force);
}
this.SelectedCount = 0;
this.CheckDependencies('Grid.ClearSelection');
}
Grid.prototype.GetSelected = function() {
var $ret = new Array();
for (var i in this.Items) {
if (this.Items[i].selected) {
$ret[$ret.length] = this.Items[i].ItemId;
}
}
return $ret;
}
Grid.prototype.SetSelected = function($ids) {
$ids = $ids.split(',');
for (var i in this.Items) {
if (in_array(this.Items[i].ItemId, $ids)) {
this.Items[i].Select();
}
}
}
Grid.prototype.InvertSelection = function() {
for (var i in this.Items)
{
if( this.Items[i].selected )
{
this.Items[i].UnSelect();
}
else
{
this.Items[i].Select();
}
}
this.CheckDependencies('Grid.InvertSelection');
}
Grid.prototype.SelectAll = function() {
for (var i in this.Items) {
this.Items[i].Select();
}
this.CheckDependencies('Grid.SelectAll');
this.ClearAlternativeGridsSelection('Grid.SelectAll');
}
Grid.prototype.SelectRangeUpTo = function( last_sequence ) {
for (var i in this.Items) {
if (this.Items[i].FallsInRange(this.LastSelectedSequence, last_sequence)) {
this.Items[i].Select();
}
}
}
Grid.prototype.CountSelected = function ()
{
return this.SelectedCount;
}
Grid.prototype.Edit = function() {
if ( this.CountSelected() == 0 ) return;
this.DblClick(this.prefix);
}
Grid.prototype.SetDependantToolbarButtons = function($buttons, $direct, $mode) {
if (!isset($direct)) $direct = true; // direct (use false for invert mode)
if (!isset($mode)) $mode = 1; // enable/disable (use 2 for show/hide mode)
- for (var i in $buttons) {
+ for (var i = 0; i < $buttons.length; i++) {
this.DependantButtons.push(new Array($buttons[i], $direct, $mode));
}
//this.DependantButtons = buttons;
this.CheckDependencies('Grid.SetDependantToolbarButtons');
}
Grid.prototype.CheckDependencies = function($called_from)
{
// alert('prefix: ' + this.prefix + '; ' + $called_from + ' -> Grid.CheckDependencies');
var enabling = (this.CountSelected() > 0);
- for (var i in this.DependantButtons) {
+ for (var i = 0; i < this.DependantButtons.length; i++) {
if (this.DependantButtons[i][0].match("portal:(.*)")) {
button_name = RegExp.$1;
if (toolbar) {
if (enabling == this.DependantButtons[i][1]) {
toolbar.enableButton(button_name, true);
}
else
{
toolbar.disableButton(button_name, true);
}
}
}
else {
if (this.DependantButtons[i][2] == 1) {
this.ToolBar.SetEnabled(this.DependantButtons[i][0], enabling == this.DependantButtons[i][1]);
}
else {
this.ToolBar.SetVisible(this.DependantButtons[i][0], enabling == this.DependantButtons[i][1]);
}
}
}
//if (enabling) this.ClearAlternativeGridsSelection('Grid.CheckDependencies');
}
Grid.prototype.ClearAlternativeGridsSelection = function (called_from)
{
$GridManager.ClearAlternativeGridsSelection(this.prefix);
}
Grid.prototype.AddAlternativeGrid = function (alt_grid, reciprocal)
{
var $dst_prefix = typeof('alt_grid') == 'string' ? alt_grid : alt_grid.prefix;
$GridManager.AddAlternativeGrid(this.prefix, $dst_prefix, reciprocal);
}
Grid.prototype.FirstSelected = function ()
{
min_sequence = null;
var res = null
for (var i in this.Items) {
if (!this.Items[i].selected) continue;
if (min_sequence == null)
min_sequence = this.Items[i].sequence;
if (this.Items[i].sequence <= min_sequence) {
res = this.Items[i].ItemId;
min_sequence = this.Items[i].sequence;
}
}
return res;
}
Grid.prototype.each = function($callback) {
var $result = null;
for (var i in this.Items) {
$result = $callback.call(this.Items[i], i);
if ($result === false) {
break;
}
}
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/forms.js
===================================================================
--- branches/RC/core/admin_templates/js/forms.js (revision 11931)
+++ branches/RC/core/admin_templates/js/forms.js (revision 11932)
@@ -1,347 +1,347 @@
var last_shown_error = false;
var errors = new Object();
var first_error = new Object();
var fields = new Object();
function show_form_error(prefix, field, sticky)
{
if (isset(errors[prefix]) && isset(errors[prefix][field])) {
span = document.getElementById('error_msg_'+prefix);
span.innerHTML = fields[prefix][field] + ' - ' + errors[prefix][field];
if (sticky) last_shown_error = field;
}
}
function hide_form_error(prefix)
{
span = document.getElementById('error_msg_'+prefix);
if (!span) return;
span.innerHTML = '<br/>';
if (typeof(last_shown_error) != 'undefined' && last_shown_error) {
show_form_error(prefix, last_shown_error);
}
}
function add_form_error(prefix, field, element, error_msg) {
if (error_msg != '') {
if (typeof(errors[prefix]) == 'undefined') {
errors[prefix] = new Object();
}
errors[prefix][field] = error_msg;
if (document.getElementById(element)) {
// some controls don't have element to focus on (e.g. swf uploader)
addEvent(
document.getElementById(element),
'focus',
function() {
show_form_error(prefix, field, true)
}
);
addEvent(
document.getElementById(element),
'blur',
function() {
last_shown_error = false
}
);
}
/*else {
console.log('error: focusing failed for [', prefix, '.', field, '] = ', element);
}*/
if (typeof(first_error[prefix]) == 'undefined' || first_error[prefix] == false) {
first_error[prefix] = [field, element];
}
}
}
function FCKeditor_OnComplete( editor )
{
Form.Resize();
}
function InitEditors() {
// process all FCKEditor instances
var iframes = document.getElementsByTagName('IFRAME');
for (var i=0; i<iframes.length; i++) {
if (iframes[i].id.match(/___Frame$/)) {
iframes[i].contentWindow.location = iframes[i].getAttribute('latesrc');
}
}
// process all CodePress instances
if ($.isFunction(window.CodePress)) {
CodePress.run(/*FCKeditor_OnComplete*/);
}
}
function Form() {}
Form = new Form();
Form.Controls = new Array();
Form.Div = false;
Form.MinControlsHeight = 0;
Form.Options = new Object();
Form.FlexibleCount = 0;
Form.ScrollerW = 17;
Form.ScrollerH = 17;
Form.HasChanged = false;
Form.Init = function(id) {
this.Div = document.getElementById(id);
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
dim = getDimensions( document.getElementById(this.Controls[i]) );
options = this.Options[this.Controls[i]];
if (options.height) { // fixed height
options.min_height = options.height;
options.max_height = options.height;
}
if (!options.min_height) {
options.min_height = $( jq('#' + this.Controls[i]) ).outerHeight(); // dim.innerHeight
}
// if ( $( jq('#' + this.Controls[i]) ).parents('tr:first').is(':visible') ) {
this.MinControlsHeight += options.min_height;
// }
if (dim.innerHeight < options.min_height) {
document.getElementById(this.Controls[i]).style.height = options.min_height+'px';
}
// alert('adding element '+this.Controls[i]+' height: '+options.min_height+' total: '+this.MinControlsHeight)
}
// all <script> tags will be executed again after wrap method is called, so remove them to prevent that
$('script', this.Div).remove();
$(this.Div).wrap('<div id="' + this.Div.id + '_container" style="position: relative; overflow: auto; width: 100%;"></div>');
Application.removeDebuggerStatistics();
this.Table = $('table:first', this.Div).get(0);
this.Table.style.height = 'auto';
// this.Table.style.width = 'auto';
this.MinHeight = this.Table.offsetHeight;
this.MinWidth = this.Table.offsetWidth;
// alert('Measuring min width now')
addEvent(window, 'resize', function() {Form.Resize()})
this.Resize();
if (isset(first_error)) {
for (var i in first_error) {
if (first_error[i] != false) {
if (document.getElementById(first_error[i][1])) {
// some controls don't have element to focus on (e.g. swf uploader)
document.getElementById(first_error[i][1]).focus();
}
show_form_error(i, first_error[i][0], true);
// alert('focused on '+first_error[i][1])
}
}
}
if (_Simultanious_Edit_Message != '') {
alert(_Simultanious_Edit_Message);
}
this.InitOnChange();
Application.processHooks('m:OnAfterFormInit');
InitEditors();
}
Form.InitOnChange = function()
{
var inputs = window.document.getElementsByTagName('INPUT');
var selects = window.document.getElementsByTagName('SELECT');
var textareas = window.document.getElementsByTagName('TEXTAREA');
var groups = [inputs, selects, textareas];
for (var g=0; g<groups.length; g++) {
for (var i=0; i<groups[g].length; i++) {
var elem = groups[g][i];
if (elem.tagName == 'INPUT' && elem.type == 'hidden') continue;
addEvent(elem, elem.type=='button' ? 'click' : 'change', function() {Form.Changed()});
}
}
}
Form.Changed = function()
{
this.HasChanged = true;
}
Form.addControl = function(id, options) {
this.Controls.push(id);
if (!options) {
options = {coeff: 1, max_height: 0, min_height: 0};
}
else {
if (typeof(options['coeff']) == 'undefined') options['coeff'] = 1;
if (typeof(options['max_height']) == 'undefined') options['max_height'] = 0;
if (typeof(options['min_height']) == 'undefined') options['min_height'] = 0;
}
options['real_height'] = 0;
this.Options[id] = options; // for future use
// print_pre(this.Options[id]);
}
Form._parseSize = function ($size) {
if ($size.toString().match(/^([\d]+)px$/)) {
return parseInt(RegExp.$1);
}
return parseInt($size);
}
Form.Resize = function()
{
var h = (document.all ? window.document.body.offsetHeight : window.innerHeight);
var $div = $(this.Div);
var pos = $div.offset();
h -= pos.top;
if (this.Div.style.height.length) {
// height set for scroll_container overrides automatic container height detection
h = this._parseSize(this.Div.style.height);
}
if ($div.attr('mode') == 'minimal') {
// height will become minimal required (when data height is smaller, then window)
h = this.MinHeight;
}
h -= ($div.outerHeight() - $div.height());
// alert('h after correction is '+h);
window.document.body.style.width = '100%';
var w = (document.all ? window.document.body.offsetWidth : window.innerWidth);
w -= pos.left + ($div.outerWidth() - $div.width());
scroller_height = this.MinWidth > w ? this.ScrollerH : 0; // width of 1st table in scroll_container is larger, then window width?
scroller_width = this.MinHeight > h - scroller_height ? this.ScrollerW : 0; // table height > total height - scroller_height -> vertical scroller is found
scroller_height = this.MinWidth > w - scroller_width ? this.ScrollerH : 0; // table width > total width - scroller_width -> horizontal scroller is found
var st = document.getElementById('width_status');
if (st) st.innerHTML = 'minWdith: '+this.MinWidth+' minHeight: '+this.MinHeight+' w: '+w+' h: '+h+' scroll_w: '+scroller_width+' scroll_h: '+scroller_height;
// alert('scroller W x H = '+scroller_width+' x '+scroller_height);
// alert('resize: '+w+'x'+h)
this.Table.style.width = (w-scroller_width) + 'px';
this.Div.parentNode.style.width = w + 'px';
this.Div.style.width = (w-scroller_width) + 'px';
this.Div.parentNode.style.height = h + 'px';
var count = this.Controls.length;
// -count here is adjustment - 1px for each control
var split = h /*- (count * 2)*/ - this.MinHeight + this.MinControlsHeight;
if (split < this.MinControlsHeight) {
split = this.MinControlsHeight;
}
this.ResetHeights();
var used = this.SetMinHeights();
split -= used;
var cur_diff = 0;
var iterations = 0;
do {
var prev_diff = cur_diff;
var cur_diff = this.SplitExtra(split);
split = cur_diff;
iterations++;
} while (cur_diff != 0 && cur_diff != prev_diff && iterations < 10);
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
document.getElementById(this.Controls[i]).style.height = this.Options[ this.Controls[i] ]['real_height'] + 'px';
// document.getElementById(this.Controls[i]).value = this.Options[this.Controls[i]]['real_height'];
}
// alert('h is: '+h+' min height is '+this.MinHeight+' MinControlsHeight is '+this.MinControlsHeight+' -> '+split+' to split between '+count);
// print_pre(this.Controls)
IterateUploaders('syncBrowseButton');
}
Form.ResetHeights = function()
{
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
var options = this.Options[this.Controls[i]]
options['real_height'] = 0;
options.fixed = false;
}
this.FlexibleCount = this.Controls.length;
}
// Enlarge heights when possible
// Return any not split pixels number
Form.SplitExtra = function(split) {
var number = 0;
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
var options = this.Options[ this.Controls[i] ];
if (options['max_height'] == 0 || options['real_height'] < options.max_height) {
number++;
}
}
if (number == 0) {
return 0;
}
var delta = Math.floor(split / number);
// alert('splitting '+split+' between '+number+' delta is '+delta)
var added = 0;
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
var options = this.Options[this.Controls[i]];
var to_add;
if (options['max_height'] != 0 && options['real_height'] + delta > options['max_height']) {
to_add = options['max_height'] - options['real_height'];
}
else {
to_add = delta;
}
// alert('delta: '+delta+' current real: '+options['real_height']+' min: '+options['min_height']+' max:'+options['max_height']+' to_add: '+to_add)
options['real_height'] = options['real_height'] + to_add;
added += to_add;
}
// alert('added total '+added)
// removing extra added from the last (any) control
if (added > split) {
extra = added - split;
options['real_height'] -= extra;
added -= extra;
}
return split - added;
}
Form.SetMinHeights = function()
{
var used = 0;
- for (var i in this.Controls) {
+ for (var i = 0; i < this.Controls.length; i++) {
var options = this.Options[this.Controls[i]]
if (options['real_height'] < options['min_height']) {
options['real_height'] = options.min_height;
used += options.min_height;
}
}
return used;
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/form_controls.js
===================================================================
--- branches/RC/core/admin_templates/js/form_controls.js (revision 11931)
+++ branches/RC/core/admin_templates/js/form_controls.js (revision 11932)
@@ -1,540 +1,540 @@
function MultiInputControl($field_name, $field_mask, $field_labels, $result_mask) {
this.FieldName = $field_name;
this.ValidateURL = '';
this.FieldMask = $field_mask;
this.FieldLabels = $field_labels;
this.ResultMask = $result_mask; // format of record in list
this.Permissions = new Array (); // action groups allowed
this.Messages = new Array (); // various phrase (errors, confirmations, button titles)
- this.Controls = new Array (); // controls used for editing list content
+ this.Controls = {}; // controls used for editing list content
this.Records = new Array (); // data to be submitted (needs to be parsed using formatters)
- this.Errors = new Array (); // error messages in fields
+ this.Errors = {}; // error messages in fields
this.InEditing = false;
}
MultiInputControl.prototype.registerControl = function($field_name, $type, $required, $options) {
this.Controls[$field_name] = {'type' : $type, 'required' : $required, 'options' : $options};
}
MultiInputControl.prototype.getControl = function ($field, $appendix, $prepend) {
$appendix = isset($appendix) ? '_' + $appendix : '';
$prepend = isset($prepend) ? $prepend + '_' : '';
return document.getElementById( $prepend + this.FieldMask.replace('#FIELD_NAME#', $field) + $appendix );
}
MultiInputControl.prototype.getControlValue = function ($field) {
var $value = '';
switch (this.Controls[$field]['type']) {
case 'select':
var $control = this.getControl($field);
$value = $control.options[$control.selectedIndex].value;
break;
/*case 'datetime':
$value = this.getControl($field + '_date').value + ' ' + this.getControl($field + '_time').value;
break;*/
default:
$value = this.getControl($field).value;
break;
}
return $value;
}
MultiInputControl.prototype.setControlValue = function ($field, $value) {
switch (this.Controls[$field]['type']) {
case 'select':
var $i = 0;
var $control = this.getControl($field);
if ($value === null) {
$control.selectedIndex = 0;
}
while ($i < $control.options.length) {
if ($control.options[$i].value == $value) {
$control.selectedIndex = $i;
break;
}
$i++;
}
break;
case 'checkbox':
this.getControl($field).value = ($value === null) ? 0 : $value;
this.getControl($field, null, '_cb').checked = parseInt($value) == 1;
break;
/*case 'datetime':
$value = $value.split(' ');
this.getControl($field + '_date').value = $value[0];
this.getControl($field + '_time').value = $value[1];
break;*/
default:
this.getControl($field).value = ($value === null) ? '' : $value;
break;
}
}
MultiInputControl.prototype.formatValue = function ($field, $value) {
if (this.Controls[$field]['type'] == 'select') {
var $i = 0;
var $control = this.getControl($field);
while ($i < $control.options.length) {
if ($control.options[$i].value == $value) {
$value = $control.options[$i].innerHTML;
break;
}
$i++;
}
}
if (this.Controls[$field]['type'] == 'textbox') {
var $field_options = this.Controls[$field]['options'];
if ($field_options && parseInt($field_options.first_chars) > 0) {
$value = $value.substring(0, parseInt($field_options.first_chars));
}
}
if (this.Controls[$field]['type'] == 'checkbox') {
$value = this.Controls[$field]['options'][ parseInt($value) ];
}
return $value;
}
MultiInputControl.prototype.formatLine = function($record_index) {
var $ret = this.ResultMask;
for (var $field_name in this.Controls) {
var $value = this.Records[$record_index][$field_name];
$ret = $ret.replace('#' + $field_name + '#', this.formatValue($field_name, $value));
}
return this.htmlspecialchars($ret);
}
MultiInputControl.prototype._getRecordIndex = function ($selected_index) {
var $object = this.getControl(this.FieldName, 'minput');
if (!isset($selected_index)) {
$selected_index = $object.selectedIndex;
}
return $selected_index == -1 ? -1 : $object.options[$selected_index].value;
}
MultiInputControl.prototype.makeRequest = function($request_type, $record, $skip_index) {
var $url = this.ValidateURL;
for (var $field_name in $record) {
$url += '&' + this.FieldMask.replace('#FIELD_NAME#', $field_name) + '=' + escape($record[$field_name]);
}
Request.makeRequest($url, this.BusyRequest, '', this.successCallback, this.errorCallback, [$request_type, $record, $skip_index], this);
}
MultiInputControl.prototype.AddRecord = function() {
var $record = this.prepareRecord();
if (this.InEditing) {
// already in editing
var $record_index = this.getControl(this.FieldName, 'minput').selectedIndex;
this.makeRequest('SaveRecord', $record, $record_index);
return ;
}
if (this.hasPermission('add')) {
this.makeRequest('AddRecord', $record, false);
}
}
MultiInputControl.prototype.EditRecord = function() {
var $record_index = this._getRecordIndex(); // this.getControl(this.FieldName, 'minput').selectedIndex;
if ($record_index == -1 || this.InEditing) {
// no record selected
return ;
}
this.InEditing = true;
var $edit_record = this.Records[$record_index];
for (var $field_name in $edit_record) {
this.setControlValue($field_name, $edit_record[$field_name]);
}
this.getControl(this.FieldName, 'add_button').value = this.Messages['save_button'];
this.getControl(this.FieldName, 'minput').disabled = true;
this.SetButtonState('edit', false);
this.SetButtonState('delete', false);
}
MultiInputControl.prototype.ResetControls = function() {
for (var $field_name in this.Controls) {
this.setControlValue($field_name, null);
}
- this.Errors = new Array ();
+ this.Errors = {};
}
MultiInputControl.prototype.CancelEditing = function() {
this.ResetControls();
this.getControl(this.FieldName, 'add_button').value = this.Messages['add_button'];
this.getControl(this.FieldName, 'minput').disabled = false;
this.SetButtonState('edit', true);
this.SetButtonState('delete', true);
this.InEditing = false;
}
MultiInputControl.prototype.ShowRecord = function($option_index) {
var $options = this.getControl(this.FieldName, 'minput').options;
if ($option_index < $options.length) {
// update existing record
$options[$option_index].innerHTML = this.formatLine( this._getRecordIndex($option_index) );
}
else {
// create new record
var $new_option = document.createElement('OPTION');
$options.add($new_option, $options.length);
$new_option.value = $option_index; // will be used in move up/down & sorting (if any)
$new_option.innerHTML = this.formatLine(this.Records.length - 1);
}
}
MultiInputControl.prototype.DeleteRecords = function() {
if (!confirm(this.Messages['delete_confirm'])) {
return ;
}
var $control = this.getControl(this.FieldName, 'minput');
var $i = $control.length - 1;
while ($i >= 0) {
if ($control.options[$i].selected == true) {
this.Records[$control.options[$i].value] = null; // preserves index, when removing element from middle of array. this.Records.splice($control.options[$i].value, 1);
$control.remove($i);
}
$i--;
}
this.SaveValues();
}
MultiInputControl.prototype.MoveRecordsUp = function() {
move_options_up(this.getControl(this.FieldName, 'minput'), 1);
this.SaveValues();
}
MultiInputControl.prototype.MoveRecordsDown = function() {
move_options_down(this.getControl(this.FieldName, 'minput'), 1);
this.SaveValues();
}
MultiInputControl.prototype.AddFromXML = function($xml) {
var $document = getDocumentFromXML($xml);
this.ProcessXMLNode($document);
}
MultiInputControl.prototype.ProcessXMLNode = function($node, $root_name) {
for (var $i = 0; $i < $node.childNodes.length; $i++) {
var $child = $node.childNodes.item($i);
if ($child.tagName == 'record') {
this.Records[this.Records.length] = new Array ();
this.ProcessXMLNode($child, $root_name);
this.ShowRecord(this.Records.length - 1);
}
else if ($child.tagName == 'field') {
if ($root_name == 'records') {
// no firstChild, when node value is empty!
this.Records[this.Records.length - 1][$child.getAttribute('name')] = $child.firstChild ? $child.firstChild.nodeValue : '';
}
else if ($root_name == 'errors') {
this.Errors[$child.getAttribute('name')] = $child.firstChild.nodeValue;
}
}
else if ($child.tagName == 'records') {
this.ProcessXMLNode($child, $child.tagName);
}
else if ($child.tagName == 'errors') {
- this.Errors = new Array ();
+ this.Errors = {};
this.ProcessXMLNode($child, $child.tagName);
}
}
}
MultiInputControl.prototype.LoadValues = function() {
var $current_value = this.getControl(this.FieldName).value;
if ($current_value) {
this.AddFromXML($current_value);
}
}
MultiInputControl.prototype.SaveValues = function() {
var $object = this.getControl(this.FieldName, 'minput');
var $record_index = 0;
var $xml = '';
var $i = 0;
while ($i < $object.options.length) {
$record_index = $object.options[$i].value;
$xml += '<record>';
for (var $field_name in this.Controls) {
$xml += '<field name="' + $field_name + '">' + this.htmlspecialchars(this.Records[$record_index][$field_name]) + '</field>';
}
$xml += '</record>';
$i++;
}
this.getControl(this.FieldName).value = $xml ? '<records>' + $xml + '</records>' : '';
}
MultiInputControl.prototype.htmlspecialchars = function (string) {
string = string.toString();
string = string.replace(/&/g, '&amp;');
string = string.replace(/</g, '&lt;');
string = string.replace(/>/g, '&gt;');
string = string.replace(/\"/g, '&quot;');
return string;
}
MultiInputControl.prototype.prepareRecord = function() {
- var $record = new Array ();
+ var $record = {};
for (var $field_name in this.Controls) {
$record[$field_name] = this.getControlValue($field_name);
}
return $record;
}
MultiInputControl.prototype.ValidateRecord = function($record, $skip_index) {
var $valid = true;
$valid = $valid && this.ValidateRequired($record);
$valid = $valid && this.ValidateUnique($record, $skip_index);
return $valid;
}
MultiInputControl.prototype.ValidateRequired = function($record) {
for (var $field_name in $record) {
if (this.Controls[$field_name]['required'] && !$record[$field_name]) {
alert(this.Messages['required_error']);
return false;
}
}
return true;
}
MultiInputControl.prototype.compareRecords = function($record_a, $record_b) {
var $equals = true;
for (var $field_name in $record_a) {
if ($record_a[$field_name] !== $record_b[$field_name]) {
return false;
}
}
return $equals;
}
MultiInputControl.prototype.ValidateUnique = function($record, $skip_index) {
var $i = 0;
if (!isset($skip_index)) {
$skip_index = -1;
}
while ($i < this.Records.length) {
if (this.Records[$i] == null) {
// skip deleted records
$i++;
continue;
}
if ($i != $skip_index && this.compareRecords($record, this.Records[$i])) {
alert(this.Messages['unique_error']);
return false;
}
$i++;
}
return true;
}
MultiInputControl.prototype.displayErrors = function() {
var $has_errors = false;
var $field_label = '';
for (var $field_name in this.Errors) {
$has_errors = true;
alert(this.FieldLabels[$field_name] + ': ' + this.Errors[$field_name]);
}
return $has_errors;
}
MultiInputControl.prototype.successCallback = function($request, $params, $object) {
if (Request.processRedirect($request) === true) {
return ;
}
var $document = getDocumentFromXML($request.responseText);
$object.ProcessXMLNode($document);
if ($object.displayErrors()) {
return ;
}
// params: 0 - action type, 1 - record data, 2 - option index
switch ($params[0]) {
case 'AddRecord':
if (!$object.ValidateRecord($params[1])) {
return ;
}
$object.Records.push($params[1]);
$object.ShowRecord($object.Records.length - 1);
$object.ResetControls();
break;
case 'SaveRecord':
$record_index = $object._getRecordIndex($params[2]);
if (!$object.ValidateRecord($params[1], $record_index)) {
return ;
}
$object.Records[$record_index] = $params[1];
$object.ShowRecord($params[2]);
$object.CancelEditing();
break;
}
$object.SaveValues();
}
MultiInputControl.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX Error; class: MultiInputControl; ' + Request.getErrorHtml($request));
}
MultiInputControl.prototype.SetMessage = function($pseudo, $message) {
this.Messages[$pseudo] = $message;
}
MultiInputControl.prototype.InitEvents = function() {
var $button = null;
var $var_name = this.FieldName;
$button = this.getControl(this.FieldName, 'add_button');
$button.onclick = function() { eval($var_name).AddRecord() };
if (this.hasPermission('add') || this.hasPermission('edit')) {
$button = this.getControl(this.FieldName, 'cancel_button');
$button.onclick = function() { eval($var_name).CancelEditing() };
}
if (this.hasPermission('edit')) {
$button = this.getControl(this.FieldName, 'edit_button');
$button.onclick = function() { eval($var_name).EditRecord() };
$button = this.getControl(this.FieldName, 'minput');
$button.ondblclick = function() { eval($var_name).EditRecord() };
}
if (this.hasPermission('delete')) {
$button = this.getControl(this.FieldName, 'delete_button');
$button.onclick = function() { eval($var_name).DeleteRecords() };
}
if (this.hasPermission('move')) {
$button = this.getControl(this.FieldName, 'moveup_button');
$button.onclick = function() { eval($var_name).MoveRecordsUp() };
$button = this.getControl(this.FieldName, 'movedown_button');
$button.onclick = function() { eval($var_name).MoveRecordsDown() };
}
}
MultiInputControl.prototype.hasPermission = function ($perm_name) {
return in_array($perm_name, this.Permissions);
}
MultiInputControl.prototype.SetPermission = function ($perm_name, $perm_value) {
var $perm_index = array_search($perm_name, this.Permissions);
if ($perm_index != -1) {
// permission found
if (!$perm_value) {
this.Permissions = this.Permissions.splice($perm_index, 1);
}
}
else if ($perm_value) {
// permission not found
this.Permissions.push($perm_name);
}
}
MultiInputControl.prototype.SetButtonState = function ($button, $mode) {
if (!this.hasPermission($button)) {
return ;
}
var $button = this.getControl(this.FieldName, $button + '_button');
$button.disabled = !$mode;
$button.className = $mode ? 'button' : 'button-disabled';
}
// =======================================================================================
function EditPickerControl($field_name, $field_mask) {
this.FieldName = $field_name;
this.FieldMask = $field_mask;
this.Messages = new Array ();
this.InitEvents();
select_sort( this.getControl('available') );
}
EditPickerControl.prototype.getControl = function ($type) {
var $control_id = this.FieldMask + (isset($type) ? '_' + $type : '');
return document.getElementById($control_id);
}
EditPickerControl.prototype.SetMessage = function ($pseudo, $message) {
this.Messages[$pseudo] = $message;
}
EditPickerControl.prototype.SaveValues = function () {
this.getControl().value = select_to_string(this.getControl('selected'));
this.getControl('available_field').value = select_to_string(this.getControl('available'));
}
EditPickerControl.prototype.MoveLeft = function () {
move_selected(this.getControl('available'), this.getControl('selected'), this.Messages['nothing_selected']);
this.SaveValues();
}
EditPickerControl.prototype.MoveRight = function () {
move_selected(this.getControl('selected'), this.getControl('available'), this.Messages['nothing_selected']);
select_sort( this.getControl('available') );
this.SaveValues();
}
EditPickerControl.prototype.InitEvents = function() {
var $button = null;
var $var_name = this.FieldName;
$button = this.getControl('move_left_button');
$button.onclick = function() { eval($var_name).MoveLeft() };
$button = this.getControl('move_right_button');
$button.onclick = function() { eval($var_name).MoveRight() };
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/grid_scroller.js
===================================================================
--- branches/RC/core/admin_templates/js/grid_scroller.js (revision 11931)
+++ branches/RC/core/admin_templates/js/grid_scroller.js (revision 11932)
@@ -1,1220 +1,1220 @@
var sheetRules; // all rules in stylesheet Set by initStyleChange()
var currentRule; // which rule are we editing? Set by assignRule()
var defaultStyles = new Array();
function StyleManager() {}
StyleManager.InitStyles = function() {
if (!document.styleSheets) return;
var sheets = document.styleSheets;
this.Map = new Object();
// alert('total '+sheets.length+' sheets')
for (var i=0;i<sheets.length;i++) {
var currentSheet = sheets[i];
if (currentSheet.cssRules)
sheetRules = currentSheet.cssRules
else if (currentSheet.rules)
sheetRules = currentSheet.rules;
else {
// alert('bad sheet '+currentSheet.href);
continue;
}
// alert('sheet: '+currentSheet.href)
for (var ii=0;ii<sheetRules.length;ii++) {
var value = sheetRules[ii].selectorText;
if (value.match(',')) { // Mozilla does not break comma-separated selectors into separate rules...
var subselectors = value.split(',');
- for (var sub in subselectors) {
+ for (var sub = 0; sub < subselectors.length; sub++) {
var real_name = subselectors[sub].replace(/^[ \t]*(.*)[ \t]*/, '$1');
this.Map[real_name] = sheetRules[ii]
}
}
else {
this.Map[value.toLowerCase()] = sheetRules[ii];
}
}
}
this.Inited = true;
// preg_print_pre(this.Map, /last/);
}
StyleManager.ChangeStyle = function(selector, s, value)
{
if (!this.Inited) this.InitStyles()
rule = this.Map[selector.toLowerCase()];
if (!rule) {
if (this.AddStyle(selector, s, value)) {
return true;
}
alert('rule '+selector+' not found')
return;
}
alert('adjusting rule '+selector+' setting '+s+' to '+value+' from '+rule.style[s])
rule.style[s] = value;
alert('now it is '+rule.style[s])
}
StyleManager.AddStyle = function(selector, style, value)
{
var sheet = document.styleSheets[0];
var rule = false;
if (sheet.insertRule) {
sheet.insertRule(selector+'{'+style+':'+value+'}', sheet.cssRules.length);
rule = sheet.cssRules[sheet.cssRules.length-1];
}
else if(sheet.addRule) {
sheet.addRule(selector, style+':'+value);
rule = sheet.rules[sheet.rules.length-1];
}
if (rule) {
alert ('adding rule as '+selector);
this.Map[selector.toLowerCase()] = sheet.cssRules[sheet.cssRules.length-1];
return true;
}
return false;
}
StyleManager.GetStyle = function(selector)
{
if (!this.Inited) this.InitStyles()
rule = this.Map[selector.toLowerCase()];
if (!rule) return false;
return rule;
}
StyleManager.GetStyleValue = function(selector, style)
{
rule = this.GetStyle(selector);
if (!rule) return false;
return rule.selector;
}
function preg_print_pre(obj, reg)
{
if (!reg) reg = /.*/;
var p = ''
for (var prop in obj) {
if (prop.match(reg) ) {
p += prop + ': '+obj[prop] + '\n'
}
}
alert(p)
}
var startTime,endTime;
var profile = 0;
var profile_total = 0;
var startTime = new Date().getTime();
function Profile(message,force)
{
if (profile || force) {
endTime = new Date().getTime();
var tmp = (endTime-startTime);
profile_total += tmp;
alert(message+' took '+tmp+' ms of '+profile_total)
startTime = new Date().getTime();
}
}
function ResetStart()
{
startTime = new Date().getTime();
profile_total = 0;
}
function GridScroller(grid_id, w, h)
{
this.GridId = grid_id
this.Footer = false;
this.LeftCells = 0;
this.LeftWidth = 0;
this.BottomOffset = 0;
this.Width = w;
this.Height = h;
this.MaxHeight = h; // maximal grid height from constructor (also save here, because this.Height will be changed after Resize method call)
this.AutoWidth = true;
this.ScrollerW = 0;
this.ScrollerH = 0;
this.MinWidths = [];
this.IDs = [];
this.Rendered = false;
this.PickerCRC = '';
this.MaxHeaderHeights = [50,30];
this.MaxRowHeight = 45;
this.Html = ''; // html from last grid rendering
}
GridScroller.prototype._getMeasureHtml = function() {
return '<div id="my_measure_'+this.GridId+'" style="width: auto; height: 0px; z-index: -105;"></div>';
}
GridScroller.prototype._prepareHtml = function($container) {
if (typeof($container) == 'undefined') {
var dot = this._getMeasureHtml();
// console.log('dot without container');
document.write(dot);
}
else {
// console.log('dot inside container');
var dot = document.createElement('div');
dot.id = 'my_measure_'+this.GridId;
dot.style.width = 'auto';
dot.style.height = '0px';
dot.style.zIndex = '-105';
document.getElementById($container).appendChild(dot);
}
var dot = document.getElementById('my_measure_'+this.GridId);
var measure = document.getElementById('my_measure_'+this.GridId);
this.pos = findPos(dot);
// alert('dot: '+this.pos[0]+','+this.pos[1])
var collapse_correction = this._getCollapseCorrection();
if (is.ie) this.pos[0] += 1;
// this.MainOuter.style.width = 'auto'
var w = measure.offsetWidth;
var h = document.body.clientHeight;
var dim = getDimensions(measure);
h -= this.pos[1] + dim.padding[0] + dim.padding[2] + dim.borders[0] + dim.borders[2] + this.BottomOffset;
var $html = this.AltHTML(this.pos[0],this.pos[1], w, h);
return $html;
}
GridScroller.prototype._getCollapseCorrection = function() {
return is.ie ? 0 : -1;
}
GridScroller.prototype.Render = function(id)
{
Application.removeDebuggerStatistics();
ResetStart();
// var widths = this.PrepareWidths();
// this.MinWidths = [40,null,null,250]
this.MinWidths = this.PrepareWidths(); // [50,70,90,150,150,110,70,111];
document.body.style.height = '100%';
document.body.style.overflow = 'hidden';
document.body.scroll = 'no';
// this.Html = this.AltHTML();
// Profile('Getting HTML',1);
// console.log('GridScroller.Render(', id, ')');
if (id && id != '') {
// console.log('id given');
if (this.Html.length == 0) {
// 1st render and inside container -> prepare html
// console.log('1st render and no html');
this.Html = this._prepareHtml(id);
var collapse_correction = this._getCollapseCorrection();
// direct innerHTML assignment results empty line (15px height) to be added before
// container when grid data is set from ajax responce (like in catalog) in IE, so
// use jQuery here
// document.getElementById(id).innerHTML = this._getMeasureHtml() + '<div id="main_div_'+this.GridId+'" style="margin-left: '+collapse_correction+'px">'+this.Html+'</div>';
$( jq('#' + id) ).html( this._getMeasureHtml() + '<div id="main_div_'+this.GridId+'" style="margin-left: '+collapse_correction+'px">'+this.Html+'</div>' );
}
else {
// direct innerHTML assignment results empty line (15px height) to be added before
// container when grid data is set from ajax responce (like in catalog) in IE, so
// use jQuery here
// document.getElementById(id).innerHTML = '<div id="main_div_'+this.GridId+'">'+this.Html+'</div>';
$( jq('#' + id) ).html( '<div id="main_div_'+this.GridId+'">'+this.Html+'</div>' );
}
// execJS(document.getElementById(id));
}
else {
// console.log('id not given');
if (this.Rendered) {
// console.log('rendering inside container');
this.Render('main_div_'+this.GridId);
return;
}
// console.log('just rendering');
this.Html = this._prepareHtml();
var collapse_correction = this._getCollapseCorrection();
document.write('<div id="main_div_'+this.GridId+'" style="margin-left: '+collapse_correction+'px">'+this.Html+'</div>');
}
this.Rendered = true;
// Profile('Main render & refs',1)
this.SetReferences();
// return;
if (getFrame('head').ScrollerW) {
this.ScrollerW = getFrame('head').ScrollerW;
this.ScrollerH = getFrame('head').ScrollerH;
}
else {
this.ScrollerW = 17;
this.ScrollerH = 17;
/*this.ScrollerW = this.MainInner.offsetWidth - this.MainInner.clientWidth
this.ScrollerH = this.MainInner.offsetHeight - this.MainInner.clientHeight
getFrame('head').ScrollerW = this.ScrollerW
getFrame('head').ScrollerH = this.ScrollerH*/
}
// Profile('Up to col widths',1);
if (!this.UpdateColWidths()) return;
if (this.Width == 'auto') {
this.Resize( this.GetAutoSize(this.Height) );
}
else {
this.Resize();
}
this.AdjustInputWidths();
this.TheGrid.style.visibility = 'visible'
this.MainScroller.style.visibility = 'visible'
// Profile('Finalizng', 1);
var the_grid = this;
if (document.all) {
$status = window.attachEvent('onresize', function(ev) { the_grid.AutoResize() });
} else {
$status = window.addEventListener('resize', function(ev) { the_grid.AutoResize() }, true);
}
if (document.all) {
this.DataScroller.onmousewheel = function(ev) {
var e = document.all ? window.event : ev;
this.TheGrid.MainInner.scrollTop += -e.wheelDelta/2
this.TheGrid.SyncScroll();
}
if (this.LeftCells > 0) {
this.LeftDataInner.onmousewheel = function(ev) {
var e = document.all ? window.event : ev;
this.TheGrid.MainInner.scrollTop += -e.wheelDelta/2
this.TheGrid.SyncScroll();
}
}
}
else {
this.DataScroller.addEventListener("DOMMouseScroll", function(ev) {
var e = document.all ? window.event : ev;
this.TheGrid.MainInner.scrollTop += e.detail*10
this.TheGrid.SyncScroll();
}, false);
if (this.LeftCells > 0) {
this.LeftDataInner.addEventListener("DOMMouseScroll", function(ev) {
var e = document.all ? window.event : ev;
this.TheGrid.MainInner.scrollTop += e.detail*10
this.TheGrid.SyncScroll();
}, false);
}
}
addLoadEvent(
function() {
the_grid.RefreshPos();
the_grid.AutoResize();
the_grid.SetResizeHandles();
}
);
}
GridScroller.prototype.SetReferences = function() {
this.MainOuter = document.getElementById('outer_main_'+this.GridId );
this.MainInner = document.getElementById('inner_main_'+this.GridId)
this.MainScroller = document.getElementById('main_scroller_'+this.GridId)
this.TheGrid = document.getElementById(this.GridId );
this.HeadTable = document.getElementById('header_'+this.GridId);
this.HeadScroller = document.getElementById('inner_header_'+this.GridId);
this.HeadOuter = document.getElementById('outer_header_'+this.GridId);
this.DataTable = document.getElementById('data_'+this.GridId);
this.DataScroller = document.getElementById('inner_data_'+this.GridId);
this.DataOuter = document.getElementById('outer_data_'+this.GridId);
if (this.HasFooter) {
this.FooterTable = document.getElementById('footer_'+this.GridId);
this.FooterScroller = document.getElementById('inner_footer_'+this.GridId);
this.FooterOuter = document.getElementById('outer_footer_'+this.GridId);
}
if (this.LeftCells != 0) {
this.LeftHeaderTable = document.getElementById('left_header_'+this.GridId);
this.LeftHeaderScroller = document.getElementById('inner_left_header_'+this.GridId);
this.LeftHeaderOuter = document.getElementById('outer_left_header_'+this.GridId);
this.LeftHeaderInner = document.getElementById('inner_left_header_'+this.GridId);
this.LeftDataTable = document.getElementById('left_data_'+this.GridId);
this.LeftDataOuter = document.getElementById('outer_left_data_'+this.GridId);
this.LeftDataInner = document.getElementById('inner_left_data_'+this.GridId);
if (this.HasFooter) {
this.LeftFooterTable = document.getElementById('left_footer_'+this.GridId);
this.LeftFooterInner = document.getElementById('inner_left_footer_'+this.GridId);
this.LeftFooterOuter = document.getElementById('outer_left_footer_'+this.GridId);
}
}
this.DataScroller.TheGrid = this;
this.MainInner.TheGrid = this;
if (this.LeftCells > 0) this.LeftDataInner.TheGrid = this;
// this.Dot = document.getElementById('my_dot_'+this.GridId)
this.MainOuter.className = 'grid-scrollable'
if (!is.ie) {
// this.MainOuter.style.marginLeft = '-1px';
}
}
GridScroller.prototype.SetLeftHeights = function() {
if (this.LeftCells != 0) {
this.SetHeights('left_header_'+this.GridId, 'header_'+this.GridId);
this.SetHeights('left_data_'+this.GridId, 'data_'+this.GridId);
if (this.HasFooter()) {
this.SetHeights('left_footer_'+this.GridId, 'footer_'+this.GridId);
}
}
}
GridScroller.prototype.UpdateColWidths = function() {
// pos = findPos(this.Dot)
pos = this.pos;
this.TheGrid.style.left = (pos[0])+ 'px'
this.TheGrid.style.top = (pos[1]) + 'px'
this.SetLeftHeights();
if (this.HasFooter()) {
this.FooterHeight = this.FooterTable.offsetHeight;
this.FooterOuter.style.height = this.FooterHeight + 'px'
}
else {
this.FooterHeight = 0;
}
this.HeadHeight = this.HeadTable.offsetHeight;
// console.log('measured Head Height: '+this.HeadHeight);
this.DataHeight = this.DataTable.offsetHeight;
this.HeadOuter.style.height = (this.HeadHeight) + 'px'
if (this.LeftCells != 0) {
this.LeftWidth = Math.max(this.LeftHeaderTable.offsetWidth, this.LeftDataTable.offsetWidth)
this.LeftHeaderOuter.style.height = (this.HeadHeight) + 'px'
if (this.HasFooter()) {
this.LeftFooterOuter.style.height = (this.FooterHeight) + 'px'
this.LeftWidth = Math.max(this.LeftWidth, this.LeftFooterTable.offsetWidth);
}
// console.log('measured Left Width: '+this.LeftWidth);
}
this.MainInner.onscroll = function() {
this.TheGrid.SyncScroll()
}
this.MainOuter.style.width = 'auto'
this.UpdateTotalDimensions();
return true;
}
GridScroller.prototype.UpdateTotalDimensions = function()
{
this.HeadHeight = this.HeadTable.offsetHeight;
this.DataHeight = this.DataTable.offsetHeight;
this.HeaderWidth = this.HeadTable.offsetWidth + this.LeftWidth - this.HeadTable.rows[0].cells[(this.HeadTable.rows[0].cells.length-1)].offsetWidth;
this.DataTotalHeight = this.DataHeight + this.HeadHeight + this.FooterHeight;
}
GridScroller.prototype.ResetHeights = function(table1_id, table2_id)
{
var table1 = document.getElementById(table1_id);
var table2 = document.getElementById(table2_id);
var height1_div, height2_div;
for (var row=0; row<table1.rows.length; row++)
{
// reseting heights
table1.rows[row].cells[0].style.height = 'auto';
table2.rows[row].cells[0].style.height = 'auto';
table1.rows[row].style.height = 'auto';
table2.rows[row].style.height = 'auto';
var height1_div = document.getElementById(table1_id+'_left_height_'+row);
if (height1_div) {
height1_div.style.height = 'auto';
}
var height2_div = document.getElementById(table2_id+'_left_height_'+row);
if (height2_div) {
height2_div.style.height = 'auto';
}
}
}
GridScroller.prototype.SetHeights = function(table1_id, table2_id)
{
var table1 = document.getElementById(table1_id);
var table2 = document.getElementById(table2_id);
var height1_div, height2_div;
this.ResetHeights(table1_id, table2_id);
var heights1 = this.GetHeights(table1_id);
var heights2 = this.GetHeights(table2_id);
var table, the_height, num;
for (var row=0; row<table1.rows.length; row++)
{
if (heights1[row] > heights2[row])
{
the_height = heights1[row];
table = table2;
id = table2_id;
}
else {
the_height = heights2[row];
table = table1;
id = table1_id;
}
var height_div = document.getElementById(id+'_left_height_'+row);
if (height_div) { // the div only exists for FF
height_div.style.height = the_height+'px';
height_div.style.width = table.rows[row].cells[0].clientWidth+'px'
}
else {
if (!is.ie) { // firefox needs div, but it can display it as table-cell
var width = table.rows[row].cells[0].clientWidth;
// table.rows[row].cells[0].innerHTML = '<div id="'+id+'_left_height_'+row+'" style="display: table-cell; background-color: inherit; width: '+width+'px; height: '+(the_height) +'px; overflow: hidden;">' + table.rows[row].cells[0].innerHTML + '</div>'
}
}
// IE can't display div as table-cell, but it respects the tr height
table.rows[row].cells[0].style.height = the_height+'px';
table.rows[row].style.height = the_height+'px';
}
}
GridScroller.prototype.GetHeights = function(table_id)
{
var table = document.getElementById(table_id);
var heights = new Array();
var height
for (var row=0; row<table.rows.length; row++)
{
var dim = getDimensions( table.rows[row].cells[0] );
height = dim.innerHeight + (is.ie ? 0 : dim.padding[0] + dim.padding[2] + dim.borders[0] + dim.borders[2]);
heights.push( height )
// alert('get ('+row+')'+table.rows[row].cells[0].innerHTML+' height (offset/client/computed (coorection)): '+table.rows[row].cells[0].offsetHeight + '/' + table.rows[row].cells[0].clientHeight + '/ ' +height + ' ('+correction+')')
}
return heights;
}
GridScroller.prototype.GetWidths = function(table_id)
{
var table = document.getElementById(table_id);
var widths = new Array();
if (!table.rows[0]) return [];
for (var col=0; col<table.rows[0].cells.length; col++)
{
var tmp = getDimensions(table.rows[0].cells[col]);
widths.push( tmp.innerWidth )
// widths.push( table.rows[0].cells[col].offsetWidth )
if (table_id.match(/^header_/)) {
// alert('get ('+col+')'+table.rows[0].cells[col].innerHTML+' width '+table.rows[0].cells[col].offsetWidth)
}
}
return widths;
}
GridScroller.prototype.SetResizeHandles = function()
{
var points = new Array();
if (this.LeftCells > 0) {
var table = this.LeftHeaderTable;
var points = new Array();
if (!table.rows[0]) return [];
for (var col=0; col<table.rows[0].cells.length; col++)
{
var tmp = findPos(table.rows[0].cells[col]);
points.push(tmp);
}
}
var table = this.HeadTable;
if (!table.rows[0]) return [];
for (var col=0; col<table.rows[0].cells.length; col++)
{
var tmp = findPos(table.rows[0].cells[col]);
points.push(tmp);
}
var scroller = this;
var resize_bar = document.getElementById(this.GridId + '[resize_bar]');
if (!resize_bar) {
resize_bar = addElement(document.body, 'div');
resize_bar.id = this.GridId + '[resize_bar]';
}
resize_bar.style.display = 'none';
resize_bar.style.width = '2px';
resize_bar.style.height = '200px';
resize_bar.style.backgroundColor = '#777';
resize_bar.style.zIndex = 40;
resize_bar.style.position = 'absolute';
for (var i=1; i<points.length; i++) {
var handle = document.getElementById(this.GridId + '[grid_resize_handle_' + i + ']');
if (!handle) {
handle = addElement(document.body, 'div');
handle.id = this.GridId + '[grid_resize_handle_' + i + ']';
}
handle.style.width='6px';
handle.style.height=this.HeadTable.offsetHeight+'px';
handle.style.position='absolute';
// handle.style.backgroundColor='red';
handle.style.left = (points[i][0] - 3)+'px';
handle.style.top = points[i][1]+'px';
handle.style.zIndex = 50;
handle.style.cursor = 'col-resize';
handle.col_num = i-1;
DragManager.MakeDragable(this.GridId + '[grid_resize_handle_' + i + ']',
function(a_handle) {
var resize_bar = document.getElementById(scroller.GridId + '[resize_bar]');
var pos = findPos(a_handle);
resize_bar.style.left = (pos[0])+'px';
resize_bar.style.top = pos[1]+'px';
resize_bar.style.height = scroller.Height+'px';
resize_bar.style.display = 'block';
var col_num = a_handle.col_num;
DragManager.DragObject.min_col_width = scroller.GetColWidth(col_num);
},
function(drag_object, coords) {
var offset = coords.x - DragManager.MouseOffset[0] - DragManager.InitialPos[0];
if (parseInt(DragManager.DragObject.min_col_width) + offset > 15) {
var resize_bar = document.getElementById(scroller.GridId + '[resize_bar]');
resize_bar.style.left = (coords.x - DragManager.MouseOffset[0] + 2) + 'px';
}
},
function(a_handle) {
var resize_bar = document.getElementById(scroller.GridId + '[resize_bar]');
resize_bar.style.display = 'none';
coords = findPos(a_handle);
var offset = (coords[0] - DragManager.InitialPos[0]);
// alert('offset: '+offset+' ('+coords[0]+' - '+DragManager.MouseOffset[0]+' - '+DragManager.InitialPos[0]+')');
var col_num = a_handle.col_num;
var cur_w = scroller.GetColWidth(col_num);
if (cur_w + offset < 15) {
offset = 15-cur_w;
}
scroller.SetColWidth(col_num, cur_w+offset);
scroller.Resize( scroller.GetAutoSize() );
scroller.ScrollResizeHandles();
DragManager.InitialPos = [coords[0] - DragManager.MouseOffset[0], coords[1] - DragManager.MouseOffset[1]];
},
{VerticalDrag: false}
)
}
}
GridScroller.prototype.GetColWidth = function(col)
{
return this.MinWidths[col];
}
GridScroller.prototype.AdjustInputWidths = function()
{
var elems = new Array();
var inputs = this.HeadTable.getElementsByTagName('INPUT');
for (var i=0; i<inputs.length; i++) {elems[elems.length] = inputs[i];}
var selects = this.HeadTable.getElementsByTagName('SELECT');
for (var i=0; i<selects.length; i++) {elems[elems.length] = selects[i];}
if (this.LeftCells > 0) {
var left_inputs = this.LeftHeaderTable.getElementsByTagName('INPUT');
for (var i=0; i<left_inputs.length; i++) {elems[elems.length] = left_inputs[i];}
var left_selects = this.LeftHeaderTable.getElementsByTagName('SELECT');
for (var i=0; i<left_selects.length; i++) {elems[elems.length] = left_selects[i];}
}
var widths = new Array()
for (var i=0; i<elems.length; i++) {
elems[i].style.width = '1px';
}
for (var i=0; i<elems.length; i++) {
var input_dim = getDimensions(elems[i]);
var parent_dim = getDimensions(elems[i].parentNode);
widths[i] = (parent_dim.innerWidth - parent_dim.borders[1] - parent_dim.borders[3] - input_dim.borders[1] - input_dim.borders[3] - 2)+'px';
}
for (var i=0; i<elems.length; i++) {
try {
elems[i].style.width = widths[i];
}
catch (e) {
// IE don't allow to set width for hidden element
// alert('IE exception:' + e);
}
}
}
GridScroller.prototype.SetColWidth = function(col, width)
{
if (col >= this.LeftCells) {
if (this.DataTable.rows.length) this.DataTable.rows[0].cells[col - this.LeftCells].style.width = width+'px';
for (var row=0; row < this.HeadTable.rows.length; row++)
{
this.HeadTable.rows[row].cells[col - this.LeftCells].style.width = width+'px';
var a = document.getElementById(this.GridId + '[cursor_work_around_A_'+col+'_'+row+']');
var b = document.getElementById(this.GridId + '[cursor_work_around_B_'+col+'_'+row+']');
if (a) a.style.width = width+'px';
if (b) b.style.width = width+'px';
}
if (this.HasFooter()) {
this.FooterTable.rows[0].cells[col - this.LeftCells].style.width = width+'px';
}
}
else {
if (this.LeftDataTable.rows.length) this.LeftDataTable.rows[0].cells[col].style.width = width+'px';
for (var row=0; row < this.LeftHeaderTable.rows.length; row++)
{
this.LeftHeaderTable.rows[row].cells[col].style.width = width+'px';
var a = document.getElementById(this.GridId + '[cursor_work_around_A_'+col+'_'+row+']');
var b = document.getElementById(this.GridId + '[cursor_work_around_B_'+col+'_'+row+']');
if (a) a.style.width = width+'px';
if (b) b.style.width = width+'px';
}
if (this.HasFooter()) {
this.LeftFooterTable.rows[0].cells[col].style.width = width+'px';
}
var cur_left_total_w = 0;
var new_left_total_w = 0;
for (var i=0; i < this.LeftCells; i++) {
cur_left_total_w += this.MinWidths[i];
new_left_total_w += i==col? width : this.MinWidths[i];
};
var left_diff = this.LeftWidth - cur_left_total_w;
this.SetLeftWidth(new_left_total_w+left_diff);
}
this.AdjustInputWidths();
this.MinWidths[col] = width;
this.SetLeftHeights();
this.UpdateTotalDimensions();
this.SyncScroll();
this.ScheduleSaveWidths();
}
GridScroller.prototype.ScrollResizeHandles = function()
{
for (var col=1; col<this.LeftHeaderTable.rows[0].cells.length; col++)
{
var handle = document.getElementById(this.GridId + '[grid_resize_handle_' + col + ']');
if (!handle) return;
var pos = findPos(this.LeftHeaderTable.rows[0].cells[col]);
handle.style.left = (pos[0]-3)+'px';
}
if (this.HeadTable.rows[0].cells.length) {
var left_most_pos = findPos(this.HeadTable.rows[0].cells[0]);
var handle = document.getElementById(this.GridId + '[grid_resize_handle_' + (this.LeftCells) + ']');
if (handle) handle.style.left = (left_most_pos[0]-3)+'px';
}
for (var col=1; col<this.HeadTable.rows[0].cells.length; col++)
{
var handle = document.getElementById(this.GridId + '[grid_resize_handle_'+(col+this.LeftCells)+']');
if (!handle) continue;
var pos = findPos(this.HeadTable.rows[0].cells[col]);
var n_left = pos[0]-this.MainInner.scrollLeft-3
if (n_left <= left_most_pos[0] || n_left > left_most_pos[0] + this.DataOuter.clientWidth) {
handle.style.display = 'none'; //resize handle is outside of visible range
}
else {
handle.style.display = 'block';
}
handle.style.left = n_left+'px';
}
}
GridScroller.prototype.GetAutoSize = function(h)
{
this.MainOuter.style.width = 'auto'
var w = this.MainInner.offsetWidth;
if (!isset(h)) {
h = this.MaxHeight; // 'auto';
}
if (h == 'auto') {
var h = document.body.clientHeight;
var pos = findPos(this.MainOuter);
var dim = getDimensions(this.MainOuter);
h -= pos[1] + dim.padding[0] + dim.padding[2] + dim.borders[0] + dim.borders[2] + this.BottomOffset;
}
return [w, h];
}
GridScroller.prototype.AutoResize = function()
{
var obj = this;
if (this.ResizeHappening && this.ResizeTimer) {
window.clearTimeout(this.ResizeTimer);
this.ResizeTimer = false;
}
this.ResizeHappening = true;
this.ResizeTimer = window.setTimeout(function() {
// GridScroller sets references to it's elements after Render method is called (once).
// When grid elements are replaced from ajax responce, then all stored
// refrences are invalid (GridScroller.Render method is called after this timer is execuded).
// To prevent "Unspecified error" in IE reset all references.
obj.SetReferences();
obj.RefreshPos();
obj.Resize( obj.GetAutoSize() );
obj.ResizeHappening = false;
}, 300)
}
GridScroller.prototype.RefreshPos = function() {
var dot = document.getElementById('my_measure_'+this.GridId);
this.pos = findPos(dot);
if (is.ie) {
// measure div is moved left for 1 pixel in IE during resize (nothing strange, it's IE)
this.pos[0] += 1;
}
}
GridScroller.prototype.Resize = function(w,h)
{
// alert('-1');
if (typeof(w) == 'object') {
h = w[1];
w = w[0];
}
if (w) this.Width = w;
if (h) this.Height = h;
var x,y;
// pos = findPos(this.Dot)
pos = this.pos;
x = pos[0];
y = pos[1];
this.TheGrid.style.left = (x)+ 'px'
this.TheGrid.style.top = (y) + 'px'
// alert('moved');
// alert('0');
this.MainOuter.style.height = (this.Height)+'px'
this.MainOuter.style.width = (this.Width)+'px'
// alert('1');
var scroller_width;
// this.HeadTable.rows[0].cells[(this.HeadTable.rows[0].cells.length-1)].offsetWidth
scroller_height = this.HeaderWidth > this.Width ? this.ScrollerH : 0;
scroller_width = this.DataTotalHeight > this.Height - scroller_height ? this.ScrollerW : 0;
scroller_height = this.HeaderWidth > this.Width - scroller_width ? this.ScrollerH : 0;
// alert('min: '+this.MinDataWidth+' pos: '+pos[0]+','+pos[1]+' scroller W x H: '+scroller_width+' x '+scroller_height+' will resize to '+this.Width+' x '+this.Height+' data: '+this.HeaderWidth+' x '+this.DataHeight)
this.HeadOuter.style.width = (this.Width -scroller_width -this.LeftWidth)+ 'px';
this.DataOuter.style.width = (this.Width -scroller_width -this.LeftWidth)+ 'px';
// alert('1.2');
this.TheGrid.style.width = (this.Width - scroller_width) + 'px';
this.TheGrid.style.height = (this.Height - scroller_height) + 'px';
// alert('1.5');
this.SetLeftWidth();
// alert('2');
if (this.HasFooter()) {
this.FooterOuter.style.width = (this.Width -scroller_width -this.LeftWidth)+ 'px';
}
if (this.DataTotalHeight < this.Height - scroller_height) {
var adjusted_data_height = this.DataTotalHeight - this.HeadHeight - this.FooterHeight
}
else {
var adjusted_data_height = this.Height - this.HeadHeight - this.FooterHeight - scroller_height
}
this.DataOuter.style.height = adjusted_data_height + 'px'
if (this.LeftCells != 0) {
this.LeftDataOuter.style.height = adjusted_data_height + 'px'
}
// alert('3');
this.MainScroller.style.width = (this.HeadTable.offsetWidth + this.LeftWidth)+'px'
this.MainScroller.style.height = ( this.DataHeight + this.HeadHeight + this.FooterHeight)+'px'
// alert('4');
}
GridScroller.prototype.SetLeftWidth = function(left_width)
{
if (left_width) this.LeftWidth = left_width;
if (this.LeftCells != 0) {
// there was -1 for Mozilla, but somehow it's not needed anymore...
this.LeftHeaderOuter.parentNode.style.width = (this.LeftWidth + (is.ie ? 0 : 0) ) + 'px';
this.LeftHeaderOuter.style.width = (this.LeftWidth) + 'px';
this.LeftHeaderInner.style.width = (this.LeftWidth) + 'px';
this.LeftDataOuter.style.width = (this.LeftWidth) + 'px';
this.LeftDataInner.style.width = (this.LeftWidth) + 'px';
if (this.HasFooter()) {
this.LeftFooterOuter.style.width = (this.LeftWidth) + 'px';
this.LeftFooterInner.style.width = (this.LeftWidth) + 'px'
}
// this is IE workaround, we have to set inner div width to given px (above) and then back to 100%
// for IE to readjust the surrounding tables, otherwise it memorizes inner div pixel width and
// cannot make surrounding table cells smaller then that
this.LeftHeaderInner.style.width = '100%';
this.LeftDataInner.style.width = '100%';
if (this.HasFooter()) {
this.LeftFooterInner.style.width = '100%';
}
}
}
GridScroller.prototype.SyncScroll = function()
{
this.HeadScroller.scrollLeft = this.MainInner.scrollLeft;
this.DataScroller.scrollLeft = this.MainInner.scrollLeft;
if (this.HasFooter()) {
this.FooterScroller.scrollLeft = this.MainInner.scrollLeft;
}
this.DataScroller.scrollTop = this.MainInner.scrollTop;
if (this.LeftCells != 0) {
this.LeftDataInner.scrollTop = this.MainInner.scrollTop;
}
this.ScrollResizeHandles();
}
GridScroller.prototype.AltHTML = function(x,y,w,h)
{
var o = '';
o += this.CreateScroller( '<div id="main_scroller_'+this.GridId+'" style="background-color: inherit; position: relative; width: auto; z-index: 20; height: '+(h)+'px;"></div>', w, h, 'main_'+this.GridId, false, 1, 'grid-scrollable' );
// console.log(o)
// return o+'</div>'
o += '<div id="'+this.GridId+'" class="grid-container" style="background-color: inherit; position: absolute; left: '+(x)+'px; top: '+(y)+'px; visibility: visible; z-index: 10; width: auto; height: '+(h)+'px; overflow: hidden;">';
var header_rows = this.Header.length;
var cols = this.Header[0].length;
var data_rows = this.Data.length;
var footer_rows = this.Footer.length;
var header_h = 80;
if (this.LimitedHeights) {
for (var i=0; i<this.MaxHeaderHeights.length; i++) {header_h += this.MaxHeaderHeights[i]};
header_h += this.MaxHeaderHeightCorrection;
}
data_h = h - header_h;
// console.log('header_h: %i, data_h: %i', header_h, data_h)
var header = 'b';
var data = 'd';
var footer = 'f';
var left_header = '1';
var left_data = 'c';
var left_footer = 'e';
var header = this.GetTableWithScroller(this.Header, [this.LeftCells, 0, cols, header_rows], 'header', null, null, null, header_h)
var data = this.GetTableWithScroller(this.Data, [this.LeftCells, 0, cols, data_rows], 'data', 'grid-data-row-even', '', null, data_h)
var footer = this.HasFooter() ? this.GetTableWithScroller(this.Footer, [this.LeftCells, 0, cols, footer_rows], 'footer') : '';
var left_header = this.GetTableWithScroller(this.Header, [0,0,this.LeftCells, header_rows], ['header','left_header'], null, null, null, header_h)
var left_data = this.GetTableWithScroller(this.Data, [0,0,this.LeftCells, data_rows], ['data','left_data'], 'grid-data-row-even', 'left_', null, data_h)
var left_footer = this.GetTableWithScroller(this.Footer, [0,0,this.LeftCells, footer_rows], ['footer','left_footer'])
/*var css = '';
for (var i=0;i<this.Header[0].length; i++) {
css += '.width-adj-grid-col-'+i+' {} ';
}
o += '<style type="text/css">'+css+'</style>';*/
if (this.LeftCells != 0) {
o += '<table style="width: 100%; table-layout: fixed; border-collapse: collapse;">\n'
o += '<tr>\n<td style="vertical-align: top; margin: 0px; padding: 0px;">\n' + left_header + '\n</td>\n'
o += '<td style="vertical-align: top; margin: 0px; padding: 0px;">\n' + header + '\n</td>\n</tr>\n'
o += '<tr>\n<td style="vertical-align: top; margin: 0px; padding: 0px;">\n' + left_data + '\n</td>\n'
o += '<td style="vertical-align: top; margin: 0px; padding: 0px;">\n' + data + '\n</td>\n</tr>\n'
if (this.HasFooter()) {
o += '<tr><td style="vertical-align: top; margin: 0px; padding: 0px">' + left_footer + '</td>'
o += '<td style="vertical-align: top; margin: 0px; padding: 0px">' + footer + '</td></tr>'
}
o += '</table>\n'
}
else {
o += header + data + footer;
}
o += '</div>';
return o;
}
GridScroller.prototype.PrepareWidths = function()
{
cache = getFrame('head').grid_widths_cache;
if (!isset(cache)) {
cache = new Object
}
if (this.MinWidths.length >= this.Header[0].length) {
var has_all_widths = true;
for (var i=0; i < this.MinWidths.length; i++) {
if (isNaN(parseInt(this.MinWidths[i]))) {
this.MinWidths[i] = 100;
// has_all_widths = false;
}
}
if (has_all_widths) {
widths = this.MinWidths
cache[this.GridId+'_'+this.PickerCRC] = widths;
return widths;
}
}
if (cache[this.GridId+'_'+this.PickerCRC]) {
// return cache[this.GridId+'_'+this.PickerCRC]
}
// print_pre(this.MinWidths)
var o = '';
data = this.Header.concat(this.Data).concat(this.Footer);
o += this.GetTableCells(this.Header, [0,0,this.Header[0].length,this.Header.length], 'header', null, null, false, true)[0];
if (this.Data.length) {
var data= this.GetTableCells(this.Data, [0,0,this.Data[0].length,this.Data.length], 'data', null, null, false, true)[0];
o += data;
}
var w = document.all ? window.document.body.offsetWidth : window.innerWidth
var table_width = w < 500 ? '1024px' : 'auto';
// console.log('tmp table width: %s (window width: %s)', table_width, w)
o = '<table style="visibility: visible; width: '+table_width+'; border-collapse: collapse" id="tmp_'+this.GridId+'">'+o+'</table>'
document.write(o)
widths = this.GetWidths('tmp_'+this.GridId);
// print_pre(widths)
tmp_el = document.getElementById('tmp_'+this.GridId);
var p = tmp_el.parentNode;
p.removeChild(tmp_el);
cache[this.GridId+'_'+this.PickerCRC] = widths;
return widths;
}
GridScroller.prototype.GetTableWithScroller = function(source, dim, class_mode, even_class, id_prefix, w, h)
{
// console.log(source, dim, class_mode, even_class, id_prefix, w, h)
var tmp = this.GetIdAndClassName(class_mode);
var id = tmp[1];
if (!h) h = 100;
var cells = this.GetTableCells(source, dim, class_mode, even_class, id_prefix);
// var cells = this.GetTableCells(source, dim, class_mode, even_class, id_prefix, false, true);
// console.log('createing scroller %s w,h: %i,%i', id, cells[1],h)
return this.CreateScroller('<table style="table-layout: fixed; width: 100%;" id="'+id+'_'+this.GridId+'">\n'+cells[0]+'\n</table>\n\n', cells[1], h, id+'_'+this.GridId, true, 5);
}
GridScroller.prototype.GetIdAndClassName = function(class_mode)
{
if (typeof(class_mode)=='object') {
var class_name = class_mode[0];
var id = class_mode[1]
}
else {
var class_name = class_mode;
var id = class_mode;
}
return [class_name, id]
}
GridScroller.prototype.GetTableCells = function(source, dim, class_mode, even_class, id_prefix, needs_last, no_inner_div)
{
if (!source.length) return ['', 0];
var o = '';
var start_col = dim[0];
var start_row = dim[1];
var end_col = dim[2];
var end_row = dim[3];
var even = false;
if (!even_class) even_class = '';
var tmp = this.GetIdAndClassName(class_mode);
var class_name = tmp[0];
var id = tmp[1];
if (id_prefix==null) id_prefix = id;
var needs_last = needs_last == null ? (end_col == (source[0].data ? source[0].data.length : source[0].length)) : needs_last;
var total_width = 0;
var width_printed = false;
for (var row=start_row; row<end_row; row++) {
row_data = source[row].data ? source[row].data : source[row];
var rh = '';
var row_id = this.IDs[row] ? 'id="'+id_prefix+this.IDs[row]+'"' : '';
var row_class = 'grid-'+class_name+'-row '+(even ? even_class : '')+' grid-'+class_name+'-row-'+row + (source[row].row_class ? ' '+source[row].row_class : '');
rh +='<tr '+row_id+' class="'+row_class+'" sequence="'+(row+1)+'">'+"\n"
even = !even;
total_width = 0;
if (this.LimitedHeights) {
var row_height = id.match(/^(left_)?header/) ? this.MaxHeaderHeights[row]+'px;' : this.MaxRowHeight+'px;'
var height_style = id.match(/^(left_)?header/) ? 'height: '+this.MaxHeaderHeights[row]+'px;' : 'height: '+this.MaxRowHeight+'px;';
}
else {
var row_height = 'auto'
var height_style = '';
}
for (var col=start_col; col<end_col; col++) {
total_width += this.MinWidths[col]+12;
var cursor_workaround = ['',''];
if (id.match(/^(left_)?header/) && is.gecko) {
cursor_workaround = ['<div id="' + this.GridId + '[cursor_work_around_A_'+col+'_'+row+']" style="width: '+(this.MinWidths[col])+'px; overflow: auto;"><div id="' + this.GridId + '[cursor_work_around_B_'+col+'_'+row+']" style="width: '+(this.MinWidths[col])+'px; overflow: hidden;">', '</div></div>'];
}
else {
if (this.LimitedHeights) {
cursor_workaround = ['<div id="_clipper_'+col+'_'+row+'" style="'+(is.ie ? '' : 'display: table-cell; ')+'vertical-align: inherit; overflow: hidden; max-height: '+row_height+'"><div style="overflow: hidden; max-height: '+row_height+'">','</div></div>'];
}
}
var width_style = width_printed ? '' : 'width: '+this.MinWidths[col]+'px;"'
var td_style = 'style="overflow: hidden; max-height: '+row_height+'; '+width_style+'"';
var td_class = 'grid-'+class_name+'-col-'+col;
if (this.FieldNames) {
td_class += ' '+this.FieldNames[col];
}
rh += "\t"+'<td '+td_style+' class="'+td_class+'">'+cursor_workaround[0]+row_data[col]+cursor_workaround[1]+'</td>'+"\n"
}
width_printed = true; // print widths in first row only
if (needs_last) {
rh += "\t"+'<td class="grid-'+class_name+'-last-cell"><img src="'+this.Spacer+'" width="1" height="1" alt=""/></td>'+"\n"
}
rh += '</tr>'+"\n"
o += rh;
}
return [o, total_width];
}
GridScroller.prototype.HasFooter = function()
{
return (this.Footer != false)
}
var colors = ['red', 'blue', 'green', 'pink', 'orange', 'brown', 'yellow', 'magenta', '#999', '#AAA', '#BBB', '#CCC', '#DDD', '#EEE', '#FFF'];
var next_color = 0;
GridScroller.prototype.CreateScroller = function(content, w, h, id, hidden, z, outer_class)
{
// console.log('creating scroller: ',w,h,id,hidden,z)
if (hidden) {
overflow = 'hidden'
}
else {
overflow = 'auto'
}
if (!z) {
z = 0;
}
if (id && id != '') {
outer_id = 'id="outer_'+id+'"';
inner_id = 'id="inner_'+id+'"';
}
else {
outer_id = '';
inner_id = '';
}
var o = '';
if (!outer_class) outer_class='scoller-outer';
o += '<div '+outer_id+' class="'+outer_class+'" style="z-index: '+z+'; width: '+w+'px; height: '+h+'px;">'
o += '<div '+inner_id+' class="scroller-inner" style="z-index: '+z+'; width: 100%; height: 100%; overflow: '+overflow+'; position: relative;">'
o += content
o += '</div></div>'
return o
}
GridScroller.prototype.SetData = function(a_data)
{
this.Data = a_data;
}
GridScroller.prototype.SetHeader = function(a_header)
{
this.Header = a_header;
this.MaxHeaderHeightCorrection = (6*this.Header.length)+1;
}
GridScroller.prototype.SetFooter = function(a_footer)
{
this.Footer = a_footer;
}
GridScroller.prototype.SaveWidths = function()
{
if (!this.SaveURL) return;
var w = this.MinWidths.join(':');
Request.makeRequest(this.SaveURL.replace('#WIDTHS#', w), this.BusyRequest, '', this.successCallback, this.errorCallback, '', this);
}
GridScroller.prototype.ScheduleSaveWidths = function()
{
var obj = this;
if (this.SaveWidthsScheduled && this.SaveWidthsTimer) {
window.clearTimeout(this.SaveWidthsTimer);
this.SaveWidthsTimer = false;
}
this.SaveWidthsScheduled = true;
this.SaveWidthsTimer = window.setTimeout(function() {
obj.SaveWidths();
obj.SaveWidthsScheduled = false;
}, 800)
}
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/calendar/calendar-setup.js
===================================================================
--- branches/RC/core/admin_templates/js/calendar/calendar-setup.js (revision 11931)
+++ branches/RC/core/admin_templates/js/calendar/calendar-setup.js (revision 11932)
@@ -1,215 +1,215 @@
/* Copyright Mihai Bazon, 2002, 2003 | http://dynarch.com/mishoo/
* ---------------------------------------------------------------------------
*
* The DHTML Calendar
*
* Details and latest version at:
* http://dynarch.com/mishoo/calendar.epl
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*
* This file defines helper functions for setting up the calendar. They are
* intended to help non-programmers get a working calendar on their site
* quickly. This script should not be seen as part of the calendar. It just
* shows you what one can do with the calendar, while in the same time
* providing a quick and simple method for setting it up. If you need
* exhaustive customization of the calendar creation process feel free to
* modify this code to suit your needs (this is recommended and much better
* than modifying calendar.js itself).
*/
// $Id: calendar-setup.js,v 1.2.2.2 2009-05-03 15:46:13 valex Exp $
/**
* This function "patches" an input field (or other element) to use a calendar
* widget for date selection.
*
* The "params" is a single object that can have the following properties:
*
* prop. name | description
* -------------------------------------------------------------------------------------------------
* inputField | the ID of an input field to store the date
* displayArea | the ID of a DIV or other element to show the date
* button | ID of a button or other element that will trigger the calendar
* eventName | event that will trigger the calendar, without the "on" prefix (default: "click")
* ifFormat | date format that will be stored in the input field
* daFormat | the date format that will be used to display the date in displayArea
* singleClick | (true/false) wether the calendar is in single click mode or not (default: true)
* firstDay | numeric: 0 to 6. "0" means display Sunday first, "1" means display Monday first, etc.
* align | alignment (default: "Br"); if you don't know what's this see the calendar documentation
* range | array with 2 elements. Default: [1900, 2999] -- the range of years available
* weekNumbers | (true/false) if it's true (default) the calendar will display week numbers
* flat | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
* flatCallback | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
* disableFunc | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
* onSelect | function that gets called when a date is selected. You don't _have_ to supply this (the default is generally okay)
* onClose | function that gets called when the calendar is closed. [default]
* onUpdate | function that gets called after the date is updated in the input field. Receives a reference to the calendar.
* date | the date that the calendar will be initially displayed to
* showsTime | default: false; if true the calendar will include a time selector
* timeFormat | the time format; can be "12" or "24", default is "12"
* electric | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
* step | configures the step of the years in drop-down boxes; default: 2
* position | configures the calendar absolute position; default: null
* cache | if "true" (but default: "false") it will reuse the same calendar object, where possible
* showOthers | if "true" (but default: "false") it will show days from other months too
*
* None of them is required, they all have default values. However, if you
* pass none of "inputField", "displayArea" or "button" you'll get a warning
* saying "nothing to setup".
*/
Calendar.setup = function (params) {
function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
param_default("inputField", null);
param_default("displayArea", null);
param_default("button", null);
param_default("eventName", "click");
param_default("ifFormat", "%Y/%m/%d");
param_default("daFormat", "%Y/%m/%d");
param_default("singleClick", true);
param_default("disableFunc", null);
param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
param_default("dateText", null);
param_default("firstDay", null);
param_default("align", "Br");
param_default("range", [1900, 2999]);
param_default("weekNumbers", true);
param_default("flat", null);
param_default("flatCallback", null);
param_default("onSelect", null);
param_default("onClose", null);
param_default("onUpdate", null);
param_default("date", null);
param_default("showsTime", false);
param_default("timeFormat", params['ifFormat'].match(/%l|%p|%P/) ? "12" : "24");
param_default("electric", true);
param_default("step", 2);
param_default("position", null);
param_default("cache", false);
param_default("showOthers", false);
param_default("multiple", null);
var tmp = ["inputField", "displayArea", "button"];
- for (var i in tmp) {
+ for (var i = 0; i < tmp.length; i++) {
if (typeof params[tmp[i]] == "string") {
params[tmp[i]] = document.getElementById(params[tmp[i]]);
}
}
if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code");
return false;
}
function onSelect(cal) {
var p = cal.params;
var update = (cal.dateClicked || p.electric);
if (update && p.inputField) {
p.inputField.value = cal.date.print(p.ifFormat);
if (typeof p.inputField.onchange == "function")
p.inputField.onchange();
}
if (update && p.displayArea)
p.displayArea.innerHTML = cal.date.print(p.daFormat);
if (update && typeof p.onUpdate == "function")
p.onUpdate(cal);
if (update && p.flat) {
if (typeof p.flatCallback == "function")
p.flatCallback(cal);
}
if (update && p.singleClick && cal.dateClicked)
cal.callCloseHandler();
};
if (params.flat != null) {
if (typeof params.flat == "string")
params.flat = document.getElementById(params.flat);
if (!params.flat) {
alert("Calendar.setup:\n Flat specified but can't find parent.");
return false;
}
var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
cal.showsOtherMonths = params.showOthers;
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.params = params;
cal.weekNumbers = params.weekNumbers;
cal.setRange(params.range[0], params.range[1]);
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
if (params.ifFormat) {
cal.setDateFormat(params.ifFormat);
}
if (params.inputField && typeof params.inputField.value == "string") {
cal.parseDate(params.inputField.value);
}
cal.create(params.flat);
cal.show();
return false;
}
var triggerEl = params.button || params.displayArea || params.inputField;
triggerEl["on" + params.eventName] = function() {
var $check_field = params.inputField;
if ($check_field.getAttribute('type') == 'hidden') {
// date + time control -> main field is hidden
$regex = /full_date_(.*)\[(.*)\]$/.exec($check_field.id);
$check_field = document.getElementById($regex[1] + '[' + $regex[2] + '_date]');
}
if ($check_field.disabled || $check_field.readOnly) {
// don't show calendar, when date/time field is disabled
return false;
}
var dateEl = params.inputField || params.displayArea;
var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
var mustCreate = false;
var cal = window.calendar;
if (dateEl)
params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
if (!(cal && params.cache)) {
window.calendar = cal = new Calendar(params.firstDay,
params.date,
params.onSelect || onSelect,
params.onClose || function(cal) { cal.hide(); });
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.weekNumbers = params.weekNumbers;
mustCreate = true;
} else {
if (params.date)
cal.setDate(params.date);
cal.hide();
}
if (params.multiple) {
cal.multiple = {};
for (var i = params.multiple.length; --i >= 0;) {
var d = params.multiple[i];
var ds = d.print("%Y%m%d");
cal.multiple[ds] = d;
}
}
cal.showsOtherMonths = params.showOthers;
cal.yearStep = params.step;
cal.setRange(params.range[0], params.range[1]);
cal.params = params;
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
cal.setDateFormat(dateFmt);
if (mustCreate)
cal.create();
cal.refresh();
if (!params.position)
cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
else
cal.showAt(params.position[0], params.position[1]);
return false;
};
return cal;
};
Index: branches/RC/core/admin_templates/js/calendar/calendar.js
===================================================================
--- branches/RC/core/admin_templates/js/calendar/calendar.js (revision 11931)
+++ branches/RC/core/admin_templates/js/calendar/calendar.js (revision 11932)
@@ -1,1867 +1,1867 @@
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* -----------------------------------------------------------
*
* The DHTML Calendar, version 1.0 "It is happening again"
*
* Details and latest version at:
* www.dynarch.com/projects/calendar
*
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*/
// $Id: calendar.js,v 1.2.2.1 2009-03-26 22:02:16 alex Exp $
/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
// member variables
this.activeDiv = null;
this.currentDateEl = null;
this.getDateStatus = null;
this.getDateToolTip = null;
this.getDateText = null;
this.timeout = null;
this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;
// HTML elements
this.table = null;
this.element = null;
this.tbody = null;
this.firstdayname = null;
// Combo boxes
this.monthsCombo = null;
this.yearsCombo = null;
this.hilitedMonth = null;
this.activeMonth = null;
this.hilitedYear = null;
this.activeYear = null;
// Information
this.dateClicked = false;
// one-time initializations
if (typeof Calendar._SDN == "undefined") {
// table of short day names
if (typeof Calendar._SDN_len == "undefined")
Calendar._SDN_len = 3;
var ar = new Array();
for (var i = 8; i > 0;) {
ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
}
Calendar._SDN = ar;
// table of short month names
if (typeof Calendar._SMN_len == "undefined")
Calendar._SMN_len = 3;
ar = new Array();
for (var i = 12; i > 0;) {
ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
}
Calendar._SMN = ar;
}
};
// ** constants
/// "static", needed for event handlers.
Calendar._C = null;
/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent) );
Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );
/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
// library, at some point.
Calendar.getAbsolutePos = function(el) {
var SL = 0, ST = 0;
var is_div = /^div$/i.test(el.tagName);
if (is_div && el.scrollLeft)
SL = el.scrollLeft;
if (is_div && el.scrollTop)
ST = el.scrollTop;
var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
if (el.offsetParent) {
var tmp = this.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
Calendar.isRelated = function (el, evt) {
var related = evt.relatedTarget;
if (!related) {
var type = evt.type;
if (type == "mouseover") {
related = evt.fromElement;
} else if (type == "mouseout") {
related = evt.toElement;
}
}
try {
while (related) {
if (related == el) {
return true;
}
related = related.parentNode;
}
}
catch (e) {
}
return false;
};
Calendar.removeClass = function(el, className) {
if (!(el && el.className)) {
return;
}
var cls = el.className.split(" ");
var ar = new Array();
for (var i = cls.length; i > 0;) {
if (cls[--i] != className) {
ar[ar.length] = cls[i];
}
}
el.className = ar.join(" ");
};
Calendar.addClass = function(el, className) {
Calendar.removeClass(el, className);
el.className += " " + className;
};
// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
while (f.nodeType != 1 || /^div$/i.test(f.tagName))
f = f.parentNode;
return f;
};
Calendar.getTargetElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.target;
while (f.nodeType != 1)
f = f.parentNode;
return f;
};
Calendar.stopEvent = function(ev) {
ev || (ev = window.event);
if (Calendar.is_ie) {
ev.cancelBubble = true;
ev.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
return false;
};
Calendar.addEvent = function(el, evname, func) {
if (el.attachEvent) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
};
Calendar.removeEvent = function(el, evname, func) {
if (el.detachEvent) { // IE
el.detachEvent("on" + evname, func);
} else if (el.removeEventListener) { // Gecko / W3C
el.removeEventListener(evname, func, true);
} else {
el["on" + evname] = null;
}
};
Calendar.createElement = function(type, parent) {
var el = null;
if (document.createElementNS) {
// use the XHTML namespace; IE won't normally get here unless
// _they_ "fix" the DOM2 implementation.
el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
} else {
el = document.createElement(type);
}
if (typeof parent != "undefined") {
parent.appendChild(el);
}
return el;
};
// END: UTILITY FUNCTIONS
// BEGIN: CALENDAR STATIC FUNCTIONS
/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
with (Calendar) {
addEvent(el, "mouseover", dayMouseOver);
addEvent(el, "mousedown", dayMouseDown);
addEvent(el, "mouseout", dayMouseOut);
if (is_ie) {
addEvent(el, "dblclick", dayMouseDblClick);
el.setAttribute("unselectable", true);
}
}
};
Calendar.findMonth = function(el) {
if (typeof el.month != "undefined") {
return el;
} else if (typeof el.parentNode.month != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.findYear = function(el) {
if (typeof el.year != "undefined") {
return el;
} else if (typeof el.parentNode.year != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.showMonthsCombo = function () {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var mc = cal.monthsCombo;
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
if (cal.activeMonth) {
Calendar.removeClass(cal.activeMonth, "active");
}
var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
Calendar.addClass(mon, "active");
cal.activeMonth = mon;
var s = mc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var mcw = mc.offsetWidth;
if (typeof mcw == "undefined")
// Konqueror brain-dead techniques
mcw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};
Calendar.showYearsCombo = function (fwd) {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var yc = cal.yearsCombo;
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
if (cal.activeYear) {
Calendar.removeClass(cal.activeYear, "active");
}
cal.activeYear = null;
var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
var yr = yc.firstChild;
var show = false;
for (var i = 12; i > 0; --i) {
if (Y >= cal.minYear && Y <= cal.maxYear) {
yr.innerHTML = Y;
yr.year = Y;
yr.style.display = "block";
show = true;
} else {
yr.style.display = "none";
}
yr = yr.nextSibling;
Y += fwd ? cal.yearStep : -cal.yearStep;
}
if (show) {
var s = yc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var ycw = yc.offsetWidth;
if (typeof ycw == "undefined")
// Konqueror brain-dead techniques
ycw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
}
};
// event handlers
Calendar.tableMouseUp = function(ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
if (cal.timeout) {
clearTimeout(cal.timeout);
}
var el = cal.activeDiv;
if (!el) {
return false;
}
var target = Calendar.getTargetElement(ev);
ev || (ev = window.event);
Calendar.removeClass(el, "active");
if (target == el || target.parentNode == el) {
Calendar.cellClick(el, ev);
}
var mon = Calendar.findMonth(target);
var date = null;
if (mon) {
date = new Date(cal.date);
if (mon.month != date.getMonth()) {
date.setMonth(mon.month);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
} else {
var year = Calendar.findYear(target);
if (year) {
date = new Date(cal.date);
if (year.year != date.getFullYear()) {
date.setFullYear(year.year);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
}
}
with (Calendar) {
removeEvent(document, "mouseup", tableMouseUp);
removeEvent(document, "mouseover", tableMouseOver);
removeEvent(document, "mousemove", tableMouseOver);
cal._hideCombos();
_C = null;
return stopEvent(ev);
}
};
Calendar.tableMouseOver = function (ev) {
var cal = Calendar._C;
if (!cal) {
return;
}
var el = cal.activeDiv;
var target = Calendar.getTargetElement(ev);
if (target == el || target.parentNode == el) {
Calendar.addClass(el, "hilite active");
Calendar.addClass(el.parentNode, "rowhilite");
} else {
if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
Calendar.removeClass(el, "active");
Calendar.removeClass(el, "hilite");
Calendar.removeClass(el.parentNode, "rowhilite");
}
ev || (ev = window.event);
if (el.navtype == 50 && target != el) {
var pos = Calendar.getAbsolutePos(el);
var w = el.offsetWidth;
var x = ev.clientX;
var dx;
var decrease = true;
if (x > pos.x + w) {
dx = x - pos.x - w;
decrease = false;
} else
dx = pos.x - x;
if (dx < 0) dx = 0;
var range = el._range;
var current = el._current;
var count = Math.floor(dx / 10) % range.length;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
var year = Calendar.findYear(target);
if (year) {
if (year.year != cal.date.getFullYear()) {
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
Calendar.addClass(year, "hilite");
cal.hilitedYear = year;
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.tableMouseDown = function (ev) {
if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
return Calendar.stopEvent(ev);
}
};
Calendar.calDragIt = function (ev) {
var cal = Calendar._C;
if (!(cal && cal.dragging)) {
return false;
}
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posX = ev.pageX;
posY = ev.pageY;
}
cal.hideShowCovered();
var st = cal.element.style;
st.left = (posX - cal.xOffs) + "px";
st.top = (posY - cal.yOffs) + "px";
return Calendar.stopEvent(ev);
};
Calendar.calDragEnd = function (ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
cal.dragging = false;
with (Calendar) {
removeEvent(document, "mousemove", calDragIt);
removeEvent(document, "mouseup", calDragEnd);
tableMouseUp(ev);
}
cal.hideShowCovered();
};
Calendar.dayMouseDown = function(ev) {
var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};
Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
return stopEvent(ev);
}
};
/**
* A generic "click" handler :) handles all types of buttons defined in this
* calendar.
*/
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;
// a date was clicked
if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date()); // TODAY
// unless "today" was clicked, we assume no date was clicked so
// the selected handler will know not to close the calenar when
// in single-click mode.
// cal.dateClicked = (el.navtype == 0);
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {
// FIXME: this should be removed as soon as lang files get updated!
text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:
// TODAY will bring us here
if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
// END: CALENDAR STATIC FUNCTIONS
// BEGIN: CALENDAR OBJECT FUNCTIONS
/**
* This function creates the calendar inside the given parent. If _par is
* null than it creates a popup calendar inside the BODY element. If _par is
* an element, be it BODY, then it creates a non-popup calendar (still
* hidden). Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
// default parent is the document body, in which case we create
// a popup calendar.
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();
var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
div.appendChild(table);
var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;
var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};
row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;
// hh("?", 1, 999).ttip = Calendar._TT["INFO"];
cell = Calendar.createElement("td", row);
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
}
row = Calendar.createElement("tr", thead);
row.className = "headrow";
this._nav_py = hh("&#x00ab;", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
this._nav_pm = hh("&#x2039;", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];
this._nav_nm = hh("&#x203a;", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
this._nav_ny = hh("&#x00bb;", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
// day names
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = Calendar._TT["WK"];
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();
var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;
for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}
if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;
(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = "&nbsp;";
cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};
cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}
var tfoot = Calendar.createElement("tfoot", table);
row = Calendar.createElement("tr", tfoot);
row.className = "footrow";
cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;
div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}
div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}
this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37: // KEY left
act && Calendar.cellClick(cal._nav_pm);
break;
case 38: // KEY up
act && Calendar.cellClick(cal._nav_py);
break;
case 39: // KEY right
act && Calendar.cellClick(cal._nav_nm);
break;
case 40: // KEY down
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32: // KEY space (now)
Calendar.cellClick(cal._nav_now);
break;
case 27: // KEY esc
act && cal.callCloseHandler();
break;
case 37: // KEY left
case 38: // KEY up
case 39: // KEY right
case 40: // KEY down
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37: // KEY left
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38: // KEY up
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39: // KEY right
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40: // KEY down
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13: // KEY enter
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
/**
* (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
// calendar voodoo for computing the first day that would actually be
// displayed in the calendar, even if it's from the previous month.
// WARNING: this is magic. ;-)
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);
var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = date.getWeekNumber();
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = "&nbsp;";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (this.getDateToolTip) {
var toolTip = this.getDateToolTip(date, year, month, iday);
if (toolTip)
cell.title = toolTip;
}
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
// PROFILE
// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};
Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};
Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};
Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
/**
* Calls _init function above for going to a certain date (but only if the
* date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
/**
* Refreshes the calendar. Useful if the "disabledHandler" function is
* dynamic, meaning that the list of disabled date can change at runtime.
* Just * call this function if you think that the list of disabled dates
* should * change.
*/
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
/**
* Allows customization of what dates are enabled. The "unaryFunction"
* parameter must be a function object that receives the date (as a JS Date
* object) and returns a boolean value. If the returned value is true then
* the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
/**
* Moves the calendar element to a different section in the DOM tree (changes
* its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
// 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.
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {
// calls closeHandler which should hide the calendar.
window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
/** Shows the calendar. */
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
/**
* Hides the calendar. Also removes any "hilite" from the class of any TD
* element.
*/
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};
/**
* Shows the calendar at a given absolute position (beware that, depending on
* the calendar element style -- position property -- this might be relative
* to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_fucking_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}
// vertical alignment
switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break; // already there
}
// horizontal alignment
switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break; // already there
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
else
Calendar.continuation_for_the_fucking_khtml_browser();
};
/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
/**
* Tries to identify the date represented in a string. If successful it also
* calls this.setDate which moves the calendar to the given date.
*/
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) { // IE
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};
var tags = new Array("applet", "iframe", "select");
var el = this.element;
var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;
for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;
for (var i = ar.length; i > 0;) {
cc = ar[--i];
p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;
if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
/** Internal function. Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
/** Internal function. Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
Calendar.phpDateFormat = function(php_format) {
originals = [
// date
'm', // Numeric representation of a month, with leading zeros
'n', // Numeric representation of a month, without leading zeros
'd', // Day of the month, 2 digits with leading zeros
'j', // Day of the month without leading zeros
'y', // A two digit representation of a year
'Y', // A full numeric representation of a year, 4 digits
// time (hours)
'h', // 12-hour format of an hour with leading zeros
'g', // 12-hour format of an hour without leading zeros
'H', // 24-hour format of an hour with leading zeros
'G', // 24-hour format of an hour without leading zeros
// time (minutes, seconds, am/pm)
'i', // Minutes with leading zeros
's', // Seconds, with leading zeros
'a', // Lowercase Ante meridiem and Post meridiem
'A' // Uppercase Ante meridiem and Post meridiem
];
replacements = [
// date
'%m',
'%m' /* '%n' is new line format, so use month with leading zeros here too */,
'%d',
'%e',
'%y',
'%Y',
// time (hours)
'%I',
'%l',
'%H',
'%k',
// time (minutes, seconds, am/pm)
'%M',
'%S',
'%P',
'%p'
];
- for (var i in originals) {
+ for (var i = 0; i < originals.length; i++) {
php_format = php_format.replace(new RegExp(originals[i]), replacements[i]);
}
return php_format;
}
// BEGIN: DATE OBJECT PATCHES
/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;
Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break;
case "%m":
m = parseInt(a[i], 10) - 1;
break;
case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break;
case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break;
case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break;
case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break;
case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
var ms = d.valueOf(); // GMT
d.setMonth(0);
d.setDate(4); // Thu in Week 1
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
s["%A"] = Calendar._DN[w]; // full weekday name
s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = Calendar._MN[m]; // full month name
// FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
s["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr; // hour, range 0 to 23 (24h format)
s["%l"] = ir; // hour, range 1 to 12 (12h format)
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = y; // year with the century
s["%%"] = "%"; // a literal '%' character
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });
var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}
return str;
};
Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};
// END: DATE OBJECT PATCHES
// global object that remembers the calendar
window._dynarch_popupCalendar = null;
Index: branches/RC/core/admin_templates/js/tree.js
===================================================================
--- branches/RC/core/admin_templates/js/tree.js (revision 11931)
+++ branches/RC/core/admin_templates/js/tree.js (revision 11932)
@@ -1,645 +1,645 @@
var last_hightlighted = null;
var last_highlighted_key = null;
function TreeItem(title, url, icon, onclick, priority)
{
this.Title = title;
this.Url = url;
this.Rendered = false;
this.Displayed = false;
this.Level = 0;
this.Icon = icon;
this.Onclick = onclick;
this.Priority = isset(priority) ? priority : false;
this.Children = false;
}
TreeItem.prototype.isFolder = function()
{
return typeof(this.folderClick) == 'function';
}
TreeItem.prototype.isContainer = function()
{
return this.isFolder() && this.Container;
}
TreeItem.prototype.Render = function(before, force)
{
if (!this.Rendered || force) {
if (!isset(before)) {before = null}
tr = document.createElement('tr');
this.ParentElement.insertBefore(tr, before);
if (!this.Displayed) { tr.style.display = 'none' }
td = document.createElement('td');
td.TreeElement = this;
tr.appendChild(td);
this.appendLevel(td);
if (this.ParentFolder != null) this.appendNodeImage(td);
this.appendIcon(td);
this.appendLink(td);
this.Tr = tr;
this.Rendered = true;
// alert(this.Tr.innerHTML)
}
}
TreeItem.prototype.remove = function()
{
var p = this.Tr.parentNode;
p.removeChild(this.Tr);
}
TreeItem.prototype.appendLevel = function(td)
{
for (var i=0; i < this.Level; i++)
{
img = document.createElement('img');
img.style.width = '16px';
img.style.height = '22px';
img.src = TREE_ICONS_PATH+'/ftv2blank.gif';
img.style.verticalAlign = 'middle';
td.appendChild(img);
}
}
TreeItem.prototype.getNodeImage = function(is_last)
{
return is_last ? TREE_ICONS_PATH+'/ftv2lastnode.gif' : TREE_ICONS_PATH+'/ftv2node.gif';
}
TreeItem.prototype.appendNodeImage = function(td)
{
img = document.createElement('img');
img.style.width = '16px';
img.style.height = '22px';
img.src = this.getNodeImage();
img.style.verticalAlign = 'middle';
td.appendChild(img);
}
TreeItem.prototype.appendIcon = function (td)
{
img = document.createElement('img');
img.style.width = '24px';
img.style.height = '22px';
if (this.Icon.indexOf('http://') != -1) {
img.src = this.Icon;
}
else {
img.src = this.Icon;
}
img.style.verticalAlign = 'middle';
td.appendChild(img);
}
TreeItem.prototype.appendLink = function (td)
{
var $node_text = document.createElement('span');
$node_text.innerHTML = this.Title;
if (TREE_SHOW_PRIORITY && this.Priority !== false) {
$node_text.innerHTML += '<span class="priority"><sup>' + this.Priority + '</sup></span>';
}
link = document.createElement('a');
link.nodeValue = this.Title;
link.href = this.Url;
link.target = 'main';
link.appendChild($node_text);
link.treeItem = this;
//addEvent(link, 'click',
link.onclick =
function(ev) {
var e = is.ie ? window.event : ev;
res = true;
if (isset(this.treeItem.Onclick)) {
res = eval(this.treeItem.Onclick);
}
if (!res) { // if we need to cancel onclick action
if (is.ie) {
window.event.cancelBubble = true;
window.event.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
return res;
}
else {
// ensures, that click is made before AJAX request will be sent
if (res === true) {
// only in case of "true" is returned, used in catalog
if (this.treeItem.isContainer()) {
this.href = this.treeItem.locateFirstItem().Url;
}
getFrame(link.target).location.href = this.href;
}
if (!this.treeItem.Expanded && this.treeItem.isFolder()) {
if (this.treeItem.folderClick());
}
this.treeItem.highLight();
return false;
}
}
td.appendChild(link);
/*
if (this.LateLoadURL) {
var span = document.createElement('span');
span.innerHTML = '&nbsp;Reload';
span.treeItem = this;
span.onclick = function(ev) {
this.treeItem.reload();
}
td.appendChild(span);
}
*/
}
TreeItem.prototype.display = function()
{
this.Tr.style.display = is.ie ? 'block' : 'table-row';
this.Displayed = true;
var do_sub = TreeManager.isExpanded(this.Key);
if (this.Children && do_sub && !this.Expanding) {
this.expand();
}
if (this.ParentFolder != null && !this.ParentFolder.Expanded) {
this.ParentFolder.expand();
}
}
TreeItem.prototype.hide = function()
{
this.Tr.style.display = 'none';
this.Displayed = false;
}
TreeItem.prototype.highLight = function()
{
if (last_hightlighted) last_hightlighted.Tr.className = '';
if (this.Children && this.Children.length > 0 && this.isContainer()) {
if (!this.Expanded) {
this.expand();
}
this.Children[0].highLight();
return;
}
this.Tr.className = "highlighted";
last_hightlighted = this;
last_highlighted_key = this.Key;
if (!this.Expanded) {
this.expand();
}
}
TreeItem.prototype.expand = function() {
this.display();
}
TreeItem.prototype.collapse = function() { this.hide() }
TreeItem.prototype.updateLastNodes = function(is_last, lines_pattern)
{
if (!isset(is_last)) is_last = true;
if (!isset(this.Tr)) return;
if (!isset(lines_pattern)) { var lines_pattern = new Array() }
imgs = this.Tr.getElementsByTagName('img');
found = false;
for (var i=0; i<imgs.length; i++)
{
the_img = imgs.item(i);
if (in_array(i, lines_pattern) && the_img.src.indexOf('ftv2blank.gif') != -1) {
the_img.src = TREE_ICONS_PATH+'/ftv2vertline.gif';
}
if (this.isNodeImage(the_img))
{
found = true;
break;
}
}
if (found) {
the_img.src = this.getNodeImage(is_last);
}
this.isLast = is_last;
return lines_pattern;
}
TreeItem.prototype.isNodeImage = function(img)
{
return (
img.src.indexOf('ftv2node.gif') != -1 ||
img.src.indexOf('ftv2lastnode.gif') != -1
)
}
TreeItem.prototype.locateLastItem = function()
{
return this;
}
TreeItem.prototype.locateItemByURL = function(url)
{
if (this.Url == url) return this;
return false;
}
TreeItem.prototype.locateItemByKey = function(key)
{
if (this.Key == key) return this;
return false;
}
TreeItem.prototype.reload = function()
{
}
/* FOLDER */
function TreeFolder(parent_id, title, url, icon, late_load_url, onclick, priority, container)
{
var render = false;
if (isset(parent_id)) {
this.ParentElement = document.getElementById(parent_id);
render = true;
}
else {
}
this.Title = title;
this.Url = url;
this.Rendered = false;
this.Displayed = false;
this.Expanded = false;
this.Level = 0;
this.Id = 0;
this.Tr = null;
this.Icon = icon;
this.LateLoadURL = isset(late_load_url) ? late_load_url : false;
this.Loaded = false;
this.Onclick = onclick;
this.Priority = isset(priority) ? priority : false;
this.Container = isset(container) ? parseInt(container) : false;
this.Children = new Array();
this.ChildIndex = 0;
this.Reloading = false;
if (render) {
this.Expanded = true;
this.Displayed = true;
this.Render();
this.expand();
}
}
TreeFolder.prototype = new TreeItem;
TreeFolder.prototype.locateLastItem = function()
{
if (this.Children.length == 0) return this;
for (var i=0; i<this.Children.length; i++)
{
last_item = this.Children[i].locateLastItem()
}
return last_item;
}
TreeFolder.prototype.locateFirstItem = function()
{
var $folder_node = this;
while ($folder_node.isContainer() && $folder_node.Children.length > 0) {
$folder_node = $folder_node.Children[0];
}
return $folder_node;
}
TreeFolder.prototype.locateItemByURL = function(url, with_late_load)
{
last_item = false;
if (this.Url == url && ( (with_late_load && this.LateLoadURL) || !with_late_load) ) {
return this;
}
for (var i=0; i<this.Children.length; i++)
{
last_item = this.Children[i].locateItemByURL(url, with_late_load)
if (last_item) return last_item;
}
return last_item;
}
TreeFolder.prototype.locateItemByKey = function(key)
{
last_item = false;
if (this.Key == key) {
return this;
}
for (var i=0; i<this.Children.length; i++)
{
last_item = this.Children[i].locateItemByKey(key)
if (last_item) return last_item;
}
return last_item;
}
TreeFolder.prototype.locateTopItem = function()
{
if (this.ParentFolder == null) return this;
return this.ParentFolder.locateTopItem();
}
TreeFolder.prototype.AddItem = function(an_item, render, display) {
an_item.ParentElement = this.ParentElement;
an_item.Level = this.ParentFolder != null ? this.Level + 1 : 0;
an_item.ParentFolder = this;
last_item = this.locateLastItem();
this.Children.push(an_item);
an_item.Id = this.Children.length;
an_item.Render(last_item.Tr.nextSibling);
var keys = new Array()
var tmp = an_item;
keys.push(tmp.Level + '_' + tmp.Id);
while (tmp.ParentFolder) {
tmp = tmp.ParentFolder
keys.push(tmp.Level + '_' + tmp.Id);
}
keys = keys.reverse();
key_str = keys.join('-');
an_item.Key = key_str;
if (this.Expanded)
{
an_item.display();
}
return an_item;
}
TreeFolder.prototype.AddFromXML = function(xml, render)
{
// start = new Date();
if (!isset(render)) render = true;
doc = getDocumentFromXML(xml);
this.LastFolder = this;
this.ProcessXMLNode(doc, render);
// end = new Date();
this.locateTopItem().updateLastNodes();
// alert('AddFromXML took: '+(end - start))
}
TreeFolder.prototype.ProcessXMLNode = function(node, render)
{
if (!isset(render)) render = true;
if (!isset(this.LastFolder)) this.LastFolder = this;
for (var i=0; i<node.childNodes.length; i++)
{
child = node.childNodes.item(i);
if (child.tagName == 'folder') {
var backupLastFolder = this.LastFolder;
this.LastFolder = this.LastFolder.AddItem(new TreeFolder(null, child.getAttribute('name'), child.getAttribute('href'), child.getAttribute('icon'), child.getAttribute('load_url'), child.getAttribute('onclick'), child.getAttribute('priority'), child.getAttribute('container')), render);
if (child.hasChildNodes) {
this.ProcessXMLNode(child);
}
this.LastFolder = backupLastFolder;
}
else if (child.tagName == 'item') {
this.LastFolder.AddItem(new TreeItem(child.firstChild.nodeValue, child.getAttribute('href'), child.getAttribute('icon'), child.getAttribute('onclick'), child.getAttribute('priority')), render)
}
else if (child.tagName == 'tree') {
this.LastFolder = this;
this.ProcessXMLNode(child);
}
}
}
TreeFolder.prototype.getNodeImage = function(is_last)
{
if (is_last) {
return this.Expanded ? TREE_ICONS_PATH+'/ftv2mlastnode.gif' : TREE_ICONS_PATH+'/ftv2plastnode.gif';
}
else {
return this.Expanded ? TREE_ICONS_PATH+'/ftv2mnode.gif' : TREE_ICONS_PATH+'/ftv2pnode.gif';
}
}
TreeFolder.prototype.appendNodeImage = function(td, is_last)
{
img = document.createElement('img');
img.style.width = '16px';
img.style.height = '22px';
img.src = this.getNodeImage(is_last);
img.style.cursor = 'hand';
img.style.cursor = 'pointer';
img.style.verticalAlign = 'middle';
img.onclick = function() { this.parentNode.TreeElement.folderClick(this) }
this.Img = img;
td.appendChild(img);
}
TreeFolder.prototype.updateLastNodes = function(is_last, lines_pattern)
{
if (!isset(is_last)) is_last = true;
if (!isset(lines_pattern)) { var lines_pattern = new Array() }
if (!is_last && !in_array(this.Level, lines_pattern)) { lines_pattern.push(this.Level) }
lines_pattern = TreeItem.prototype.updateLastNodes.apply(this, new Array(is_last, lines_pattern))
for (var i=0; i<this.Children.length; i++)
{
lines_pattern = this.Children[i].updateLastNodes((i+1) == this.Children.length, lines_pattern)
}
lines_pattern[array_search(this.Level, lines_pattern)] = -1;
return lines_pattern;
}
TreeFolder.prototype.isNodeImage = function(img)
{
return (
img.src.indexOf('ftv2mlastnode.gif') != -1 ||
img.src.indexOf('ftv2plastnode.gif') != -1 ||
img.src.indexOf('ftv2mnode.gif') != -1 ||
img.src.indexOf('ftv2pnode.gif') != -1
)
}
TreeFolder.prototype.folderClick = function(img)
{
if (this.Expanded) {
this.collapse();
}
else {
this.expand();
}
}
TreeFolder.prototype.remove = function()
{
this.removeChildren();
var p = this.Tr.parentNode;
p.removeChild(this.Tr);
}
TreeFolder.prototype.removeChildren = function()
{
- for (var i in this.Children) {
+ for (var i=0; i<this.Children.length; i++) {
this.Children[i].remove();
}
this.Children = new Array();
}
TreeFolder.prototype.successCallback = function ($request, $params, $object) {
if ($params == 'reload') {
$object.removeChildren();
}
$object.Loaded = true;
$object.ProcessXMLNode($request.responseXML);
$object.Render();
$object.locateTopItem().updateLastNodes();
$object.expand();
if (last_highlighted_key) {
var fld = $object.locateItemByKey(last_highlighted_key)
if (fld) {
fld.highLight();
}
}
$object.Reloading = false;
}
TreeFolder.prototype.reload = function()
{
if (this.Reloading) {
return ;
}
this.Reloading = true;
Request.headers['Content-type'] = 'text/xml';
Request.makeRequest(this.LateLoadURL, false, '', this.successCallback, this.errorCallback, 'reload', this);
}
TreeFolder.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX ERROR: ' + Request.getErrorHtml($request));
$object.Reloading = false;
}
TreeFolder.prototype.expand = function(mode)
{
if (this.Expanding) {
return;
}
this.Expanding = true;
if (!isset(mode)) mode = 0;
this.display();
if (mode == 0 || this.Expanded ) {
for (var i=0; i<this.Children.length; i++)
{
this.Children[i].expand(mode+1);
}
}
if (mode == 0) {
if (this.LateLoadURL && !this.Loaded) {
Request.headers['Content-type'] = 'text/xml';
Request.makeRequest(this.LateLoadURL, false, '', this.successCallback, this.errorCallback, '', this);
}
this.Expanded = true;
TreeManager.markStatus(this.Key, 1)
if (isset(this.Img)) {
this.Img.src = this.getNodeImage(this.isLast);
}
}
this.Expanding = false;
}
TreeFolder.prototype.collapse = function(mode)
{
if (!isset(mode)) mode = 0;
for (var i=0; i<this.Children.length; i++)
{
this.Children[i].collapse(mode+1);
this.Children[i].hide();
}
if (mode == 0) {
this.Expanded = false;
TreeManager.markStatus(this.Key, 0)
if (isset(this.Img)) {
this.Img.src = this.getNodeImage(this.isLast);
}
}
}
function TreeManager() {}
-TreeManager.ExpandStatus = new Array ();
+TreeManager.ExpandStatus = {};
TreeManager.markStatus = function(id, status)
{
this.ExpandStatus[id] = status;
if (!status) {
for (var i in this.ExpandStatus) {
if (i.indexOf(id) == 0) { // if i starts with the same as id, meaning it is its child node
this.ExpandStatus[i] = 0;
}
}
}
TreeManager.saveStatus()
}
TreeManager.isExpanded = function(id)
{
return (this.ExpandStatus[id] == 1);
}
TreeManager.saveStatus = function ()
{
var cookieString = new Array();
for (var i in this.ExpandStatus) {
if (this.ExpandStatus[i] == 1) {
cookieString.push(i);
}
}
document.cookie = 'TreeExpandStatus=' + cookieString.join(':');
}
TreeManager.loadStatus = function () {
var $tree_status = getCookie('TreeExpandStatus');
if (!$tree_status) {
return ;
}
$tree_status = $tree_status.split(':');
for (var $i = 0; $i < $tree_status.length; $i++) {
this.ExpandStatus[$tree_status[$i]] = true;
}
// print_pre(this.ExpandStatus);
}
TreeManager.loadStatus();
\ No newline at end of file
Index: branches/RC/core/admin_templates/js/dropdown_mapper.js
===================================================================
--- branches/RC/core/admin_templates/js/dropdown_mapper.js (revision 11931)
+++ branches/RC/core/admin_templates/js/dropdown_mapper.js (revision 11932)
@@ -1,129 +1,129 @@
function DropDownMapper(map, request, input_mask) {
this.Map = map;
this.Request = request;
this.InputMask = input_mask;
this.Objects = new Object();
this.WatchFields = [];
this.UpdateFields = {};
this.Init()
}
DropDownMapper.prototype.Init = function()
{
this.AssignDrills(this.Map);
this.DrillDownRequests(this.Map,'root');
- for (var i in this.WatchFields) {
+ for (var i = 0; i < this.WatchFields.length; i++) {
var elem = document.getElementById(this.InputMask.replace('#FIELD#', this.WatchFields[i]));
elem.fieldName = this.WatchFields[i];
addEvent(elem, 'change', function(ev) {
var el = !is.ie ? ev.currentTarget : window.event.srcElement;
mapper.Changed(el.fieldName);
})
}
}
DropDownMapper.prototype.GetFilters = function(map, o)
{
if (!map) map = this.Map;
if (!o) o = '';
for (var i in map) {
if (map[i].Field) o += escape(map[i].Field+'='+this.GetValue(map[i].Field)+'&');
if (map[i].Pass) { // additional fields to pass to the ajax query
for (var x in map[i].Pass) {
o += escape(map[i].Pass[x]+'='+this.GetValue(map[i].Pass[x])+'&');
}
}
if (map[i].SubNodes) {
o += this.GetFilters(map[i].SubNodes)
}
}
return o;
}
DropDownMapper.prototype.GetValue = function(field)
{
elem = document.getElementById(this.InputMask.replace('#FIELD#', field));
if (elem.type && elem.type == 'checkbox') return elem.checked ? 1:0;
return elem.value;
}
DropDownMapper.prototype.Changed = function(field)
{
var branch = this.FindBranch(field);
this.DrillDownRequests(branch, field);
if (this.UpdateFields[field]) {
for (var i in this.UpdateFields[field]) {
this.Objects[this.UpdateFields[field][i]].Query();
}
}
}
DropDownMapper.prototype.AssignDrills = function(map)
{
var mapper = this;
for (var i in map) {
if ( map[i].Field ) {
this.WatchFields.push(map[i].Field);
if ( map[i].Pass ) {
for (var p in map[i].Pass) {
if (!in_array(map[i].Pass[p], this.WatchFields)) {
this.WatchFields.push(map[i].Pass[p]);
}
if (!this.UpdateFields[map[i].Pass[p]]) this.UpdateFields[map[i].Pass[p]] = new Array();
if (!in_array(map[i].Field, this.UpdateFields[map[i].Pass[p]])) {
this.UpdateFields[map[i].Pass[p]].push(map[i].Field);
}
}
}
}
if ( typeof(map[i].Dependent) == 'undefined' || i.Dependent ) {
var val = map[i].Value ? map[i].Value : null
var obj = new AjaxDropdownPreloader(this.Request, this.InputMask, null, map[i].Field, val );
obj.prepareURL = function()
{
return this.URL.replace('#QUESTIONED#', this.DependendField).replace('#FILTERS#', mapper.GetFilters().replace(/%26$/, ''))
}
this.Objects[map[i].Field] = obj;
}
if (typeof(map[i].SubNodes) == 'object') {
if ( typeof(map[i].Dependent) == 'undefined' || i.Dependent ) {
var ii = i; // we need this, otherwise AfterProcess will use the wrong i (be reference)
obj.AfterProcess = function() {
// mapper.DrillDownRequests(map[ii].SubNodes, ii);
}
}
this.AssignDrills(map[i].SubNodes);
}
}
}
DropDownMapper.prototype.FindBranch = function(branch, map)
{
if (!map) map = this.Map;
for (var i in map) {
if (typeof(map[i].SubNodes) == 'object') {
if (map[i].Field == branch) return map[i].SubNodes;
var res = this.FindBranch(branch, map[i].SubNodes);
if (res) return res;
}
}
return false;
}
DropDownMapper.prototype.DrillDownRequests = function(map,item)
{
for (var i in map) {
if (map[i].Field && this.Objects[map[i].Field]) {
this.Objects[map[i].Field].Query();
}
else {
this.DrillDownRequests(map[i].SubNodes,item); //if there is no object for current item, try its children
}
}
}
DropDownMapper.prototype.QueryByField = function(field)
{
this.Objects[field].Query();
}
\ No newline at end of file

Event Timeline