var ogcore_debug_html_elementid = "ogcore_debug_div";
var ogcore_debug_ajax_url = '/immformer/ajax_debug.jsp';
var ogcore_ajax_baseurl = "/immformer/servlet/";

function requestStart(){};
function requestEnd(){};
function showHourGlass(){};
function hideHourGlass(){};

function createCookie(name,value,days,path) {
	var expires = "";
	if(days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	
	if (!path) path='/';
	document.cookie = name+"="+value+expires+"; path="+path;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function ogcore_isOfType(v, type) {
	return typeof v == type;
}

function checkJSVersioning () {
	if ( immformer_js_libs_vers ) {
		immformer_js_libs_vers.each(function(pair){
			var n = pair.key;
			var v = pair.value;
			var _v = null;
			try {
				_v = eval(n);
			} catch (ex) {}
			ogcore_debug(_v + '==>' + v);
			if ( _v && v>parseInt(_v) ) {
				alert('Reloading...');
				window.location.reload(true);
				throw $break;
			}
		});
	} else {
		alert('Fatal error at JS-Versioning check!');
	}
}

function ogcore_debug(message) {
	//alert(message);
	//new Ajax.Request(ogcore_debug_ajax_url, { parameters : {'level':'DEBUG', 'message' : message} });
}

function ogcore_ajax_divupdate(divId, state, params, oncomplete) {
  var workinkProgressElem = null;//$("toolPopup1_working_progress");  
  if (!workinkProgressElem) workinkProgressElem=$(divId);
  var ajaxListeners = {
//                        onUninitialized: function()       {ogcore_debug("Uninitialized...");},    // [cgin, 23.4.07s] never triggered by any browser I've tested (FF, IE67)
//                        onCreate:        function(xhr)    {ogcore_debug("["+xhr['og_requestId']+"] Create." + xhr['og_requestId']);},   // [cgin, 23.4.07s] never triggered by any browser I've tested (FF, IE67)

// the following events are triggered in this order (onLoading, onLoaded, onInteractive, onSuccess, onComplete)
// In Firefox the 'onInteractive'-Event is triggered every x milliseconds, so it fires not only once
                        onLoading:       function(xhr)    {
                          ogcore_debug("["+xhr['og_requestId']+"] Loading... ");
//                          new Insertion.Top('AjaxDBG', '[Loading]: '+xhr.responseText+'<br />');
                          if ( xhr['completed'] ) return;
                          if(workinkProgressElem) workinkProgressElem.innerHTML = "<div style='padding:15px;'>Loading...</div>";
                        },
                        onLoaded:        function(xhr)    {
                          ogcore_debug("["+xhr['og_requestId']+"] Loaded...");
//                          new Insertion.Top('AjaxDBG', '[Loaded]: '+xhr.responseText+'<br />');
                        },
                        onInteractive:   function(xhr)    {
                          ogcore_debug("["+xhr['og_requestId']+"] Interactive...");
//                          new Insertion.Top('AjaxDBG', '[Interactive]: '+xhr.responseText+'<br />');
                          if(workinkProgressElem) workinkProgressElem.innerHTML += ".";
                        },
                        onSuccess:       function(xhr)    {
                          ogcore_debug("["+xhr['og_requestId']+"] Done: Success.");
//                          new Insertion.Top('AjaxDBG', '[Success]: '+xhr.responseText+'<br />');
                        },
                        onComplete:      function(xhr)    {
                          ogcore_debug("["+xhr['og_requestId']+"] Complete. still active: " + Ajax.activeRequestCount);
//                          new Insertion.Top('AjaxDBG', '[Complete]: '+xhr.responseText+'<br />');
                          if(oncomplete) {
                            if(typeof oncomplete == "function") {
                              oncomplete();
                            }else{
                              eval(oncomplete);
                            }
                          }
                          xhr['completed'] = true;
                        },

// failure-events                       
                        on204:           function()       {ogcore_debug("HttpError 204.");},
                        on403:           function()       {ogcore_debug("HttpError 403.");},
                        on404:           function()       {ogcore_debug("HttpError 404.");},
                        on500:           function()       {ogcore_debug("HttpError 500.");},
                        onFailure:       function(xhr)    {ogcore_debug("["+xhr['og_requestId']+"] Done: Failure.");},
                        onException:     function(ajaxObject, e) {ogcore_debug("["+ajaxObject.transport['og_requestId']+"] Done: Exception. [timeout?"+(ajaxObject.transport['og_abortOnTimeout']==true?"true":"false")+"] [e.message="+e.message+"] {"+e+"}");},
                        
// evaluate JavaScript                        
                        evalScripts:     true,
                        encoding:        'UTF-8'
                      };
  var url = ogcore_ajax_getRequestUrl(state, params);
  return new Ajax.Updater(divId, url, ajaxListeners);

}
function ogcore_isUndefined(v) {
	return ogcore_isOfType(v, 'undefined');
}

function ogcore_ajax_getRequestUrl(state, params, forPopup) {
	  if (winid) {
	    var _w = '';
	    if (forPopup) {
	      _w = WINDOW_PARENT_ID_PARAM + '=' + winid.getId();
	    } else {
			  _w = WINDOW_ID_PARAM + '='+winid.getId();
			  if (winid.getOpenerId() != null && winid.getOpenerId() != winid.getId()) _w += '&' + WINDOW_PARENT_ID_PARAM + '=' + winid.getOpenerId();
			} 
		  if (params && params.length>0) 
		    params += '&' + _w;
		  else
		    params = _w;
	  }
		//if ( ogcore_isUndefined(ogcore_ajax_baseurl) ) alert("ogcore_ajax_getRequestUrl(): ogcore_ajax_baseurl IS UNDEFINED");
		/*if ( ogcore_ajax_baseurl.include('jsessionid') ) {
			var t = (/^(.*)(;jsessionid.*)$/gi).exec(ogcore_ajax_baseurl);
			return t[1] + state + ".state?" + params + t[2];
		} else {
			return ogcore_ajax_baseurl + state + ".state?" + params;
		}*/
		/*if (ogcore_ajax_baseurl.include('jsessionid')) {
			ogcore_ajax_baseurl = ogcore_ajax_baseurl.substr(0, ogcore_ajax_baseurl.indexOf(';'));
		}*/
		var jsid = '';
		if (jsessionid) {
			jsid = ';jsessionid=' + jsessionid;
		}
		return ogcore_ajax_baseurl + state + '.state' + jsid + '?' + params;
	}


/**
 * Retrieves iframe's document height
 * @param object doc
 * @return integer
 */
function iframe_getDocHeight(doc)
{
	var docHt = 0, sh, oh;
	if (doc.height) {
		docHt = doc.height;
	} else if (doc.body) {
		if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
		if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
		if (sh && oh) docHt = Math.max(sh, oh);
	}
	return docHt;
}

/**
 * Tries to set iframe's outter hight to be equal to inner height
 * @param string iframeName
 * @param integer incrementPx
 * @return void
 */
function iframe_setIframeHeight(iframeName, incrementPx)
{
	incrementPx = incrementPx || 0;
	if (frames[iframeName]) {
		try {
			var iframeWin = window.frames[iframeName];
			var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
			if (iframeEl && iframeWin) {
				iframeEl.style.height = "auto";
				var docHt = iframe_getDocHeight(iframeWin.document);
				$(iframeName).setStyle({'height':docHt + incrementPx + 'px'});
			}
		} catch (err) {
			alert("Can't set iframe's height\nPossible reason: not the same domain as " + location.host);
		}
	}
}
