/** 
 *
 *  CR utils
 *  
 *  @author Erling Limm (eibon.dott at gmail.com)
 */

function prependHttp(inputObject) {
  if (inputObject) {
    if (inputObject.value.toLowerCase().indexOf("http://") == -1 &&
        inputObject.value != '')
      inputObject.value = "http://" + inputObject.value;
  }
}

/* @author John Resig */
function getStyle(elem, name) {
    // J/S Pro Techniques p136
    if (elem.style[name]) {
        return elem.style[name];
    } else if (elem.currentStyle) {
        return elem.currentStyle[name];
    }
    else if (document.defaultView && document.defaultView.getComputedStyle) {
        name = name.replace(/([A-Z])/g, "-$1");
        name = name.toLowerCase();
        s = document.defaultView.getComputedStyle(elem, "");
        return s && s.getPropertyValue(name);
    } else {
        return null;
    }
}

/* Warning: this function is not "properly" written, as it is only a POC.
 * Rewrite with total 1337ness.
 *
 * @author Erling Limm (eibon.dott at gmail.com) */
function placeButton(object, container, fileInput, byFileInputWidth) {

  if (!object || !container) return;

  // Get user agent
  var isOpera = isIe = isIe8 = isWebkit = isGecko = isCamino = false;
  var ua = navigator.userAgent;
  isOpera = typeof opera != 'undefined';
  isIe = !isOpera && ua.indexOf('MSIE') != -1;
  isIe8 = !isOpera && ua.indexOf('MSIE 8.0') != -1;
  isWebKit = !isOpera && ua.indexOf('WebKit') != -1;
  isGecko = !isOpera && window.navigator.product == 'Gecko' && !isWebKit;
  isCamino = isGecko && window.navigator.vendor == 'Camino'; // Do we really give a damn?

  // Determine placement method
  if (byFileInputWidth) {

    // Get subtraction of file input width and real button width
    // Due to slight variations in browser file input positioning, place input accordingly
    var variation = 6; // Gecko FF3
    if (isOpera) variation = 7;
    else if (isIe) variation = 4;
    var offset = (fileInput.offsetWidth - object.offsetWidth) + variation;

    fileInput.style.left = '-' + offset + 'px';

  } else {

    // Get the left offset for object and place container
    var offset = object.offsetLeft;
    container.style.left = '-' + offset + 'px';

    // Due to slight variations in browser file input positioning, place input accordingly
    var variation = 6;
    if (isOpera) variation = 15;
    else if (isIe) variation = 80; // Assume we are in a iframe thingy. 50 for outside, 80 for inside? These are try and fail values.
    fileInput.style.left = variation + 'px';

  }

}


/**
 * Does a genie-effect-ish animation on an opinion into the link of its belonging
 *
 * Note: needs the reallySimpleHighlight function to function. The scriptaculous
 * highlight thing didn't function properly when using this green color we use here
 *
 * TODO: maybe rewrite to include some scriptaculous effect queueing?
 *
 * @author Erling Limm (eibon.dott at gmail.com) */
function animateTempOpinion(obj) {

  // Get the link that belongs to the objects grand-parent
  var children = obj.parentNode.parentNode.childElements();
  var link = null;
  children.each(function(element) {
    if (element.hasClassName('opinions-title-list-link')) {
      link = element;
    }
  });

  // Calc offsets and such
  var objOffsetLeft = obj.offsetLeft;
  var objOffsetTop = obj.offsetTop;
  var linkOffsetLeft = link.offsetLeft;
  var linkOffsetTop = link.offsetTop;
  var finalOffsetLeft = linkOffsetLeft - objOffsetLeft + (link.offsetWidth / 4);
  var finalOffsetTop = linkOffsetTop - objOffsetTop;
  var replacementDivWidth = obj.offsetWidth;
  var replacementDivHeight = obj.offsetHeight;

  // Make new replacement element
  newElement = document.createElement('div');
  newElement.setAttribute('class', obj.className);
  var textNode = document.createTextNode("");
  newElement.appendChild(textNode);
  //newElement.style.backgroundColor = 'white';
  newElement.style.cssFloat = 'left';
  newElement.style.height = replacementDivHeight + 'px';
  obj.parentNode.insertBefore(newElement, obj);

  // Make new blocker
  //blocker = document.createElement('div');
  //blocker.setAttribute('class', 'clear-float');
  //obj.parentNode.insertBefore(blocker, newElement);

  // Make original absolute
  obj.style.position = 'absolute';

  // Run effects and set timers
  new Effect.Move(obj, {
    x: finalOffsetLeft, y: finalOffsetTop, mode: 'relative',
    transition: Effect.Transitions.sinoidal
  });
  Effect.Squish(obj);
  setTimeout(function () {
    Effect.Pulsate(link);
  }, 700);
  setTimeout(function () {
    reallySimpleHighlight(link, '#d9f4bd');
  }, 1400);
  setTimeout(function () {
    Effect.BlindUp(newElement);
  }, 1000);
}

function initTempOpinionTimer() {
  $$(".is-temp-opinion").each(function(temp) {
    setTimeout(function () {
      animateTempOpinion(temp);
    }, 2000);
  });
}

function renderEditableArea(obj, mode) {
  // Find edit node first
  obj = Element.extend(obj)
  var children = obj.childElements();
  var editNode = null;

  // Check if the position field is set to relative on obj
  //var objStyle = getStyle(obj, 'position');
  //if (objStyle != 'relative') {
    obj.style.position = 'relative';
  //}
  
  children.each(function(element) {
    if (element.className.indexOf('editable-tooltip') != -1) {
      editNode = element;
    }
  });

  // If the editNode is not found, then create it!
  if (editNode == null) {
    editNode = document.createElement('div');
    editNode.setAttribute('class', 'editable-tooltip');
    var textNode = document.createTextNode("Rediger");
    editNode.appendChild(textNode);
    obj.insertBefore(editNode, obj.children[0]); // Insert before the first child element
  }

  // TODO: move to css?
  if (mode) {
    obj.style.border = '1px solid #DCDCDC';
    obj.style.cursor = 'text';
    editNode.style.zoom = '1';
    editNode.style.padding = '5px 10px';
    editNode.style.border = '1px solid #D9F4BD';
    editNode.style.display = 'inline';
    editNode.style.cssFloat = 'right';
    editNode.style.backgroundColor = '#EFFAE4';
    editNode.style.fontSize = '10px';
    editNode.style.fontWeight = 'normal';
    editNode.style.position = 'absolute';
    editNode.style.right = '-10px';
    editNode.style.top = '-14px';
    editNode.style.opacity = '0.8';
    /*
    if (typeof Effect == 'object') {
      editNode = Element.extend(editNode);
      if (Effect.Pulsate) {
        Effect.Pulsate(editNode, { pulses: 2, duration: 1.0 });
      }
    }
    */
  } else {
    obj.style.border = '1px solid transparent';
    obj.style.cursor = 'default';
    editNode.style.display = 'none';
  }
}

function processObjectsChangexx(suggestionBox) {
  //console.log("sdfsdf");
    var items = suggestionBox.getSelectedItems();
    if (items && items.length > 0) {
        setQuote(items[0]);
    }
}


/*
 * Simple Ajax call method.
 *
 * From http://en.wikipedia.org/wiki/XMLHttpRequest
 */
function ajax(url, vars, callbackFunction) {
  var request =  new XMLHttpRequest();
  request.open("POST", url, true);
  request.setRequestHeader("Content-Type",
                           "application/x-www-form-urlencoded");

  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      if (request.responseText) {
        callbackFunction(request.responseText);
      }
    }
  };
  request.send(vars);
}



/**
 *  Suggest login box
 *
 *  @author Erling Limm
 */
function hideSuggestLoginBox() {

  // Stop event observing (actually stops all events, so TODO: stop specific handlers!)
  var body = document.getElementsByTagName('body')[0];
  Event.stopObserving(body, 'mousewheel');
  Event.stopObserving(body, 'DOMMouseScroll');
  Event.stopObserving(body, 'onmousewheel');

  $('suggest-login-box').remove();
  $('suggest-dark-layer').remove();
  //$('suggest-login-arrow').remove();
}

function showLoginSpeechBox(event, obj) {
  var x = event.clientX;
  var y = event.clientY;
  var box = $('suggest-login-box');
  if (!box) {

    // Determine if we're in an iframe
    //var inIframe = window.frameElement != null; // This thing gives 'access denied' in IE!

    var darkLayer = document.createElement('div');
    darkLayer.setAttribute('id', 'suggest-dark-layer');
    darkLayer.style.position = 'fixed';
    darkLayer.style.width = '100%';
    darkLayer.style.height = '100%';
    darkLayer.style.top = '0';
    darkLayer.style.left = '0';
    /*if (!inIframe) {
      darkLayer.style.backgroundColor = 'black';
    }*/
    darkLayer.style.zIndex = '100';
    var ua = navigator.userAgent;
    isIe = ua.indexOf('MSIE') != -1;
    if (isIe) {
      darkLayer.style.filter = 'alpha(opacity=40)';
    } else {
      darkLayer.style.opacity = '0.5';
    }
    document.body.appendChild(darkLayer);

    box = document.createElement('div');
    box.setAttribute('id', 'suggest-login-box');
    box.style.position = 'absolute';
    box.style.width = 250 + 'px';
    box.innerHTML = '<a href="javascript:;" onclick="hideSuggestLoginBox();" class="opinions-child-deletelink">x</a>'
    box.innerHTML += 'Logg inn med din facebook- <br />eller internettkanalenkonto<br/><br/>';
    box.innerHTML += '<img src="http://static.ak.fbcdn.net/rsrc.php/z6MJW/hash/9cymg7nd.gif" alt="Connect" onclick="facebook_login(); FB.Connect.requireSession(function() { RefreshPageLogin(); }); return false;" style="cursor: pointer;">';
    box.innerHTML += '<img alt="Internettkanalen logg inn" src="../assets/img/xsnakk/ik-connect-button.png" onclick="window.open(\'index.php?widget=crlogin\', \'\', \'width=450px, height=400px\');" style="margin-left: 5px; cursor: pointer; vertical-align: top;" />';
    box.style.backgroundColor = '#D3D3D3';
    box.style.padding = '10px';
    box.style.fontSize = '11px';
    box.style.zIndex = '101';
    box.style.textAlign = 'left';
    if (isIe) {
      box.style.filter = 'alpha(opacity=0)';
    } else {
      box.style.opacity = '0';
    }
    document.body.appendChild(box);

    // Determine if this box is out of bounds
    var boxOffsetX = (x + 22);
    var boxWidth = box.offsetWidth;
    var bodyWidth = document.body.offsetWidth;

    if ((boxOffsetX + boxWidth) > bodyWidth) {
      // Place on left side instead of right
      box.style.left = (x - boxWidth - 22) + 'px';
    } else {
      // Place on default right side
      box.style.left = (x + 22) + 'px';
    }
    box.style.top = (y - getScrollPos()) + 'px';

    //box.style.top = (y - 10 + getScrollPos()) + 'px';
    //box.style.left = (x + 22) + 'px';

    /*var arrow = document.createElement('div');
    arrow.setAttribute('id', 'suggest-login-arrow');
    arrow.style.position = 'absolute';
    arrow.style.width = '12px';
    arrow.style.height = '12px';
    arrow.style.top = (y + getScrollPos()) + 'px';
    arrow.style.left = (x + 10) + 'px';
    arrow.style.backgroundImage = 'url(assets/img/icons/talk_arrow_left.png)';
    arrow.style.zIndex = '101';
    if (isIe) {
      arrow.style.filter = 'alpha(opacity=0)';
    } else {
      arrow.style.opacity = '0';
    }
    document.body.appendChild(arrow);*/

    /* TODO: include scriptaculous dynamicly? */
    if (typeof Effect == 'object') {
      if (isIe) {
        //arrow.style.filter = 'alpha(opacity=100)';
        box.style.filter = 'alpha(opacity=100)';
      }
      Effect.Fade(box, { duration: 0.7, from: 0, to: 1 });
      //Effect.Fade(arrow, { duration: 0.7, from: 0, to: 1 });
    } else {
      if (isIe) {
        //arrow.style.filter = 'alpha(opacity=100)';
        box.style.filter = 'alpha(opacity=100)';
      } else {
        //arrow.style.opacity = '1';
        box.style.opacity = '1';
      }
    }

    // Attach a mousescroll events to the body to prevent scrolling while viewing this box
    var body = document.getElementsByTagName('body')[0];
    Event.observe(body, 'mousewheel', function(e) { disruptEvent(e) });
    Event.observe(body, 'DOMMouseScroll', function(e) { disruptEvent(e) });
    Event.observe(body, 'onmousewheel', function(e) { disruptEvent(e) });

    // Because one cannot cancel the scroll event, we must implement something super,
    // i.e. register pos on first scroll and return to this pos on last scroll event. yeah!
    
    //Event.observe(body, 'scroll', function(e) { handleScroll(e); });
    //Event.observe(document, 'scroll', function(e) { handleScroll(e); });
  }
}

function showCustomBox(event, obj, node, width) {
  var x = event.clientX;
  var y = event.clientY;
  var box = $('suggest-login-box-custom');
  if (!box) {

    // Determine if we're in an iframe
    //var inIframe = window.frameElement != null;

    //if (window.frameElement) {
      // This is an iframe
      //alert(window.frameElement.height);
    //}

    var darkLayer = document.createElement('div');
    darkLayer.setAttribute('id', 'suggest-dark-layer-custom');
    darkLayer.style.position = 'fixed';
    darkLayer.style.width = '100%';
    darkLayer.style.height = '100%';
    darkLayer.style.top = '0';
    darkLayer.style.left = '0';
    /*if (!inIframe) {
      darkLayer.style.backgroundColor = 'black';
    }*/
    darkLayer.style.zIndex = '100';
    var ua = navigator.userAgent;
    isIe = ua.indexOf('MSIE') != -1;
    if (isIe) {
      darkLayer.style.filter = 'alpha(opacity=40)';
    } else {
      darkLayer.style.opacity = '0.5';
    }
    document.body.appendChild(darkLayer);

    /*box = document.createElement('div');
    box.setAttribute('id', 'suggest-login-box');
    box.style.position = 'absolute';
    box.style.width = width + 'px';
    box.style.backgroundColor = '#fff';
    //box.style.padding = '10px';
    box.style.fontSize = '11px';
    box.style.zIndex = '101';
    box.style.textAlign = 'left';
    if (isIe) {
      box.style.filter = 'alpha(opacity=0)';
    } else {
      box.style.opacity = '0';
    }
    document.body.appendChild(box);*/

    box = node;

    //box.setAttribute('id', 'custom-login-box');
    box.style.position = 'absolute';
    box.style.width = width + 'px';
    box.style.backgroundColor = '#fff';
    //box.style.padding = '10px';
    box.style.fontSize = '11px';
    box.style.zIndex = '102';
    box.style.textAlign = 'left';
    if (isIe) {
      //box.style.filter = 'alpha(opacity=0)';
      $(box).hide();
    } else {
      box.style.opacity = '0';
    }

    // Determine if this box is out of bounds
    var boxOffsetX = (x + 22);
    var boxWidth = box.offsetWidth;
    var bodyWidth = document.body.offsetWidth;

    if ((boxOffsetX + boxWidth) > bodyWidth) {
      // Place on left side instead of right
      box.style.left = (x - boxWidth - 22) + 'px';
    } else {
      // Place on default right side
      box.style.left = (x + 22) + 'px';
    }
    box.style.top = (y - getScrollPos()) + 'px';

    /*
    var arrow = document.createElement('div');
    arrow.setAttribute('id', 'suggest-login-arrow');
    arrow.style.position = 'absolute';
    arrow.style.width = '12px';
    arrow.style.height = '12px';
    arrow.style.top = (y + getScrollPos()) + 'px';
    arrow.style.left = (x + 10) + 'px';
    arrow.style.backgroundImage = 'url(assets/img/icons/talk_arrow_left.png)';
    arrow.style.zIndex = '101';
    if (isIe) {
      arrow.style.filter = 'alpha(opacity=0)';
    } else {
      arrow.style.opacity = '0';
    }
    document.body.appendChild(arrow);
    */

    /* TODO: include scriptaculous dynamicly? */
    if (typeof Effect == 'object') {
      if (isIe) {
        box.style.filter = 'alpha(opacity=99)';
        $(box).show();
      } else {
        //Effect.Fade(box, { duration: 0.7, from: 0, to: 1 });
        box.style.opacity = '1';
      }
      
    } else {
      if (isIe) {
        //arrow.style.filter = 'alpha(opacity=100)';
        box.style.filter = 'alpha(opacity=99)';
        $(box).show();
      } else {
        //arrow.style.opacity = '1';
        box.style.opacity = '1';
      }
    }

    // Attach a mousescroll events to the body to prevent scrolling while viewing this box
    var body = document.getElementsByTagName('body')[0];
    Event.observe(body, 'mousewheel', function(e) { disruptEvent(e) });
    Event.observe(body, 'DOMMouseScroll', function(e) { disruptEvent(e) });
    Event.observe(body, 'onmousewheel', function(e) { disruptEvent(e) });

    // Because one cannot cancel the scroll event, we must implement something super,
    // i.e. register pos on first scroll and return to this pos on last scroll event. yeah!

    //Event.observe(body, 'scroll', function(e) { handleScroll(e); });
    //Event.observe(document, 'scroll', function(e) { handleScroll(e); });
  }
}

/**
 *  Suggest login box
 *
 *  @author Erling Limm
 */
function hideCustomBox() {

  // Stop event observing (actually stops all events, so TODO: stop specific handlers!)
  var body = document.getElementsByTagName('body')[0];
  Event.stopObserving(body, 'mousewheel');
  Event.stopObserving(body, 'DOMMouseScroll');
  Event.stopObserving(body, 'onmousewheel');
  
  var box = $('custom-login-box');
  box.style.filter = 'alpha(opacity=0)';
  box.style.opacity = '0';
  box.style.left = '-1000px';
  box.style.top = '-1000px';
  $('suggest-dark-layer-custom').remove();
}

function getScrollPos() {
  var scrollPos = document.body.scrollTop;
  if (scrollPos == 0) {
    if (window.pageYOffset)
      scrollPos = window.pageYOffset;
    else
      scrollPos = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
  }
  return scrollPos;
}

// handleScroll helper variable
var lastPageYOffset = -1;

function handleScroll(e) {
  return;
  var pageY = window.pageYOffset;
  if (lastPageYOffset == -1) {
    lastPageYOffset = pageY;

    // Give browser time to update pageYOffset
    setTimeout(function () {
      handleScroll(e);
    }, 50);
  }
    

  var move = pageY - lastPageYOffset;

  console.log("pageY: " + pageY);
  console.log("lastPageY: " + lastPageYOffset);
  console.log("move: " + move);

  if (pageY > lastPageYOffset) {
    // Scrolled down
    console.log("Scrolling down");
    //console.log("Scrolling back to: " + (pageY - move))
    //scrollTo(0, pageY - move);
  } else {
    // Scrolled up
    console.log("Scrolling up");
    //console.log("Scrolling back to: " + (pageY + move))
    //scrollTo(0, pageY + move);
  }

  // Update last page Y offset
  lastPageYOffset = pageY;
}


function disruptEvent(e) {
  if (!e) e = window.event;

  if (e.preventDefault)
    e.preventDefault();
  else
    e.returnValue = false;
}

function cancelEvent(e) {
  e = e ? e : window.event;
  if (e.stopPropagation)
    e.stopPropagation();
  if (e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

function toggleBlind(element) {
  if (!element) return;

  var mode = null;
  if (element && element.getAttribute('viewMode')) {
    mode = element.getAttribute('viewMode');
  } else {
    mode = 'show'; // initialize mode
  }

  if (mode == 'show') {
    element.setAttribute('viewMode', 'hide');
    Effect.BlindDown(element, { duration: 1.0 });
    setTimeout(
      new Effect.Opacity(
      element, {
        from: 0.0,
        to: 1.0,
        duration: .5
      }), 1000);
  } else if (mode == 'hide') {
    element.setAttribute('viewMode', 'show');
    new Effect.Opacity(
    element, {
      from: 1.0,
      to: 0.0,
      duration: .5
    });
    setTimeout(function() {
      Effect.BlindUp(element, { duration: 1.0 });
    }, 500);
  }
}

function toggleOpacity(event, element, from, to, mode) {
  if (!element) return;

  // Check if hide and if pointer still is within bounds of box. If so,
  // then return, because it's over another div within bounds

  /*
  var x = 0;
  var y = 0;
  if (event != null) {
    x = event.clientX;
    y = event.clientY;
  }

  var left = element.offsetLeft;
  var top = element.offsetTop;
  var width = element.offsetWidth;
  var height = element.offsetHeight;

  if (x >= left && x <= (left + width) &&
      y >= top && y <= (top + height)) {
    console.log('pointer still inside');  
    return;
  } else {
    console.log('pointer NOT still inside');
  }*/


  if (mode == 'show') {
    new Effect.Opacity(
    element, {
      from: from,
      to: to,
      duration: .5
    });
  } else if (mode == 'hide') {
    new Effect.Opacity(
    element, {
      from: to,
      to: from,
      duration: .5
    });
  }
}

var __gradientsLoaded = false;
var __timesRun = 0;

function loadGradients() {
  // Since we can't trust dom/window load events with ajax, and we have to run
  // this method several times during load to guarantee gradient visuals, we'll
  // do a check for a backgroundImage on each panel every time this function is run
  // This improves speed and gradient visuals reliability alot!
  $$('.news-panel').each(function(panel) {
    if (!panel.style.backgroundImage) {
      setGradient(panel, '#f2f2f2', '#d3d3d3', 0);
    }
  });
  $$('.syndication-panel').each(function(panel) {
    if (!panel.style.backgroundImage) {
      setGradient(panel, '#373737', '#000000', 0);
    }
  });
  $$('.component-info-panel').each(function(panel) {
    if (!panel.style.backgroundImage) {
      setGradient(panel, '#f9f9f9', '#e6e6e6', 0);
    }
  });
  //setGradient($('bottom-bar'), '#373737', '#000000', 0);
}

function loadGradients2(e) {
  __timesRun++;

	/*
  var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
  */

  // Since we can't trust dom/window load events with ajax, and we have to run
  // this method several times during load to guarantee gradient visuals, we'll
  // do a check for a backgroundImage on each panel every time this function is run
  // This improves speed and gradient visuals reliability alot!
  $$('.news-panel').each(function(panel) {
    if (!panel.style.backgroundImage) {
      setGradient(panel, '#f2f2f2', '#d3d3d3', 0);
    }
  });
  $$('.syndication-panel').each(function(panel) {
    if (!panel.style.backgroundImage) {
      setGradient(panel, '#373737', '#000000', 0);
    }
  });
  setGradient($('bottom-bar'), '#373737', '#000000', 0);
}


function popupRequestForm(params) {

  var dialogTitle = 'Inviter en eller flere venner';
  var friendSelectorDescription = 'Inviter en eller flere venner';
  var requestMessage = 'Jeg har blitt medlem p&aring; ' + window.location.host + ', trykk her og bli medlem du ogs&aring;!';

  var confirmUrl = 'http://' + window.location.host;
  if(params) {
    if(params.dialogTitle) { dialogTitle = params.dialogTitle; }
    if(params.friendSelectorDescription) { friendSelectorDescription = params.friendSelectorDescription; }
    if(params.requestMessage) { requestMessage = params.requestMessage; }
    if(params.confirmUrl) { confirmUrl = params.confirmUrl; }
  }

  FB.IFrameUtil.CanvasUtilServer.run(true);
  var _de = document.createElement("div");
  _de.setAttribute("iframeHeight", "675px");
  _de.setAttribute("iframeWidth", "630px");
  var _df = new FB.UI.PopupDialog(dialogTitle, _de, false, false);
  _df.setContentWidth(630);
  _df.setContentHeight(675);
  _df.set_placement(FB.UI.PopupPlacement.topCenter);
  _de.setAttribute("fbml",
		  "<fb:fbml>" +
		  "  <fb:request-form style=\"width:630px; height:675px;\" action=\"" + document.location.href + "?invite\" " +
		  "    method=\"POST\" invite=\"false\" type=\"Verv en venn\" " + "content=\"" + requestMessage + " <fb:req-choice url='" + confirmUrl + "' label='Confirm' />\">" +
		  "    <fb:multi-friend-selector\tshowborder=\"false\" actiontext=\"" + friendSelectorDescription + "\" rows=\"5\" bypass=\"cancel\"\tshowborder=\"false\" />" +
		  "  </fb:request-form>" +
		  "</fb:fbml>");
  _df.show();

  $$(".invite-worker").each(function(worker) {
    worker.hide();
  });

  FB_RequireFeatures(["XFBML"], function() {
    var _e0 = new FB.XFBML.ServerFbml(_de);
    FB.XFBML.Host.addElement(_e0);
  });
}
function popupFacebookInvite(params) {


  FB.Facebook.get_sessionState().waitUntilReady(Delegate.create(null, function(_e1) {
    FB.Facebook.apiClient.connect_getUnconnectedFriendsCount(function(o, e) {
      if (o > 1) {
        FB.Connect.inviteConnectUsers();
      } else {
        popupRequestForm(params);
      }
    });
  }));

  return false;
}


function ppost(post_id, exception, data) {
  // Handle feedback
  if (post_id == null || post_id == 'null') {
  // If post_id eq null, then Facebook post was skipped
  } else {
  // Facebook post success
  }

  // Handle user message data
  if (post_id) {
   if (exception) {}
   if (data && data.user_message) {
     //ajax('/rodekors/save.php', 'msg=' + data.user_message, rodekors);
   }
  }
}

function postBack(whyMessage, iveDoneMessage, channelHost, clubid, link, callbackf) {
  /*var logoHack = $$('.site-logo')
  var logo = null;
  if (logoHack && logoHack.length > 0) {
    logo = logoHack[0].src;
  }
  if (logo == null) {*/
  //var logo = 'http://www.internettkanalen.no/ext/' + clubid + '/logo.png';
  //}

  var logo = "http://www.internettkanalen.no/assets/img/xsnakk2/subimg/" + clubid + "-logo.png";
  
  var callback = callbackf || ppost;

  FB.ensureInit(function () {
    var attachment = {'name':'Trykk her for å se',
                      'href':link,
                      'description':'',
                      'caption':iveDoneMessage,
                      'media':[{'type':'image','src':logo,'href':'http://' + channelHost}]};
    var actionLinks = [{ 'text': channelHost, 'href': 'http://' + channelHost}];

    FB.Connect.streamPublish('', attachment, actionLinks, null, whyMessage, callback);

  });
}

/* returns don't work - ofcourse... so reimpl. */
function imageExist(url, posCallback, negCallback) {
  var img = new Image();
  img.onload = function() {
    if (img.width == 0) {
      if (negCallback) negCallback();
      else return false;
    } else {
      if (posCallback) posCallback();
      else return true;
    }
  }

  img.onerror = function() {
    if (negCallback) negCallback();
    else return false;
  }

  img.src = url;
}

function animateDiscreteOpinion(event, item, delay) {

  var ua = navigator.userAgent;
  //isIe = ua.indexOf('MSIE') != -1;
  ie6 = ua.indexOf('MSIE 6.0') != -1;
  ie7 = ua.indexOf('MSIE 7.0') != -1;
  ie8 = ua.indexOf('MSIE 8.0') != -1;
  ie9 = ua.indexOf('MSIE 9.0') != -1;
  if ((ie6 || ie7 || ie8) && !ie9)
    return;
  
  var idIdx = item.className.lastIndexOf("_") + 1;
  var id = item.className.substring(idIdx, item.className.length);
  var box = $$('.discrete_box_' + id)[0];

  // Delay feature. Enables not showing the box until 400 millis has passed.
  // If mouseout before then, do nothing. If mouseout after it's shown, 
  // fade out normally.
  if (delay) {
    var timeout = setTimeout(function() {
      box.setAttribute('timeMode', '');
      animateDiscreteOpinion({type : event.type}, item, false);
    }, 400);
    box.setAttribute('timeMode', timeout);
    return;
  }

  if (event.type == 'mouseout' && box.getAttribute('timeMode')) {
    var _timeout = box.getAttribute('timeMode');
     if (_timeout && _timeout != '') {
      clearTimeout(_timeout);
      box.setAttribute('timeMode', '');
      return;
    }
  }

  // Due to a stupid IE8 bug (no opacity on children with position relative),
  // we have to find .box which, and set it as box (because IE8 will work with
  // elements that has position relative themselves)
  //box = box.select('.box')[0];

  if (box == null) {
    if (window.console && window.console.firebug) {
      console.log("CR_ERROR: Discrete opinion box not found in DOM");
    }
    return;
  }

  //document.body.appendChild(box); // move out of overflow:hidden area

  // Get box out of display: none so that we can measure dims
  Effect.Appear(box, { duration: 0, from: 0, to: .01 });

  // Position element accordingly
  var nWidth = box.offsetWidth;
  var nHeight = box.offsetHeight;
  var itemWidth = item.offsetWidth;
  var itemHeight = item.offsetHeight;
  

  //var pos = getAbsoluteElementPos(item); // only use this is box is appended to body
  var margin = 5; // space between box arrow and user picture
  var boxWidth = 300;

  if (box.style.width != '300px') {
    // is box is appended to body
    /*box.style.left = (pos.x - (boxWidth / 2) + (itemWidth / 2)) + 'px';
    box.style.top = (pos.y - nHeight - margin) + 'px';*/

    // place relative to image  box.offsetLeft
    box.style.left = '-' + ((boxWidth / 2) - ((itemWidth / 2)) - item.offsetLeft) + 'px';
    box.style.bottom = (itemHeight + (itemHeight * 0.3)) + 'px';
    box.style.width = boxWidth + 'px';
    box.style.position = 'absolute';
    box.style.zIndex = '5';
  }

  if (event.type == 'mouseover') {

    /*if (isIe) {
      new Effect.Opacity(item, { from: 0.7, to: .99, duration: 0.5 });
      $(box).show();
    } else {*/
      new Effect.Opacity(item, { from: .7, to: .99, duration: 0.5 });
      new Effect.Opacity(box, { from: .01, to: .99, duration: 0.5 });
    //}

    //crFadeIn(box, {duration: 1000, steps: 20});
    //fadeObject(box, {begin: 0, end: 100, millis: 500});
  } else if (event.type == 'mouseout') {

    /*if (isIe) {
      new Effect.Opacity(item, { from: .99, to: 0.7, duration: 0.5 });
      $(box).hide();
    } else {*/
      new Effect.Opacity(item, { from: .99, to: .7, duration: 0.5 });
      //new Effect.Opacity(box, { from: .99, to: 0, duration: 0.5 });
      Effect.Fade(box, { duration: 0.5, from: .99, to: 0 }); // display: none is set
    //}

    //crFadeOut(box, {duration: 1000, steps: 20});
    //fadeObject(box, {begin: 100, end: 0, millis: 500});
  }
}

function getAbsoluteElementPos(item) {
  var x = 0;
  var y = 0;
  if (item.offsetParent) {
    x = item.offsetLeft;
    y = item.offsetTop;
    while (item = item.offsetParent) {
      x += item.offsetLeft;
      y += item.offsetTop;
    }
  }
  return {x: x, y: y};
}

function crSetOpacity(object, value) {
  object.style.opacity = value;
  object.style.filter = "alpha(opacity=" + (value * 100) + ");";
}

/* Options are duration and steps (1000 and 20 is default) */
function crFadeIn(object, options) {
  for (i = 0; i <= 1; i += (1 / options.steps)) {
    //setTimeout("crSetOpacity("+ object +"," + i + ")", i * options.duration);
    setTimeout(function () { crSetOpacity(object, i); }, i * options.duration);
  }
}

function crFadeOut(object, options) {
  for (i = 0; i <= 1; i += (1 / options.steps)) {
    //setTimeout("crSetOpacity("+ object +"," + (1 - i) + ")", i * options.duration);
    setTimeout(function () { crSetOpacity(object, 1 - i); }, i * options.duration);
  }
}


/** Fades a #div in or out
  *
  *	@author Erling Limm (eibon.dott at gmail.com) */

/* Begins transition */
function fadeObject(object, param) {
	var frame = 0;
	var duration = Math.round(param.millis / 100);

  console.log("param.begin " + param.begin);
  console.log("param.end " + param.end);
  console.log("param.millis " + param.millis);
  console.log("duration " + duration);



	if (param.begin > param.end) {
		for (opacity = param.begin; opacity >= param.end; opacity--) {
			//setTimeout("doChange("+opacity+",\""+id+"\")",
			//	(frame * duration));
      setTimeout(function() { doOpacityChange(object, opacity); }, (frame * duration));
			frame++;
      console.log("dur: " + (frame * duration));
		}
	} else if (param.begin < param.end) {
		for (opacity = param.begin; opacity <= param.end; opacity++) {
			//setTimeout("doChange("+opacity+ ",\""+id+"\")", (frame * duration));
      setTimeout(function() { doOpacityChange(object, opacity); }, (frame * duration));
			frame++;
      console.log("dur: " + (frame * duration));
		}
	}
}

/* Changes an element "frame" to given opacity */
function doOpacityChange(object, value) {
    console.log("   new opacity value: " + value);
  //if (isIE)
    object.style.filter = 'alpha(opacity=' + value + ')';
  //else
	  object.style.opacity = value / 100;
}


// Google Maps
var gMap;
var geocoder;
var gPlace;

function gMapInitialize() {
  gMap = new GMap2(document.getElementById("map_canvas"));
  gMap.setCenter(new GLatLng(0, 0), 14);
  geocoder = new GClientGeocoder();
}

function addAddressToMap(response) {
  gMap.clearOverlays();
  if (!response || response.Status.code != 200) {
    //alert("Beklager, men vi klarer ikke å geokode den adressen");
  } else {
    gPlace = response.Placemark[0];
    point = new GLatLng(gPlace.Point.coordinates[1],
                        gPlace.Point.coordinates[0]);
    marker = new GMarker(point);
    gMap.addOverlay(marker);
    marker.openInfoWindowHtml(gPlace.address + '<br>' +
      '<b>Country code:</b> ' + gPlace.AddressDetails.Country.CountryNameCode);
  }
}

function showLocation() {
  var address = document.forms[0].address.value;
  geocoder.getLocations(address, addAddressToMap);
}

function setGLocation(address) {
  geocoder.getLocations(address, addAddressToMap);
}

function findLocation(address) {
  document.forms[0].address.value = address;
  showLocation();
}

var __gInitTries = 0;

function initAndShowMap() {
  var gCanvas = $('map_canvas');
  if (gCanvas) {
    gMapInitialize(); // only init if a canvas exists
    var location = gCanvas.getAttribute("address");
    setGLocation(location);
  } else {
    if (__gInitTries < 5) {
      __gInitTries++;
      setTimeout(initAndShowMap, 1000);
    }
  }
}


function toggleSubCategories(event, item) {

  var idIdx = item.className.lastIndexOf("-") + 1;
  var id = item.className.substring(idIdx, item.className.length);
  var sub = $$('.sub-cat-' + id)[0];
  var subContent = $$('.sub-cat-' + id + ' .sub-content')[0];
  var button = $$('.button-cat-' + id)[0];

  if (sub == null || button == null) {
    if (window.console && window.console.firebug) {
      console.log("CR_ERROR: Sub category element not found.");
    }
    return;
  }

  var ua = navigator.userAgent;
  isIe = ua.indexOf('MSIE') != -1;

  // Find sub that's already open and close it, but not if it's the one we clicked
  var _return = false;
  $$('.sub-categories').each(function(subc) {
    if (subc.style.display != 'none') {
      if (subc != sub) {
        if (isIe) {
          $(subc).hide();
        } else {
          Effect.BlindUp(subc, { duration: .2 });
        }
      } else {
        _return = true; // No further messing with this object
      }
    }
  });
  if (_return)
    return;
  
  //document.body.appendChild(box); // move out of overflow:hidden area

  // Position element accordingly
  var buttonWidth = button.offsetWidth;
  var buttonHeight = button.offsetHeight;

  var arrowX = buttonWidth / 2;
  
  var subWidth = sub.offsetWidth;
  var subHeight = sub.offsetHeight;
  var subPos = getAbsoluteElementPos(sub);

  // Do not show if there's no content
  if (event.type == 'click' && subContent.innerHTML != '') {
    if (isIe) {
      $(sub).show();
    } else {
      Effect.BlindDown(sub, { duration: .5 });
    }
  }
}

function setCategory(event, item, id) {
  item = $(item);
  if (item.hasClassName('super-category')) {
    var _class = item.className;
    var start = _class.indexOf("button-cat-") + 11;
    var end = _class.indexOf(" ", start);
    if (end == -1) end = _class.length; // no space = end of string
    var _id = _class.substring(start, end);

    if (!isNaN(_id)) {
      var sub = $$('.sub-cat-' + _id)[0];
      var subContent = $$('.sub-cat-' + _id + ' .sub-content')[0];
      var _return = false;
      $$('.sub-categories').each(function(subc) {
        if (subc.style.display != 'none') {
          if (subc != sub) {
            Effect.BlindUp(subc, { duration: .2 });
          } else {
            _return = true; // No further messing with this object
          }
        }
      });
      if (_return)
        return;
      if (event.type == 'click' && subContent.innerHTML != ''
          && !item.hasClassName('no-subs')) {
        Effect.BlindDown(sub, { duration: .5 });
      }
    }
  }

  var cat = $('_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_catSelected');
  var subCat = $('_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_subCatSelected');
  if (!cat && !subCat) {
    cat = $('_catSelected');
    subCat = $('_subCatSelected');
  }

  var pressed = 'generic-button-pressed';
  if (!item.hasClassName(pressed)) {
    var catItems = {};
    if (item.hasClassName('super-category')) {
      catItems = $$('.super-category');
      cat.value = id;
      subCat.value = '';
      if (item.hasClassName('no-subs')) { // close if this item doesn't have any subs
        $$('.sub-categories').each(function(subc) {
          if (subc.style.display != 'none') {
            Effect.BlindUp(subc, { duration: .2 });
          }
        });
      }
    } else {
      catItems = $$('.sub-categories .category-item');
      subCat.value = id;
    }
    catItems.each(function(sc) {
      if (sc.hasClassName(pressed)) {
        sc.removeClassName(pressed);
      }
    });
    item.addClassName(pressed);
  } else {
    item.removeClassName(pressed);
    if (item.hasClassName('super-category')) {
      setCategory(event, $('all-categories'), '');
    } else {
      var subAll = item.parentNode.firstDescendant();
      setCategory(event, subAll, '');
    }
  }
}


function setFlags(event, item, id) {
  item = $(item);

  var pressed = 'generic-button-pressed';
  if (!item.hasClassName(pressed)) {
    item.addClassName(pressed);
  } else {
    item.removeClassName(pressed);
  }

  var finalFlags = '';
  $$('.generic-button-pressed').each(function(pressedItem) {
    if (pressedItem.hasClassName('flag-item')) {
      finalFlags += pressedItem.getAttribute('flagid') + ',';
    }
  });
  finalFlags = finalFlags.replace(/^,+|,+$/g, '');

  var flags = $('_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_flagsSelected');
  if (!flags) flags = $('_flagsSelected');
  flags.value = finalFlags;

}


function initDatePickers() {
  var opts1 = {
    formElements:{"_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_dateStart":"d-sl-m-sl-Y"}
  };
  datePickerController.createDatePicker(opts1);
  var opts2 = {
    formElements:{"_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_dateEnd":"d-sl-m-sl-Y"}
  };
  datePickerController.createDatePicker(opts2);
}

function destroyDatePickers() {
  datePickerController.destroyDatePicker("_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_dateStart");
  datePickerController.destroyDatePicker("_fbTestComponent:_showViewEvents:_loggedInView:_clubLists:_clubEventx:_advancedView:_categoryFilter:_searchForm:_dateEnd");
}



function evalScripts(text) {
  
  for (var i = 0; i < text.length;) {
    var start = text.indexOf("<script ", i);
    if (start != -1) {
      start = text.indexOf(">", start) + 1;
      var end = i = text.indexOf("</script>", start);
      var sub = text.substring(start, end);

      // fix this code some day
      start = sub.indexOf("//<![CDATA[") + "//<![CDATA[".length;
      end = sub.indexOf("//]]>");
      if (start != -1 && end != -1) {
        sub = sub.substring(start, end);
      }
      start = sub.indexOf("// <![CDATA[") + "// <![CDATA[".length;
      end = sub.indexOf("// ]]>");
      if (start != -1 && end != -1) {
        sub = sub.substring(start, end);
      }

      eval(sub);
    } else {
      break; // no scripts
    }
  }

}


function animateGenericInfo(event, item, delay, content) {

  var x = event.clientX;
  var y = event.clientY;

  // Delay feature. Enables not showing the box until 400 millis has passed.
  // If mouseout before then, do nothing. If mouseout after it's shown,
  // fade out normally.
  if (delay) {
    var timeout = setTimeout(function() {
      item.setAttribute('timeMode', '');
      animateGenericInfo(event, item, false, content);
    }, 100);
    item.setAttribute('timeMode', timeout);
    return;
  }

  if (event.type == 'mouseout' && item.getAttribute('timeMode')) {
    var _timeout = item.getAttribute('timeMode');
     if (_timeout && _timeout != '') {
      clearTimeout(_timeout);
      item.setAttribute('timeMode', '');
      return;
    }
  }

  var ua = navigator.userAgent;
  isIe = ua.indexOf('MSIE') != -1;

  var box;
  if (!content.id) {
    box = $('generic-info');
    if (box) box.remove();

    box = document.createElement('div');
    box.setAttribute('id', 'generic-info');
  } else {
    box = content;
  }

  box.style.position = 'absolute';
  box.style.width = 250 + 'px';
  box.style.backgroundColor = '#D3D3D3';
  box.style.padding = '10px';
  box.style.fontSize = '11px';
  box.style.zIndex = '102';
  box.style.textAlign = 'left';
  if (isIe) {
    box.style.filter = 'alpha(opacity=0)';
    //$(box).hide();
  } else {
    box.style.opacity = '0';
  }
  
  document.body.appendChild(box);
  
  // Determine if this box is out of bounds
  var boxOffsetX = (x + 22);
  var boxWidth = box.offsetWidth;
  var bodyWidth = document.body.offsetWidth;

  if ((boxOffsetX + boxWidth) > bodyWidth) {
    // Place on left side instead of right
    box.style.left = (x - boxWidth - 22) + 'px';
  } else {
    // Place on default right side
    box.style.left = (x + 22) + 'px';
  }
  box.style.top = (y - getScrollPos()) + 'px';

  if (!content.id) {
    box.innerHTML = '<a href="javascript:;" onclick="this.parentNode.hide(); this.parentNode.style.left = \'-10000px;\'" class="opinions-child-deletelink">x</a>';
    box.innerHTML += content;
  } else {
    var element = box.getElementsByTagName('a')[0];
    if (!element) {
      var xElement = document.createElement('span');
      xElement.innerHTML = '<a href="javascript:;" onclick="this.parentNode.parentNode.hide(); this.parentNode.parentNode.style.left = \'-10000px;\'" class="opinions-child-deletelink">x</a>';
      box.appendChild(xElement);
    }
  }

  if (event.type == 'mouseover' || event.type == 'click') {
    if (typeof Effect == 'object') {
      Effect.Appear(box, { duration: 0.7, from: 0, to: 1 });
    } else {
      box.show();
      if (isIe) {
        box.style.filter = 'alpha(opacity=100)';
      } else {
        box.style.opacity = '1';
      }
    }
  } else if (event.type == 'mouseout') {
    if (typeof Effect == 'object') {
      Effect.Fade(box, { duration: 0.7, from: 0, to: 1 });
    } else {
      box.hide();
      if (isIe) {
        box.style.filter = 'alpha(opacity=0)';
      } else {
        box.style.opacity = '0';
      }
    }
  }

}


function fetchMailBox(event, item, delay, content) {
  var ua = navigator.userAgent;
  isIe = ua.indexOf('MSIE') != -1;
  box = content;

  /*box.style.position = 'absolute';
  box.style.width = 250 + 'px';
  box.style.backgroundColor = '#2a2424';
  box.style.padding = '10px';
  box.style.fontSize = '11px';
  box.style.color = 'white';
  box.style.zIndex = '102';*/
  box.style.textAlign = 'left';
  if (isIe) box.style.filter = 'alpha(opacity=0)';
  else box.style.opacity = '0';

  /*var sourceLeft = item.offsetLeft;
  box.style.left = (sourceLeft - 250 - 10) + 'px';
  box.style.top = (10) + 'px';*/

  var element = box.getElementsByTagName('a')[0];
  if (!element) {
    var xElement = document.createElement('span');
    xElement.innerHTML = '<a href="javascript:;" onclick="this.parentNode.parentNode.hide(); this.parentNode.parentNode.style.left = \'-10000px;\'" class="opinions-child-deletelink">x</a>';
    if (box.hasChildNodes()) {
      var firstChild = box.firstDescendant(); // real first child, no text node
      box.insertBefore(xElement, firstChild);
    } else {
      box.appendChild(xElement);
    }
  }

  if (event.type == 'mouseover' || event.type == 'click') {
    if (typeof Effect == 'object') {
      Effect.Appear(box, { duration: 0.7, from: 0, to: 1 });
    } else {
      box.show();
      if (isIe) {
        box.style.filter = 'alpha(opacity=100)';
      } else {
        box.style.opacity = '1';
      }
    }
  }
}


function showCustomBoxIndeed(event, obj, node, width) {
  var x = event.clientX;
  var y = event.clientY;
  var box = $('suggest-login-box-custom');
  if (!box) {

    // Determine if we're in an iframe
    //var inIframe = window.frameElement != null;

    var ua = navigator.userAgent;
    isIe = ua.indexOf('MSIE') != -1;


    box = document.createElement('div');
    box.setAttribute('id', 'suggest-login-box');
    box.style.position = 'absolute';
    box.style.width = width + 'px';
    box.style.backgroundColor = '#fff';
    //box.style.padding = '10px';
    box.style.fontSize = '11px';
    box.style.zIndex = '101';
    box.style.textAlign = 'left';
    if (isIe) {
      box.style.filter = 'alpha(opacity=0)';
    } else {
      box.style.opacity = '0';
    }
    document.body.appendChild(box);

    //box.setAttribute('id', 'custom-login-box');
    box.style.position = 'absolute';
    box.style.width = width + 'px';
    box.style.backgroundColor = '#fff';
    //box.style.padding = '10px';
    box.style.fontSize = '11px';
    box.style.zIndex = '102';
    box.style.textAlign = 'left';
    if (isIe) {
      //box.style.filter = 'alpha(opacity=0)';
      $(box).hide();
    } else {
      box.style.opacity = '0';
    }

    // Determine if this box is out of bounds
    var boxOffsetX = (x + 22);
    var boxWidth = box.offsetWidth;
    var bodyWidth = document.body.offsetWidth;

    if ((boxOffsetX + boxWidth) > bodyWidth) {
      // Place on left side instead of right
      box.style.left = (x - boxWidth - 22) + 'px';
    } else {
      // Place on default right side
      box.style.left = (x + 22) + 'px';
    }
    box.style.top = (y - getScrollPos()) + 'px';

    /*
    var arrow = document.createElement('div');
    arrow.setAttribute('id', 'suggest-login-arrow');
    arrow.style.position = 'absolute';
    arrow.style.width = '12px';
    arrow.style.height = '12px';
    arrow.style.top = (y + getScrollPos()) + 'px';
    arrow.style.left = (x + 10) + 'px';
    arrow.style.backgroundImage = 'url(assets/img/icons/talk_arrow_left.png)';
    arrow.style.zIndex = '101';
    if (isIe) {
      arrow.style.filter = 'alpha(opacity=0)';
    } else {
      arrow.style.opacity = '0';
    }
    document.body.appendChild(arrow);
    */

    /* TODO: include scriptaculous dynamicly? */
    if (typeof Effect == 'object') {
      if (isIe) {
        box.style.filter = 'alpha(opacity=99)';
        $(box).show();
      } else {
        //Effect.Fade(box, { duration: 0.7, from: 0, to: 1 });
        box.style.opacity = '1';
      }

    } else {
      if (isIe) {
        //arrow.style.filter = 'alpha(opacity=100)';
        box.style.filter = 'alpha(opacity=99)';
        $(box).show();
      } else {
        //arrow.style.opacity = '1';
        box.style.opacity = '1';
      }
    }

    // Attach a mousescroll events to the body to prevent scrolling while viewing this box
    var body = document.getElementsByTagName('body')[0];
    Event.observe(body, 'mousewheel', function(e) { disruptEvent(e) });
    Event.observe(body, 'DOMMouseScroll', function(e) { disruptEvent(e) });
    Event.observe(body, 'onmousewheel', function(e) { disruptEvent(e) });

    // Because one cannot cancel the scroll event, we must implement something super,
    // i.e. register pos on first scroll and return to this pos on last scroll event. yeah!

    //Event.observe(body, 'scroll', function(e) { handleScroll(e); });
    //Event.observe(document, 'scroll', function(e) { handleScroll(e); });
  }
}

function getFBCEPermission(apiKey) {
  //window.open('http://www.facebook.com/authorize.php?api_key=' + apiKey + '&v=1.0&ext_perm=create_event', 'Permission');
  var link = $$('.accept-link')[0];
  if (link) {
    var href = link.href;
    link.href = href.replace("API_KEY", apiKey);
    var wrapper = $$('.accept-rights')[0];
    if (wrapper) {
      wrapper.toggle();
      new Effect.Hightlight(wrapper, {startcolor: '#ffff99', endcolor: '#ffffff'});
    }
  }
}

function getFBEmailPermission(apiKey) {
  window.open('http://www.facebook.com/authorize.php?api_key=' + apiKey + '&v=1.0&ext_perm=email', '', 'scrollbars=1, width=640px, height=800px');
}

function getFBPermission() {
  alert("getFBPermission() -> entered");
  FB.ensureInit(function() {
    alert("getFBPermission() -> ensure init: create_event");
    FB.Connect.showPermissionDialog("create_event", function(perms) {
      alert("getFBPermission() -> permissions selected");
      if (!perms) {
        alert("No");
      } else {
        alert("yes");
      }
    });
  });
}


/*
 * Prompts the user to grant a permission to the application - if the user already hasn't done it
 */
function facebook_prompt_permission(permission, callbackFunc) {
  ensure_init(function() {
    //check is user already granted for this permission or not
    FB.Facebook.apiClient.users_hasAppPermission(permission,
     function(result) {
        // prompt offline permission
        if (result == 0) {
            // render the permission dialog
            FB.Connect.showPermissionDialog(permission, callbackFunc);
        } else {
            // permission already granted.
            callbackFunc(true);
        }
    });
  });
}


/*
 * Get a parameter from an URL
 */
function getParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return null;
  else
    return results[1];
}


function tmOnchangeHandler(instance) {
  var con = instance.getContent();
  con = con.replace(/<[^<>]*>/g, '');
  instance.setContent(con);
}



