var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++) {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
  },
  dataBrowser: [
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {   // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};

BrowserDetect.init();
var IE = BrowserDetect.browser == 'Explorer' ? true : false;
var IE7 = IE && BrowserDetect.version == '7' ? true : false;


function set_cookie(name,value,expires,path) {
  if(!path) path = '/';
  //document.cookie = name+'='+value; expires="+ablauf.toGMTString();
  var c = name+'='+value+'; path='+path+'';
  document.cookie = c;
}

function get_cookie(name) {
  var c = document.cookie.split(/; /); // space is important!!
  for(var i=0;i<c.length;i++) {
    var cookie = c[i].split(/=/);
    if(cookie[0] == name) {
      return cookie[1];
    }
  }
  return '';
}

function clear_cookie(name) {
  document.cookie = name+'=""; expires:0';
}

var onload_stack = new Array();

function add_onload(fnc) {
  onload_stack.push(fnc);
}
function run_onload() {
  n = onload_stack.length;
  for(var i=0;i<n;i++) {
    fnc = onload_stack.pop();
    fnc();
  }
}

function InfoBubbleToggle(buttonId,elemId,posX,posY) {
	var b = $(buttonId);
  var e = $(elemId);

  var bubbles = document.getElementsByClassName('info-bubble');
  for(var i=0;i<bubbles.length;i++) {
    if(!bubbles[i].className.match(/info\-bubble/)) {
      bubbles[i].display = 'none';
    }
  }

  if(e.className.match(/info\-bubble/)) {
  	Position.absolutize(b);
  	Position.absolutize(e);
  	Position.clone(b,e);
  	e.style.top = '0px';
  	e.style.left = '0px';
  	e.style.width = '200px';
  	e.style.height = 'auto';
  	e.style.zIndex = 300;
/*    e.style.position = 'absolute';
    e.style.top  = parseInt(posY)+'px';
    e.style.left = parseInt(posX)+'px';
*/
    if(e.style.display == 'none') {
      Effect.Appear(e, {duration:0.2});
    } else {
      Effect.Fade(e, {duration:0.2});
    }
  }
}

function AjaxFormCollect(formId) {
  var values = '';
  var inputs = $(formId).getElementsByTagName('input');
  for(var i=0;i<inputs.length;i++) {
    switch(inputs[i].type) {
      case 'text':
      case 'hidden':
      case 'password':
        values += inputs[i].name+'='+encodeURIComponent(inputs[i].value)+'&';
        break;
      case 'radio':
      case 'checkbox':
        if(inputs[i].checked == true) {
          values += inputs[i].name+'='+encodeURIComponent(inputs[i].value)+'&';
        }
        break;
    }
  }

  var textareas = $(formId).getElementsByTagName('textarea');
  for(var i=0;i<textareas.length;i++) {
    if(textareas[i].className.match(/mceEditorEnabled/)) {
      values += textareas[i].name+'='+encodeURIComponent(tinyMCE.getContent(textareas[i].id))+'&';
    } else {
  	  values += textareas[i].name+'='+encodeURIComponent(textareas[i].value)+'&';
  	}
  }
  var selects = $(formId).getElementsByTagName('select');
  for(var i=0;i<selects.length;i++) {
    switch(selects[i].multiple) {
      case true:
        for(var j=0;j<selects[i].options.length;j++) {
          if(selects[i].options[j].selected == true) {
            values += selects[i].name+'[]='+encodeURIComponent(selects[i].options[j].value)+'&';
          }
        }
        break;
      case false:
        values += selects[i].name+'='+encodeURIComponent(selects[i].options[selects[i].selectedIndex].value)+'&';
        break;
    }
  }
  return values;
}

function StdAjax(url,vars) {
  if(!vars.onFailure) {
    vars.onFailure = function() {
      alert('Connectivity error!');
    }
  }
  if(!vars.onSuccess) {
    vars.onSuccess = function() { }
  }
  if(!vars.onError) {
    vars.onError = function() { }
  }
  // onWhatever gets called on EVERY ajax call, as long as
  // the server responded (AFTER onSuccess/onError)
  if(!vars.onWhatever) {
    vars.onWhatever = function() { }
  }

  if(!vars.parameters) {
    vars.parameters = '';
  }

  new Ajax.Request(
    url,
    {
      method: 'post',
      parameters: vars.parameters,
      onSuccess: function(result) {
        try
        {
          eval('var res = '+result.responseText+'');

          if (res.success)
          {
            if(document.getElementById('no_ajaxactions') == null) ajax_action(res.result);
            vars.onSuccess(res.result);
          }
          else
          {
            vars.onError(res.result, res.errors);
          }
          vars.onWhatever(res.result);
        }
        catch (e)
        {
          // turn me off after developing
          //console.log(result.responseText);
        }
      },
      onFailure: vars.onFailure
    }
  );
}

function sFetchInlineScripts(node,targetNode) {
  var scripts = $(node).getElementsByTagName('script');
  var script = '';

  for(var i=0;i<scripts.length;i++) {
  	if(scripts[i].innerHTML.match(/tinyMCE\.init/)) continue;
    script += scripts[i].innerHTML;
  }
  return script;
}

function ajax_action( oAjaxResult ){

   if( oAjaxResult.actions != null ){

     var nHtmlContentCount = 0;

     for( var loop = 0 ; loop < oAjaxResult.actions.length ; loop++ ){

       var sActionString = oAjaxResult.actions[ loop ];

       var sSeparator = sActionString.charAt( 0 );
       var aParts = sActionString.split( sSeparator );

       var sCommand = "";

       try{
         switch( aParts[ 1 ] ){

          case 'func':

           sCommand = aParts[ 2 ] + '(' + aParts[ 3 ] + ')';
           eval( sCommand );

           break;

          case 'style':

           document.getElementById( aParts[ 2 ] ).style[ aParts[ 3 ] ] = aParts[ 4 ];
           break;

          case 'class':

           document.getElementById( aParts[ 2 ] ).className = aParts[ 3 ];
           break;

          case 'html':
           document.getElementById( aParts[ 2 ] ).innerHTML = oAjaxResult.html_action_contents[ nHtmlContentCount ];
           nHtmlContentCount++;
           break;

          case 'value':
           document.getElementById( aParts[ 2 ] ).value = aParts[ 3 ];
           break;

          case 'redirect':
           document.location.href = aParts[ 2 ];
           break;

          case 'imagesrc':
           document.getElementById( aParts[ 2 ] ).src = aParts[ 3 ];
           break;

         }
       }catch( exception ){
         //alert( 'command: "' + sActionString + '" failed!\n' + exception );
       }
     }
   }
}

AjaxOnCreateHook = function(oRequest)
{
  oRequest.options.requestHeaders = { 'X-CT-AjaxRequest' : '1' }
  /*oRequest.oTimeout = window.setTimeout('vShowLoading', 1000);*/
  vShowLoading();
}

AjaxOnCompleteHook = function(oRequest)
{
  if (oRequest.oTimeout)
    window.clearTimeout(oRequest.oTimeout);

  vHideLoading();
}

Ajax.Responders.register(
{
   onCreate: AjaxOnCreateHook
  ,onComplete: AjaxOnCompleteHook
});

function vShowLoading()
{
  if ($('MBLoader1'))
  {
    $('MBLoader1').show();
  }
}

function vHideLoading()
{
  if ($('MBLoader1'))
  {
    $('MBLoader1').hide();
  }
}

function oDateToObject(sDate) {

	var aDateTime = sDate.split(' ');
	var aDate = aDateTime[0].split('-');
	var aTime = aDateTime[1].split(':');
	return {
		year:lz(aDate[0]), month:lz(aDate[1]), day:lz(aDate[2]), hour:lz(aTime[0]), minute:lz(aTime[1]), second:lz(aTime[2])
	};
}

function oDateToday() {
	oDate = new Date();
	return {
  	year:lz(oDate.getFullYear()), month:lz(oDate.getMonth()+1), day:lz(oDate.getDate()), hour:lz(oDate.getHours()), minute:lz(oDate.getMinutes()), second:lz(0)
	};
}
function lz(num) { // leading zero
  var str = ''+num+'';
	if(str.length == 1) {
	  return '0'+str;
	}
	return num;
}
function sDateToday() {
	oDate = new Date();
	var sDate = lz(oDate.getFullYear())+'-'+lz(oDate.getMonth()+1)+'-'+lz(oDate.getDate())+' '+lz(oDate.getHours())+':'+lz(oDate.getMinutes())+':'+lz(0);
  return sDate;
}

function vFocus(sField)
{
  if ($(sField))
    $(sField).focus();
}

var AssocSwitcher = Class.create();
AssocSwitcher.prototype = {

  aLogos: new Array(),
  iIdx: 0,

  initialize: function()
  {
    this.aLogos = $A(document.getElementsByClassName('AssocSwitchLogo', $('AssocSwitch')));
    this.iIdx = 0;

    if (this.aLogos.length <= 1)
      return;

    $('AssocBack').show();
    $('AssocNext').show();

    var _this = this;

    Event.observe($('AssocBack'), 'click', function(e) { Event.stop(e); Event.element(e).blur(); _this.PrevAssoc(); });
    Event.observe($('AssocNext'), 'click', function(e) { Event.stop(e); Event.element(e).blur(); _this.NextAssoc(); });

    return this;
  },

  PrevAssoc: function()
  {
    var iPrevIdx = this.iIdx == 0
      ? this.aLogos.length - 1
      : this.iIdx - 1;

    $(this.aLogos[this.iIdx]).hide();
    this.iIdx = iPrevIdx;
    $(this.aLogos[this.iIdx]).show();
  },

  NextAssoc: function()
  {
    var iNextIdx = this.aLogos[(this.iIdx + 1)]
      ? this.iIdx + 1
      : 0;

    $(this.aLogos[this.iIdx]).hide();
    this.iIdx = iNextIdx;
    $(this.aLogos[this.iIdx]).show();
  }
}

var oAssocSwitcher = null;
function vLoadAssocSwitcher()
{
  if ($('AssocSwitch'))
    oAssocSwitcher = new AssocSwitcher();
}

add_onload(vLoadAssocSwitcher);

function UpdateRegions(poSelector, piCountryId)
{
  StdAjax(
    '/registrierung',
    {
      parameters: { iCountryId: piCountryId, command: 'getRegions' },
      onSuccess: function(result) 
      {
        poSelector.innerHTML = '';
        var o = document.createElement('option');
        o.value = 0;
        o.appendChild(document.createTextNode('Auswahl'));
        poSelector.appendChild(o);

        $H(result).each(function(e)
        {
          var o = document.createElement('option');
          o.value = e.key;
          o.appendChild(document.createTextNode(e.value));
          poSelector.appendChild(o);
        });
      },
      onError: function(result, errors) {}
    }
  );
}

/* popup functions images */
var attribWithoutAll="location=no,menubar=no,toolbar=no,status=no";
attribWithoutAll+=",resizable=yes,scrollbars=no,width=600,height=400";
var subwindow=0;
function ClosePopUp(){
  if (!subwindow) { return; }  
  if (subwindow.closed) { return; }  
  subwindow.close();
}
    
function detailShow(target){
  subwindow=window.open(target,"Detail",attribWithoutAll);
  subwindow.moveTo(10,50); 
}
