/*
INDEX
General
Window
Validation
Ranking
Array
Button & Flaps
String
Form fields
Ajax
List frame
*/



// G L O B A L   E V E N T 


// G E N E R A L
function getKeyCode(event) {
	return event.keyCode?event.keyCode:event.which?event.which:event.charCode;
}
function getRandom(theMax) {
	return Math.floor(Math.random()*theMax);
}
function trace(output,single) {
	setParam('developer',false);
	if (developer) {
		var o;
		if (!get_object('debugger')) {
			o=document.createElement('div');
			o.setAttribute('id','debugger');
			document.body.appendChild(o);
		} else {
			o=get_object('debugger');
		}
		if (single)
			o.innerHTML=output+'<br />';
		else
			o.innerHTML+=output+'<br />';
	}
}
function evaluateEvent(type,e) {
	switch(type) {
		case 'rightclick':
			var rightclick;
			if (!e)
				var e=window.event;
			if (e.which)
				rightclick=(e.which == 3);
			else if (e.button)
				rightclick=(e.button == 2);
			return rightclick;
		break;
		case 'enter':
			return (getKeyCode(e) == 13);
		break;
	}
}
function doReloadPage() {
	window.location.href=window.location.href;
}
function doExpandGroup(prefix,id) {
	var activeListGroupId=eval('activeListGroupId_'+prefix);
	if (activeListGroupId == id) {//collapse
		get_object('div_group_list_'+prefix+'_'+id).style.display='none';
		get_object('img_group_'+prefix+'_'+id).src='../../graphic/icon/12/collapsed.gif';
		eval('activeListGroupId_'+prefix+'=-1;');
	} else {//expand
		if (activeListGroupId != -1) {
			get_object('div_group_list_'+prefix+'_'+activeListGroupId).style.display='none';
			get_object('img_group_'+prefix+'_'+activeListGroupId).src='../../graphic/icon/12/collapsed.gif';
		}
		get_object('div_group_list_'+prefix+'_'+id).style.display='block';
		get_object('img_group_'+prefix+'_'+id).src='../../graphic/icon/12/expanded.gif';
		eval('activeListGroupId_'+prefix+'=id;');
		switch (prefix) {
			case 'usr':
				if (eval('document.form_userSearch_'+id))
					eval('document.form_userSearch_'+id+'.inputted_value_'+id+'.focus();');
			break;
			case 'ipvEdit':
				if (eval('document.form_ipvSearch_'+id))
					eval('document.form_ipvSearch_'+id+'.inputted_value_'+id+'.focus();');
			break;
		}
	}
}
function confirmChoice(msg) {
	var agree=confirm(msg);
	if (agree)
		return true ;
	else
		return false ;
}
function get_object(o) {
	if (document.getElementById && document.getElementById(o) != null)
		return document.getElementById(o);
	else if (document.layers && document.layers[object] != null)
		return document.layers[o];
	else if (document.all)
		return document.all[o];
}
function getPixelsFromTop(obj){
	var objFromTop=obj.offsetTop;
	var objParent;
	while(obj.offsetParent!=null) {
		objParent=obj.offsetParent;
		objFromTop+=objParent.offsetTop;
		obj=objParent;
	}
	return objFromTop;
}
function OnMouseMove(e) {
	var debug=false;
	var IE=document.all?true:false;
	var newX,newY;
	try {
		if (IE) { // grab the x-y pos.s if browser is IE
			newX=event.clientX+document.body.scrollLeft;
			newY=event.clientY+document.body.scrollTop;
		} else {  // grab the x-y pos.s if browser is NS
			newX=e.pageX;
			newY=e.pageY;
		}
		xMousePos=newX;
		yMousePos=newY;
		positionOnMouseMove();
		if (debug)
			trace('xMousePos: '+xMousePos+' - yMousePos: '+yMousePos,true);
	}
	catch (err) {
	}
}
document.onmousemove=OnMouseMove;

/*
function trackMouse(event) {
	var debug=false;
	if (document.layers) {
		// When the page scrolls in Netscape, the event's mouse position
		// reflects the absolute position on the screen. innerHight/Width
		// is the position from the top/left of the screen that the user is
		// looking at. pageX/YOffset is the amount that the user has
		// scrolled into the page. So the values will be in relation to
		// each other as the total offsets into the page, no matter if
		// the user has scrolled or not.
		xMousePos=e.pageX;
		yMousePos=e.pageY;
		xMousePosMax=window.innerWidth+window.pageXOffset;
		yMousePosMax=window.innerHeight+window.pageYOffset;
	} else if (document.all) {
		// When the page scrolls in IE, the event's mouse position
		// reflects the position from the top/left of the screen the
		// user is looking at. scrollLeft/Top is the amount the user
		// has scrolled into the page. clientWidth/Height is the height/
		// width of the current page the user is looking at. So, to be
		// consistent with Netscape (above), add the scroll offsets to
		// both so we end up with an absolute value on the page, no
		// matter if the user has scrolled or not.
		xMousePos=window.event.x+document.body.scrollLeft;
		yMousePos=window.event.y+document.body.scrollTop;
		xMousePosMax=document.body.clientWidth+document.body.scrollLeft;
		yMousePosMax=document.body.clientHeight+document.body.scrollTop;
	} else if (document.getElementById) {
		// Netscape 6 behaves the same as Netscape 4 in this regard
		xMousePos=event.pageX;
		yMousePos=event.pageY;
		xMousePosMax=window.innerWidth+window.pageXOffset;
		yMousePosMax=window.innerHeight+window.pageYOffset;
	}
}
*/
var kmWindowToDrag='';
var activeToolTip='';
function positionOnMouseMove() {
	if (kmWindowToDrag != '') {
		o=get_object(kmWindowToDrag);
		o.style.left=parseInt(xMousePos-kmWindowDragOffset_x)+'px';
		o.style.top=parseInt(yMousePos-kmWindowDragOffset_y)+'px';
	}
	if (activeToolTip != '') {
		o=get_object(activeToolTip);
		o.style.left=parseInt(xMousePos+20)+'px';
		o.style.top=parseInt(yMousePos-10)+'px';
	}
}
function setSelectable(target,flag){
	if (typeof target.onselectstart != "undefined") //IE route
		target.onselectstart=function() { return flag }
	else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
		target.style.MozUserSelect=(flag)?"":"none";
	else //All other route (ie: Opera)
		target.onmousedown=function() { return flag }
	//target.style.cursor="default"
}
function isIE() {
	if (document.all)
		return true
	else
		return false
}
function kmPopup(file) {
	kmPopupWindow=window.open('../model/custom/dsp_popup.cfm?image='+file,'filePopup','directories=no,menubar=no,scrollbars=no,status=no,location=no,toolbar=no,resizable=no,top=0,left=0,width=300,height=300');
	kmPopupWindow.focus();
}
function getBrowser() {
	if (navigator.appName.toLowerCase() == 'opera') return 'Opera';
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
	return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else return 'Netscape';} else if (agt.indexOf(' ') != -1)
	return navigator.userAgent.substr(0,agt.indexOf(' '));
	else return navigator.userAgent;
}
function getBrowserSimple() {
	if (navigator.appName.toLowerCase() == 'opera') return 'Opera';
	var agt=navigator.userAgent.toLowerCase();
	var browser='';
	var platform=(agt.indexOf('windows') != -1)?'pc':'mac';
	if (agt.indexOf("opera") != -1) browser='Opera';
	else if (agt.indexOf("staroffice") != -1) browser='Star Office';
	else if (agt.indexOf("webtv") != -1) browser='WebTV';
	else if (agt.indexOf("beonex") != -1) browser='Beonex';
	else if (agt.indexOf("chimera") != -1) browser='Chimera';
	else if (agt.indexOf("netpositive") != -1) browser='NetPositive';
	else if (agt.indexOf("phoenix") != -1) browser='Phoenix';
	else if (agt.indexOf("firefox") != -1) browser='Firefox';
	else if (agt.indexOf("safari") != -1) browser='Safari';
	else if (agt.indexOf("skipstone") != -1) browser='SkipStone';
	else if (agt.indexOf("msie") != -1) browser='Internet Explorer';
	else if (agt.indexOf("netscape") != -1) browser='Netscape';
	else if (agt.indexOf("mozilla/5.0") != -1) browser='Mozilla';
	else browser=navigator.userAgent;
	return [browser,platform];
}
function doProgress(i) {
	var updateBarAndPercent=true;
	var updateEstimatedFinishedAt=true;
	var progress=i/progress_totalCount;
	switch (progress_mode) {
		case 'detailed':
			if (i%progress_unitInterval == 0) {
				get_object('progress_counter').innerHTML=i;
				//calculate time left
				var progress_left=1-progress;
				var now=new Date();
				var timePassed=now.getTime()-progress_startTime;
				var timeLeft=parseInt(timePassed*progress_left/progress);
				var timeLeftInSeconds=Math.ceil(timeLeft/1000);
				var secondMod=timeLeftInSeconds%60;
				var timeLeftInMinutes=parseInt((timeLeftInSeconds-secondMod)/60);
				var secondModFormatted=(secondMod < 10)?'0'+secondMod:secondMod;
				get_object('progress_timeLeft').innerHTML=timeLeftInMinutes+':'+secondModFormatted+' minuter';
			}
/*
				if (i%progress_unitInterval == 0) {
					//if reached a unit interval, calculate timePerUnit based on last interval (this is ran always first time)
					var now=new Date();
					var timeElapsedForInterval=now.getTime()-progress_startTime;
					progress_timePerUnit=timeElapsedForInterval/progress_unitInterval;
					//set new startTime for next interval
					progress_startTime=now.getTime();
				}
				var timeLeft=Math.ceil((progress_totalCount-i)*progress_timePerUnit);
				var timeLeftInSeconds=Math.ceil(timeLeft/1000);
				progress_timeLeftInSeconds_lastTime=timeLeftInSeconds;
				var secondMod=timeLeftInSeconds%60;
				var timeLeftInMinutes=parseInt((timeLeftInSeconds-secondMod)/60);
				var secondModFormatted=(secondMod < 10)?'0'+secondMod:secondMod;
				get_object('progress_timeLeft').innerHTML=timeLeftInMinutes+':'+secondModFormatted+' minuter';
				updateBarAndPercent=true;
*/
		break;
		case 'percent':
		break;
	}
	if (updateBarAndPercent) {
		//progress bar
		get_object('progress_bar').style.width=parseInt(progress*progress_barWidth)+'px';
		//percentage
		get_object('progress_percent').innerHTML=parseInt(progress*100);
		if (updateEstimatedFinishedAt) {
			//estimated finished at
			var now=new Date();
			var timePassed=now.getTime()-progress_startTime;
			var progress_left=1-progress;
			var timeLeft=parseInt(timePassed*progress_left/progress);
			var finishedAtTime=new Date();
			finishedAtTime.setTime(now.getTime()+timeLeft);
			var estimatedFinishedAtMinutes=finishedAtTime.getMinutes();
			if (estimatedFinishedAtMinutes < 10)
				estimatedFinishedAtMinutes='0'+estimatedFinishedAtMinutes;
			var estimatedFinishedAt=finishedAtTime.getHours()+':'+estimatedFinishedAtMinutes;
			get_object('progress_estimatedFinishedAt').innerHTML='- Beräknad klar kl '+estimatedFinishedAt;
		}
	}
	if (i == progress_totalCount)
		hideProgress();
}
var progress={
	setLabel: function(label) {
		get_object('progress_label').innerHTML=label;
	},
	setTotalCount: function(i) {
		progress_totalCount=i;
		get_object('progress_totalCount').innerHTML=i;
	}
}
function hideProgress() {
	if (get_object('progressInfo'))
		get_object('progressInfo').style.display='none';
}

// W I N D O W
var popupHandle='';
function createDimmer() {
	var dimmer=document.createElement('div');
	dimmer.setAttribute('id','dimmer');
	document.body.appendChild(dimmer);
	dimmer.className='dimmer_white';
}
function doDimmer(activate,classname,zindex) {
	var debug=false;
	if (debug) { get_object('debugwindow').innerHTML+='<br>doDimmer('+activate+','+classname+','+zindex+')'; }
	if (!get_object('dimmer'))
		createDimmer();
	var dimmer=get_object('dimmer');
	if (activate) {
		/*
		window.onscroll=function() {
			var offset_array=getScrollXY();
			dimmer.style.left=offset_array[0]+'px';
			dimmer.style.top=offset_array[1]+'px';
			activeDialogue_array[0].style.left=(activeDialogue_array[1]+offset_array[0])+'px';
			activeDialogue_array[0].style.top=(activeDialogue_array[2]+offset_array[1])+'px';
			if (debug) { get_object('debugwindow').innerHTML+='<br>'+offset_array.toString(); }
		};
		*/
		var offset_array=getScrollXY();
		dimmer.style.left=offset_array[0]+'px';
		dimmer.style.top=offset_array[1]+'px';
		dimmer.className=classname;
		if (zindex)
			dimmer.style.zIndex=zindex;
		dimmer.style.display='block';
	} else {
		dimmer.style.display='none';
	}
}
function openPhoto(theId,doEdit_value) {
	var theUrl='popupPhoto.cfm?id='+theId+'&doEdit='+doEdit_value;
	if (!popupHandle.closed && popupHandle.location)
		popupHandle.location.href=theUrl;
	else
		popupHandle=window.open(theUrl,'','width=100,height=100,menubar=0,scrollbars=0,status=0,location=0,directories=0,resizable=0,titlebar=0,toolbar=0');
	if (window.focus)
		popupHandle.focus();
	return false;
}
function showKmWindow(label,frameNo,modal) {
	var debug=false;
	if (get_object('helpWindowHolder'))
		get_object('helpWindowHolder').style.display='block';
	var o=get_object(label);
	var frameWidth,frameHeight;
	if (parent.frames[1]) {
		switch (window.name) {
			case 'itemFrame':
				frameWidth=660;
			break;
			default:
				frameWidth=220;
		}
	} else {
		frameWidth=getWindowSize()[0];
	}
	frameHeight=getWindowSize()[1];
	var divHeight=convertToInteger(o.style.height);
	var offset_array=getScrollXY();
	o.style.top=parseInt(offset_array[1]+(frameHeight-divHeight)/3)+'px';
	if (debug) trace('offset_array: '+offset_array.toString());
	if (debug) trace('frameHeight: '+frameHeight);
	if (debug) trace('divHeight: '+divHeight);
	if (debug) trace('o.style.top: '+o.style.top);
	var divWidth=convertToInteger(o.style.width);
	o.style.left=parseInt((frameWidth-divWidth)/2)+'px';
	if (debug) trace('frameWidth: '+frameWidth);
	if (debug) trace('divWidth: '+divWidth);
	if (debug) trace('o.style.left: '+o.style.left);
	if (modal)
		doDimmer(true,'dimmer_white');
	o.style.display='block';
}
function hideKmWindow(label) {
	if (get_object('dimmer'))
		doDimmer(false);
	get_object(label).style.display='none';
}
function setKmWindowToDrag(id,action) {
	switch (action) {
		case 'begin':
			setSelectable(document.body,false);
			o=get_object(id);
			kmWindowDragOffset_x=xMousePos-convertToInteger(o.style.left);
			kmWindowDragOffset_y=yMousePos-convertToInteger(o.style.top);
			kmWindowToDrag=id;
		break;
		case 'end':
			setSelectable(document.body,true);
			kmWindowToDrag='';
		break;
	}
}
function setToolTip(id) {
	if (id) {
		activeToolTip=id;
		get_object(id).style.display='block';
	} else {
		get_object(activeToolTip).style.display='none';
		activeToolTip='';
	}
}
function showHelp(i) {
	setParam('clientRootPath','../../');
	if (get_object('help_prototype')) {
		get_object('helpWindowHolder').style.display='block';
		//run ajax
		var url=clientRootPath+'model/ajax/getHlp.cfm?id='+i;
		loadXML('hlp',url)
	} else {
		showKmWindow('help_'+i);
	}
	if (showHelp.arguments[1])//restore square help
		doSquareCollapse(showHelp.arguments[1]);
}
function popXML_hlp(responseXML) {
	var settings=responseXML.getElementsByTagName('settings')[0];
	/* since ajax integration top and left are ignored, because showKmWindow always center
	var theTop=settings.attributes[2].nodeValue;
	var theLeft=settings.attributes[3].nodeValue;
	*/
	var label='help_prototype';
	var height=parseInt(settings.attributes[0].nodeValue);
	var width=parseInt(settings.attributes[1].nodeValue);
	var innerWidth=width-14;
	var innerHeight=height-22;
	get_object(label).style.height=height+'px';
	get_object(label).style.width=width+'px';
	get_object('kmWindowTable_'+label).style.width=width+'px';
	get_object('kmWindowTop_'+label).style.width=innerWidth+'px';
	get_object('kmWindowHeader_'+label).style.width=innerWidth+'px';
	get_object('kmWindowContentHolder_'+label).style.height=innerHeight+'px';
	get_object('kmWindowContent_'+label).innerHTML=responseXML.getElementsByTagName('content')[0].firstChild.data;
	get_object('kmWindowTitle_'+label).innerHTML=responseXML.getElementsByTagName('title')[0].firstChild.data;
	showKmWindow(label);
}
function getWindowSize() {
	var myWidth=0, myHeight=0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth=window.innerWidth;
		myHeight=window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth=document.documentElement.clientWidth;
		myHeight=document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth=document.body.clientWidth;
		myHeight=document.body.clientHeight;
	}
	return [myWidth,myHeight];
}
function getScreenSize() {
	var myWidth=0, myHeight=0;
	myWidth=screen.availWidth;
	myHeight=screen.availHeight;
	return [myWidth,myHeight];
}
function getScrollXY() {
	var scrOfX=0, scrOfY=0;
	if (typeof(window.pageYOffset) == 'number') {
		//Netscape compliant
		scrOfY=window.pageYOffset;
		scrOfX=window.pageXOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		scrOfY=document.body.scrollTop;
		scrOfX=document.body.scrollLeft;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		//IE6 standards compliant mode
		scrOfY=document.documentElement.scrollTop;
		scrOfX=document.documentElement.scrollLeft;
	}
	return [scrOfX,scrOfY];
}


// V A L I D A T I O N
function isPdfOrDoc(theFile) {
	var re=/.pdf$/i;
	if (re.test(theFile))
		return true;
	var re=/.doc$/i;
	if (re.test(theFile))
		return true;
	return false;
}
function isWebImg(theFile) {
	var re=/.jpg$/i;
	if (re.test(theFile))
		return true;
	var re=/.jpeg$/i;
	if (re.test(theFile))
		return true;
	var re=/.gif$/i;
	if (re.test(theFile))
		return true;
	var re=/.png$/i;
	if (re.test(theFile))
		return true;
	return false;
}
function isValid(type,value) {
	switch (type) {
		case 'email':
			var lCaseValue=value.toLowerCase();
			return lCaseValue.match(/^[\_]*([a-z0-9]+(\.|\_*|\-*)?)+@([a-z0-9\-\.]+(\.|\-*\.))+[a-z]{2,6}$/);
		break;
		case 'jpg':
			var lCaseValue=value.toLowerCase();
			var re=/.jpg$/i;
			if (re.test(lCaseValue))
				return true;
			var re=/.jpeg$/i;
			if (re.test(lCaseValue))
				return true;
			return false;
		break;
		case 'webImage':
			var lCaseValue=value.toLowerCase();
			var re=/.jpg$/i;
			if (re.test(lCaseValue))
				return true;
			var re=/.jpeg$/i;
			if (re.test(lCaseValue))
				return true;
			var re=/.gif$/i;
			if (re.test(lCaseValue))
				return true;
			var re=/.png$/i;
			if (re.test(lCaseValue))
				return true;
			return false;
		break;
		case 'swf':
			var re=/.swf$/i;
			if (re.test(value))
				return true;
			return false;
		break;
		case 'integer':
			return (parseInt(value) == value);
		break;
		case 'date':
			//validates real date in format yyyy-mm-dd
			var theDate=trim(value);
			var theDate_split=theDate.split('-');
			if (theDate_split.length == 3) {
				var theYear=theDate_split[0].replace(/\D/g,'');
				var theMonth=theDate_split[1].replace(/\D/g,'');
				var theDay=theDate_split[2].replace(/\D/g,'');
				if (theYear != '' && theMonth != '' && theDay != '') {
					var jsMonth=theMonth-1;
					var d=new Date(theYear,jsMonth,theDay);
					if (d.getFullYear() == theYear && d.getMonth() == jsMonth && d.getDate() == theDay)
						return true;
				}
			}
			return false;
		break;
	}
	return false;
}
function isInt(theValue) {
	if (isNaN(theValue) || theValue.indexOf(',') > 0 || theValue.indexOf('.') > 0)
		return false;
	else
		return true;
}


// R A N K I N G
/*
function saveRanking(sortingId) {
	var current_form=eval('document.form_serial_'+sortingId);
	current_form.serialized.value=Sortable.serialize('div_sortable_'+sortingId);
	//alert(Sortable.serialize('div_sortable_'+sortingId)+' submitting to '+current_form.target);
	current_form.submit();
}
*/
function generateRankingList(id) {
	var rankingList='';
	var order=Sortable.serialize('div_sortable_'+id);
	rankingList+=Sortable.sequence('div_sortable_'+id);
	return rankingList;
}
function saveRanking(id) {
	var saveThis=true;
	//check if this sortable has a toggle on/off button
	if (window.editEnabled_array) {
		var i=editEnabled_array.getIndex('sortableId',id);
		if (i != -1)
			saveThis=eval("editEnabled_"+editEnabled_array[i]['label']);
	}
	if (saveThis) {
		var rankingList=generateRankingList(id);
		var sortableSuffix='';
		if (saveRanking.arguments[1])
			sortableSuffix=saveRanking.arguments[1];
		var debug=false;
		if (get_object('debug' && debug)) {
			get_object('debug').innerHTML+='<br>presentRankingList: '+eval('presentRankingList'+sortableSuffix+'_'+id);
			get_object('debug').innerHTML+='<br>rankingList: '+rankingList;
		}
		if (rankingList != eval('presentRankingList'+sortableSuffix+'_'+id)) {
			if (get_object('debug') && debug)
				get_object('debug').innerHTML+='<br>Submitting new ranking';
			var saveForm=eval('document.form_serial'+sortableSuffix+'_'+id);
			saveForm.serialized.value=rankingList;
			saveForm.submit();
			eval('presentRankingList'+sortableSuffix+'_'+id+'=rankingList;');
			return false;
		} else {
			return true;
		}
	}
}
function initRankingList(id) {
	var sortableSuffix='';
	if (initRankingList.arguments[1])
		sortableSuffix=initRankingList.arguments[1];
	eval('presentRankingList'+sortableSuffix+'_'+id+'=generateRankingList(id);');
}
function doOneLevelSortable(act,labelOrObject) {
	var i;
	var label=(typeof labelOrObject == 'string')?labelOrObject:labelOrObject.id.split('_')[1];
//	trace(label+': '+act);
	switch (act) {
		case 'create':
			var sectionSubs=document.getElementsByClassName(label+'_child_sortable');
			for (i=0;i<sectionSubs.length;i++) {
				sectionSubs[i].style.cursor='move';
			}
			Sortable.create('sortableHolder_'+label,{tag:'div',only:label+'_child_sortable',handle:label+'_child_sortable_handle'});
			eval("presentRankingList_"+label+"=doOneLevelSortable('rankingList','"+label+"');");
			//initiate trigger onmouseup of entire div
//			get_object('sortableHolder_'+label).onmouseup=function() {
//				doOneLevelSortable('save',this);
//			}
			eval('sortableActive_'+label+'=true;');
		break;
		case 'destroy':
			Sortable.destroy('sortableHolder_'+label);
			var sectionSubs=document.getElementsByClassName(label+'_child_sortable');
			for (i=0;i<sectionSubs.length;i++) {
				sectionSubs[i].style.cursor='pointer';
			}
//			get_object('sortableHolder_'+label).onmouseup=null;
			eval('sortableActive_'+label+'=false;');
		break;
		case 'rankingList':
			return Sortable.sequence('sortableHolder_'+label);
		break;
		case 'save':
			var rankingList=doOneLevelSortable('rankingList',label);
			if (rankingList != eval('presentRankingList_'+label)) {
				var saveFile=(window.saveRankingFilePath)?saveRankingFilePath:'somefile whatever';
				var url=saveFile+'?label='+label+'&rankingList='+rankingList;
				loadXML('saveRanking',url,'text');
			}
		break;
		case 'saveAndDestroy':
			doOneLevelSortable('save',label);
			doOneLevelSortable('destroy',label);
		break;
	}
}
function popXML_saveRanking(response) {
}

// A R R A Y
Array.prototype.inArray=function (value,caseSensitive) {
	var i;
	for (i=0;i<this.length;i++) {
		if (caseSensitive) {
			if (this[i].toLowerCase() == value.toLowerCase())
				return true;
		} else {
			if (this[i] == value)
				return true;
		}
	}
	return false;
}
Array.prototype.isKey=function(){
  for(i in this){
    if(i === arguments[0])
      return true;
  };
  return false;
};
Array.prototype.removeItems=function(itemsToRemove) {
	if (!/Array/.test(itemsToRemove.constructor))
		itemsToRemove=[itemsToRemove];
	var j;
	for (var i=0;i<itemsToRemove.length;i++) {
		j=0;
		while (j < this.length) {
			if (this[j] == itemsToRemove[i])
				this.splice(j,1);
			else
				j++;
		}
	}
}
Array.prototype.getIndex=function(secondDimension,value) {
	for (var i=0;i<this.length;i++) {
		if (this[i][secondDimension] == value)
			return i;
	}
	return -1;
}
Array.prototype.valueCount=function(secondDimension,value) {
	var hitCount=0;
	for (var i=0;i<this.length;i++) {
		if (this[i][secondDimension] == value)
			hitCount++;
	}
	return hitCount;
}
function setParam(variableName,defaultValue) {
	if (typeof(defaultValue) == 'string')
		eval(variableName+'=window.'+variableName+' || "'+defaultValue+'";');
	else
		eval(variableName+'=window.'+variableName+' || '+defaultValue+';');
}
function setTinymceEditor(editorCount,action) {
	var debug=false;
	if (setTinymceEditor.arguments[2])
		var value=setTinymceEditor.arguments[2];
	if (debug) { get_object('debug').innerHTML+='<br>setTinymceEditor('+editorCount+','+action+','+value+')'; }
	for (var i=0;i<editorCount;i++) {
		try {
			switch (action) {
				case 'width':
					get_object('mce_editor_'+i).style.width=value+'px';
				break;
				case 'bgColor':
					tinyMCE.get('mce_editor_'+i).contentDocument.body.style.backgroundColor=value;
//					tinyMCE.getInstanceById('mce_editor_'+i).getWin().document.body.style.backgroundColor=value;
				break;
				case 'padding':
					var paddingPart_array=['Top','Right','Bottom','Left'];
					for (var j=0;j<paddingPart_array.length;j++) {
						eval("tinyMCE.get('mce_editor_'+i).contentDocument.body.style.padding"+paddingPart_array[j]+"=value[j];");
//						eval("tinyMCE.getInstanceById('mce_editor_'+i).contentDocument.body.style.padding"+paddingPart_array[j]+"=value[j];");
					}
				break;
				case 'css':
					setTimeout("tinyMCE.execCommand('mceRemoveControl',false,'editorId')",i);
					initializeTinyMCE(value);
					setTimeout("tinyMCE.execCommand('mceAddControl',false,'editorId')",i);
				break;
				case 'blur':
					value.focus();
					value.blur();
				break;
			}
		}
		catch (err) {
			if (debug) { alert(err); }
		}
	}
}
function blurTinyMce(someOtherFieldThanTinyMceArea) {
	someOtherFieldThanTinyMceArea.focus();
	someOtherFieldThanTinyMceArea.blur();
}
function duplicateArray(theArray) {
	return theArray.slice();
}


// B U T T O N S   &   F L A P S
function doMore(label) {
	setParam('more_'+label,false);
	setParam('clientRootPath','../../');
	var active=eval('more_'+label);
	if (eval('collapsed_'+label)) {//if collapsed, dont do more, but uncollapse
		doSquareCollapse(label,true);
	} else {
		var image=get_object('img_more_'+label);
		var fileName_array=getFileName(image.src).split('_');
		var kmMode=fileName_array[fileName_array.length-1];
		image.src=(active)?clientRootPath+'graphic/interface/label_more_'+kmMode+'.gif':clientRootPath+'graphic/interface/label_less_'+kmMode+'.gif';
		eval('more_'+label+'=(active)?false:true;');
		setParam('more_'+label,false);
		if (eval('more_'+label)) {
			var display_tfoot='';
			var display_div='block';
		} else {
			var display_tfoot='none';
			var display_div='none';
		}
		eval('doMore_'+label+'(display_tfoot,display_div);');
	}
}
function doSquareCollapse(label) {
	if (eval('squareCollapsable_'+label) || doSquareCollapse.arguments[1]) {
		var theDisplay=(get_object('square_tr_body_'+label).style.display == 'none' || doSquareCollapse.arguments[1])?'':'none';
		if (get_object('square_tr_header_'+label))
			get_object('square_tr_header_'+label).style.display=theDisplay;
		get_object('square_tr_body_'+label).style.display=theDisplay;
		get_object('square_tr_bottom_'+label).style.display=theDisplay;
		eval('collapsed_'+label+'=(theDisplay == "")?false:true;');
		switch (label) {
			case 'importItems':
				if (get_object('btn_import')) {
					get_object('btn_import').style.display=theDisplay;
				}
			break;
			case 'pageLayout':
				//fix bug in IE, that otherwise still shows sortables in collapsed square
				get_object('pageLayout_sortableHolder').style.display=(theDisplay == 'none')?'none':'block';
			break;
		}
	}
}
function setSquareCollapseEnablement(label,enabled) {
	eval('squareCollapsable_'+label+'=enabled;');
}
function resetMore(label) {
	get_object('img_more_'+label).src='../../graphic/interface/label_more.gif';
	eval('more_'+label+'=false;');
	eval('doMore_'+label+'();');
}
function doLanguageFlap(label,id) {
	if (lng_array.length < 2) { return false; }
	var activeId=eval('activeLng_'+label);
	if (activeId != id) {
		get_object('flap_div_'+activeId+'_'+label).className='flap';
		var flap=get_object('flap_lng_'+activeId+'_'+label);
		flap.src=getImagePath(flap)+'/flagLabel_'+activeId+'_off.gif';
		get_object('flapContent_'+activeId+'_'+label).style.display='none';
	}
	get_object('flap_div_'+id+'_'+label).className='flap_on';
	var flap=get_object('flap_lng_'+id+'_'+label);
	flap.src=getImagePath(flap)+'/flagLabel_'+id+'_on.gif';
	get_object('flapContent_'+id+'_'+label).style.display='block';
	eval('activeLng_'+label+'=id;');
/*	switch (label.toLowerCase()) {
		case 'ctx':
			tinyMCE.execCommand('mceAddControl', true, 'mceArea_'+activeLng_CTX);
		break;
	}
*/
}
function doButton(o,action) {
	if (action == 'resetClickedInGroup') {
		buttonGroup=true;
		var groundIdName=o;//in this particular case, yes;
		var activeId=eval(groundIdName);
		o=get_object(groundIdName+'_'+activeId);
		currentId='';
		action='click';
	} else {
		var buttonGroup=false;
		if (action == 'click' && doButton.arguments[2]) {
			buttonGroup=true;
			var groundIdName=o.id.substr(0,o.id.lastIndexOf('_'));
			var activeId=eval(groundIdName);
			var id_array=o.id.split('_');
			var currentId=id_array[id_array.length-1];
		}
		var isActive=eval(o.id);
	}
	var className_array=o.className.split('_');
	var suffix=className_array[className_array.length-1];
	var groundClass=o.className;
	var groundSuffix=suffix;
	if (suffix == 'over' || suffix == 'clicked') {
		groundClass=groundClass.substr(0,groundClass.lastIndexOf('_'));//get rid of suffix
		var groundClass_array=groundClass.split('_');
		groundSuffix=groundClass_array[groundClass_array.length-1];
	}
	switch(action) {
		case 'over':
			o.className=groundClass+'_over';
		break;
		case 'out':
			if (isActive && !doButton.arguments[2])
				o.className=groundClass+'_clicked';
			else
				o.className=groundClass;
		break;
		case 'click':
			if (buttonGroup) {
//				trace("activeId: "+activeId+" (activeId.length != 0)="+(activeId.length != 0));
				if (activeId.length != 0 && activeId != currentId) {
//					trace("activeId: "+activeId+" currentId: "+currentId+" get_object(groundIdName+'_'+activeId).className='"+groundClass);
					get_object(groundIdName+'_'+activeId).className=groundClass;
					eval(groundIdName+'_'+activeId+'=false;');
				}
				if (currentId != '') {
					get_object(groundIdName+'_'+currentId).className=groundClass+'_clicked';
					eval(o.id+'=true;');
				}
				eval(groundIdName+'=currentId;');
			} else {
				if (isActive)
					o.className=groundClass;
				else//if just has been inactivated, but mouse still on and click
					o.className=groundClass+'_clicked';
				eval(o.id+'=(isActive)?false:true;');//toggle status
			}
		break;
	}
	//get_object('debug').innerHTML+=o.className+'<br>';
}
function doRollImage(o,action) {
	if (action == 'resetClickedInGroup') {
		imageGroup=true;
		var groundIdName=o;//in this particular case, yes;
		var activeId=eval(groundIdName);
		o=get_object(groundIdName+'_'+activeId);
		currentId='';
		action='click';
	} else {
		var imageGroup=false;
		if (action == 'click' && doRollImage.arguments[2]) {
			imageGroup=true;
			var groundIdName=o.id.substr(0,o.id.lastIndexOf('_'));
			var activeId=eval(groundIdName);
		}
		var id_array=o.id.split('_');
		var currentId=id_array[id_array.length-1];
		var isActive=eval(o.id);
	}
	var groundFilePath=getFilePath(o.src);
	var groundFile=getFile(o.src);
	var groundFileNameWithSuffix=getFileName(o.src);
	var groundFileNameWithId=groundFileNameWithSuffix.substr(0,groundFileNameWithSuffix.lastIndexOf('_'));
	var groundFileName=groundFileNameWithId.substr(0,groundFileNameWithId.lastIndexOf('_'));
	var groundFileExt=getFileExt(o.src);
	switch(action) {
		case 'over':
			if (!isActive)
				o.src=groundFilePath+'/'+groundFileName+'_'+currentId+'_on.'+groundFileExt;
		break;
		case 'out':
			if (!isActive || doRollImage.arguments[2])
				o.src=groundFilePath+'/'+groundFileName+'_'+currentId+'_off.'+groundFileExt;
		break;
		case 'click':
			if (imageGroup) {
				if (activeId != '' && activeId != currentId) {
					get_object(groundIdName+'_'+activeId).src=groundFilePath+'/'+groundFileName+'_'+activeId+'_off.'+groundFileExt;
					eval(groundIdName+'_'+activeId+'=false;');
				}
				if (currentId != '') {
					//get_object(groundIdName+'_'+currentId).src=groundFilePath+'/'+groundFileName+'_'+currentId+'_on.'+groundFileExt;
					eval(o.id+'=true;');
				}
				eval(groundIdName+'=currentId;');
			} else {
				if (isActive)
					o.src=groundFilePath+'/'+groundFileName+'_'+currentId+'_off.'+groundFileExt;
				else//if just has been inactivated, but mouse still on and click
					o.src=groundFilePath+'/'+groundFileName+'_'+currentId+'_on.'+groundFileExt;
				eval(o.id+'=(isActive)?false:true;');//toggle status
			}
		break;
	}
	//get_object('debug').innerHTML+=isActive+': '+o.src+'<br>';
}
function doRollOverImage(theImage) {
	theImage.src=getFilePath(theImage.src)+'/'+theImage.id+'_on.'+getFileExt(theImage.src);
}
function doRollOutImage(theImage) {
	theImage.src=getFilePath(theImage.src)+'/'+theImage.id+'.'+getFileExt(theImage.src);
}
function doOnMouseOutFlap(theListSub,flapType) {
	switch (flapType) {
		case 'list':
			if (activeListSub != theListSub)
				get_object('divFlap'+theListSub).style.backgroundColor=''
		break;
	}
}
function doAccordion(action,rowId,accId) {
	var active_acc=eval('active_acc_'+rowId);
	switch (action) {
		case 'over':
			if (active_acc != accId && !eval('acc_'+rowId+'_'+accId+'_disabled'))
				doAccordion('highlight',rowId,accId);
		break;
		case 'out':
			if (active_acc != accId && !eval('acc_'+rowId+'_'+accId+'_disabled'))
				doAccordion('downlight',rowId,accId);
		break;
		case 'click':
			if (!eval('acc_'+rowId+'_'+accId+'_disabled')) {
				if (active_acc == accId) {//hide clicked
					get_object('div_acc_content_'+rowId+'_'+accId).style.display='none';
					eval('active_acc_'+rowId+'=0;');
					doAccordion('downlight',rowId,accId);
				} else {//show clicked
					if (active_acc != 0) {//hide active
						get_object('div_acc_content_'+rowId+'_'+active_acc).style.display='none';
						doAccordion('downlight',rowId,active_acc);
					}
					get_object('div_acc_content_'+rowId+'_'+accId).style.display='block';
					doAccordion('highlight',rowId,accId);
					eval('active_acc_'+rowId+'=accId;');
				}
			}
		break;
		case 'highlight':
			get_object('img_acc_'+rowId+'_'+accId).src='../../graphic/accordion_vertical_top_hover.gif';
			get_object('div_acc_'+rowId+'_'+accId).className='accordion_vertical_hover';
		break;
		case 'downlight':
			get_object('img_acc_'+rowId+'_'+accId).src='../../graphic/accordion_vertical_top.gif';
			get_object('div_acc_'+rowId+'_'+accId).className='accordion_vertical';
		break;
		case 'disable':
			get_object('div_acc_'+rowId+'_'+accId).className='accordion_vertical_disabled';
			eval('acc_'+rowId+'_'+accId+'_disabled=true;');
		break;
		case 'enable':
			get_object('div_acc_'+rowId+'_'+accId).className='accordion_vertical';
			eval('acc_'+rowId+'_'+accId+'_disabled=false;');
		break;
	}
}
function doUniversalTab(action,label,id) {
	setParam('tab_active_'+label,-1);
//	if (action == 'click')
//		trace('doUniversalTab('+action+','+label+','+id+')');
	var activeId=eval('tab_active_'+label);
	switch (action) {
		case 'over':
			if (activeId != id)
				doUniversalTab('highlight',label,id);
		break;
		case 'out':
			if (activeId != id)
				doUniversalTab('downlight',label,id);
		break;
		case 'click':
			if (activeId != id) {
				if (activeId != -1) {//hide active
					get_object('div_tab_content_'+label+'_'+activeId).style.display='none';
					doUniversalTab('downlight',label,activeId);
				}
				get_object('div_tab_content_'+label+'_'+id).style.display='block';
				doUniversalTab('highlight',label,id);
				eval('tab_active_'+label+'=id;');
			}
		break;
		case 'highlight':
			get_object('div_tab_'+label+'_'+id).style.backgroundColor='white';
		break;
		case 'downlight':
			get_object('div_tab_'+label+'_'+id).style.backgroundColor='';
		break;
	}
}
function doButtonHover(o,action) {
	o.className=(action == 'over')?'button_hover':'button';
}


// S T R I N G S
function getFilePath(filePath) {
	return filePath.substr(0,filePath.lastIndexOf('/'));
}
function getFileExt(filePath) {
	var temp=filePath.split('.');
	var lastIndex=temp.length-1;
	return temp[lastIndex];
}
function getFile(filePath) {
	var temp=filePath.split('/');
	var lastIndex=temp.length-1;
	return file=temp[lastIndex];
}
function getFileName(filePath) {
	var temp=filePath.split('/');
	var lastIndex=temp.length-1;
	var file=temp[lastIndex];
	return file.substr(0,file.lastIndexOf('.'));
}
function createValidFileName(theFileName) {
	/*IMPORTANT! this function must be a replica of the cf component with the same name in com_upload*/
	var validName=theFileName;
	var re;
	re=new RegExp("å","g");
	validName=validName.replace(re,'a');
	re=new RegExp("ä","g");
	validName=validName.replace(re,'a');
	re=new RegExp("ö","g");
	validName=validName.replace(re,'o');
	re=new RegExp("Å","g");
	validName=validName.replace(re,'A');
	re=new RegExp("Ä","g");
	validName=validName.replace(re,'A');
	re=new RegExp("Ö","g");
	validName=validName.replace(re,'O');
	validName=validName.replace(/\s/g,'_');
	validName=validName.replace(/[^A-Za-z0-9_]/g,'_');
	return validName;
}
function LTrim(value) {
	var re=/\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
function RTrim(value) {
	var re=/((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
function trim(value) {
	/*if (value)
		return LTrim(RTrim(value));
	else
		return '';*/
		
	return LTrim(RTrim(value));
}
function convertCssAttribute(attr,type) {
	switch(type) {
		case 'js':
			var temp=attr.replace(/-/g,'_');
			var temp_array=temp.split('_');
			var newAttr='';
			var currentAdd;
			for (var i=0;i<temp_array.length;i++) {
				if (i == 0)
					currentAdd=temp_array[i];
				else
					currentAdd=temp_array[i].substr(0,1).toUpperCase()+temp_array[i].substr(1,temp_array[i].length-1);
				newAttr+=currentAdd;
			}
			return newAttr;
		break;
	}
	return false;
}
function getDirectoryFromPath(path) {
	return path.substr(0,path.lastIndexOf('/'));
}
function getImagePath(img) {
	return getDirectoryFromPath(img.src);
}


//F O R M   F I E L D
function doMaxLength(theField,theMax) {
	if (theField.value.length > theMax)
		theField.value=theField.value.substr(0,theMax);
}
function doOnChangeForm(theForm) {
	theForm.hasChanged=true;
}
function setInputDefault(theField,defaultLabel,didFocus) {
	var theInput=trim(theField.value);
	var defaultValue=eval('txt_enter'+defaultLabel);
	if (didFocus && theInput == defaultValue)
		theField.value='';
	else if (!didFocus && theInput.length == 0)
		theField.value=defaultValue;
}
function doFlashDate(theDate,hiddenDateField) {
	var date_array=theDate.split(' ');
	var theDateObject=new Date(date_array[1]+' '+date_array[2]+','+date_array[5]);
	var theMonth=theDateObject.getMonth()+1;
	if (theMonth < 10)
		theMonth='0'+theMonth;
	var theDay=theDateObject.getDate();
	if (theDay < 10)
		theDay='0'+theDay;
	theFormattedDate=theDateObject.getFullYear()+'-'+theMonth+'-'+theDay;
	hiddenDateField.value=theFormattedDate;
	alert(hiddenDateField.value);
}
function setSelect(theSelect,theValue) {
	var j;
	if (setSelect.arguments[2])
		theAction=setSelect.arguments[2];
	else
		theAction='select';
	for (var i=0;i<theSelect.length;i++) {
		if (theSelect.options[i].value == theValue)
			j=i;
	}
	switch (theAction) {
		case 'select':
			theSelect.selectedIndex=j;
		break;
		case 'disable':
			theSelect.options[j].disabled=true;
		break;
		case 'enable':
			theSelect.options[j].disabled=false;
		break;
	}
}
function setChecker(theChecker,theValue) {
	var j;
	if (setChecker.arguments[2])
		theAction=setChecker.arguments[2];
	else
		theAction='check';
	for (var i=0;i<theChecker.length;i++) {
		if (theChecker[i].value == theValue)
			j=i;
	}
	switch (theAction) {
		case 'check':
			theChecker[j].checked=true;
		break;
		case 'disable':
			theChecker[j].disabled=true;
		break;
		case 'enable':
			theChecker[j].disabled=false;
		break;
	}
}
function replaceBadMSWordCharacter(theField) {
	theField.value=theField.value.replace(/\u201A/g,"'");//baseline single quote
	theField.value=theField.value.replace(/\u0192/g,'<i>f</i>');//florin (small letter f with hook)
	theField.value=theField.value.replace(/\u201E/g,'"');//baseline double quote
	theField.value=theField.value.replace(/\u2026/g,'...');//ellipsis (3 horisontal ellipsis)
	theField.value=theField.value.replace(/\u2020/g,'&sup1');//dagger (cross)
	theField.value=theField.value.replace(/\u2021/g,'&sup2');//double dagger (cross with two horisontal lines)
	theField.value=theField.value.replace(/\u02C6/g,'^');//circumflex accent
	theField.value=theField.value.replace(/\u2030/g,'o/oo');//permile (as procent sign, but with double zeros)
	theField.value=theField.value.replace(/\u0160/g,'Sh');//S Hacek
	theField.value=theField.value.replace(/\u2039/g,'"');//left single guillemet (single left-pointing angle quotation mark)
	theField.value=theField.value.replace(/\u0152/g,'OE');//OE ligature
	theField.value=theField.value.replace(/\u2018/g,"'");//left single quote
	theField.value=theField.value.replace(/\u2019/g,"'");//right single quote
	theField.value=theField.value.replace(/\u201C/g,'"');//left double quotation mark
	theField.value=theField.value.replace(/\u201D/g,'"');//right double quotation mark
	theField.value=theField.value.replace(/\u2022/g,"*");//bullet
	theField.value=theField.value.replace(/\u2013/g,"-");//endash
	theField.value=theField.value.replace(/\u2014/g,"--");//emdash
	theField.value=theField.value.replace(/\u02DC/g,'~');//tilde accent
	theField.value=theField.value.replace(/\u2122/g,'<sup>TM</sup>');//trademark ligature
	theField.value=theField.value.replace(/\u0161/g,'sh');//s Hacek
	theField.value=theField.value.replace(/\u203A/g,'"');//right single guillement  (single right-pointing angle quotation mark)
	theField.value=theField.value.replace(/\u0153/g,'oe');//oe ligature
	theField.value=theField.value.replace(/\u0178/g,'Y');//Y Dieresis
}
function getHiddenValue(label,id) {
	var hiddenColumnSuffix=(getHiddenValue.arguments[2])?getHiddenValue.arguments[2]:'Hidden';
	return eval('theForm.'+label+'_bit_'+hiddenColumnSuffix+'_'+id+'.value');
}
function doHidden(label) {
	if (doHidden.arguments[1]) {//specific language
		var id=doHidden.arguments[1];
		var hiddenColumnSuffix=(doHidden.arguments[3])?doHidden.arguments[3]:'Hidden';
		if (doHidden.arguments[2])//called from all languages
			var newHidden=doHidden.arguments[2];
		else//specific language toggle
			var newHidden=(getHiddenValue(label,id,hiddenColumnSuffix) == 1)?0:1;
		eval('theForm.'+label+'_bit_'+hiddenColumnSuffix+'_'+id+'.value=newHidden');
		if (get_object('flap_img_'+id+'_'+label)) {
			var flag=get_object('flap_img_'+id+'_'+label);
			flag.src=getImagePath(flag)+'/flag_'+id+'_'+newHidden+'.gif';
		}
		//check if all are hidden or all are not hidden (affect main hidden button then)
		var hiddenCount=0;
		for (var i=0;i<lng_array.length;i++) {
			if (eval('theForm.'+label+'_bit_'+hiddenColumnSuffix+'_'+lng_array[i]['id']+'.value') == 1)
				hiddenCount++;
		}
		//affect main hidden button
		if (hiddenCount == 0)
			setMainHiddenButton(label,0)
		else if (hiddenCount == lng_array.length)
			setMainHiddenButton(label,1)
	} else {//all possible languages
		var newHidden=(getHiddenValue(label,lng_array[0]['id']) == 1)?0:1;
		for (var i=0;i<lng_array.length;i++) {
			doHidden(label,lng_array[i]['id'],newHidden);
		}
		setMainHiddenButton(label,newHidden);
	}
}
function setMainHiddenButton(label,hidden) {
	var button=get_object('button_hidden_'+label);
	var imageSuffix=(hidden == 1)?'on':'off';
	button.src=getImagePath(button)+'/button_hidden_'+imageSuffix+'.gif';
}
function restoreInteger(theField) {
	if (restoreInteger.arguments[1] && !restoreInteger.arguments[2]) {
		switch (restoreInteger.arguments[1]) {
			case 'allowNegative':
				theField.value=theField.value.replace(/[^\d\-]/g, "");
			break;
		}
	} else {
		var restoredValue=theField.value.replace(/[^\d]/g, "");
		theField.value=restoredValue;
		//keep within span?
		if (restoredValue.length != 0 && restoreInteger.arguments[2]) {
			if (restoreInteger.arguments[3]) {//also allow negative
				var minValue=restoreInteger.arguments[2];
				var maxValue=restoreInteger.arguments[3];
			} else {
				var minValue=restoreInteger.arguments[1];
				var maxValue=restoreInteger.arguments[2];
			}
			if (restoredValue < minValue)
				theField.value=minValue;
			else if (restoredValue > maxValue)
				theField.value=maxValue;
		}
	}
}
function convertToInteger(theString) {
	if (convertToInteger.arguments[1]) {
		switch (convertToInteger.arguments[1]) {
			case 'allowNegative':
				return parseInt(theString.replace(/[^\d\-]/g, ""));
			break;
		}
	} else {
		return parseInt(theString.replace(/[^\d]/g, ""));
	}
}
function restoreNumeric(theField) {
	theField.value=theField.value.replace(",",".");
	if (restoreNumeric.arguments[1]) {
		switch (restoreNumeric.arguments[1]) {
			case 'allowNegative':
				theField.value=theField.value.replace(/[^\d\.\-]/g, "");
			break;
		}
	} else {
		theField.value=theField.value.replace(/[^\d\.]/g, "");
	}
}
function getCheckedValues(o,theReturnType,careForDisabled) {
	if (!theReturnType)
		theReturnType='list';
	switch (theReturnType) {
		case 'list'://returns a list with the checked values
			var theList='';
			if (o[0])
				for (i=0;i<o.length;i++) {
					if (o[i].checked && (!o[i].disabled || careForDisabled)) {
						if (theList.length > 0)
							theList=theList+',';
						theList=theList+o[i].value;
					}
				}
			else if (o.checked && (!o.disabled || careForDisabled))
				theList=o.value;
			return theList;
		break;
		case 'array'://returns an array with the checked values
			var theArray=new Array();
			if (o[0])
				for (i=0;i<o.length;i++) {
					if (o[i].checked && (!o[i].disabled || careForDisabled))
						theArray.push(o[i].value);
				}
			else if (o.checked && (!o.disabled || careForDisabled))
				theArray.push(o.value);
			return theArray;
		break;
		case 'count'://returns number of checked items
			var checkedCount=0;
			if (o[0])
				for (i=0;i<o.length;i++) {
					if (o[i].checked && (!o[i].disabled || careForDisabled))
						checkedCount++;
				}
			else if (o.checked && (!o.disabled || careForDisabled))
				checkedCount++;
			return checkedCount;
		break;
		case 'boolean'://returns if any is checked
			if (o[0])
				for (i=0;i<o.length;i++) {
					if (o[i].checked && (!o[i].disabled || careForDisabled)) {
						return true;
						break;
					}
				}
			else if (o.checked && (!o.disabled || careForDisabled))
				return true;
		break;
		case 'indexList'://returns list with the checked indexes
			var theList='';
			if (o[0])
				for (i=0;i<o.length;i++) {
					if (o[i].checked && (!o[i].disabled || careForDisabled)) {
						if (theList.length > 0)
							theList=theList+',';
						theList=theList+''+i;
					}
				}
			else if (o.checked && (!o.disabled || careForDisabled))
				theList=-1;
			return theList;
		break;
	}
	return false;
}
function getSelectedValues(theSelect) {
	if (getSelectedValues.arguments[1])
		theReturnType=getSelectedValues.arguments[1];
	else
		theReturnType='list';
	switch (theReturnType) {
		case 'list':
			var theList='';
			for (i=0;i<theSelect.options.length;i++) {
				if (theSelect.options[i].selected) {
					if (theList.length > 0)
						theList=theList+',';
					theList=theList+theSelect.options[i].value;
				}
			}
			return theList;
		break;
		case 'array':
			var theArray=new Array();
			for (i=0;i<theSelect.options.length;i++) {
				if (theSelect.options[i].selected)
					theArray.push(theSelecttheSelect.options[i].value);
			}
			return theArray;
		break;
		case 'count':
			var selectedCount=0;
			for (i=0;i<theSelect.options.length;i++) {
				if (theSelect.options[i].selected)
					selectedCount++;
			}
			return selectedCount;
		break;
		case 'boolean':
			for (i=0;i<theSelect.options.length;i++) {
				if (theSelect.options[i].selected) {
					return true;
					break;
				}
			}
		break;
	}
	return false;
}
function addOption(theSelect,theValue,theText) {
	var theOption=new Option(theText, theValue, false, false)
	var selectLength=theSelect.options.length;
	theSelect.options[selectLength]=theOption;
}
function getCheckedRadioValue(theRadio) {
	var considerDisabled=(getCheckedRadioValue.arguments[1]);
	for (i=0;i<theRadio.length;i++) {
		if (theRadio[i].checked && (!considerDisabled || (considerDisabled && !theRadio[i].disabled)))
			return theRadio[i].value;
	}
	return '';
}
function getCheckedRadioIndex(theRadio) {
	for (i=0;i<theRadio.length;i++) {
		if (theRadio[i].checked)
			return i;
	}
	return -1;
}
function getSelectIndexForValue(theSelect,theValue) {
	for (i=0;i<theSelect.options.length;i++) {
		if (theSelect.options[i].value == theValue)
			return i;
	}
	return -1;
}
function resetChecked(theRadioOrCheckbox,check) {
	if (theRadioOrCheckbox[1]) {
		for (i=0;i<theRadioOrCheckbox.length;i++) {
			theRadioOrCheckbox[i].checked=check;
		}
	} else {
		theRadioOrCheckbox.checked=check;
	}
}


// A J A X
function callAjax(theForm,theUrl,theCallback) {
	ColdFusion.Ajax.submitForm(theForm,theUrl,eval(theCallback),errorHandler_ajax,'POST',true);
}
function errorHandler_ajax(stat,error) {
	alert(stat+'\n'+error);
}
function parseAjaxErrorMessage(ajaxErrorMessage) {
	var errorMessage_array=ajaxErrorMessage.split('@');
	var errorMessage='';
	for (var i=0;i<errorMessage_array.length;i++) {
		errorMessage+='\n* '+errorMessage_array[i];
	}
	return errorMessage;
}
function loadXML(label,url) {
	XMLRequestTypeInProcess=(loadXML.arguments[2])?loadXML.arguments[2]:'xml';//probably 'text' if not 'xml';
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		eval('XMLRequest_'+label+'=new XMLHttpRequest();');
		var XMLRequest=eval('XMLRequest_'+label);
		XMLRequest.open("GET",url,true);
		XMLRequestLabelInProcess=label;
		XMLRequest.onreadystatechange=processXML;
		XMLRequest.send(null);
		// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		eval('XMLRequest_'+label+'=new ActiveXObject("Microsoft.XMLHTTP");');
		var XMLRequest=eval('XMLRequest_'+label);
		if (XMLRequest) {
			XMLRequest.open("GET",url,true);
			XMLRequestLabelInProcess=label;
			XMLRequest.onreadystatechange=processXML;
			XMLRequest.send();
		}
	}
}
function processXML() {
	var theRequest=eval('XMLRequest_'+XMLRequestLabelInProcess);
	// only if req shows "complete"
	if (theRequest.readyState == 4) {
		// only if "OK"
		if (theRequest.status == 200) {
			response=(XMLRequestTypeInProcess == 'xml')?theRequest.responseXML.documentElement:theRequest.responseText;
			eval('popXML_'+XMLRequestLabelInProcess+'(response);');
		}
	}
}
//loadAJAX is more secure than loadXML
//with multitasking => handling multible AJAX requests at once (developed for SRF Accredit originally)
function loadAJAX(label,url) {
	var ajaxType=(loadAJAX.arguments[2])?loadAJAX.arguments[2]:'xml';//probably 'text' if not 'xml';
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		eval('AJAXRequest_'+label+'=new XMLHttpRequest();');
		var AJAXRequest=eval('AJAXRequest_'+label);
		AJAXRequest.open("GET",url,true);
		AJAXRequest.onreadystatechange=new Function("processAJAX('"+label+"','"+ajaxType+"')");
		AJAXRequest.send(null);
		// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		eval('AJAXRequest_'+label+'=new ActiveXObject("Microsoft.XMLHTTP");');
		var AJAXRequest=eval('AJAXRequest_'+label);
		if (AJAXRequest) {
			AJAXRequest.open("GET",url,true);
			AJAXRequest.onreadystatechange=new Function("processAJAX('"+label+"','"+ajaxType+"')");
			AJAXRequest.send();
		}
	}
}
function processAJAX(label,ajaxType) {
	var theRequest=eval('AJAXRequest_'+label);
	// only if req shows "complete"
	if (theRequest.readyState == 4 && theRequest.status == 200 && eval('window.popAJAX_'+label)) {
		var response=(ajaxType == 'xml')?theRequest.responseXML.documentElement:theRequest.responseText;
		eval('popAJAX_'+label+'(response);');
	}
}

function hideCfWindow(theWindow) {
	ColdFusion.Window.hide(theWindow);
}


// L I S T   F R A M E
function doListSub(theListSub,flapType) {
	var lng_id=0;
	var o,flap;
	if (doListSub.arguments[2]) {//if language support (ONLY for imageFlaps!)
		lng_id=doListSub.arguments[2];
		var activeListSub_current=eval('activeListSub_'+lng_id);
	} else {
		var activeListSub_current=activeListSub;
	}
	switch (flapType) {
		case 'flaps':
			if (activeListSub_current != '')
				get_object('tdFlap'+activeListSub_current).className='flap_td_inactive';
			if (get_object('tdFlap'+theListSub))
				get_object('tdFlap'+theListSub).className='flap_td_active';
		break;
		case 'imageFlaps':
			var imgExt;
			if (activeListSub_current != '') {
				flap=(lng_id == 0)?get_object('flap_img_'+activeListSub_current):get_object('flap_img_'+activeListSub_current+'_'+lng_id);
				imgExt=getFileExt(flap.src);
				flap.src=getImagePath(flap)+'/flap_'+activeListSub_current+'_off.'+imgExt;
			}
			if (get_object('flap_img_'+theListSub) || get_object('flap_img_'+theListSub+'_'+lng_id)) {
				flap=(lng_id == 0)?get_object('flap_img_'+theListSub):get_object('flap_img_'+theListSub+'_'+lng_id);
				imgExt=getFileExt(flap.src);
				flap.src=getImagePath(flap)+'/flap_'+theListSub+'_on.'+imgExt;
			}
		break;
		case 'list':
			if (activeListSub_current != '')
				get_object('divFlap'+activeListSub_current).style.backgroundColor=''
			if (get_object('divFlap'+theListSub))
				get_object('divFlap'+theListSub).style.backgroundColor='white';
		break;
	}
	if (activeListSub_current != '') {
		o=(lng_id == 0)?get_object('divListSub'+activeListSub_current):get_object('divListSub'+activeListSub_current+'_'+lng_id);
		o.style.display='none';
	}
	o=(lng_id == 0)?get_object('divListSub'+theListSub):get_object('divListSub'+theListSub+'_'+lng_id);
	o.style.display='block';
	if (lng_id == 0)
		activeListSub=theListSub;
	else
		eval('activeListSub_'+lng_id+'=theListSub;');
}
function doEditItem(id,x) {
	var urlString='';
	if (doEditItem.arguments[2])
		urlString=doEditItem.arguments[2];
	var completeUrl='index.cfm?x='+x+'&ID='+id+urlString;
	//alert(completeUrl);
	parent.itemFrame.location.href=completeUrl;
}
function doNewObject(id,x,urlString,prefix) {
	parent.itemFrame.location.href='index.cfm?x='+x+'&ID='+id+'&'+prefix+'_id=0'+urlString;
}
function doNewItem(x,urlString) {
	parent.itemFrame.location.href='index.cfm?x='+x+urlString;
}
function doCollapseListFrame(collapse) {
	parent.document.body.cols=(collapse)?'20,*':'220,*';
	get_object('frameCollapsed').style.display=(collapse)?'block':'none';
	get_object('frameExpanded').style.display=(collapse)?'none':'block';
	document.body.className=(collapse)?'collapsed':'body_medium';
}
function doOnloadListFrameCollapse() {
	if (parent.frames[0].innerWidth == 20)
		doCollapseListFrame(true);
	else
		doCollapseListFrame(false);
}
function doListItem(action,o) {
	var className_array=o.className.split('_');
	var classNameBase='';
	for (var i=0;i<className_array.length;i++) {
		if (className_array[i] != 'on')
			classNameBase+=(classNameBase.length == 0)?className_array[i]:'_'+className_array[i];
		else
			break;
	}
	switch(action) {
		case 'over':
			o.className=classNameBase+'_on';
		break;
		case 'out':
			o.className=classNameBase;
		break;
	}
	//alert(classNameBase);
}
function switchEditMode(label,button) {
	setParam('editEnabled_'+label,false);
	var i;
	var enabled=eval('editEnabled_'+label);
	switch(label) {
		case 'mnu':
			var sectionSubs=document.getElementsByClassName('sortable_mnu_child');
			var sections=document.getElementsByClassName('sortable_mnu_parent');
			if (enabled) {
				for (i=0;i<sectionSubs.length;i++) {
					Sortable.destroy(sectionSubs[i]);
				}
				for (i=0;i<sections.length;i++) {
					Sortable.destroy(sections[i]);
					Sortable.destroy(sections[i].id);
				}
				Sortable.destroy('menu');
			} else {
				for (i=0;i<sectionSubs.length;i++) {
					Sortable.create(sectionSubs[i],{tag:'div',dropOnEmpty:true, containment:sectionSubs,only:'sortable_mnu_grandchild'});
				}
				for (i=0;i<sections.length;i++) {
					Sortable.create(sections[i],{tag:'div',dropOnEmpty:true, containment:sections,only:'sortable_mnu_child'});
					Sortable.create(sections[i].id,{tag:'div',only:'sortable_mnu_child',handle:'sortable_mnu_child_handle'});
				}
				Sortable.create('menu',{tag:'div',only:'sortable_mnu_parent',handle:'sortable_mnu_parent_handle'});
				presentRankingList=generateRankingList_menu();
			}
		break;
		default:
			var i=editEnabled_array.getIndex('label',label);
			var sortableId=editEnabled_array[i]['sortableId'];
			if (enabled)
				Sortable.create('div_sortable_'+sortableId,{tag:'div',dropOnEmpty:true,containment:['div_sortable_'+sortableId],constraint:false});
			else
				Sortable.destroy('div_sortable_'+sortableId);
	}
	//toggle button
	button.src=(enabled)?'../../graphic/interface/button_edit.gif':'../../graphic/interface/button_done.gif';
	//toggle list edit icons
	var list_edit_holder=document.getElementsByClassName('list_edit_holder');
	for (i=0;i<list_edit_holder.length;i++) {
		list_edit_holder[i].style.display=(enabled)?'none':'block';
	}
	//toggle variable
	eval('editEnabled_'+label+'=(!enabled);');
}
function doListHidden(o,id,type) {
	var className_array=o.className.split('_');
	var newHidden=(className_array[1] == 1)?0:1;
	var url='../../model/ajax/setHidden.cfm?type='+type+'&id='+id+'&hidden='+newHidden;
	//alert(url);
	loadXML('setHidden',url,'text');
	o.className=(o.className == 'listHidden_1')?'listHidden_0':'listHidden_1';
}
function popXML_setHidden(response) {
	var myResp=trim(response);
	if (myResp != 'done')
		alert(myResp);
}

// S U G G E S T I O N   A J A X   L I S T
var suggestion_active=-1;
var suggestion_array=new Array();
function doSuggest(e,field,id,label) {
	setParam('mainLngId',1);
	var input=trim(field.value);
	switch (getKeyCode(e)) {
		case 38://up
			if (input.length > 1 && suggestion_array.length != 0 && suggestion_active != 0)
				markSuggestion(suggestion_active-1,label,id);
		break;
		case 40://down
			if (input.length > 1 && suggestion_active < suggestion_array.length-1)
				markSuggestion(suggestion_active+1,label,id);
		break;
		case 13://enter
			selectSuggestion(id,suggestion_active,label);
		break;
		default:
			if (input.length > 1) {
				var url='http://cms.webomaten.se/model/ajax/getSuggestion.cfm?id='+id+'&lg='+mainLngId+'&lb='+label+'&input='+escape(input);
				//trace(url);
				loadXML('suggestion',url);
			}
	}
	if (input.length < 2)
		hideSuggest(id,label);
}
function selectSuggestion(id,i,label) {
	var sgId=0;
	if (suggestion_array.length != 0) {
		var currentForm=getSuggestionForm(id,label);
		var inputField=eval('currentForm.inputted_value_'+id);
		inputField.value=get_object('suggestion_'+label+'_'+id+'_'+i).innerHTML;
		sgId=suggestion_array[i];
	}
//	trace('doSuggestionOnEnter('+id+','+sgId+','+label+');');
	doSuggestionOnEnter(id,sgId,label);
	hideSuggest(id,label);
}
function hideSuggest(id,label) {
	get_object('suggestions_'+label+'_'+id).style.visibility='hidden';
}
function markSuggestion(i,label,id) {
	var debug=false;
	if (debug) { get_object('debugger').innerHTML+=suggestion_array[suggestion_active]+':'+suggestion_array[i]+'<br>'; }
	get_object('suggestion_'+label+'_'+id+'_'+suggestion_active).className='suggestion_item';
	get_object('suggestion_'+label+'_'+id+'_'+i).className='suggestion_item_on';
	suggestion_active=i;
}
function popXML_suggestion(responseXML) {
	var debug=false;
	var id=responseXML.getElementsByTagName('id')[0].firstChild.data;
	var label=responseXML.getElementsByTagName('lb')[0].firstChild.data;
	var showLimit=parseInt(responseXML.getElementsByTagName('lm')[0].firstChild.data);
	var sgTag=responseXML.getElementsByTagName('sg');
	var theId,theName,className,theNameFormatted;
	var o=get_object('suggestions_'+label+'_'+id);
	o.innerHTML='';
	suggestion_array=new Array();
	suggestion_active=0;
	var newDiv;
	var re_amp=new RegExp('&amp;','g');
	for (var i=0;i<sgTag.length;i++) {
		className=(i == 0)?'suggestion_item_on':'suggestion_item';
		sgId=sgTag[i].attributes[0].nodeValue;
		theName=sgTag[i].firstChild.data;
//		theNameFormatted=theName.replace(re_amp,'&');
		suggestion_array.push(sgId);
		newDiv=document.createElement('div');
		newDiv.setAttribute('id','suggestion_'+label+'_'+id+'_'+i);
//		alert(theName+' '+theNameFormatted);
		newDiv.setAttribute('class',className);
//		newDiv.setAttribute('onClick',"selectSuggestion("+id+","+i+",'"+label+"'");
		newDiv.innerHTML=theName;
		o.appendChild(newDiv);
/*
newHtml='<div id="suggestion_'+label+'_'+sgId+'" class="'+className+'" onclick="selectSuggestion('+id+','+i+',\''+label+'\');">'+theName+'</div>';
		o.innerHTML+=newHtml;

*/
		if (i > showLimit)
			break;
	}
	//append hit count info
	var totalHits=parseInt(responseXML.getElementsByTagName('rc')[0].firstChild.data);
	newDiv=document.createElement('div');
	newDiv.setAttribute('class','suggestion_hitCountInfo');
	newDiv.innerHTML=(totalHits > showLimit)?'(Visar '+showLimit+' tr&auml;ffar av '+totalHits+')':'(Visar alla tr&auml;ffar)';
	o.appendChild(newDiv);
	get_object('suggestions_'+label+'_'+id).style.visibility=(sgTag.length != 0)?'visible':'hidden';
}
function getSuggestionForm(id,label) {
	switch(label) {
		case 'usr':
			return eval('document.form_userSearch_'+id);
		break;
		case 'ipvEdit':
			return eval('document.form_ipvSearch_'+id);
		break;
		case 'itmEdit':
			return eval('document.form_itmSearch_'+id);
		break;
		case 'zfl':
			return document.form_main;
		break;
		default:
			return theForm;
	}
}
function doSuggestionOnEnter(id,sgId,label) {
	var currentForm=getSuggestionForm(id,label);
	var newSg=trim(eval('currentForm.inputted_value_'+id+'.value'));
	if (newSg.length != 0) {
		switch(label) {
			case 'ipv':
				addIpv(id,sgId);
			break;
			case 'pus':
				addPus(sgId);
			break;
			case 'usr':
			case 'ipvEdit':
			case 'itmEdit':
				var completeUrl='index.cfm?x='+currentForm.x.value+'&ID='+sgId+currentForm.urlString.value;
				parent.itemFrame.location.href=completeUrl;
			break;
			case 'zfl':
				ref.srch(newSg);
			break;
		}
	}
}

//JQUERY
var JQ={
	getRankList: function(id) {
		var id=(id)?id:'sortable';
		var ar=new Array();
		var jq_ar=$("#"+id).sortable('toArray');
		for (var i=0;i<jq_ar.length;i++) {
			ar.push(jq_ar[i].split('_')[1]);
		}
		return ar;
	}
}
/* error message */
function displayEr(em_ar) {
	alert('Ofullständiga uppgifter'+convertArrayToJSMessage(em_ar));
}
function convertArrayToJSMessage(em_ar) {
	var msg='';
	for (var i=0;i<em_ar.length;i++) {
		msg+='\n* '+em_ar[i];
	}
	return msg;
}

