/*
 * tripedia.org
 * 
 * (c) Jan Poeschko
 * 
 */

function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark = $('dark');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = $$("body")[0];
    var tnode = new Element('div', {'class': 'dark', 'id': 'dark'}).hide(); // Create the layer.
        /*tnode.style.position = 'absolute';                 // Position absolutely
        tnode.style.top = '0px';                           // In the top
        tnode.style.left = '0px';                          // Left corner of the page
        tnode.style.overflow = 'hidden';                   // Try to avoid making scroll bars            
        tnode.style.display = 'none';                      // Start out Hidden
        
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
        */
    tbody.appendChild(tnode);                            // Add it to the web page
    //dark = $('darkenScreenObject');  // Get the object.
    dark = tnode;
  }
  if (vis) {
    // Calculate the page width and height 
    if (document.body && (document.body.scrollWidth || document.body.scrollHeight)) {
      var pageWidth = document.body.scrollWidth + 'px';
      var pageHeight = (document.body.scrollHeight + 20) + 'px';
      //pageHeight = Math.max(pageHeight, document.body.getHeight()) + 'px';
      //log(pageHeight);
    } else if (document.body.offsetWidth) {
      var pageWidth = document.body.offsetWidth + 'px';
      var pageHeight = (document.body.offsetHeight + 20) + 'px';
    } else {
      var pageWidth = '100%';
      var pageHeight = '100%';
    }
    //set the shader to cover the entire page and make it visible.
    /*dark.style.opacity = opaque;                      
    dark.style.MozOpacity = opaque;                   
    dark.style.filter = 'alpha(opacity='+opacity+')';*/ 
    dark.style.zIndex = zindex;        
    dark.style.backgroundColor = bgcolor;  
    //dark.style.backgroundColor = 'white';
    dark.style.width = pageWidth;
    dark.style.height = pageHeight;
    //dark.style.display = 'block';   
    new Effect.Appear(dark, {duration: 0.3, 'to': opaque});
    /*dark.show();
    new Effect.Morph(dark, {
    	backgroundColor: bgcolor
    }, {
    	duration: 1
    })*/
    
    //$('everything').style.backgroundColor = 'white';
    var body = $$('body')[0];
    body.style.backgroundImage = 'url(/media/img/design/message_background.gif)';
    body.style.backgroundPosition = '0 ' + pageHeight;
    body.style.backgroundRepeat = 'repeat-x';
  } else {
    //dark.style.display = 'none';
  	dark.hide();
    
    $$('body')[0].style.backgroundImage = 'none';
  }
}

function showPopup(elements, options) {
	options = options || {};
	var container = new Element('div', {'class': 'popupContainer'});
	var div = new Element('div', {'class': 'popup'});
	// to fix IE SELECT z-index bug, see http://drupal.org/node/84608
	var frameContainer = new Element('div', {'class': 'popupFrameContainer'});
	var frame = new Element('iframe', {'class': 'popupFrame'});
	elements.each(function(item) {
		div.appendChild(item)
	});
	container.appendChild(div);
	//div.hide();
	Element.insert($$('body')[0], {'bottom': container});
	var dimensions = div.getDimensions();
	frame.setStyle({'width': dimensions.width + 'px', 'height': dimensions.height + 'px'});
	frameContainer.appendChild(frame);
	Element.insert($$('body')[0], {'bottom': frameContainer});
	grayOut(true, {zindex: 9});
	//div.show();
	//new Effect.Shake(div, { duration: 0.3, distance: 5 });
	frame.scrollIntoView();
	return [[container, frameContainer], options];
}

function hidePopup(popup) {
	var containers = popup[0];
	var options = popup[1];
	var focus = options.focus || null;
	
	var isVisible = containers.pluck('parentNode').all();
	containers.each(function(item) {
		item.deleteElement();
	});
	
	$('dark').deleteElement();
	
	if (isVisible)
		grayOut(false);
	if (focus) {
		function setFocus(item) {
			if (Object.isElement(item))
				return item.tryFocus();
			else if (item.setFocus)
				return item.setFocus();
			else
				return false;
		}
		
		if (Object.isArray(focus))
			focus.any(function(item) {
				return $(item).tryFocus();
			});
			//focus.any(Element.saveFocus.bind);
		else
			$(focus).tryFocus();
	}
}

function showMessage(text, options) {
	var p = new Element('p').setText(text);
	var a = new Element('a', {'class': 'button'}).setText("OK");
	var popup = showPopup([p, a], options);
	a.focus();
	
	function enter() {
		Event.stopObserving(window.document, 'keydown', onKeyDown);
		hidePopup(popup);
	}
	
	function onKeyDown(event) {
		if (event.keyCode == Event.KEY_RETURN || event.keyCode == Event.KEY_ESC || event.keyCode == 32) {
			enter();
			Event.stop(event);
		}
	}
	
	Event.observe(window.document, 'keydown', onKeyDown);
	Event.observe(a, 'click', enter);
}

function startMessage(title, text) {
	var elements = [];
	if (title)
		elements.push(new Element('h2').setText(title));
	if (text)
		elements.push(new Element('p').setText(text));
	var popup = showPopup(elements);
	return popup;
}

function stopMessage(popup) {
	hidePopup(popup);
}

function showDialog(title, text, buttons) {
	var elements = [];
	if (title)
		elements.push($E('h2').setText(title));
	if (text)
		elements.push($E('p').setText(text));
	if (buttons) {
		var div = $E('div', {'class': 'buttons'});
		elements.push(div);
		buttons.each(function(button) {
			var element = $E('a', {'class': 'button'}, $T(button.caption));
			//element._callback = button[1];
			div.appendChild(element);
			button.element = element;
		});
	}
	
	var popup = showPopup(elements);
	buttons.each(function(button) {
		button.element.observe('click', function() {
			hidePopup(popup);
			button.callback();
		});
	})
	
	if (buttons.length == 2) {
		buttons[0].element.focus();
		
		function enter(escape) {
			Event.stopObserving(window.document, 'keydown', onKeyDown);
			hidePopup(popup);
			if (escape)
				buttons[1].callback();
			else
				buttons[0].callback();
		}
		
		function onKeyDown(event) {
			if (event.keyCode == Event.KEY_RETURN || event.keyCode == 32 || event.keyCode == Event.KEY_ESC) {
				enter(event.keyCode == Event.KEY_ESC);
				Event.stop(event);
			}
		}
		
		Event.observe(window.document, 'keydown', onKeyDown);
	}
	
	return popup;
}

function askQuestion(title, text, buttons, onConfirm) {
	return showDialog(title, text, [
	  {caption: buttons[0], callback: onConfirm},
	  {caption: buttons[1], callback: Prototype.emptyFunction}
	]);
}