// IE-Version detection
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

// is used with an observer on load: searches document for error-tags (<div class="errorExplanation" ...>)
// and jumps to that point if exists, but goes 30 px up and left for a nicer overview
function searchForError()
{
  var errors = $$('.errorExplanation')
  
  if (errors.first())
  {
    var pos = Position.cumulativeOffset(errors.first());
    window.scrollTo(pos[0]-30, pos[1]-30);
  }
}

function goTo(element)
{
  element = $(element);
  location.href = '#' + element.id;
  highlight(element);
}

function setInnerHTML(div_id, value)
{
 var dstDiv = $(div_id);
 dstDiv.innerHTML = value;
}

if (typeof direktzu == 'undefined' || !direktzu)  { direktzu          = {}; }
// TODO refactor if prototype 1.6 is used 
direktzu.Element = Class.create(); 
direktzu.Element.cumulativeOffset = function(elem, offsetElement) {
  var left = typeof(offsetElement) == "undefined" ? 0 : -1 * direktzu.Element.cumulativeOffset(offsetElement).left;
  var top = typeof(offsetElement) == "undefined" ? 0 : -1 * direktzu.Element.cumulativeOffset(offsetElement).top;
  left += elem.offsetLeft || 0;
  top += elem.offsetTop  || 0;
  elem = elem.offsetParent;
  do {
    left += elem.offsetLeft || 0;
    // alert('left ' + elem.offsetLeft);
    top += elem.offsetTop  || 0;
    elem = elem.offsetParent;
  } while (elem);
  var offset = [left, top];
  offset.left = left;
  offset.top = top;
  return offset;
};

// TODO refactor if prototype 1.6 is used 
direktzu.Popup = Class.create();
// layerID: id for popup-boxes wrapper, contentText: innerHTML of popup, contentId: id of innerHTML, button: positioning anchor, position: "left" or "bottom"
direktzu.Popup.toggle = function(layerId, contentText, contentId, button, position, overwrite_top) {
  var position = (position == null) ? 'right' : position;
  var anchorElement = $('popup_positioning_anchor');
    
  if ($(layerId)) {
    $(layerId).remove();
  } else {
    new Insertion.Bottom(anchorElement, '<div id="' + layerId + '" style="width: 0px; height: 0px; position: absolute; top: 0; left: 0;" class="popup_container"></div>');
    if (!!(window.attachEvent && !window.opera)) {
      new Insertion.Bottom($(layerId), '<iframe id="' +  contentId + '_frame" src="javascript:false;" frameborder="0">&nbsp;</iframe>');
    }
    new Insertion.Bottom($(layerId), contentText);
    
    var top, left;
    switch(position) {
      case "right":
        top = (direktzu.Element.cumulativeOffset(button, anchorElement).top) + 'px'
        left = (direktzu.Element.cumulativeOffset(button, anchorElement).left + $(button).up().getWidth()) + 'px'
        break;
      case "bottom":
        top = (direktzu.Element.cumulativeOffset(button, anchorElement).top + $(button).up().getHeight()) + 'px'
        left = (direktzu.Element.cumulativeOffset(button, anchorElement).left + 3) + 'px'
        break;
    }
    
    if (typeof(overwrite_top) != "undefined") {
      top = overwrite_top
    }
    
    $(contentId).setStyle({ 
        position: 'absolute',
        top: top,
        left: left
      });
    
    // only if IE
    if (!!(window.attachEvent && !window.opera)) {
      $(contentId + '_frame').setStyle({ 
          position: 'absolute',
          top: top,
          left: left,
          width: $(contentId).getWidth() + 'px',
          height: $(contentId).getHeight() + 'px'
        });
    }

  }
}

function hide_popups() {
  $$('.popup_container').each( function(e) { 
    direktzu.Popup.toggle(e);
  });
}

function hide_popups_but(id) {
  var elem = $(id);
  $$('.popup_container').each( function(e) { 
    if (elem != e) direktzu.Popup.toggle(e);
  });
  if($('feedback') != elem) $('feedback').hide();
  if($('search_result') != elem) $('search_result').hide();
}

function new_window_for_external_links(container) {
  $$(container + ' a').each( function(a) { 
    if (a.getAttribute('href').indexOf('http://') === 0 || a.getAttribute('href').indexOf('https://') === 0) {
      a.target = '_blank';
    }
  });
}

var registered_featured_category_functions = [];

function register_featured_category_function(f) {
  registered_featured_category_functions.push(f);
}

function invoke_featured_category_functions() {
  while(e = registered_featured_category_functions.pop()) {
    e.call();
  }
}

function show_featured_category_preview(locale) {
  //$('featured_category').update('<div class="featured_category_outer"><div class="featured_category_inner">' + $('category_description_' + locale).getValue() + '</div></div><script type="text/javascript">invoke_featured_category_functions();</script>');
  //$('featured_category_preview_header').scrollTo();
}


/* Methods for links */

function selectPageAsLink(pages) {
  url_field = $('link_url');
  title_field = $('link_title');
  select_field = $('link_page_id');
  if (select_field.value == '') {
    title_field.value = '';
    url_field.value = '';
    url_field.disabled = false;
  } else {
    title_field.value = getPageTitle(pages, select_field.value);
    url_field.value = getPageUrl(pages, select_field.value);
    url_field.disabled = true;
    title_field.focus();
  }
}
function getPageTitle(pages, id) {
  return getPageOptions(pages, id)[1];
}
function getPageUrl(pages, id) {
  return getPageOptions(pages, id)[2];
}
function getPageOptions(pages, id) {
  return pages.find(function(s){return s[0] == id;});
}

function fold_text_sidebox(element, target, unfold, fold) {
  element = $(element);
  
  if (target.hasClassName('folded')) {
    target.morph("height: " + target.getStyle("max-height") + ";", { duration: slide_default_duration });
    target.toggleClassName('folded');

    element.toggleClassName('unfold');
    element.toggleClassName('fold');
    element.innerHTML = fold;
  }
  else {
    target.morph("height: " + target.getStyle("min-height") + ";", { duration: slide_default_duration });
    target.toggleClassName('folded');

    element.toggleClassName('unfold');
    element.toggleClassName('fold');
    element.innerHTML = unfold;
  }
}

/*
	Hides/Shows fields by their class, e.g.:
	<div id='container'>
		<div class="a b c"/>
		<div class="a c"/>
		<div class="c"/>
	</div>

	show_relevant_fields("a",'container') will hide the last div and show first and second div.
	show_relevant_fields("b",'container') will hide all except the first div.
*/
direktzu.Helper = Class.create();
direktzu.Helper.show_relevant_fields = function(group, container_name){
  var container = $(container_name);
  container.childElements().each(function(item){
    item.hide();
		item.select("textarea").each(function(te){
			te.hide();
		});
  });
  $$("."+group).each(function(item){
    item.show();
		item.select("textarea").each(function(te){
			te.show();
		});
  });
  return;
};

// grows textareas while typing
direktzu.Helper.growTextarea = function(obj) {
  var temp_div_id = 'temp_' + obj.id;
  var temp_div;

  if (!(temp_div = $(temp_div_id))) {
    temp_div = $(document.createElement('div'));
    temp_div.id = temp_div_id;
    temp_div.setStyle({position: 'absolute'});
    
    temp_div.setStyle({top: '-10000px'});
    temp_div.setStyle({left: '-10000px'});
    
    temp_div.setStyle({fontSize: obj.getStyle('font-size')});
    temp_div.setStyle({width: obj.getStyle('width')});
    temp_div.setStyle({lineHeight: obj.getStyle('line-height')});
    temp_div.setStyle({paddingLeft: obj.getStyle('padding-left')});
    temp_div.setStyle({paddingRight: obj.getStyle('padding-right')});
    temp_div.setStyle({paddingTop: obj.getStyle('padding-top')});
    temp_div.setStyle({paddingBottom: obj.getStyle('padding-bottom')});
    temp_div.setStyle({overflowY: 'scroll'});

    // use margin-top as memory for storing the initial height
    temp_div.setStyle({marginTop: obj.getStyle('height')});

    obj.parentNode.appendChild(temp_div);
  }
  
  var min_height = parseInt(temp_div.getStyle('marginTop'));
  var min_calculated_height = parseInt(temp_div.getStyle('marginBottom'));
  
  if (min_calculated_height > min_height) {
    min_height = min_calculated_height;
  }
  
  temp_div.innerHTML = obj.value.gsub("\n", '<br />') + '<br /><br /><br />';
  
  new_height = parseInt(temp_div.getStyle('height'));
  
  if (new_height > min_height) {
    obj.morph({height: new_height + "px"}, { duration: slide_default_duration });
  } else {
    obj.morph({height: min_height + "px"}, { duration: slide_default_duration });
  }
  
  // use margin-bottom as memory for storing the initial height after calculating
  if (parseInt(temp_div.getStyle('marginBottom')) == 0) {
    temp_div.setStyle({marginBottom: obj.getStyle('height')});
  }
};

direktzu.Helper.confirm_checkbox = function(checkbox, msg_enable, msg_disable){
  switch($(checkbox).checked) {
    case true: if(!confirm(msg_enable)){
    		$(checkbox).checked=false;
    	}
      break;
    case false: if(!confirm(msg_disable)){
        $(checkbox).checked=true;
      }
    	break;
  }
  return;
};

direktzu.Helper.register_increment_decrement_on_arrow_up_down = function(){
	$$('input.increment').each(function(i){
	    $(i).writeAttribute('autocomplete','off');
	    $(i).observe("keyup", function(e){
				if(e.keyCode == Event.KEY_UP) { 
			     this.value = (parseInt(this.value) || 0)+1;
			  } else if(e.keyCode == Event.KEY_DOWN) {
			     if(parseInt(this.value) > 0)
			       this.value = parseInt(this.value)-1;	
				}
			  return false;  
			});
	});
};

direktzu.Helper.admin_menu_timer = null;

direktzu.Helper.clear_time_out = function(){
	if(direktzu.Helper.admin_menu_timer){
		window.clearTimeout(direktzu.Helper.admin_menu_timer);
	}
	return;
};

direktzu.Helper.show_admin_menu = function(){
	direktzu.Helper.clear_time_out();
	$('admin_menu').appear({ duration: slide_default_duration });
	return;
};

direktzu.Helper.trigger_hide_admin_menu = function(){
	direktzu.Helper.clear_time_out();
	direktzu.Helper.admin_menu_timer = direktzu.Helper.hide_admin_menu.delay(1);
	return;
};

direktzu.Helper.hide_admin_menu = function(){
	$('admin_menu').fade({ duration: slide_default_duration, from: 1, to: 0 });
	return;
};

direktzu.Helper.remove_default_value = function(element){
  element = $(element);
  
  if (element.hasClassName("default")) {
    element.value = "";
    element.removeClassName("default");
  }
};

// countdown pasted from http://aktuell.de.selfhtml.org/artikel/javascript/timer/
Function.prototype.Timer = function (interval, calls, onend) {
  var count = 0;
  var payloadFunction = this;
  var startTime = new Date();
  var callbackFunction = function () {
    return payloadFunction(startTime, count);
  };
  var endFunction = function () {
    if (onend) {
      onend(startTime, count, calls);
    }
  };
  var timerFunction =  function () {
    count++;
    if (count < calls && callbackFunction() != false) {
      window.setTimeout(timerFunction, interval);
    } else {
      endFunction();
    }
  };
  timerFunction();
};

function leadingzero (number) {
    return (number < 10) ? '0' + number : number;
}
function countdown (seconds, target) {
  var element = document.getElementById(target);

  var calculateAndShow = function () {
    if (seconds >= 0) {
      var h = Math.floor(seconds / 3600);
      var m = Math.floor((seconds % 3600) / 60);
      var s = seconds % 60;
      element.innerHTML=
        leadingzero(h) + ':' +
        leadingzero(m) + ':' +
        leadingzero(s);
      if (seconds < 60 && (seconds % 10) == 0) {
        new Effect.Pulsate(element);
      }
      seconds--;
    } else {
      return false;
    }
  };

  var completed = function () {
    element.innerHTML = "<strong>Liftoff!<\/strong>";
  };

  calculateAndShow.Timer(1000, Infinity, completed);
}
