// Prototypes
  // Number
    Number.prototype.roundTo = function (stellen) {
      if (typeof(stellen) == "undefined") stellen = 0;
      return Math.round(this * Math.pow(10, stellen)) / Math.pow(10, stellen);
    }
  // String functions
    String.prototype.parseBetween = function (source, searchStr1, searchStr2) {
      if (source.length <= searchStr1.length) return ""; // QuellString ist leer
      var pos1 = source.indexOf(searchStr1); // Position des ersten Vorkommens von Suchstring1
      if (pos1 == -1) return ""; // Suchstring1 nicht gefunden --> leeren String zurückgeben
      else pos1 += searchStr1.length;
      pos2 = source.indexOf(searchStr2, pos1); // Position des ersten Vorkommens von Suchstring2 ab Position1
      if (pos2 == -1) return ""; // Suchstring2 nicht gefunden oder Suchstring2 in einem Item gefunden --> leeren String zurückgeben
      return source.substr(pos1, pos2-pos1);
    }

var cms = {};

// Ajax
  function extecuteScriptFromAjaxReturn (html) {
    var hd = document.getElementsByTagName("head")[0];
    var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
    var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
    var typeRe = /\stype=([\'\"])(.*?)\1/i;
    var match;
    while (match = re.exec(html)) {
      var attrs = match[1];
      var srcMatch = attrs ? attrs.match(srcRe) : false;
      if (srcMatch && srcMatch[2]) {
         var s = document.createElement("script");
         s.src = srcMatch[2];
         var typeMatch = attrs.match(typeRe);
         if (typeMatch && typeMatch[2]) s.type = typeMatch[2];
         hd.appendChild(s);
      } else if (match[2] && match[2].length > 0) {
        if (window.execScript) window.execScript(match[2]);
        else window.eval(match[2]);
      }
    }
  }

// cms__form
	// validation on submit
	  function checkCmsForm (formEl) {
	    formEl = jQuery(formEl);
	    var noWarnings = true;
	    var removeClasses = "cmsFormWarning cmsFormWarningMust cmsFormWarningMail cmsFormWarningDate cmsFormWarningDateMax cmsFormWarningDateMin";
	    formEl.removeClass(removeClasses);
	    formEl.children('.cmsFormWarning').removeClass(removeClasses);
	    jQuery('.cmsFormLabelMust', formEl).each(function () {
	      var container = jQuery(this).parents('.cmsForm:first');
	      container.find('input, textarea, select').each(function () {
	        if (jQuery(this).val() != "") return;
	        container.add(formEl).addClass('cmsFormWarning cmsFormWarningMust');
	        noWarnings = false;
	      });
	    });
	    jQuery('.cms__form__mail', formEl).each(function () {
	      var container = jQuery(this);
	      container.find('input').each(function () {
	        if (jQuery(this).val() == "") return;
	        if (jQuery(this).val().match(/^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,}$/i)) return;
	        container.add(formEl).addClass('cmsFormWarning cmsFormWarningMail');
	        noWarnings = false;
	      });
	    });
	    jQuery('.cms__form__date', formEl).each(function () {
	      var container = jQuery(this);
	      container.find('input').each(function () {
	        if (jQuery(this).val() == "") return;
	        var me = jQuery(this);
	        var str2Date = function (str) {
	          var arr = str.split(".");
	          return new Date((arr[2].length<4?"20":"") + arr[2], arr[1], arr[0]);
					};
					// checking
		        var dateRegEx = new RegExp(/^[0-9]+\.[0-9]+\.([0-9]{2}|[0-9]{4})$/);
		        if (!me.val().match(dateRegEx)) {
			        container.add(formEl).addClass('cmsFormWarning cmsFormWarningDate');
			        noWarnings = false;
			        return;
						}
		        if (me.attr('mindate') && me.attr('mindate').match && me.attr('mindate').match(dateRegEx) && str2Date(me.val()) < str2Date(me.attr('mindate'))) {
			        container.add(formEl).addClass('cmsFormWarning cmsFormWarningDateMin');
			        noWarnings = false;
			        return;
						}
		        if (me.attr('maxdate') && me.attr('maxdate').match && me.attr('maxdate').match(dateRegEx) && str2Date(me.val()) > str2Date(me.attr('maxdate'))) {
			        container.add(formEl).addClass('cmsFormWarning cmsFormWarningDateMax');
			        noWarnings = false;
			        return;
						}
	      });
	    });
	    return noWarnings;
	  }
	// other validations
	  jQuery(function ($) {
	    $('.cms__form__number input').live('keypress', function (e) {
				var me = jQuery(this);
				var regex = new RegExp("[0-9" + (me.attr('allowdecimals')=='true'?'.':'') + (me.attr('allownegative')=='true'?'-':'') + "]");
				if (e.which > 31 && !regex.test(String.fromCharCode(e.which))) return false;
				return true;
			}).live('keyup', function () {
	      var me = jQuery(this);
				var val = me.val();
				var newVal = "";
				var minusDetected = (me.attr('allownegative') != 'true');
				var decimalDetected = (me.attr('allowdecimals') != 'true');
				for (var i=0; i<val.length; i++) {
				  var char = val.charAt(i);
				  if (char=="-" && newVal=="" && !minusDetected) {
						newVal += char;
						minusDetected = true;
				  } else if (char=="." && i>0 && !decimalDetected) {
						newVal += char;
						decimalDetected = true;
				  } else if (!isNaN(char)) newVal += char;
				}
				if (newVal != val) me.val(newVal);
			}).live('change', function () {
				if (jQuery(this).val() == "-") jQuery(this).val("");
			});
		});
	// form-repeats
	  jQuery(function ($) {
	    if (!$('div[repeatformbegin]').length || !$('div[repeatformend]').length) return;
	    $('div[repeatformbegin]').each(function () {
	      var me = $(this);
	      var numFormElId = me.attr('repeatformnumberelement');
	      var numFormEl = $('#cmsContentElement_' + numFormElId + ' input');
	      // get and save all elements between start and end and remove them
		      var dummyContainer = $('<div />');
		      var endReached = false;
		      me.nextAll().each(function () {
						if (endReached) return;
						else if ($(this).attr('repeatformend') == "true" && $(this).attr('repeatformnumberelement') == numFormElId) endReached = true;
						else $(this).appendTo(dummyContainer);
					});
				var template = dummyContainer.html();
				numFormEl.bind('change', function () {
				  var num = numFormEl.val();
				  // delete existing elements
				    var endReached = false;
			      me.nextAll().each(function () {
							if (endReached) return;
							else if ($(this).attr('repeatformend') == "true" && $(this).attr('repeatformnumberelement') == numFormElId) endReached = true;
							else $(this).remove();
						});
				  if (isNaN(num) || num <= 0) return;
					var html = "";
					// add existing elements, replace {i} by a incrementing number and turn names into arrays
						for (var i=0; i<num; i++) {
						  dummyContainer = $('<div />').html(template.replace(/\{i\}/g, i+1));
							dummyContainer.find("*[name^='cmsForm[']").each(function () {
							  $(this).attr('name', $(this).attr('name') + "[" + i + "]");
							});
							html += dummyContainer.html();
						}
					me.after(html);
				});
				if (numFormEl.val() > 0) numFormEl.trigger('change');
			});
		});

// Language
	function cmsChangeLanguage (sign, url) {
	  if (!url || url=="") url = window.location.href;
	  url = url.replace(/\?[^?]+/, '');
	  var ereg = /\.[a-z-]{2,}$/;
		if (url.match(ereg) && url.indexOf('index.php')<0) url = url.replace(ereg, '.' + sign);
	  else url += "?cmsChangeLanguage=" + sign;
	  window.location.href = url;
	}

// cms__contentElements__video
  jQuery(function ($) {
	  $('*[id^=cmsContentElementsVideo]').each(function () {
			jwplayer($(this).attr('id')).setup({
				controlbar: "bottom",
				flashplayer: "classes/cwx/multimedia/players/longtail/player.swf",
				file: $(this).attr('file'),
				image: $(this).attr('poster')
			});
		});
	});

// logout after session timeout
	jQuery(function ($) {
	  if (!cmsUserIsLoggedIn || !cmsSessionTimeout) return;
	  var timeoutMilliSeconds = cwx__strtotime(cmsSessionTimeout) - (new Date().getTime()) - cmsSessionTimeoutOffset;
	  if (timeoutMilliSeconds <= 0 || isNaN(timeoutMilliSeconds)) return;
	  var timeoutFunc = function () {
	    jQuery.get("index.php?logout", function () {
	    	alert("Sie wurden nach längerer Inaktivität autoamtisch ausgeloggt! Bitte loggen sie sich erneut ein.");
	      window.location.href = "login";
			});
		};
	  var resetTimeout = function () {
			window.clearTimeout(logoutTimeout);
		  logoutTimeout = window.setTimeout(timeoutFunc, timeoutMilliSeconds);
		};
		var logoutTimeout = window.setTimeout(timeoutFunc, timeoutMilliSeconds);
		$('body').ajaxComplete(resetTimeout);
		Ext.Ajax.on('requestcomplete', resetTimeout);
	});
