///////////////////////////
///////////////////////////
///////  SVANTE JAVASCRIPTS

function pageRedirect(target) {
	var magAddr = getBase(window.location.href);
	window.location = magAddr+"Magellan/pages/"+target;
}

var IE = document.all?true:false; //IE or something else

// set from mouseEvent
var currX = 0; 
var currY = 0;  

//save position of currently shown popup
var popupX=0; 
var popupY=0;
var popupXend=0;
var popupYend=0;

// special flag used by leftmenu popup
var blockSelectNode = false;

// id-s for all popup windows
var popupIds = new Array(6);
popupIds[0] = "helpSubMenu";
popupIds[1] = "reportSubMenu";
popupIds[2] = "createSubMenu";
popupIds[3] = "createDiagramPopupMenu";
popupIds[4] = "createDiagram2PopupMenu";
popupIds[5] = "moveToSubDiv";

var blockReportTextCookies = false;


///////////////////////////
///////////////////////////
///////  POPUP FUNCTIONS


// If some popup is shown, close it if someone clicked outside it
function clickedSomewhere(mouseEvent) {

	setCurrCoords(mouseEvent);
	// alert('cx='+currX+'cy='+currY);
	if(currX>=popupX && currX<popupXend && currY>=popupY && currY<popupYend) {
		return;
	}

	for(i in popupIds) {
		var pid = popupIds[i];
		var popupElt = document.getElementById(pid);
		if(popupElt!=null) {
			// alert('non-ing');
			popupElt.style.display='none';
		}
	}

	blockSelectNode = false;
}


// show a popup with id='layer' and size 'w,h' at position (x,y)
function showLayerAtWH(layer, x, y, w, h) {
	currentlayershowing=layer;

    	document.getElementById(layer).style.left= x;
    	document.getElementById(layer).style.top = y;
    	document.getElementById(layer).style.display='block';

	popupX = x;
	popupY = y;
	popupXend = popupX + w;
	popupYend = popupY + h;
	return true;
}

//  show a popup with id='layer' at position (x,y)
function showLayerAt(layer, x, y) {
	currentlayershowing=layer;

    	document.getElementById(layer).style.left= x;
    	document.getElementById(layer).style.top = y;
    	document.getElementById(layer).style.display='block';

	var width = document.getElementById(layer).offsetWidth;
	var height = document.getElementById(layer).offsetHeight;

	popupX = x;
	popupY = y;
	popupXend = popupX + width;
	popupYend = popupY + height;
	return true;
}

//  show a popup with id='layer' at position determined by mouseEvent
function showLayer(mouseEvent, layer) {
	setCurrCoords(mouseEvent);
	return showLayerAt(layer, currX, currY);
}

//  show a popup with id='layer' and size 'w,h'  at position determined by mouseEvent
function showLayerWH(mouseEvent, layer, w, h) {
    	setCurrCoords(mouseEvent);
   	return showLayerAtWH(layer, currX, currY, w, h);
}

// set currX and currY from the mouseEvent
function setCurrCoords(mouseEvent) {
    if (IE) { // hämta X Y i IE
        currX = event.clientX + document.body.scrollLeft;
        currY = event.clientY + document.body.scrollTop;
    }else if(navigator.appVersion.indexOf("Safari") > -1){   //bugjunkcrapsafari
            document.captureEvents(Event.CLICK)
            currX = event.pageX;
            currY = event.pageY;
    }else{  //FireFox
	currX = mouseEvent.pageX;
  	currY = mouseEvent.pageY;     
    }
}



///////////////////////////
///////////////////////////
// DIAGRAM POPUP HELPER FUNCTIONS

function checkAddDiagram(toIdxStr, headline) { 
	var toIdx = vd_trim(toIdxStr);
	alert('cad, toidx='+toIdx);
	try {
		if(vd_isPosInt(toIdx)==false || toIdx>(noOfReportItems+1) || toIdx < 1) {
			alert('ogiltigt index att placera diagrammet: '+toIdx);
			return false;
		} 
	} catch(err) {
		alert('Ange heltalsindex att placera diagrammet p&aring;!');
		return false;
	}
	if(vd_trim(headline).length == 0) {
		alert('du m&aring;ste ange en rubrik för diagrammet!');
		return false;
	}
	alert('cad, toidxStr='+toIdxStr);
	return true;
}

function popupMouseOver(nodeId) {
	document.getElementById(nodeId).className='popupSelected';
}

function popupMouseOut(nodeId) {
	document.getElementById(nodeId).className='popupUnSelected';
}

function closePopup(divId) {
	document.getElementById(divId).style.display = 'none';
}




///////////////////////////
///////////////////////////
// GENERAL UTILITIES

// removes all parameters except the first 
function clearParams(url) {
	idx = url.indexOf("&");
	if(idx == -1) {
		return url;
	} else {
		return url.substring(0, idx);
	}
}

// removes all parameters including the first 
function clearAllParams(url) {
	idx = url.indexOf("&");
	if(idx != -1) {
		url = url.substring(0, idx);
	} 
	idx = url.indexOf("?");
	if(idx != -1) {
		url = url.substring(0, idx);
	} 
	return url;
}

// removes the parameter with name='param'
function clearNamedParam(url, param) {
	idx = url.indexOf(param);
	if(idx == -1) {
		return url;
	}	
	nextIdx = url.indexOf(idx, "&");
	if(nextIdx == -1) {
		return url.substring(0, idx-1);
	} else {
		url1 = url.substring(0,idx);
		url2 = url.substring(nextIdx+1);
		toturl = url1+url2;
		return clearedNamedParam(toturl, param);
	}
}

function getArgPrefix(url) {
    if(url.indexOf("?")!= -1) {
    	return "&";
    } else {
    	return "?";
    }
}

function getBase(url) {
	idx = url.indexOf("Magellan/");
	if(idx == -1) {
		return url;
	} else {
		return url.substring(0, idx);
	}
}

function isNumBelowLimit(str, limit) {
	if(str=='') return false;
	if(vd_isPosInt(str)==false) return false;
	if(str >= limit) return false;
	return true;
}


function submitForm(formId) {
	document.getElementById(formId).submit();
}



//////////////////////
//////////////////////
// COOKIES


// the first three functions are simplified versions  
// that always sets the cookie path to '/'
function setCookie(name, value) {
	Set_Cookie(name, value, '', '/', '', '');
}

function getCookie(name) {
	return Get_Cookie(name);
}

function deleteCookie(name) {
	Delete_Cookie(name, '/', '');
}




function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	// original code used escape(value) below
	document.cookie = name + "=" + escape(value) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );

	// alert('setCO,co='+document.cookie);
}


function Get_Cookie( name ) {
	// alert('GC='+name+' cok='+document.cookie);
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}

	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}

	return unescape( document.cookie.substring( len, end ) );
}

function Delete_Cookie ( name, path, domain ) {
	var d = new Date();
	if ( Get_Cookie( name ) ) {
		var sett = name + "=" + 
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=d.toGMTString()";

		// alert('delcok, sett='+sett);

		document.cookie = sett;
		// alert('delcok, cok='+document.cookie);
	} else {
		// alert('no getcookie: '+name);
	}
}





//////////////////////
//////////////////////
// AJAX

function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}




//////////////////////
//////////////////////
// REPORT HELPER FUNCTIONS



// toggles the text field showing the text with id='textId' as visible/not visible
function toggleText(textId, prefix) {
	var tr = document.getElementById("form1Disp"+textId);
	var timg = document.getElementById("toggleImg"+textId);
	if(tr.style.display == 'none') {
		tr.style.display = '';
		timg.src = '/svante/pix/14hide.jpg';
		setCookie(prefix+'RepTr'+textId, 'TEXT_EDITABLE');
		keyUpId(textId, prefix);
	} else {
		tr.style.display = 'none';
		timg.src = '/svante/pix/14show.jpg';
		setCookie(prefix+'RepTr'+textId, 'TEXT_HIDDEN');
		
		// only necessary when blockReportTextCookies == true
		document.getElementById("form2Disp"+textId).style.display = 'none';
	}	
}


// This function is called whenever a key is released within the text field showing the text with id='textId'
// It determines whether or not to display the textfield as containing uncommitted changes 
function keyUpId(textId, prefix) {
	
	var tfId = prefix+"TextField"+textId;
	var imgId = "toggleImg"+textId;
	var buttonsId = "form2Disp"+textId;
	var textElt = document.getElementById(tfId);
	var imgElt = document.getElementById(imgId);
	var buttonsTr = document.getElementById(buttonsId);

	if(blockReportTextCookies != false) {
		// EXCEPTIONAL CASE
		textElt.className = 'reportTextUnchanged';
		imgElt.style.display = '';
		buttonsTr.style.display = '';
		return;
	}

	var oldval = getCommittedValue(tfId);
	// alert('id='+textId+'oldv='+oldval+' tev='+textElt.value);
	if(textElt.value != oldval) {	
		textElt.className = 'reportTextChanged';
		imgElt.style.display = 'none';
		buttonsTr.style.display = '';	
	} else {
		textElt.className = 'reportTextUnchanged';
		imgElt.style.display = '';
		buttonsTr.style.display = 'none';
	}
}

// clears the values of all cookies used to store text field foldout information
function clearTextToggleCookies(prefix) {
	var cks = document.cookie.split(";");
	// alert('clearToggleCookies. #cookies='+cks.length+' cookie='+document.cookie);	
	for(var i=0;i<cks.length;i++) {
		var cookPair = cks[i].split("=");
		var cookName = cookPair[0];
		if(cookName.indexOf(prefix+"RepTr") != -1) {
			//alert('ck1:'+cookName);
			deleteCookie(cookName);
		}
	}
	// alert('after clearToggleCookies. cookie= <'+document.cookie+'>');	
}

//////////////////////////////////
//////////////////////////////////
// VALIDATION HELPER FUNCTIONS

function vd_isNumeric(str) {
	var re1 = /^-?[0-9.]+$/;
	var re2 = /\..*\./;
	var re3 = /^\.$/;
	
	str = vd_trim(str);
	
	if(vd_countChars('Ee', str) == 1) {
		return vd_isNumericE(str);
	}
	
	// reject non-numeric characters
	if(!re1.test(str)) { 	
		return false; 
	}
		
	// reject some special cases
	if(re2.test(str) || re3.test(str)) { 
		return false;
	}
	
	return true;
}


function vd_isNumericE(str) {
	var idx = str.indexOf('E');
	if(idx == -1) {
		idx = str.indexOf('e');
	}
	if(idx < 0) {
		return false;
	}
	str1 = str.substring(0,idx);
	str2 = str.substring(idx+1);
	
	if((str1.length == 0) || (str2.length == 0)) {
		return false;
	}
	if((str1.charAt(str1.length-1) == ' ') || (str2.charAt(0) == ' ')) {
		return false;
	}
	// at most 1 digit before decimal point in str1
	if((str1.length>1) && (str1.charAt(0)!='.') && (str1.charAt(1)!='.')) {
		return false;
	}
	// str1 must be numeric, str2 must be integer
	if(!vd_isNumeric(str1) || !vd_isInt(str2)) {
		return false;
	}
	return true;
}

function vd_isPosNumeric(str) {
	if(vd_countChars('-', str) > 0) {
		return false;
	} else {
		return vd_isNumeric(str);
	}
}

function vd_isInt(str){
	var re1 = /^-?[0-9]+$/;
	str = vd_trim(str);
	if(!re1.test(str)) { 
		return false; 
	}
   	return true;
}

function vd_isPosInt(str){
	var re1 = /^[0-9]+$/;
	str = vd_trim(str);
	if(!re1.test(str)) { 
		return false; 
	}
   	return true;
}

function vd_fixDecimalCommaForField(field) {
	var str = field.value;
	// the first comma is transformed to a dot
	for (var j=0; j < str.length; j++) {
   		if (str.charAt(j) == ',') {
 	   		str = str.substring(0,j) + '.' + str.substring(j+1, str.length);
 	   		break;
    	}
	}
	field.value = str;
}


function vd_trim(str) {
	str = str.replace(/^\s+|\s+$/g, '') ;
	return str;
}

function vd_countChars(chars, str) {
	var count = 0;
	for(var i=0; i<chars.length; i++) {
		var thisChar = chars.charAt(i);
		for (var j=0; j < str.length; j++) {
   			if (str.charAt(j) == thisChar) {
 		   		count = count + 1;
    		}
		}
	}
	
	return count;
}

//function vd_hasAAO(str) {
//	slc = str.toLowerCase();
//	if(slc.indexOf('å')!=-1 || slc.indexOf('ä')!=-1 || slc.indexOf('ö')!=-1) {
//		return true;
//	}
//	return false;
//}