dojo.require("dojo.cookie");

String.prototype.trim = function () 
{
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}

String.prototype.startsWith = function(str)
{
  return (this.indexOf(str) === 0);
}

function Connector()
{
  this._subscribers = [];
  this._subscribers1 = [];
  this._subscribersId = new Array();
  this.subscribe = function(func, once)
  {
    if (once)
      this._subscribers1.push(func);
    else
      this._subscribers.push(func);
  }
  this.subscribeOnce = function(func)
  {
    this.subscribe(func, true);
  }
  this.subscribeId = function(func, _call_id)
  {
    this._subscribersId[_call_id] = func;
  }
  this.publish = function(args)
  {
    for (var i = 0; i < this._subscribers1.length; i++)
      this._subscribers1[i](args);
    for (var i = 0; i < this._subscribers.length; i++)
      this._subscribers[i](args);
      
    this._subscribers1 = [];
	
	if (typeof(args['_call_id']) != 'undefined')
	{
	  var _call_id = args['_call_id'];
	  if (typeof(this._subscribersId[_call_id]) != 'undefined')
	  {
		this._subscribersId[_call_id](args);
		delete this._subscribersId[_call_id];
	  }
	}
  }
};

/**
 *  smoothy class with utility functions for smoothy
 */
var smoothy = 
{
  /**
   * getOptionOrDefault from an options object
   * smoothy.getOptionOrDefault(options, "title", "Helloworldd");
   *
   * @param   object  options   object with option key-values, e.g. { title: 'name?', onOk: function(result) { alert(result); }}
   * @param   string  name   key/property
   * @param   defaultValue
   */
  getOptionOrDefault : function(options, name, defaultValue) 
  {  
    if (typeof(options) == 'undefined' || typeof(options[name]) == 'undefined')
      return defaultValue;
    return options[name];
  },

  getExceptionMessage : function(e) { return 'exception: ' + e.message + ' (' + e.name + ')'; },
  
  /**
   * stores a named value into cookie
   * smoothy.setCookie('test', 23);
   * smoothy.setCookie("smoothy", smoothy, { expires: 265 });
   *
   * @param   string  name   name of cookie
   * @param   string  value   value to be stored
   * @param   dojo.__cookieProps  cookieProps  
   */
  setCookie : function(name, value, cookieProps) 
  {
    if (cookieProps)
      dojo.cookie(name, value, cookieProps);
    else
      dojo.cookie(name, value);
  },
  
  /**
   * gets a cookie value
   * var x = smoothy.getCookie('test');
   *
   * @param   string  name    name of cookie
   * @return value
   */
  getCookie : function(name)
  { 
    return dojo.cookie(name);
  },
  /**
   * deletes a cookie
   * smoothy.deleteCookie('test');
   *
   * @param   string  name    name of cookie
   */
  deleteCookie : function(name)
  {
    dojo.cookie(name, null, {expires: -1});
  },
  
  /*---------------------------------------------------------------------------------*/
  
  /**
   * smoothy.ensureJsScript('libs/ckeditor/ckeditor.js');
   */
  ensureJsScript : function(scriptSrc)
  {
    var scripts = document.getElementsByTagName("script");
    for (var i=0; i < scripts.length; i++) 
	  {
		  if (scripts[i].src == scriptSrc)
        return;
		}
    var head = document.getElementsByTagName("head")[0];
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptSrc;
    head.appendChild(script);   
  },
  /*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.form class with utility functions for form
   */
  form : 
  {
    isNotFilled : function(element)
    {
      return (element.value == "" || element.value == null);
    },
    isNumeric : function(value)
    {
      return /^\d+$/.test(value);
    }
  },

  /*---------------------------------------------------------------------------------*/
  
  requestLastPath : function()
  {
    lastPath = smoothy.getCookie("prev_path");
    if (lastPath)
      smoothy.ajax.postParams( { path: lastPath } ); // prev_path cookie set by server
    else
      alert('lastPath undefined: ' + document.cookie);
  },
    
  /*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.paging class with utility functions for paging
   */
  paging : 
  {
    /**
      * smoothy.paging.setPageNumber('/admin', 2);
      */
    setPageNumber : function(path, pageNumber)
    {
      smoothy.ajax.postParams( { path: path, smoothyPageNumber: pageNumber } );
    },
    /**
      * smoothy.paging.setPageRowCount('/admin', 200);  -1 is all
      */
    setPageRowCount : function(path, pageRowCount)
    {
      smoothy.ajax.postParams( { path: path, smoothyPageRowCount: pageRowCount } );
    }
  },
    
  /*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.ui class with utility functions for ui
   */
  ui : 
  {
    /**
     * smoothy.ui.transferCheckboxToHidden(this, 'hidden1');
     */
    transferCheckboxToHidden : function(checkbox, hiddenId)
    {
      var hiddenNode = dojo.byId(hiddenId);
      hiddenNode.value = checkbox.checked ? 1 : 0;
    },
    /**
     * smoothy.ui.setShowNode('div2', false);
     */
    setShowNode : function(id, enable)
    {
      var node = dojo.byId(id);
      if (enable)
      {
        node.style.display = '';
      }
      else
      {
        node.style.display = 'none';
      }
    },
    /**
     * smoothy.ui.getShowNode('div2');
     */
    getShowNode : function(id)
    {
      var node = dojo.byId(id);
      return node.style.display == '';
    },
    /**
     * smoothy.ui.alert('', 'invalid entry' + x);
     */
    alert : function(title, content)
    {
      dojo.require('dijit.Dialog');
      dojo.require('dijit.form.Button');
       
      var dlg = new dijit.Dialog(
      { 
        title: title, 
        content: content,
        style: "text-align: center; width: 400px;"
      });

      var okButton = new dijit.form.Button(
      {
        label: "Ok",
        iconClass: "smoothyIcons smoothyIconYes",
        style: "margin: 0 auto; margin-bottom: 10px;",
        onClick: function()
        {
          dlg.hide();
          return true;
        }
      });
      
      dlg.domNode.appendChild(okButton.domNode);
      dojo.body().appendChild(dlg.domNode);
      dlg.show(); 
    },
    /**
       * smoothy.ui.confirm('', 'are you suuuur?', function() { alert('ok'); });
       */
    confirm : function(title, content, onOK, onCancel)
    {
      dojo.require('dijit.Dialog');
      dojo.require('dijit.form.Button');
       
      var dlg = new dijit.Dialog(
      { 
        title: title, 
        content: content,
        style: "width: 400px;"
      });

     // var coords = dojo.coords(cancelButton.domNode);
      
      var okButton = new dijit.form.Button(
      {
        label: "Ok",
        iconClass: "smoothyIcons smoothyIconYes",
        style: "float: left; margin-left: 80px; margin-bottom: 10px;",
        onClick: function()
        {
          dlg.hide();
          return (onOK ? onOK() : true);
        }
      });
      
      var cancelButton = new dijit.form.Button(
      {
        label: "Cancel",
        iconClass: "smoothyIcons smoothyIconNo",
        style: "float: right; margin-right: 70px; margin-bottom: 10px;",
        onClick: function()
        {
          dlg.hide();
          return (onCancel ? onCancel() : true);
        }
      });
      
      dlg.domNode.appendChild(okButton.domNode);
      dlg.domNode.appendChild(cancelButton.domNode);
      dojo.body().appendChild(dlg.domNode);
      dlg.show(); 
    },
    
    /**
      * smoothy.ui.inputDlg({ title: 'your name?', onOk: function(result) { alert(result); }});
      */
    inputDlg : function(options) // title, content, input, maxLength, onOK, onCancel
    {
      dojo.require('dijit.Dialog');
      dojo.require('dijit.layout.ContentPane');
      dojo.require('dijit.form.Button');
      dojo.require('dijit.form.SimpleTextarea');
      
      var title = smoothy.getOptionOrDefault(options, 'title', '');
      var content = smoothy.getOptionOrDefault(options, 'content', '');
      var input = smoothy.getOptionOrDefault(options, 'input', '');
      var maxLength = smoothy.getOptionOrDefault(options, 'maxLength', 100);
      var onOK = smoothy.getOptionOrDefault(options, 'onOK', null);
      var onCancel = smoothy.getOptionOrDefault(options, 'onCancel', null);
      var dialogStyle = smoothy.getOptionOrDefault(options, 'dialogStyle', "width: 550px; ");
       
      var dlg = new dijit.Dialog(
      { 
        title: title, 
        content: content,
        style: dialogStyle
      });

      var contentPane = new dijit.layout.ContentPane(
      {
        style: "width: 500px; margin-left: 25px;"
      }, 
      document.createElement("div"));

      var textArea = new dijit.form.SimpleTextarea(
      { 
        rows: 10, 
        maxLength: maxLength,
        style: "width: 490px"
      },
      document.createElement("textarea"));
      textArea.attr('value', input);
      textArea.domNode.setAttribute('maxLength', maxLength);
      
      var counterDiv = document.createElement("div"); 
      linkTextAreaAndCounter(textArea.domNode, counterDiv);
      
      contentPane.domNode.appendChild(textArea.domNode);
      contentPane.domNode.appendChild(counterDiv);   
      
      var okButton = new dijit.form.Button(
      {
        label: "Ok",
        iconClass: "smoothyIcons smoothyIconYes",
        style: "float: left; margin-left: 80px; margin-bottom: 10px;",
        onClick: function()
        {
          dlg.hide();
          return (onOK ? onOK(textArea.attr('value')) : true);
        }
      });
      
      var cancelButton = new dijit.form.Button(
      {
        label: "Cancel",
        iconClass: "smoothyIcons smoothyIconNo",
        style: "float: right; margin-right: 70px; margin-bottom: 10px;",
        onClick: function()
        {
          dlg.hide();
          return (onCancel ? onCancel() : true);
        }
      });
      
      dlg.domNode.appendChild(contentPane.domNode);    
      dlg.domNode.appendChild(okButton.domNode);
      dlg.domNode.appendChild(cancelButton.domNode);
      dojo.body().appendChild(dlg.domNode);
      dlg.show(); 
    },
    
    /**
     * smoothy.ui.zoomImage('imgA', 'styles/codediver/images/IE.png', 600, 450);
     * smoothy.ui.zoomImage('imgA', 'styles/codediver/images/IE.png', 600, 450, 2000);
     */
    zoomImage : function(imageNodeId, zoomedImageSrc, scaleToX, scaleToY, duration)
    { 
      if (typeof(duration) == 'undefined')
        duration = 1000;
        
      dojo.require("dojo.fx"); //for dojo.fx.chain and dojo.fx.combine
      dojo.require("dijit.dijit");
      
      var zoomImageId = imageNodeId + 'zoomedImg';
      var zoomDivId = imageNodeId + 'zoomedDiv';
      if (dojo.byId(zoomDivId) != null) // already shown, ignore
        return;
      
      // get start position of image
      var imageNode = dojo.byId(imageNodeId);
      var startPos = dojo.coords(imageNodeId, true);
      var startx = startPos.x;
      var starty = startPos.y;
      var startWidth = imageNode.width;
      var startHeight = imageNode.height;
        
      //get the dimensions of the current viewport
      var viewport = dijit.getViewport();
      var viewportHeight = viewport.h;
      var viewportWidth = viewport.w;
      var viewportTop = viewport.t;

      // create div with image & button
	  
	  // create image
      var img = document.createElement("img");
      img.id = zoomImageId;
      img.src = zoomedImageSrc;
      dojo.style(img, { width: "100%", height: "100%" } );
      
	  // create div for button      
      var buttonDiv = document.createElement("div");
      dojo.style(buttonDiv, { position: 'absolute', left: '-15px', top: '-15px', visibility: 'visible', opacity: 1 } );
	  
	  // create img for button
      var buttonImg = document.createElement("img");
	  buttonImg.src = '/styles/images/closebox.png';
      dojo.style(buttonImg, { width: "30px", height: "30px", cursor: 'pointer' } );
	  buttonDiv.appendChild(buttonImg);
	  
      // create outer div 
      var div = document.createElement("div");
      div.id = zoomDivId;
      div.appendChild(img);
	  div.appendChild(buttonDiv);
      dojo.style(div, "position", "absolute");
      dojo.style(div, "left", startx + 'px'); //(viewportWidth-scaleToX)/2);
      dojo.style(div, "top", starty + 'px'); // (viewportHeight-scaleToY)/2);
      dojo.style(div, "width", startWidth + 'px');
      dojo.style(div, "height", startHeight + 'px');
      dojo.style(div, "zIndex", 50);
      dojo.style(div, "opacity", 0);
      dojo.body().appendChild(div);

      // the fade animations
      fadeInAnim = dojo.fadeIn({node : zoomDivId, duration: duration});
      fadeOutAnim = dojo.fadeOut({node : zoomDivId, duration: duration});

      // the implode animation
      var implode = dojo.animateProperty(
      {
        node : zoomDivId,
        duration: duration,
        properties : 
        {
         left : {end : startx},
         top : {end : starty},
         width  : {end : startWidth},
         height : {end : startHeight}
        },
        onEnd: function()
        {           
          document.body.removeChild(dojo.byId(zoomDivId));
        }
      });
      var endx = (viewportWidth - scaleToX)/2;
      var endy = (viewportHeight - scaleToY)/2;
      if (endx < 0)
        endx = 0;
      if (endy < 0)
        endy = 0;
      // the explode animation
      var explode = dojo.animateProperty(
      {
        node : zoomDivId,
        duration: duration,
        properties : 
        {
         left : {end: endx},
         top : {end: viewportTop + endy},
         height : {end : scaleToY},
         width  : {end : scaleToX}
        }
      });
      
      var hideAnim = dojo.fx.combine([fadeOutAnim, implode]);
	  buttonImg.onclick = img.onclick = function() 
      {
        hideAnim.play();
      };
      
      var showAnim = dojo.fx.combine([fadeInAnim, explode]);
      showAnim.play();
    },
  
    /**
     * smoothy.ui.fadeNodesFromTo('imgA', 'imgB', 1000);
     */
    fadeNodesFromTo : function(nodeId1, nodeId2, duration)
    {
      if (nodeId1 == nodeId2)
        return;
      if (typeof(duration) == 'undefined')
        duration = 1000;
        
      dojo.require("dojo.fx"); // for dojo.fx.chain and dojo.fx.combine
      
      // set start opacity & make sure they're visible
      dojo.style(nodeId1, "opacity", 1.0);
      dojo.style(nodeId2, "opacity", 0.0);
      smoothy.ui.setShowNode(nodeId1, true);
      smoothy.ui.setShowNode(nodeId2, true);
      
      // the fade animations
      fadeInAnim = dojo.fadeIn({node : nodeId2, duration: duration});
      fadeOutAnim = dojo.fadeOut({node : nodeId1, duration: duration, onEnd: function() { smoothy.ui.setShowNode(nodeId1, false); }});
      
      var fadeAnim = dojo.fx.combine([fadeOutAnim, fadeInAnim]);
      fadeAnim.play();
    },
    
    /**
     * smoothy.ui.fadeLastImageInContainer('containerId', 1000);
     */
    fadeLastImageInContainer : function(containerId, duration)
    {
      smoothy.ui.fadeForwardImagesInContainer(containerId, duration, true);
    },
    /**
     * smoothy.ui.fadeNextImagesInContainer('containerId', 1000);
     */
    fadeNextImagesInContainer : function(containerId, duration)
    {
      smoothy.ui.fadeForwardImagesInContainer(containerId, duration, false);
    },
    /**
     * smoothy.ui.fadeForwardImagesInContainer('containerId', 1000, false);
     */
    fadeForwardImagesInContainer : function(containerId, duration, forceLast)
    {
      var container = dojo.byId(containerId);      
      var images = container.getElementsByTagName('img');
      var startNodeIndex = 0;
      for (var i = images.length - 1; i >= 0; i--)
      {
        if (smoothy.ui.getShowNode(images[i].id)) // visible one
        {
          startNodeIndex = i;
          break;
        }
      }
      nextNodeIndex = startNodeIndex + 1;
      if (nextNodeIndex >= images.length)
        nextNodeIndex = 0;
      if (forceLast)
        nextNodeIndex = images.length - 1;
      smoothy.ui.fadeNodesFromTo(images[startNodeIndex].id, images[nextNodeIndex].id, duration);
    },
    
    /**
     * smoothy.ui.fadePreviousImagesInContainer('containerId', 1000);
     */
    fadePreviousImagesInContainer : function(containerId, duration)
    {
      smoothy.ui.fadeBackwardImagesInContainer(containerId, duration, false);
    },
    /**
     * smoothy.ui.fadeFirstImageInContainer('containerId', 1000);
     */
    fadeFirstImageInContainer : function(containerId, duration)
    {
      smoothy.ui.fadeBackwardImagesInContainer(containerId, duration, true);
    },
    /**
     * smoothy.ui.fadeBackwardImagesInContainer('containerId', 1000, false);
     */
    fadeBackwardImagesInContainer : function(containerId, duration, forceFirst)
    {
      var container = dojo.byId(containerId);      
      var images = container.getElementsByTagName('img');
      var startNodeIndex = 0;
      for (var i = 0; i < images.length; i++)
      {
        if (smoothy.ui.getShowNode(images[i].id)) // visible one
        {
          startNodeIndex = i;
          break;
        }
      }
      previousNodeIndex = startNodeIndex - 1;
      if (previousNodeIndex < 0)
        previousNodeIndex = images.length - 1;
      if (forceFirst)
        previousNodeIndex = 0;
      smoothy.ui.fadeNodesFromTo(images[startNodeIndex].id, images[previousNodeIndex].id, duration);
    },
    /**
     * smoothy.ui.fadeToImageInContainer('containerId', 1000, 2);
     */
    fadeToImageInContainer : function(containerId, duration, imageIndex)
    {
      var container = dojo.byId(containerId);      
      var images = container.getElementsByTagName('img');
      var startNodeIndex = 0;
      for (var i = images.length - 1; i >= 0; i--)
      {
        if (smoothy.ui.getShowNode(images[i].id)) // visible one
        {
          startNodeIndex = i;
          break;
        }
      }
      nextNodeIndex = imageIndex;
      smoothy.ui.fadeNodesFromTo(images[startNodeIndex].id, images[nextNodeIndex].id, duration);
    }
  },
  /*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.ajax class with utility s for ajax
   */
  ajax : 
  {
    errorShow: function (data)
    { 
      alert('Error connecting to server\n\n' + data); 
    },
    /**
     * smoothy.ajax.get(url);
     * smoothy.ajax.get(url,  smoothy.ajax.handleResponse, 'main_ajax.php','text');
     */
    get : function(url, callback, php_page, handleAs)
    {     
      if (!callback)
        callback = smoothy.ajax.handleResponse;
      if (!php_page)
        php_page = 'main_ajax.php';
      if (!handleAs)
        handleAs = 'text';
      dojo.xhrGet({
                    url: php_page + url, // Location of the content we want to grab
                    handleAs: handleAs, // if 'json': tells Dojo to automatically parse the HTTP response into a JSON object 
                    preventCache: true, // no browser cache results please
                    load: callback, // Called when the page loaded successfully
                    error: smoothy.ajax.errorShow // Called if error (such as a 404 response)
                   });
    },
    /**
     * smoothy.ajax.post(form1);
     * smoothy.ajax.post(form1,  smoothy.ajax.handleResponse, 'main_ajax.php','text');
     */
    post : function(form, callback, php_page, handleAs)
    {
      if (!callback)
        callback = smoothy.ajax.handleResponse;
      if (!php_page)
        php_page = 'main_ajax.php';
      if (!handleAs)
        handleAs = 'text';
      dojo.xhrPost({
                    url: php_page, // Location of the content we want to grab
                    form: form, // you can provide a either the DOM node of your form or the ID of the form
                    handleAs: handleAs, // if 'json': tells Dojo to automatically parse the HTTP response into a JSON object 
                    load: callback, // Called when the page loaded successfully
                    error: smoothy.ajax.errorShow // Called if error (such as a 404 response)
                   });
    },
    /**
     * smoothy.ajax.postParams({ path: '/bla', id: 23});
     * smoothy.ajax.postParams(params, 'json',  smoothy.ajax.handleResponse, 'main_ajax.php');
     */
    postParams : function(params, handleAs, callback, php_page)
    {
      if (!callback)
        callback = smoothy.ajax.handleResponse;
      if (!php_page)
        php_page = 'main_ajax.php';
      if (!handleAs)
        handleAs = 'text';
      dojo.xhrPost({
                    url: php_page, // Location of the content we want to grab
                    content: params,
                    handleAs: handleAs, // if 'json': tells Dojo to automatically parse the HTTP response into a JSON object 
                    load: callback, // Called when the page loaded successfully
                    error: smoothy.ajax.errorShow // Called if error (such as a 404 response)
                   });
    },
    /**
     * smoothy.ajax.updateDomNode('?path=/panel', 'test_div', 'cms/default');
     * smoothy.ajax.updateDomNode('?path=/panel', 'test_div');
     */
    updateDomNode : function(url, domid, config)
    {
      if (domid)
        url += '&_ajax_response=' + domid;
      if (config)
        url += '&_config=' + config;
      this.get(url); 
    },
    
    //
    // _showResponseError
    //
    
    _showResponseError: function(result)
    {
      var content ="<font color='red'><strong>'" + result + "'</strong></font>";
      var node = dojo.byId("div_nested_content");
      if (node)
        node.innerHTML = content;
      else
        alert("showResponseError: " + result);      
    },
    
    //
    // _doResponseUpdateHTML
    //
    
    _doResponseUpdateHTML: function(result)
    {
      for (var domid in result.html) // update html
      {
        try
        {
          var node = dojo.byId(domid);
          if (node)
          {
            node.innerHTML = result.html[domid];
          }
          else
            alert('Missing node with id: ' + domid);
        }
        catch (e)
        {
          alert("Error: ajax update failed for HTML element with id " + domid + " : " + smoothy.getExceptionMessage(e));
        }
      }
    },
    //
    // _doResponseUpdate
    //
    
    _doResponseUpdate: function(result)
    {
      in_ajax_response = true;
      try
      {
        // alert(dojo.toJson(result));
        if (result.html)
        {
          smoothy.ajax._doResponseUpdateHTML(result);
          
          for (var domid in result.html) // execute script if any, TODO replace by javascriptResponseHandler ?
          {
            execute_script_code(result.html[domid]);
          }
        }
        
        if (result.javascriptResponseHandler) // optionally set by server, e.g. in getAjaxResponse
        {
          var functionName = result.javascriptResponseHandler;
          if (eval("(typeof " + functionName + ") == 'function'"))
            eval(functionName + '(result)');
        }
    
        if (result.style && CURRENT_STYLE != result.style) // update style
        {
          CURRENT_STYLE = result.style;
          set_alternate_css_style(CURRENT_STYLE);
        }
        
        if (result.errors) // errors
          alert("Errors: " + result.errors);
        else if (urlToAddToHistory) // set in request_url
          addToHistory(urlToAddToHistory);      
      }
      catch (e)
      {
        alert('responseUpdate Error'  + smoothy.getExceptionMessage(e));
      }
      in_ajax_response = false; 
    },
    //
    // handleResponse
    //
    
    handleResponse: function(result)
    {
      try
      {
        result = dojo.fromJson(result);
      }
      catch (e)
      {
        alert(smoothy.getExceptionMessage(e) + ' :' + result);
      }
      if (typeof result == "string") // something's wrong (e.g. PHP error makes response not JSON parseable)
      {
        smoothy.ajax._showResponseError(result);
      }
      else
      {
        if (result) // is null if one-way
          smoothy.ajax._doResponseUpdate(result);
      }
              
      smoothy.ajax.responseConnector.publish(result);
    },
    
    
    // smoothy.ajax.responseConnector.subscribe(function(url){ alert(url); }, true);

    requestConnector : new Connector(),
    responseConnector : new Connector()
  }
};

//smoothy.ajax.requestConnector.subscribe(function(url){ alert('request'+url); }, true);
//smoothy.ajax.responseConnector.subscribe(function(result){ alert('response'+result.url); }, true);


function url_encode(str) 
{
  return escape(str).replace(/\+/g, "%2B").replace(/\//g, "%2F");
}

function url_decode(str) 
{
  return unescape(str.replace(/\+/g, " "));
}

function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}

// IE can't deal with dynamic menu after switch to home: force re-init
function borgdorffFix(url)
{
  return (dojo.isIE &&
          CURRENT_STYLE.startsWith('borgdorffweb/') && 
          (url == '?path=/home' || url == '?path=/home/home'));
}

var urlToAddToHistory = '';

function request_url(url) 
{
  // send request to server
  var smoothy_active = smoothy.getCookie("smoothy");
  if (smoothy_active == "on" && !borgdorffFix(url))
  {
    urlToAddToHistory = url; // back / forward support
    smoothy.ajax.get(url);    
    smoothy.ajax.requestConnector.publish(url); // update wait cursor, etc.      
  }
  else
    location.href = url.replace(/\+/g, "%2B"); // url_encode(url); TODO ... also encodes ? en = ...
}

function request_popup(url) 
{
  popup_id = 'div_popup_content';
  
  // previous version may exist, re-use
  var popup_div = dojo.byId(popup_id);
  var first_time = !popup_div;
  if (first_time) // create 1st time
  {
    popup_div = document.createElement('div');
    //  set popup_div properties
    popup_div.id = popup_id;
    popup_div.style.top = '110px';
    popup_div.style.left = '280px';
    popup_div.style.width = '720px';
    popup_div.style.position = 'absolute';
    popup_div.onmousedown = drag_popup;
    document.body.appendChild(popup_div);
  }
  // request contents, we see it at the top so make sure it is visible
  smoothy.ajax.responseConnector.subscribeOnce(function(result) { scroll(0, 0); });
  smoothy.ajax.get(url);
}

function drag_popup(event) 
{
  drag_start(event, 'div_popup_content');
}

function close_popup(popup_id) 
{
  var popup_div = dojo.byId(popup_id);
  if (popup_div)
    document.body.removeChild(popup_div);
}


function ajax_update_value(path, element_id)
{
  smoothy.ajax.get("?path=" + path + 
                   "&_ajax_response=div_nested_content" +
                   "&" + element_id + "=" + get_element_value(element_id));
}

function get_element_value(element_id)
{
  var element = dojo.byId(element_id);
  return element.value;
}

function get_element_checked(element_id)
{
  var element = dojo.byId(element_id);
  return element.checked;
}

function addToHistory(url)
{    
  if (!url) // ignore history urls, see below
    return;
  
  // support browser back button history in Ajax
  
  var gotoUrlFnc = function() 
                    {
                      urlToAddToHistory = ''; // don't add this one!
                      smoothy.ajax.get(url);
                    };

  dojo.back.addToHistory({ back : gotoUrlFnc, forward : gotoUrlFnc }); 
}

var in_ajax_response = false; // for add_window_onload_event

// TODO doesn't handle html code within script code, e.g. in a string correctly
 /* <script language="javascript" type="text/javascript">
add_window_onload_event(function() 
                        {
                          showGoogleMap("map_canvas", 
                                        "Nijverheidstraat 1, \'s Gravenzande, The Netherlands", 
                                        "CodeDiver Headquarters<br />Nijverheidstraat 1<br />2691 AX \'s Gravenzande");
                        }
                        );
</script> */
function execute_script_code(html) 
{
  try
  {
    var reg = /<[\s\/]*script\b[^>]*>([^>]*)<\/script>/i;
    var ar = reg.exec(html);
    if (ar != null)
	{
      eval(ar[1]);
	  // console.log(ar[1]);
	}
  }
  catch (e)
  {
    alert('exception in execute_script_code ' + smoothy.getExceptionMessage(e) + ' : ' + html);
  }
}  

  
function set_language(lcid) 
{
  smoothy.setCookie("language", lcid, { expires: 265 });
  smoothy.setCookie("total_refresh", true); // force refresh of language dependent nodes
  smoothy.requestLastPath();
}

function set_smoothy(smoothy_active) 
{
  smoothy.setCookie("smoothy", smoothy_active, { expires: 265 });
}

function copyright_toggle_smoothy(image_node_id)
{
  var smoothy_active = smoothy.getCookie("smoothy");
  var image_node = dojo.byId(image_node_id);
  if (smoothy_active == "on")
  {
    set_smoothy("off");
    if (image_node)
      image_node.src = "styles/smoothy/images/copyright_vinkie_inverted.gif";
  }
  else
  {
    set_smoothy("on");
    if (image_node)
      image_node.src = "styles/smoothy/images/copyright_vinkie.gif";
  }  
}

function toggle_view() 
{
  // obsolete
  //smoothy.setCookie("toggle_view", true);
  //smoothy.requestLastPath();
}

function toggle_config() 
{
}
      
function clear_search_form() 
{
  dojo.byId("txt_search").value = "";
}

function submit_search() 
{
  //document.frm_search.submit();
  request_url("?path=/search&txt_search=" + dojo.byId("txt_search").value);
}

function on_enter_key_search(e)
{
  var event = (e ? e : window.event);
  if (event)
  {
    var key = (event.charCode ? event.charCode : (event.keyCode ? event.keyCode : event.which));
    if (key == 13)
    {
      submit_search();
    }
  }  
}

function set_background_image_on_node_style(node_id, image_url)
{
  node = dojo.byId(node_id);
  if (node)
    node.style.backgroundImage = "url(" + image_url + ")";
}

function set_value_and_submit_form(id, value, form_id) 
{
  dojo.byId(id).value = value;
  dojo.byId(form_id).submit();
}

/**
 * Checks/unchecks all checkbox in given container (f.e. a form, fieldset or div)
 *
 * @param   string   container_id  the container id
 * @param   boolean  state         new value for checkbox (true or false)
 */
function set_checkboxes(table_id, state, force_events) 
{
  var table = dojo.byId(table_id);
  
  for (var r = 0; r < table.rows.length; r++) 
  {
    var row = table.rows[r];   
    if (row.style.display == "none") // skip invisible, bugfix Johan Stolk 5-9-08
      continue;
        
    var checkboxes = row.getElementsByTagName("input");
    for (var i = 0; i < checkboxes.length; i++)
    {       
      if (checkboxes[i].type == 'checkbox')
      {
        if (checkboxes[i].checked != state)
        {
          if (force_events)
            checkboxes[i].click(); // forces events to happen
          else
            checkboxes[i].checked = state;
        }
      }
    }  
  }
}

function set_node_class(node_id, clazz) 
{
  var node = dojo.byId(node_id);
  if (!node)
    return;
  node.className = clazz;
}

//
// Note: order of 1st disabling all and then enabling active is vital for crappy browsers such as IE 
// 

function set_alternate_css_style(title)
{
  var links = document.getElementsByTagName("link");
  for (var i = 0; i < links.length; i++)  // disable all
  {
    var link = links[i]; 
    if (link.getAttribute("rel").indexOf("style") != -1 && 
        link.getAttribute("title"))
      link.disabled = true;
  }
  for (var i = 0; i < links.length; i++) // enable active
  {
    var link = links[i]; 
    if (link.getAttribute("rel").indexOf("style") != -1 && 
        link.getAttribute("title") == title)
    {
      link.disabled = false;
    }
  }
}

function add_window_onload_event(func) 
{
  if (in_ajax_response)
  {
    func();
    return;
  }
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
  {
    window.onload = func;
  } 
  else 
  {
    window.onload = function() 
    {
      if (oldonload) 
        oldonload();
      func();
    }
  }
}

function set_image_from_select(image_id, select_id)
{
  var img = dojo.byId(image_id);
  if (!img)
    return;
  var select = dojo.byId(select_id);
  if (!select)
    return;
    
  img.src = select.value;
}

// textarea doesn't have a working maxlength by itself... oh well...
function linkTextAreaAndCounter(textArea, counterDiv) 
{
  counterDiv.relatedElement = textArea;
  counterDiv.innerHTML = '<span>0</span>/' + textArea.getAttribute('maxLength');
  
  textArea.relatedElement = counterDiv.getElementsByTagName('span')[0];
  textArea.onkeyup = textArea.onchange = checkTextAreaMaxLength;
  textArea.onkeyup();
}

// textarea doesn't have a working maxlength by itself... oh well...
function setTextAreaMaxLength() 
{
  var textAreas = document.getElementsByTagName('textarea');
  setTextAreaMaxLengthFor(textAreas);
}

// textarea doesn't have a working maxlength by itself... oh well...
function setTextAreaMaxLengthFor(textAreas) 
{
  var counterDivTemplate = document.createElement('div');
  counterDivTemplate.className = 'counterTextArea';
  for (var i = 0; i < textAreas.length; i++)
  {
    var textArea = textAreas[i];
    if (textArea.getAttribute('maxLength'))
    {
      var counterDiv = counterDivTemplate.cloneNode(true);      
      textArea.parentNode.insertBefore(counterDiv, textArea.nextSibling);
      linkTextAreaAndCounter(textArea, counterDiv);
    }
  }
}

function checkTextAreaMaxLength() 
{
  var maxDbLength = this.getAttribute('maxlength');
  
  // length in bytes
  var dbLength = getDatabaseLength(this.value);
  if (dbLength > maxDbLength)
  {
    // length in characters
    var currentLength = this.value.length; 
    var overhead = dbLength - currentLength; // utf8/cr-lf
  
    this.value = this.value.substring(0, maxDbLength - overhead);
    dbLength = getDatabaseLength(this.value);
  }
  this.relatedElement.firstChild.nodeValue = dbLength;//this.value.length;
}

function countWordInstances(string, word) 
{
  var substrings = string.split(word);
  return substrings.length - 1;
}

function getDatabaseLength(str)
{
  var utf8_length = encode_utf8(str).length;
  return utf8_length + countWordInstances(str, "\n");
}

// scroll: 'yes' or 'no'
// resizable: 'yes' or 'no'
function popupWindow(url, title, w, h, scroll, resizable)
{
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  var settings ='height='+h+',';
    settings +='width='+w+',';
    settings +='top='+wint+',';
    settings +='left='+winl+',';
    settings +='scrollbars='+scroll+',';
    settings +='resizable='+resizable+',toolbar=no,location=no';
  
  return window.open(url, title, settings);
}

// extract the thumnail size and remove it's subdirectory
function getRealUrl(url)
{
  var reg = /.*tn_(\d*).*/;
  var ar = reg.exec(url);
  if (ar == null)
    return url;
  var size = ar[1];
  return url.replace('/tn_' + size, '');
}

function showUrlContents(url)
{
  url = getRealUrl(url);
  showUrl(url);
}

// show at 80% size
function showUrl(url)
{
  popupWindow(url, "_blank", parseInt(0.8*window.screen.width,10), parseInt(0.8*window.screen.height,10), 'yes', 'yes');
}

function show_upload_progress(progress_id, form_id)
{
  // to fix an IE bug with gifs we need to show the div AFTER submit...
  dojo.byId(form_id).submit();
  progress_div = dojo.byId(progress_id);
  progress_div.style.display = 'block';
  return false;
}

/**
  validate date value to be dd-mm-yyyy
*/
function isValidDateDMY(dateString)
{
  dateString = dateString.trim();
  if (dateString == '')
    return true;
    
  // replace - with / because regexp expects that
 // dateString = dateString.replace('-', '/'); 

  var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
  return dateString.match(RegExPattern);
}

/**
  validateTextfieldDateDMY validate date value to be dd-mm-yyyy
*/
function validateTextfieldDateDMY(textelement_id)
{
  textelement = dojo.byId(textelement_id);
  if (!textelement)
    return false;
    
  if (isValidDateDMY(textelement.value))
    return true;
  
  var errorMessage = "De opgegeven datum '" + textelement.value + "' is ongeldig";
  alert(errorMessage);
  // textelement.value = '';
  // textelement.focus(); must delay:
  
  setTimeout("dojo.byId('"+textelement_id+"').focus();", 100);
  return false;
}


// initialize edit form of generator
function smoothyInitEditForm()
{
  clickCheckedRadioButtons();
  clickCheckedCheckboxButtons();
  setTextAreaMaxLength();
}

// execute optional eventhandlers of radio buttons to show/hide rows
function clickCheckedRadioButtons() 
{
  var found = false;
  var firstRadioNode = null;
  var x = document.getElementsByTagName('input');
  for (var i=0;i<x.length;i++)
  {
    if (x[i].getAttribute('type') == 'radio')
    {
      if (!firstRadioNode)
        firstRadioNode = x[i];
      if (x[i].getAttribute('checked'))
      {
        smoothyClickedRadio(x[i]);
        found = true;
      }
    }
  }
  if (!found && firstRadioNode) // call default if available
  {
    smoothyCustomCallback('onRadioDefault', firstRadioNode);
  }
}

// execute optional eventhandlers of radio buttons to show/hide rows
function clickCheckedCheckboxButtons() 
{
  var x = document.getElementsByTagName('input');
  for (var i=0;i<x.length;i++)
  {
    if (x[i].getAttribute('type') == 'checkbox')
    {
      if (x[i].getAttribute('checked'))
      {
        smoothyClickedCheckbox(x[i]);
      }
    }
  }
}

/**
  smoothySetChecks
   to handle mysql 'set' type gracefully, all set checkboxes values are glued together
   to prepare correct mysql value for the 'set' type
*/
function smoothySetChecks(node)
{
  var container = node.parentNode;
  if (!container)
    return;
  var inputs = container.getElementsByTagName('input');

  var set_values = new Array();
  var checkboxes = new Array();
  for (var i = 0; i < inputs.length; i++)
  {
    if (inputs[i].type == 'checkbox')
    {
      if (node.name == inputs[i].name) // only take matching ones
      {
        checkboxes.push(inputs[i]);
        if (inputs[i].checked)
        {
          set_values.push(inputs[i].getAttribute("check_value"));
        }
      }
    }
  }
  set_value = set_values.join(',');
  for (var i = 0; i < checkboxes.length; i++) // TODO maybe only set on hidden, different names for checkboxes
  {
    checkboxes[i].value = set_value;
  }
  // note 1st input is a hidden one to force sending no selection to server
}

function smoothyCallFunctionIfExists(functionName)
{
  if (eval("(typeof " + functionName + ") == 'function'"))
    eval(functionName + '()');
}

function smoothyCustomCallback(prefix, node)
{
  var functionName = prefix + node.id;
  if (eval("(typeof " + functionName + ") == 'function'"))
    eval(functionName + '(node)');
}

function smoothyClickedRadio(node)
{
  smoothyCustomCallback('onRadioClick', node);
}

function smoothyClickedCheckbox(node)
{
  smoothySetChecks(node);
  smoothyCustomCallback('onCheckboxClick', node);
}

function assert(condition, errorMessage)
{
  if (!condition) 
  {
    alert('assertion failed: ' + errorMessage);
    throw new Error(errorMessage);
  }
}

function printElementById(id)
{
  var a = popupWindow('', 'Print', '725', '800', 'yes', 'yes');
  a.document.open("text/html");
  a.document.write(dojo.byId(id).innerHTML);
  a.document.close();
  a.print();
}


/*
showGoogleMap
    *  G_NORMAL_MAP
    * G_SATELLITE_MAP
    * G_HYBRID_MAP

*/    
function showGoogleMap(idName, addressOrPoint, info, zoom, mapType)
{
  if (GBrowserIsCompatible()) 
  {
    // default args:
    if (typeof addressOrPoint == "undefined")
      addressOrPoint = "Nijverheidstraat 1, \'s Gravenzande, The Netherlands";
    if (typeof info == "undefined")
      info = '';
    if (typeof zoom == "undefined")
      zoom = 16;  
    if (typeof mapType == "undefined")
      mapType = G_NORMAL_MAP;  
  
    var map = new GMap2(dojo.byId(idName));
    var geocoder = new GClientGeocoder();
    map.setMapType(mapType);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    if (typeof addressOrPoint == 'GLatLng') // no geocoder pressure
    {
      showMarkerAndInfoWindow(map, addressOrPoint, zoom, info)
    }
    else
      geocoder.getLatLng(addressOrPoint,   
                         function(point)
                         {     
                            if (!point)
                              point = new GLatLng(52.00440, 4.16470); // default
                              
                            showMarkerAndInfoWindow(map, point, zoom, info);
                          }
                         );
  }
}

function showMarkerAndInfoWindow(map, point, zoom, info)
{
 map.setCenter(point, zoom);     
  var marker = new GMarker(point);  
  map.addOverlay(marker);
  if (info)
    marker.openInfoWindowHtml(info.replace(/\n/g, '<br />'));      
}

/**
 * toggles specific checkboxes in given table 
 *
 * @param   string   table_id  the table id
 * @param   string   row_id  the row id
 * @param   string   column_id  the column id
 * @param   string   search_text  the rows to toggle (must have value search_text)
 * @param   boolean  force_events      forces events to happen (clicks)
 */

function toggle_checkboxes_if(table_id, row_id, column_id, search_text, force_events) 
{
  var table = dojo.byId(table_id);
  var clicked_row = dojo.byId(row_id);
  var checkboxes = clicked_row.getElementsByTagName("input");
  var state = true;
  for (var i = 0; i < checkboxes.length; i++)
    if (checkboxes[i].type == 'checkbox')
      state = !checkboxes[i].checked; // toggle
  
  for (var r = 0; r < table.rows.length; r++) 
  {
    var row = table.rows[r]; 
    if (row.style.display == "none") // skip invisible, bugfix Johan Stolk 5-9-08
      continue;  
    
    for (var c = 0; c < row.cells.length; c++)
    {  
      if (column_id == table.rows[r].cells[c].id)
      {
        var item_text = jdatagrid_getInnerText(table.rows[r].cells[c]);  
        if (item_text.trim() == search_text)
        {  
          var checkboxes = row.getElementsByTagName("input");
          for (var i = 0; i < checkboxes.length; i++)
          {
            if (checkboxes[i].type == 'checkbox')
            {
              if (checkboxes[i].checked != state)
              {
                if (force_events)
                  checkboxes[i].click(); // forces events to happen
                else
                  checkboxes[i].checked = state;
              }
            }
          }
        }
      }      
    }
  }
}

/**
  requestFilterPage 
  filter_name is optional (can be project_id  or prijslijst_sjabloon)
*/
function requestFilterPage(path, filter_name)
{
  var url = "?path=" + path;
  if (filter_name)
  {
    var filter_element = "select_" + filter_name;
    var filter_value = get_element_value(filter_element);
    url += "&action=filter&name=" + filter_name + "&value=" + filter_value;
  }
  request_url(url);
}

/**
 *  smoothy.db class with db utility functions for smoothy
 */
   
smoothy.db = 
{ 
  /**
   * smoothy.db.toggleBool(path, id, columnName);
   */
  toggleBool : function(path, id, columnName)
  {
  /**
   * in PHP a clientside response handler can be specified like:
   * $ajaxResult['javascriptResponseHandler'] = 'borgdorff.updateAfterGefactureerdToggle';
   */
    var params = { path: path,
                   action: 'toggleBool',
                   id: id,
                   columnName: columnName,
                   _ajax_response: '' };
    smoothy.ajax.postParams(params);
  }
}

/**
 *  smoothy.editor class with editor utility functions for smoothy
 */
   
smoothy.editor = 
{ 
  /**
   * smoothy.editor.create(editor);
   */
  create : function(editor)
  {    
    // smoothy.ensureJsScript('libs/ckeditor/ckeditor.js'); //TODO 
    
    var old = CKEDITOR.instances[editor];
    if (old) 
      CKEDITOR.remove(CKEDITOR.instances[editor]);
    CKEDITOR.replace(editor, 
      { 
        height : "600",
        filebrowserImageBrowseUrl : '?path=/browse/imagebrowse$cms/default'
      });
  }
}
