// HEADER START
// This file is part of the wdss system.
// Author: Eduard Gode
// Copyright by the author
// Copying, distribution, inclusion (execution) without explicit permission is denied.
// Permissions granted to <wdss> websites of customers of:
//    Weitblick Internetwerkstatt, Erhard Klein or
//    Weitblick <wdss> Services, Eduard Gode
//
// Coding conventions:
// * All functions, methods and data has to be coded within the global object WDSS
// * All functions, methods and data named with a stating '_' is internal and may be change in future revisions 
if(null==window.WDSS)window.WDSS={module:{},requireModule:function(m){if(!this.module[m]){this.module[m]=1;document.write('<script type="text/javascript" src="/js-pool/wdss/'+m+'.js"></script>');}}};
// HEADER END

WDSS.requireModule('popup');

WDSS.module.editor = '$Revision: 1.47 $';


//#####################################################

if ( null == WDSS.loaded ) {

  if ( navigator.userAgent.toLowerCase().indexOf('msie') != -1 ) {
    WDSS.isMSIE = function () { return true; };
  } else {
    WDSS.isMSIE = function () { return false; };
  }


  WDSS.loaded = function (name) {
    var list  = WDSS.callOnLoaded.modules[name];
    if ( null != list ) {
      for ( var i = 0; i < list.length; i++ ) {
        if ( WDSS.isMSIE() ) {
          WDSS.callOnLoaded.toCall.push( list[i] );
        } else {
          list[i]();
        }
      }
    }
    if ( WDSS.callOnLoaded.toCall.length ) window.setTimeout( 'WDSS.callOnLoaded.call()', 0 );
  };


  WDSS.callOnLoaded = function (name,func) {
    var list = WDSS.callOnLoaded.modules[name];
    if ( null == list ) list = WDSS.callOnLoaded.modules[name] = [];
    list.push(func);
  };
  WDSS.callOnLoaded.modules = {};
  WDSS.callOnLoaded.toCall  = [];
  WDSS.callOnLoaded.call = function () {
    while ( WDSS.callOnLoaded.toCall.length ) {
      var func = WDSS.callOnLoaded.toCall.pop();
      func();
    }
  };


  WDSS.dynamicLoadJavascript = function (file) {
    if ( WDSS.dynamicLoadJavascript.loading[file] ) return;
    WDSS.dynamicLoadJavascript.loading[file] = 1;
    var scr = document.createElement('script');
    scr.setAttribute( 'type', 'text/javascript');
    scr.setAttribute( 'src',  file );
    document.getElementsByTagName('head')[0].appendChild(scr);
  };
  WDSS.dynamicLoadJavascript.loading = {};
}


//########################################################################


if ( null == WDSS.editor ) { // protect from multiple include
  WDSS.editor = {};


  WDSS.getAncestorByNodeName = function (node,nodeName) {
    for ( ; null != node; node = node.parentNode ) {
      if ( 1 == node.nodeType && nodeName == node.nodeName ) return node;
    }
    return null;
  };
  WDSS.getAncestorFORM = function (node) { return WDSS.getAncestorByNodeName(node,'FORM'); };


  WDSS._createCallbacks = function ( frame, formOrNode, field, argsIn, values ) { // intern function
    var form = ( null != formOrNode && 'string' != typeof( formOrNode ) ) ? WDSS.getAncestorFORM( formOrNode ) : formOrNode;
    if ( null != argsIn && null != argsIn.callback ) return argsIn.callback;

    var multiple = false;
    var getField;
    var getFields;
    if ( null == frame ) frame = window;
    if ( null != form && typeof(form) == 'string' ) form = frame.document.forms[form];
    if ( null == field ) {
    } else if ( 'string' == typeof(field) ) {
      var _field = form[field];
      if ( null == _field ) alert( 'could not determine input field: \''+field+'\' of form: \''+form.name+'\'');
      getField = function () { return _field; };
    } else if ( null != field.length ) {
      multiple = true;
      if ( null == form ) {
        for ( var i = 0; null == form && i < field.length; i++ ) {
  	form = field[i].form;
        }
      }
    
      var _fields = [];
      var _form = form;
      for ( var i = 0; i < field.length; i++ ) {
        var _field = field[i];
        if ( 'string' == typeof(_field) ) {
  	_field = _form[_field];
  	if ( null == _field ) alert( 'could not determine input field: \''+field+'\' of form: \''+_form.name+'\'');
        } else {
  	_form = _field.form;
        }
        _fields.push(_field);
      }
      getFields = function () { return _fields; };
    } else if ( null != field.form ) {
      form = field.form;
      getField  = function () { return field; };
    }
    getForm = function () { return form; };

    var getValues;
    if ( values != null ) {
      getValues = function () { return values; };
    } else if ( multiple ) {
      getValues = function () { var _fields = getFields();
  			      var _values = [];
  			      for ( var i = 0; i < _fields.length; i++ ) {
  				var _field = _fields[i];
  				_values.push( ( null == _field ) ? null : _field.value );
  			      }
			      return _values;
      };
    } else {
      getValues = function () { var _field = getField(); return _field.value; };
    }
  
    var setValues;
    if ( null == field ) {
    } else if ( multiple ) {
      setValues = function (arg) { var _fields = getFields();
  				 for ( var i = 0; i < _fields.length; i++ ) {
  				   var _field = _fields[i];
  				   if ( null != _field ) {
  				     _field.value = arg[i];
  				     if ( _field.onchange ) _field.onchange();
  				   }
  				 }
  				 return true;
  			       };
    } else {
      setValues = function (arg) { var _field = getField();
  				 if ( null == arg ) return;
  				 _field.value = arg;
  				 if ( _field.onchange ) _field.onchange();
  				 return true;
                                 };
    }
    var callback = { multiple: multiple };
    if ( null != getValues ) callback.getValues = getValues;
    if ( null != setValues ) callback.setValues = setValues;
    if ( null != getFields ) callback.getFields = getFields;
    if ( null != getField  ) callback.getField  = getField;
    if ( null != getForm   ) callback.getForm   = getForm;

    return callback;
  };


  WDSS._addArguments = function ( dest, source, argnames ) {
    if ( !argnames ) return;
    for ( var i = 0; i < argnames.length; i++ ) {
      var name = argnames[i];
      if ( null != source[name] ) dest[name] = source[name];
    }
  };


/* embedded dialogs */

  if ( null == WDSS._editorEmbedded ) WDSS._editorEmbedded = { id: 0, data: {} };


  WDSS._openEmbeddedDialogs = function () {
    for ( var id in WDSS._editorEmbedded.data ) {
      var place = document.getElementById(id);
      if ( null == place ) continue;
      var data = WDSS._editorEmbedded.data[id]; WDSS._editorEmbedded.data[id] = null;
      if ( null == data ) continue;
   
      if ( null != data.loader ) {
        var callInfo = data.win.__callInfos[data.name]; // see popup.js setDialogCallInfo
        var callback = callInfo.callback;
        callInfo.embedded = true;
        callback.setDefaultOnchangeHandler = function (ochandler) { // insert onchange handler into source fields
  	if ( null != callback && null != ochandler ) {
  	  var fields = callback.multiple ? callback.getFields() : [  callback.getField() ];
  	  for ( var i = 0; i < fields.length; i++ ) {
            var field = fields[i];
            if ( null != field && null == field.onchange ) { field.onchange = ochandler; if (0) alert('field: '+field.name+', func: '+ochandler); } };
    	  }
        };
        var node = document.createElement('div');
        var style = node.style;
        style.width  = data.width+'px';
        style.height = data.height+'px';
        style.border = data.border ? data.border+'px inset lightgrey' : '0';
        place.parentNode.replaceChild(node,place);
        node.setAttribute('id',id);
        //alert( 'call loader for ' + id );
        data.loader( node, callInfo );
      } else {
        var src = data.src += '?name=' + escape(data.name);
        var node = document.createElement('iframe');
        node.setAttribute('width', data.width );
        node.setAttribute('height',data.height);
        node.setAttribute('border',data.border);
        place.parentNode.replaceChild(node,place);
        node.setAttribute('src',src);
        node.setAttribute('id',id);
      }
    }
    window.clearInterval(WDSS._editorEmbedded.handler);
    WDSS._editorEmbedded.handler = null;
  };


WDSS._isEmbedded = function ( argsIn ) { return null != argsIn && ( 'string' == typeof(argsIn.embed) || argsIn.embed ); };


WDSS._openDialogOrEmbed = function ( win, url, name, args, info ) {
  if ( WDSS._isEmbedded( args ) ) {
    var id = 'string' == typeof(args.embed) ? args.embed : 'wdss_embed_'+(WDSS._editorEmbedded.id++);
    var iName = WDSS.setDialogCallInfo( window, null, info ); // set callInfo and get individual name
    //alert( '._openDialogOrEmbed:'+id+', '+name );
    WDSS._editorEmbedded.data[id] = { win: win, width: args.width, height: args.height, border: args.border, src: url, name: iName, loader: args.loader };
    if ( null == WDSS._editorEmbedded.handler ) WDSS._editorEmbedded.handler = window.setInterval('WDSS._openEmbeddedDialogs()',300);
    document.write('<span id="'+id+'">&nbsp;</span>');
  } else {
    WDSS.openDialog( window, url, name, args, info ); 
  }
};


// functions called by special links in the form

WDSS.openEditor = function ( formOrNode, field, argsIn, info, url, target ) {
  var args = WDSS.combineHash( { width: 800, height: 640, scrollbars: false, resizable: true }, argsIn );
  if ( !info ) info = {};
  info.callback = WDSS._createCallbacks(window,formOrNode,field,null);
  WDSS.openDialog( window, url, target, args, info );
};


WDSS.designEditor_loader = function ( node, callInfo ) {
  if ( null == WDSS.multiModeEditor ) {
    WDSS.callOnLoaded( 'WDSS.designModeEditor', function () { new WDSS.designModeEditor( node, callInfo ); } );
    WDSS.dynamicLoadJavascript( '/js-pool/wdss/editor/designMode_wdss.js' );
  } else {
    new WDSS.designModeEditor( node, callInfo );
  }
};


WDSS.multiEditor_loader = function ( node, callInfo ) {
  if ( null == WDSS.multiModeEditor ) {
    WDSS.callOnLoaded( 'WDSS.multiModeEditor', function () { new WDSS.multiModeEditor( node, callInfo ); } );
    WDSS.dynamicLoadJavascript( '/js-pool/wdss/editor/multiModeEditor.js' );
  } else {
    new WDSS.multiModeEditor( node, callInfo );
  }
};


WDSS.designEditor = function ( formOrNode, field, code, argsIn ) {
  var editor   = (argsIn != null && argsIn.editor != null) ? argsIn.editor.toLowerCase() : 'wdss';
  var url      = '/js-pool/wdss/editor/editor.design.'+editor+'.html';
  var defaults = WDSS._isEmbedded( argsIn ) ? { width: 300, height: 200, border: 2,  loader: WDSS.multiEditor_loader }
                                            : { width: 800, height: 640, scrollbars: false, resizable: true          };
  var args = WDSS.combineHash( defaults, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn), code: code };
  if ( argsIn ) WDSS._addArguments( info, argsIn, ['noFontAttrs','noLink','noImage','getImgUrl','getLnkUrl','helpUrl','baseHref','customStyles','style','tags','experimental','embed']);
  WDSS._openDialogOrEmbed( window, url, 'designEditor', args, info );
};


WDSS.multiEditor = function ( formOrNode, field, code, argsIn ) {
  var editor = (argsIn != null && argsIn.editor != null) ? argsIn.editor.toLowerCase() : 'wdss';
  var url    = '/js-pool/wdss/editor/editor.multi.html';
  var defaults = WDSS._isEmbedded( argsIn ) ? { width: 300, height: 200, border: 2,  loader: WDSS.multiEditor_loader }
                                            : { width: 800, height: 640, scrollbars: false, resizable: true          };
  var args = WDSS.combineHash( defaults, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn), code: code };
  if ( argsIn ) WDSS._addArguments(info,argsIn,['noFontAttrs','noLink','noImage','getImgUrl','getLnkUrl','helpUrl','baseHref','customStyles','style','tags','experimental','modes','embed']);
  WDSS._openDialogOrEmbed( window, url, 'multiEditor', args, info );
};



WDSS.codeEditor = function ( formOrNode, field, lineNrPrefix ) {
  var args = { width: 800, height: 640, scrollbars: false, resizable: true };
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,null), lineNrPrefix: lineNrPrefix }
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.code.html', 'codeEditor', args, info );
};


WDSS.urlEditor = function ( formOrNode, field, argsIn ) {
  var args = WDSS.combineHash( { width: 800, height: 640, scrollbars: false, resizable: true }, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) }
  WDSS._addArguments(info,argsIn,['nonLocal','local']);
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.url.html', 'urlEditor', args, info );
};


WDSS.htmlEditor = function ( formOrNode, field, argsIn ) {
  var args = WDSS.combineHash( { width: 800, height: 640, scrollbars: false, resizable: true, reusePopup: null }, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) }
  WDSS._addArguments(info,argsIn,['lineNrPrefix']);
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.html.html', 'htmlEditor', args, info );
};


WDSS.textileEditor = function ( formOrNode, field, argsIn ) {
  var args = WDSS.combineHash( { width: 800, height: 640, scrollbars: false, resizable: true, reusePopup: null }, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) }
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.textile.html', 'textileEditor', args, info );
};


WDSS.colorEditor = function ( formOrNode, field, argsIn ) {
  var args = WDSS.combineHash( { width: 400, height: 360, scrollbars: false, resizable: true, reusePopup: true }, argsIn );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) }
  if ( argsIn ) WDSS._addArguments(info,argsIn,['showRGB','noHash']);
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.color.html', 'colorEditor', args, info );
};


WDSS.dateEditor = function ( formOrNode, field, argsIn ) {
  var height = 132;
  var url = '/js-pool/wdss/editor/editor.date.html';
  if ( null != argsIn && argsIn.tfield ) {
    if ( 'string' == typeof( field ) || null == field.lenght ) field = [ field, null ];
    if ( null == field[1] ) field[1] = argsIn.tfield;
  }
  var args;
  if ( WDSS._isEmbedded( argsIn ) ) {
    height = 126;
    if ( null != argsIn.tfield ) height += 22;
    args = WDSS.combineHash( { width: 215, height: height, border: 1 }, argsIn );
  } else {
    args = WDSS.combineHash( { width: 215, height: height, scrollbars: false, resizable: true, reusePopup: true }, argsIn );
  }
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) };

  if ( argsIn ) WDSS._addArguments(info,argsIn,['showOtherDays','showWeek','firstWDay','deFormat','tfield','embed']);

  WDSS._openDialogOrEmbed( window, url, 'dateEditor', args, info );
};


WDSS.geoposEditor = function ( formOrNode, field, values ) {
  var args = { width: 705, height: 530, scrollbars: false, resizable: true };
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,null,values) };
  if ( null == values ) values = info.callback.getValues();
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.geopos.html?geo='+escape(values), 'geoposEditor', args, info );
};


WDSS._int_parseAttrString = function ( str ) {
  var attrs = {};
  if ( null != str ) {
    if ( 'string' == typeof(str) ) {
      var attrList = str.split(/\s*,\s*/);
      for ( var i = 0; i < attrList.length; i++ ) {
        var res;
        if ( res = /^(\w+)=(.*)$/.exec(attrList[i]) ) {
          var name = res[1];
          var val  = res[2];
          if      ( val.match(/^\d+$/) ) val = parseInt(val);
          else if ( val.match(/yes/,i) ) val = true;
          else if ( val.match(/no/,i)  ) val = false;
          attrs[name] = val;
        } else {
          alert("illegal attribute '"+attrList[i]+"' in '"+str+"' (editor.js)");
        }
      }
    } else {
      attrs = str;
    }
  }
  return attrs;
};


WDSS._int_getSingleField = function ( frame, formOrNode, field ) {
  if ( 'string' != typeof(field) ) return field;
  if ( null == formOrNode ) alert( 'no specified to determine input field: \''+field+'\'');
  var form = ( 'string' == typeof( formOrNode ) ) ? frame.document.forms[formOrNode] : WDSS.getAncestorFORM( formOrNode );
  if ( null == form ) alert( 'could not determine form of input field: \''+field+'\'');
  var _field = form[field];
  if ( null == _field ) alert( 'could not determine input field: \''+field+'\' of form \''+form.name+'\'');
  return _field;
};


WDSS.configuredExtension = function ( formOrNode, field, arg ) {
  field = WDSS._int_getSingleField ( window, formOrNode, field );
  var args = { field: field, arg: arg };
  var cgi = arg.CGI; if (null == cgi) cgi = {};
  var params = [ '_field='+encodeURIComponent(field.name), 'ref='+arg.ref ];
  for ( var p in cgi ) {
    params.push( encodeURIComponent(p)+'='+encodeURIComponent(cgi[p]) ); 
  }
  var url = '/admin/'+arg.CONFIG_KEY+'/extension.popup/simple.html?'+params.join('&');
  if ( !arg.CONFIG_KEY ) url = '/admin/editor.indiv/simple.html';
  if ( !arg.target ) arg.target = "wdssPopup";
  var geo = WDSS.combineHash( { width: 600, height: 400 }, WDSS._int_parseAttrString( arg.geo ) );
  WDSS.openDialog( window, url, arg.target, geo, args );
};


WDSS.anchorEditor = function ( formOrNode, field, argsIn ) {
  field = WDSS._int_getSingleField ( window, formOrNode, field );
  var upwinname = 'upload.'+field.name;
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn), arg: argsIn };
  info.upload = window[upwinname];
  var cgi  = argsIn.CGI; if (null == cgi) cgi = {};
  var params = [ '_field='+encodeURIComponent(field.name), 'ref='+argsIn.ref ];
  for ( var p in cgi ) { params.push( encodeURIComponent(p)+'='+encodeURIComponent(cgi[p]) ); }
  var url = '/admin/'+argsIn.CONFIG_KEY+'/editor.anchor/simple.html?'+params.join('&');
  var target = (null != argsIn.target) ? argsIn.target : 'anchorPopup';
  var geo = WDSS.combineHash( { width: 520, height: 400, scrollbars: true }, WDSS._int_parseAttrString( argsIn.geo ) );
  var win = WDSS.openDialog( window, url, target, geo, info );

  var upload = window[upwinname];
  if ( null != upload ) {
    var name = win.name;
    info.callback.upload = function () {
      //popupClose(name);
      WDSS.subEntryAdmin( formOrNode, field, upload );
    };
  }
};


// callback has to return true on success
WDSS.dataImport = function ( callback, argsIn ) {
  var args = { width: 290, height: 75, scrollbars: false, resizable: true };
  var info = { callback: { getValues: function () {}, setValues: callback }  };
  WDSS.openDialog( window, '/js-pool/wdss/editor/editor.import.html', 'dataImport', args, info );
};


WDSS.subEntryAdmin = function ( formOrNode, field, argsIn ) {
  field = WDSS._int_getSingleField ( window, formOrNode, field );
  var info = { callback: WDSS._createCallbacks(window,formOrNode,field,argsIn) };

  var feature = argsIn.FEATURE;
  if ( !feature ) feature = 'file';
  var ref     = argsIn.ref;
  if ( argsIn.key ) ref += ',H'+argsIn.key;

  var url = '/dynamic/secure/admin/entry.phtml?_frame=content&_feature='+feature+'&_field='+escape(field.name)+'&ref='+ref;
  if ( argsIn.CODE        ) url += '&_code='+escape(argsIn.CODE);
  if ( argsIn.urlParamStr ) url += argsIn.urlParamStr;

  var geo = WDSS.combineHash( { width: 700, height: 540 }, WDSS._int_parseAttrString( argsIn.geo ) );
  WDSS.openDialog( window, url, 'subEntry', geo, info );
};

}


if ( !WDSS.noDeprecatedCode ) {
  var funcs = [ 'openEditor', 'designEditor', 'codeEditor', 'urlEditor', 'htmlEditor', 'textileEditor', 'colorEditor', 'dateEditor', 'geoposEditor', 'configuredExtension', 'anchorEditor', 'dataImport' ];
  for ( var i = funcs.length; i--; ) { var n = funcs[i]; window['wdss_'+n] = WDSS[n]; }

  window.subEntryAdmin = WDSS.subEntryAdmin;
}


