/* ***********************************************************
************************************************************ */
// DHTMLapi.js custom API for cross-platform
// object positioning, and others by Johan Fändriks
// Release 2.0. Supports NN4, IE, and W3C DOMs.

// Global variables
var isCSS, isW3C, isIE4, isNN4, isIE6CSS;
// Initialize upon load to let all browsers establish content objects
function initDHTMLAPI() {
	if (document.images) {
		isCSS = (document.body && document.body.style) ? true : false;
		isW3C = (isCSS && document.getElementById) ? true : false;
		isIE4 = (isCSS && document.all) ? true : false;
		isNN4 = (document.layers) ? true : false;
		isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;
	}
	if(navigator.appName=="Netscape"){
		if(parseInt(navigator.appVersion)>=5){
			isN6=true;
		}
		else{
			isN4=true;
		}
	}
	else{
		isIE=true;
	}
}
// Set event handler to initialize API
//window.onload = initDHTMLAPI;

// Seek nested NN4 layer from string name
function seekLayer(doc, name) {
	var theObj;
	for (var i = 0; i < doc.layers.length; i++) {
		if (doc.layers[i].name == name) {
			theObj = doc.layers[i];
			break;
		}
		// dive into nested layers if necessary
		if (doc.layers[i].document.layers.length > 0) {
			theObj = seekLayer(document.layers[i].document, name);
		}
	}
	return theObj;
}

// Convert object name string or object reference
// into a valid element object reference
function getRawObject(obj) {
	var theObj;
	if (typeof obj == "string") {
		if (isW3C) {
			theObj = document.getElementById(obj);
		} else if (isIE4) {
			theObj = document.all(obj);
		} else if (isNN4) {
			theObj = seekLayer(document, obj);
		}
	} else {
		// pass through object reference
		theObj = obj;
	}
	return theObj;
}

// Convert object name string or object reference
// into a valid style (or NN4 layer) reference
function getObject(obj) {
	var theObj = getRawObject(obj);
	if (theObj && isCSS) {
		theObj = theObj.style;
	}
	return theObj;
}

// Position an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
	var theObj = getObject(obj);
	if (theObj) {
		if (isCSS) {
			// equalize incorrect numeric value type
			var units = (typeof theObj.left == "string") ? "px" : 0
			theObj.left = x + units;
			theObj.top = y + units;
		} else if (isNN4) {
			theObj.moveTo(x,y)
		}
	}
}

// Move an object by x and/or y pixels
function shiftBy(obj, deltaX, deltaY) {
	var theObj = getObject(obj);
	if (theObj) {
		if (isCSS) {
			// equalize incorrect numeric value type
			var units = (typeof theObj.left == "string") ? "px" : 0
			theObj.left = getObjectLeft(obj) + deltaX + units;
			theObj.top = getObjectTop(obj) + deltaY + units;
		} else if (isNN4) {
			theObj.moveBy(deltaX, deltaY);
		}
	}
}

// Set the z-order of an object
function setZIndex(obj, zOrder) {
	var theObj = getObject(obj);
	if (theObj) {
		theObj.zIndex = zOrder;
	}
}

// Set the background color of an object
function setBGColor(obj, color) {
	var theObj = getObject(obj);
	if (theObj) {
		if (isNN4) {
			theObj.bgColor = color;
		} else if (isCSS) {
			theObj.backgroundColor = color;
		}
	}
}

// Set the visibility of an object to visible
function show(obj) {
	var theObj = getObject(obj);
	if (theObj) {
		theObj.visibility = "visible";
		theObj.display='block';
	}
}

// Set the visibility of an object to hidden
function hide(obj) {
	var theObj = getObject(obj);
	if (theObj) {
		theObj.visibility = "hidden";
		theObj.display='none';
	}
}

// Retrieve the x coordinate of a positionable object
function getObjectLeft(obj)  {
	var elem = getRawObject(obj);
	var result = 0;
	if (document.defaultView) {
		var style = document.defaultView;
		var cssDecl = style.getComputedStyle(elem, "");
		result = cssDecl.getPropertyValue("left");
	} else if (elem.currentStyle) {
		result = elem.currentStyle.left;
	} else if (elem.style) {
		result = elem.style.left;
	} else if (isNN4) {
		result = elem.left;
	}
	return parseInt(result);
}

// Retrieve the y coordinate of a positionable object
function getObjectTop(obj)  {
	var elem = getRawObject(obj);
	var result = 0;
	if (document.defaultView) {
		var style = document.defaultView;
		var cssDecl = style.getComputedStyle(elem, "");
		result = cssDecl.getPropertyValue("top");
	} else if (elem.currentStyle) {
		result = elem.currentStyle.top;
	} else if (elem.style) {
		result = elem.style.top;
	} else if (isNN4) {
		result = elem.top;
	}
	return parseInt(result);
}

// Retrieve the rendered width of an element
function getObjectWidth(obj)  {
	var elem = getRawObject(obj);
	var result = 0;
	if(elem){
	if (elem.offsetWidth) {
		result = elem.offsetWidth;
	} else if (elem.clip && elem.clip.width) {
		result = elem.clip.width;
	} else if (elem.style && elem.style.pixelWidth) {
		result = elem.style.pixelWidth;
	}
	return parseInt(result);
	}else{
		return 0;
	}
}

// Retrieve the rendered height of an element
function getObjectHeight(obj)  {
	var elem = getRawObject(obj);
	var result = 0;
	if(elem==null){
		return 0;
	}
	if (elem.offsetHeight) {
		result = elem.offsetHeight;
	} else if (elem.clip && elem.clip.height) {
		result = elem.clip.height;
	} else if (elem.style && elem.style.pixelHeight) {
		result = elem.style.pixelHeight;
	}
	return parseInt(result);
}

// Return the available content width space in browser window
function getInsideWindowWidth() {
	if (window.innerWidth) {
		return window.innerWidth;
	} else if (isIE6CSS) {
		// measure the html element's clientWidth
		return document.body.parentElement.clientWidth
	} else if (document.body && document.body.clientWidth) {
		return document.body.clientWidth;
	}
	return 0;
}

// Return the available content height space in browser window
function getInsideWindowHeight() {
	if (window.innerHeight) {
		return window.innerHeight;
	} else if (isIE6CSS) {
		// measure the html element's clientHeight
		return document.body.parentElement.clientHeight
	} else if (document.body && document.body.clientHeight) {
		return document.body.clientHeight;
	}
	return 0;
}

function addEvent(element, eventType, lamdaFunction, useCapture) {
	if (element.addEventListener) {
		element.addEventListener(eventType, lamdaFunction, useCapture);
		return true;
	} else if (element.attachEvent) {
		var r = element.attachEvent('on' + eventType, lamdaFunction);
		return r;
	} else {
		return false;
	}
}
/*
* Kills an event's propagation and default action
*/
function knackerEvent(eventObject) {
	if (eventObject && eventObject.stopPropagation) {
		eventObject.stopPropagation();
	}
	if (window.event && window.event.cancelBubble ) {
		window.event.cancelBubble = true;
	}

	if (eventObject && eventObject.preventDefault) {
		eventObject.preventDefault();
	}
	if (window.event) {
		window.event.returnValue = false;
	}
}

/*
* Safari doesn't support canceling events in the standard way, so we must
* hard-code a return of false for it to work.
*/
function cancelEventSafari() {
	return false;
}

/*
* Cross-browser style extraction, from the JavaScript & DHTML Cookbook
* <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
*/
function getElementStyle(elementID, CssStyleProperty) {
	var element = document.getElementById(elementID);
	if (element.currentStyle) {
		return element.currentStyle[toCamelCase(CssStyleProperty)];
	} else if (window.getComputedStyle) {
		var compStyle = window.getComputedStyle(element, '');
		return compStyle.getPropertyValue(CssStyleProperty);
	} else {
		return '';
	}
}

/*
* CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
* From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>
*/
function toCamelCase(CssProperty) {
	var stringArray = CssProperty.toLowerCase().split('-');
	if (stringArray.length == 1) {
		return stringArray[0];
	}
	var ret = (CssProperty.indexOf("-") == 0)
	? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
	: stringArray[0];
	for (var i = 1; i < stringArray.length; i++) {
		var s = stringArray[i];
		ret += s.charAt(0).toUpperCase() + s.substring(1);
	}
	return ret;
}
/*
* Disables all 'test' links, that point to the href '#', by Ross Shannon
*/
function disableTestLinks() {
	var pageLinks = document.getElementsByTagName('a');
	for (var i=0; i<pageLinks.length; i++) {
		if (pageLinks[i].href.match(/[^#]#$/)) {
		addEvent(pageLinks[i], 'click', knackerEvent, false);
	}
}
}

/*
* Cookie functions
*/
function setCookie(stringCookieName, stringCookieValue){
	var today = new Date();
	var expires = 60 * (1000 * 60 * 60 * 24); //expire in 60 days
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = stringCookieName + "=" + escape( stringCookieValue ) + ";expires=" + expires_date.toGMTString();
}

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

function readCookie(name) {
	var cookieCrumbs = document.cookie.split(';');
	var nameToFind = name + '=';
	for (var i = 0; i < cookieCrumbs.length; i++) {
		var crumb = cookieCrumbs[i];
		while (crumb.charAt(0) == ' ') {
			crumb = crumb.substring(1, crumb.length); /* delete spaces */
		}
		if (crumb.indexOf(nameToFind) == 0) {
			return crumb.substring(nameToFind.length, crumb.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, '', -1);
}
function OpenWindow(theURL,winName,features) { //v2.0
	var wn=window.open(theURL,winName,features);
	wn.focus();
}
function openExternal(link){
	var extLnk=window.open(link, 'External', 'resizable=yes,scrollbars=yes,location=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes');
	extLnk.focus();
}
// Convert object name string or object reference
// into a valid object reference
function getStyleObject(obj) {
	var styleObj;
	if (typeof obj == "string") {
		if (document.getElementById) {
			styleObj = document.getElementById(obj).style;
		} else if (document.all) {
			styleObj = document.all[obj].style;
		}
	} else if (obj.style) {
		styleObj = obj.style;
	}
	return styleObj;
}
// Positioning an object at a specific pixel coordinate
/*
function shiftTo(obj, x, y) {
var styleObj = getStyleObject(obj);
if (styleObj) {
styleObj.left = x + "px";
styleObj.top = y + "px";
}
}
*/
function chkdate(objName, checktime) {
	//var strDatestyle = "US"; //United States date style
	var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var intHour;
	var intMinute;
	var strHour;
	var strMinute;
	var booFound = false;
	var datefield = objName;
	var chktime=checktime;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "Maj";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Okt";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield.value;
	if(strDate==0){
		return true;
	}
	if (strDate.length < 1) {
		return true;
	}
	if(chktime==1){
		if(strDate.length==12){
			strYear = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strDay = strDate.substr(4, 2);
			strHour = strDate.substr(7,2);
			strMinute=strDate.substr(10);
		}else if (strDate.length==14){
			strYear = strDate.substr(0, 4);
			strMonth = strDate.substr(4, 2);
			strDay = strDate.substr(6, 2);
			strHour = strDate.substr(9,2);
			strMinute=strDate.substr(12);
		}else{
			return false;
		}
	}else{
		if (strDate.length==6) {
			strYear = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strDay = strDate.substr(4);
		}else if(strDate.length==8){
			strYear = strDate.substr(0, 4);
			strMonth = strDate.substr(4, 2);
			strDay = strDate.substr(6);
		}else{
			return false;
		}
	}
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	// US style
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
		}
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		}
		else {
			if (intday > 28) {
				err = 10;
				return false;
			}
		}
	}
	if(intday<10){
		strDay="0"+intday;
	}
	if(intMonth<10){
		strMonth="0"+intMonth;
	}
	if(chktime==1){
		intHour = parseInt(strHour, 10);
		if (isNaN(intHour)) {
			err = 4;
			return false;
		}
		intMinute = parseInt(strMinute, 10);
		if (isNaN(intMinute)) {
			err = 4;
			return false;
		}
		if(intMinute > 59){
			return false;
		}
		if(intHour > 24){
			return false;
		}
		datefield.value = strYear + "" + strMonth + "" + strDay + " " + strHour + ":" + strMinute;
	}else{
		datefield.value = strYear + "" + strMonth + "" + strDay + "";
	}
	return true;
}
function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}
	else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}
function getStyleRuleByName(stringName){
	if (!document.styleSheets){
		return;
	}
	var theRules = new Array();
	for (var i = 0; i < document.styleSheets.length; i++){
		if (document.styleSheets[i].cssRules){
			theRules = document.styleSheets[i].cssRules
		}
		else if (document.styleSheets[i].rules){
			theRules = document.styleSheets[i].rules
		}
		for (var j = 0; j < theRules.length; j++){
			if (theRules[j].selectorText.toLowerCase() == stringName.toLowerCase()){
				return theRules[j];
			}
		}
	}
	return null;
}
function setFontSize(stringRuleName, intNewSize){
	var ruleToChange = getStyleRuleByName(stringRuleName);
	var tag =['p','td'];//tags array
	if (ruleToChange != null){
		if(defSize[stringRuleName] == null){
			defSize[stringRuleName]=parseInt(ruleToChange.style.fontSize);
		}
		//alert(defSize[stringRuleName] + ruleToChange.style.fontSize);
		if(isNaN(intNewSize)){
			var fs=defSize[stringRuleName] *1;
		}else{
			var fs= (defSize[stringRuleName] * (intNewSize / 100));
		}
		if(isNaN(fs)){
			fs=defSize[stringRuleName];
		}
		//alert(defSize[stringRuleName] + ' * ' + intNewSize + '/100 = ' + fs);
		ruleToChange.style.fontSize = fs + 'px';
		if(stringRuleName==".mainPageBody"){
			for (var i=0;i<tag.length;i++){
				if(document.getElementById('mainPage')){
					var el = document.getElementById('mainPage').getElementsByTagName(tag[i]);
					for(var j=0;j<el.length;j++){
						el[j].style.fontSize=fs+'px';
					}
				}
			}
		}
	} else {
	}
}
String.prototype.trim = function() {
	var re = /^\s+(.*?)\s+$/;
	return this.replace(re,"$1");
}
function showText(boxid, posparent){
	var box=document.getElementById(boxid);
	box.style.visibility='visible';
	var posx = getObjectLeft(posparent)+15;
	var posy = getObjectTop(posparent)+15;
	box.style.top=posy;
	box.style.left=posx;
	box.style.display='block';
}
function hideText(boxid){
	var box=document.getElementById(boxid);
	box.style.visibility='hidden';
	box.style.display='none';
}
function addSelectOption(selbox,nodevalue,text){
	var opt=document.createElement('option');
	opt.value=nodevalue;
	var optval=document.createTextNode(text);
	selbox.appendChild(opt);
	opt.appendChild(optval);
}
function getEventElement(evt){
	if(evt.target){
		return evt.target;
	}else if(evt.srcElement){
		return evt.srcElement;
	}
}
function createInput(type, name,id,value){
	var txtb=document.createElement('input');
	txtb.setAttribute('type',type);
	txtb.setAttribute('name',name);
	txtb.setAttribute('id',id);
	txtb.setAttribute('value',value);
	return txtb;
}
var request=null;
function createRequest(){
	try{
		request=new XMLHttpRequest();
	}catch (trymicrosoft){
		try{
			request=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(othermicrosoft){
			try{
				request=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(failed){
				request=null;
			}
		}
	}
	if(request==null){
		alert("Error creating request object");
	}
}
function blockEvents(evt){
	evt=(evt)?evt:event;
	var blockit=false;
	var elem=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);
	if(evt.cancelBubble){
		evt.cancelBubble=true;
	}
}
//Funktion för att välja ett värde i en selectbox
function selectItem(selbox, selvalue){
	for(var x=0;x<selbox.options.length;x++){
		if(selbox.options[x].value==selvalue){
			selbox.selectedIndex=x;
			break;
		}
	}
}

// Center a positionable element whose name is passed as
// a parameter in the current window/frame, and show it
function centerOnWindow(elemID,centery) {
    // 'obj' is the positionable object
    var obj = getRawObject(elemID);
    var styleObj=getObject(elemID);
    if(styleObj && centery==true){
    	styleObj.position='absolute';
    }
    // window scroll factors
    var scrollX = 0, scrollY = 0;
    if (document.body && typeof document.body.scrollTop != "undefined") {
        scrollX += document.body.scrollLeft;
        scrollY += document.body.scrollTop;
        if (document.body.parentNode &&
            typeof document.body.parentNode.scrollTop != "undefined") {
            scrollX += document.body.parentNode.scrollLeft;
            scrollY += document.body.parentNode.scrollTop;
        }
    } else if (typeof window.pageXOffset != "undefined") {
        scrollX += window.pageXOffset;
        scrollY += window.pageYOffset;
    }
    var x = Math.round((getInsideWindowWidth()/2) -
        (getObjectWidth(obj)/2)) + scrollX;
    var y = Math.round(scrollY);
    //alert(y);
    if(elemID=='admincontainer'){
    	shiftTo(obj, 0, y);
    }else{
    	if(centery==false){
    		y=0;
    	}
    	shiftTo(obj, x, y);
    	//alert(x);
    }
    //show(obj);
}

function isChosen(select){
	if(select.selectedIndex==0){
		return false;
	}else{
		return true;
	}
}
function submitViaEnter(evt){
	evt=(evt)?evt:event;
	var target=(evt.target)?evt.target:evt.srcElement;
	var form=target.form;
	if(isEnterPressed(evt)){
		form.submit();
		return false;
	}
	return true;
}
function isEnterPressed(evt){
	evt=(evt)?evt:event;
	var target=(evt.target)?evt.target:evt.srcElement;
	var form=target.form;
	var charCode=(evt.charCode)?evt.charCode:((evt.whitch)?evt.whitch:evt.keyCode);
	if(charCode==13 || charCode==3){
		return true;
	}
	return false;
}
function toggleVisibility(elemid){
	Effect.toggle(elemid, 'blind',{duration:0.2});
	//alert($(elemid).style.display);

	setCookie(elemid,$(elemid).style.display=='none','/');
}
function isValidRadio(radio){
	var valid=false;
	alert(radio.value+' ' + radio.name);
	for(var i=0;i < radio.length;i++){
		if(radio[i].checked){
			return true;
		}
	}
	alert('Du måste välja en');
	radio.focus();
	return false;
}
function isNotEmpty(field, markdivid){
	var str=field.value;
	var re=/.+/;
	if(!str.match(re)){
		alert('Fältet får inte vara tomt');
		field.focus();
		if($(markdivid)){
			$(markdivid).addClassName('error');
		}
		return false;
	}else{
		return true;
	}
}
function isNumber(field){
	if(isNotEmpty(field)){
		var str=field.value;
		var re=/^[-]?\d*\.?\d*$/;
		str=str.toString();
		if(!str.match(re)){
			alert('Endast nummer får skrivas här');
			field.focus();
			return false;
		}else{
			return true;
		}
	}else{
		return false;
	}
}
function isEmailAddress(field){
	var str=field.value;
	var re=/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
	if(!str.match(re)){
		alert('Kontrollera epostadressen');
		field.focus();
		return false;
	}else{
		return true;
	}
}
function numeralsOnly(evt){
	evt=(evt)?evt:event;
	var charCode=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
	if(charCode>31 && (charCode <48 || charCode>57) && charCode!=46){
		alert("Endast nummer");
		return false;
	}
	return true;
}
