/*
x = 0;
y = 0;
blurred = false;
*/

//window.onfocus = function (){if(blurred){$('ajax-progress').innerHTML="Focus: " + (++x) + " Blur: " + y;blurred=false;}};
//window.onblur = function (){blurred=true;$('ajax-progress').innerHTML="Focus: " + x + " Blur: " + (++y);};

function initiateActionWithArgs(actionCode, sessionString, args, method) {
    if (!method) method = 'get';
    grayOut(true);
    document.body.style.cursor = "url(/pub/images/layout/cursors/wait.png), auto";

    jj.ajax(
        {
           url:getActionUrl(actionCode, sessionString),
           type: method,
           success: onActionSuccess,
           error: onActionFailure,
           complete: function() {
                       Window.tooltipsDisabled = false;
                       grayOut(false);
                       document.body.style.cursor = "url(/pub/images/layout/cursors/normal.png), auto";
                       //$('ajax-progress').innerHTML = "";
           },
           data: args
           });
}

function initiateAction(actionCode, sessionString) {
    initiateActionWithArgs(actionCode, sessionString);
}

function initiateFormAction(actionCode, form, sessionString, loadingContainerId) {
    // Hidden "action" field should not be serialized on AJAX
    var serializedForm = form.serialize(true);
    delete(serializedForm['action']);
    
    if (loadingContainerId)
      document.getElementById(loadingContainerId).innerHTML = "Ergebnis wird berechnet, bitte warten...";

    initiateActionWithArgs(actionCode, sessionString, serializedForm, form.method);
}


// Utilities
function updateElementBody(element, newBody) {
  //jj('#'+id).replaceWith(newBody);
  element.update(newBody);
  //element.innerHTML = newBody;
}

function selectionEmpty() {
    if(document.getSelection) {
	return document.getSelection() == "";
    } else if(document.selection && document.selection.createRange) {
	return document.selection.createRange().text == "";
    } else {
	return true;
    }
}

function addCss(cssCode) {
    var styleElement = document.createElement("style");
    styleElement.type = "text/css";
    if (styleElement.styleSheet) {
	styleElement.styleSheet.cssText = cssCode;
    } else {
	styleElement.appendChild(document.createTextNode(cssCode));
    }
    document.getElementsByTagName("head")[0].appendChild(styleElement);
}

function stopPropagation(event) {
    if(event.preventDefault) {
	event.stopPropagation();
    } else {
	event.cancelBubble = true;
    };
}

function onActionSuccess(responseText) {
    if(Prototype.Browser.WebKit) {
	// We should sanitize JSON, but at the moment it crashes Safari
        json = responseText.evalJSON();
    } else {
        json = responseText.evalJSON(true);
    }
    
    // See if there are redirects
    var redirect = json['redirect'];
    if (redirect)
    {
	window.location.href = redirect;
	return;
    }
    
    execJsonCalls(json['before-load']);

    // Update dirty widgets
    var dirtyWidgets = json['widgets'];
    for(var i in dirtyWidgets) {
	var widget = $(i);
	if(widget) {
            //console.log("updating widget %s", i);
            //alert("updating widget " + i);
	    updateElementBody(widget, dirtyWidgets[i]);
	}
    }

    execJsonCalls(json['on-load']);
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

var jsUid = (function()
 {
   var id=0;
   return function(){return id++;};
 })();

function execJsonCalls (calls) {
    if(calls) {
	calls.each(function(item)
			 {
			     try {
                                 //console.log(item);
                                 //item.evalJSON().call();
				 //document.observe("dom:loaded", function () {item.evalJSON().call();});
				 //document.observe("dom:loaded", function () {item.evalScripts();});
                                 item.evalScripts();

			     } catch(e) {
                                 //console.dir(e)
                             }
			 });
    }
}

function onActionFailure(request) {
  var response = request.responseText;
  var status = request.status;
  var detail = '';

  if (status == 500) 
    detail = response;

  alert('Ein Programmfehler ist aufgetreten.\n'
      + 'Versuche, die Seite neu zu laden oder dich neu anzumelden.\n\n'
      + 'Sollte der Fehler erneut auftreten, so melde ihn uns bitte.\n\n'
      + 'Nenne dabei den folgenden Fehlercode: ' + detail + status);
}

function getActionUrl(actionCode, sessionString, isPure) {
    var url = location.href.sub(/\?.*/, "") + '?' + sessionString + '&action=' + actionCode;
    if(isPure) {
	url += '&pure=true';
    }
    return url;
}


function disableIrrelevantButtons(currentButton) {
    $(currentButton.form).getInputs('submit').each(function(obj)
						   {
						       obj.disable();
						       currentButton.enable();
						   });
}

// Fix IE6 flickering issue
if(Prototype.Browser.IE) {
    try {
	document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
}

// Table hovering for IE (can't use CSS expressions because
// Event.observe isn't available there and we can't overwrite events
// using assignment
if(!window.XMLHttpRequest) {
    // IE6 only
    Event.observe(window, 'load', function() {
	    var tableRows = $$('.table table tbody tr');
	    tableRows.each(function(row) {
		    Event.observe(row, 'mouseover', function() {
			    row.addClassName('hover');
			}); 
		    Event.observe(row, 'mouseout', function() {
			    row.removeClassName('hover');
			}); 
		});
	});
}

// Support suggest control
function declareSuggest(inputId, choicesId, resultSet, sessionString) {
    if(resultSet instanceof Array) {
	new Autocompleter.Local(inputId, choicesId, resultSet, {});
    } else {
	new Ajax.Autocompleter(inputId, choicesId, getActionUrl(resultSet, sessionString, true), {});
    }
}

function replaceDropdownWithSuggest(ignoreWelcomeMsg, inputId, inputName, choicesId, value) {
    var dropdownOptions = $(inputId).childElements();
    var suggestOptions = [];
    dropdownOptions.each(function(i)
			 {
			     if(!(i == dropdownOptions[0] && ignoreWelcomeMsg)) {
				 suggestOptions.push(i.innerHTML);
			     }
			 });

    var inputBox = '<input type="text" id="' + inputId + '" name="' + inputName + '" class="suggest"';
    if(value) {
	inputBox += 'value="' + value +'"';
    }
    inputBox += '/>';
    
    var suggestHTML = inputBox + '<div id="' + choicesId + '" class="suggest"></div>';
    $(inputId).replace(suggestHTML);
    
    declareSuggest(inputId, choicesId, suggestOptions);
}

function include_css(css_file) {
  var html_doc = document.getElementsByTagName('head').item(0);
  var css = document.createElement('link');
  css.setAttribute('rel', 'stylesheet');
  css.setAttribute('type', 'text/css');
  css.setAttribute('href', css_file);
  html_doc.appendChild(css);
  return false;
}

function include_dom(script_filename) {
  var html_doc = document.getElementsByTagName('head').item(0);
  var js = document.createElement('script');
  js.setAttribute('language', 'javascript');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', script_filename);
  html_doc.appendChild(js);
  return false;
}

function disableSelection(element) { // see also: http://www.dynamicdrive.com/forums/showpost.php?p=11951&postcount=2
    element.onselectstart = function() {
        return false;
    };
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
}

function hideTooltips () {
  var tooltips = document.getElementsByClassName('yui-tt');
  for (i=0; i<tooltips.length; ++i) {
    tooltips[i].hide();
  }
}

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 || 40;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  var body = document.getElementsByTagName("body")[0];
  var target = document.getElementById("content");

  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 tnode = document.createElement('div');           // 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
    body.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  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+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'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.width= target.offsetWidth+'px';
    dark.style.height= target.offsetHeight+'px';
    dark.style.top=getY(target)+'px';
    dark.style.left=getX(target)+'px';
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

function getY( oElement )
{
  var iReturnValue = 0;
  while( oElement != null ) {
    iReturnValue += oElement.offsetTop;
    oElement = oElement.offsetParent;
  }
  return iReturnValue;
}
function getX( oElement )
{
  var iReturnValue = 0;
  while( oElement != null ) {
    iReturnValue += oElement.offsetLeft;
    oElement = oElement.offsetParent;
  }
  return iReturnValue;
}
