/*
**********************************************************************
**                       Common functions                           **
**                                                                  **
**********************************************************************
*/
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

	var isSubmitted = false;
	function doSubmit(){
		if(!isSubmitted){
			document.getElementById('theForm').submit();
			isSubmitted = true;
		}
	}
	
	function openNewUrl(address){
		document.location.href=address;
	}
	
	
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}
	// This function shows the calendar under the element having the given id.
	// It takes care of catching "mousedown" signals on document and hiding the
	// calendar if the click was outside.
	function showCalendar(id, format, showsTime, showsOtherMonths) {
	  var el = document.getElementById(id);
	  if (_dynarch_popupCalendar != null) {
	    // we already have some calendar created
	    _dynarch_popupCalendar.hide();                 // so we hide it first.
	  } else {
	    // first-time call, create the calendar.
	    var cal = new Calendar(1, null, selected, closeHandler);
	    // uncomment the following line to hide the week numbers
	    // cal.weekNumbers = false;
	    if (typeof showsTime == "string") {
	      cal.showsTime = true;
	      cal.time24 = (showsTime == "24");
	    }
	    if (showsOtherMonths) {
	      cal.showsOtherMonths = true;
	    }
	    _dynarch_popupCalendar = cal;                  // remember it in the global var
	    cal.setRange(1900, 2070);        // min/max year allowed.
	    cal.create();
	  }
	  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
	  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
	  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use
	
	  // the reference element that we pass to showAtElement is the button that
	  // triggers the calendar.  In this example we align the calendar bottom-right
	  // to the button.
	  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar
	
	  return false;
	}
    function krypt(posturl){
        if (document.loginform.kryptering.checked){
            document.loginform.action=posturl;
        }
        else {
            document.loginform.action=posturl;
        }
        document.loginform.submit();
    }
	function CRcheck(e){
		if( !e ){
			e = window.event;
		}
		if( e.keyCode == 13 ){
			krypt(document.loginform);
		}
	}

	function popup(action,name,w,h){
		//add - date START (hack to get the popup window to reload properly)
		var time = new Date()
		var hours = time.getHours()
		var minutes = time.getMinutes()
		var seconds = time.getSeconds()
		action +=  "&x="+Math.random()+hours+minutes+seconds;
		//add - date END
		
		ScreenWidth=screen.availWidth;
		ScreenHeight=screen.availHeight;
		window.open(action,name,'toolbar=no,location=no,scrolling=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height='+ h +',status=0,copyhistory=0,left=50,top=50');
	}

/*
** openWin(path,name,w,h)
** open a pop-up window
**
** path: string: href to window source
** name: string: name of window
** w   : int   : window width
** h   : int   : window height
**
*/

function openWin(path,name,w,h) {
    if (name == "login") {
    	aWin = window.open(path,name,'toolbar=no,location=no,scrolling=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height='+ h +',status=0,copyhistory=0,screenX=100,screenY=10,top=250,left=300');
    }
	else if(name == "byggedata")
	{
		aWin = window.open(path, name, "width="+w+", height="+h+", location=no, menubar=no, status=no, toolbar=yes, scrollbars=yes, resizable=yes");
	}
    else
    {
    	aWin = window.open(path,name,'toolbar=no,location=no,directories=no,status=no,status=no,scrollbars=no,resizable=yes;copyhistory=no,width=' + w + ',height='+ h +'');
    }
    if (aWin.opener == null) aWindow.opener = self;
    return false;
}


function openWinParams(path,name,w,h, showToolbar, showMenubar, showAddressbar, showLinkbar, showStatusbar, allowScrollbars, allowResizing) {

   var str =
      'toolbar='     + ((showToolbar)?'yes':'no')      + ", " +
      'menubar='     + ((showMenubar)?'yes':'no')      + ", " +
      'location='    + ((showAddressbar)?'yes':'no')   + ", " +
      'directories=' + ((showLinkbar)?'yes':'no')      + ", " +
      'status='      + ((showStatusbar)?'yes':'no')    + ", " +
      'scrolling='   + ((allowScrollbars)?'yes':'no')  + ", " +
      'scrollbars='  + ((allowScrollbars)?'yes':'no')  + ", " +
      'resizable='   + ((allowResizing)?'yes':'no')    + ", " +
      'copyhistory=' + 'no'                            + ", " +
      'width='       + w                               + ", " +
      'height='      + h;

    aWin = window.open(path,name,str);
    if (aWin.opener == null) aWindow.opener = self;
    return false;
}

/* openwin to pic in bygerfa popup */
function openWinBygerfa(path,name,w,h) {

    aWin = window.open(path,name,'toolbar=no,location=no,directories=no,status=no,status=no,scrollbars=yes,resizable=yes;copyhistory=no,width=' + w + ',height='+ h +'');
}




/*
** closeWin(openerPath)
** close a pop-up window
**
** openerPath: string: href to main window. Optional.
**
*/
function closeWin(openerPath) {
	setTimeout("window.close()",500);
    if (openerPath) {
        // new parent window location
        window.opener.location.href=openerPath;
    } else {
        // refresh parent window
        window.opener.history.go(0);
    }
    window.opener.focus();
}

function closeWin1() {
	self.close();
}




/*
** doOpenAddToGuideList(path,name,w,h)
** open a pop-up window. Made in a separate function rather than just using openWin. So that the
** opening might be customized in the future, across all guide list popups.
**
** path   : string: href to window source (must include a questionmark, meaning if no parameters
**                  are specified in the href, then it must end with a questionmark.
** name   : string: name of window
** relID  : int   : id of the data the relation refers to
** relType: int   : type of the data refered (one of the RELATION_TYPE_ constants).
*/
function doOpenAddToGuideList(path,name,relID,relType) {
   path = path + "&id=" + relID + "&relationtype_id=" + relType + "&inPopup=true";
   return openWin(path,name,400,400);
}


/*
** doOpenAddToNewsList(path,name,w,h)
** open a pop-up window. Made in a separate function rather than just using openWin. So that the
** opening might be customized in the future, across all news list popups.
**
** path   : string: href to window source (must include a questionmark, meaning if no parameters
**                  are specified in the href, then it must end with a questionmark.
** name   : string: name of window
** relID  : int   : id of the data the relation refers to
** relType: int   : type of the data refered (one of the RELATION_TYPE_ constants).
*/
function doOpenAddToNewsList(path,name,relID,relType) {
   path = path + "&id=" + relID + "&relationtype_id=" + relType;
   return openWin(path,name,400,400);
}


/*
** doOpenAddToBCBpsRecommList(path,name,w,h)
** open a pop-up window. Made in a separate function rather than just using openWin. So that the
** opening might be customized in the future, across all Recomm list popups.
**
** path   : string: href to window source (must include a questionmark, meaning if no parameters
**                  are specified in the href, then it must end with a questionmark.
** name   : string: name of window
** relID  : int   : id of the data the relation refers to
** relType: int   : type of the data refered (one of the RELATION_TYPE_ constants).
*/
function doOpenAddToBCBpsRecommList(path,name,relID,relType) {
   path = path + "&id=" + relID + "&relationtype_id=" + relType;
   return openWin(path,name,400,400);
}


/*
** doOpenPictureUpload(path,name,w,h)
** open a pop-up window. Made in a separate function rather than just using openWin. So that the
** opening might be customized in the future, across all news list popups.
**
** path   : string: href to window source (must include a questionmark, meaning if no parameters
**                  are specified in the href, then it must end with a questionmark.
** name   : string: name of window
** relID  : int   : id of the data the relation refers to
** relType: int   : type of the data refered (one of the RELATION_TYPE_ constants).
*/
function doOpenPictureUpload(path,name,subArchivePath,type,groupId) {
   path = path
        + "&sub_archive_path=" + subArchivePath + "&type=" + type
        + "&CB_PICTURE_GROUP_" + groupId + "=true" + "&CB_PICTURE_GROUP_" + groupId + "_hidden=" + groupId
        + "&public_access_hidden=false";

   return openWin(path,name,500,350);
}



/*
** doOpenDownloadUpload(path,name,suibArchivePath,type,groupId)
**
** path: string: href to window source
** name: string: name of window
** subArchivePath : subdirectory the download should be placed in.
** right_id:        access right, necesary to acces the download.
** type:            .not used yet.
** goupId:          .not used yet.
**
*/
function doOpenDownloadUpload(path,name,subArchivePath,right_id,type,groupId) {
   path = path
        + "&sub_archive_path=" + subArchivePath + "&right_id=" + right_id + "&type=" + type
        + "&CB_DOWNLOAD_GROUP_" + groupId + "=true" + "&CB_DOWNLOAD_GROUP_" + groupId + "_hidden=" + groupId
        + "&public_access_hidden=false";

   return openWin(path,name,500,300);
}

function doOpenDownloadList(path,name,w, h) {

    aWin = window.open(path,name,'toolbar=no,location=no,directories=no,status=no,status=no,scrollbars=yes,resizable=no;copyhistory=no,width=' + w + ',height='+ h +'');
    if (aWin.opener == null) aWindow.opener = self;
    return false;
}

function doOpenUploadByggedata(path,name,subArchivePath,right_id,type,groupId) {
   path = path
        + "&sub_archive_path=" + subArchivePath + "&right_id=" + right_id + "&type=" + type
        + "&CB_DOWNLOAD_GROUP_" + groupId + "=true" + "&CB_DOWNLOAD_GROUP_" + groupId + "_hidden=" + groupId
        + "&public_access_hidden=false";

   return openWin(path,name,650,300);
}

//
// Requirements:  The opener must have a form called 'bygnetForm' with fields DOWLOAD_ID_* and DOWNLOAD_TITLE_*
// Used by:       bcbygerfa.wm
//
function doCloseDownloadList( position, id, title) {

    var  idField    = 'DOWNLOAD_ID_' + position;
    var  titleField = 'DOWNLOAD_TITLE_' + position;
    var  j = 0;

    // Find the element named 'idFiel' and 'titleField'
    for ( var i = 0; i < window.opener.document.bygnetForm.elements.length; i++) {

        if ( window.opener.document.bygnetForm.elements[i].name == idField) {
            window.opener.document.bygnetForm.elements[i].value = id;
            j++;
        }
        if ( window.opener.document.bygnetForm.elements[i].name == titleField) {
            window.opener.document.bygnetForm.elements[i].value = title;
            j++;
        }

        if (j==2) break;
    }

	setTimeout("window.close()",800);
}


/*
 *
 */
function showHelp(helpUrl, helpID, forceOpen) {
    if (parent.help) {
        parent.help.showHelp1(helpUrl, helpID, forceOpen);
    } else {
        if (window.helpWindow) {
            if (!helpWindow.closed) {
                helpWindow.location.href = helpUrl + helpID;
                helpWindow.focus();
            } else {
                if (forceOpen) helpWindow = window.open(helpUrl + helpID, 'helpWin','width=460,height=500,scrollbars=yes,resizable=yes');
            }
        } else {
            if (forceOpen) {
                helpWindow = window.open(helpUrl + helpID, 'helpWin','width=460,height=500,scrollbars=yes,resizable=yes');
                helpWindow.focus();
            }
        }

    }
}

/*
 *
 */
function submitFormPrintDialog( href)
{
   if ( window.print) {
      window.print();
      document.location.href=href;
   }
   else {
      alert( 'Der er ikke defineret en printer p? din maskine.');
      document.location.href=href;
   }

}


function snot()
{
   if ( window.print) {
      window.print();
      document.location.href=href;
   }
   else {
      alert( 'Der er ikke defineret en printer p? din maskine.');
   }

}


function submitOnKeypress(evt, form) {
	if (document.layers) {
    	var theKey = evt.which;
		if (theKey == 13) {
			form.submit();
		}
	}
}


/*
validates a form and return true or false dependent on the fields checked.

aForm : a form object
fields: an array of field names that has to be filled/checked/selected

Example: <input type="button" onClick="if(validateForm(this.form, new Array('name','username','password')))this.form.submit();">

*/
function validateForm(aForm, fields) {
    var field;
    var checked = false;
    for(i=0;i<fields.length;i++) {
        field = eval('aForm.'+fields[i]);
        if (field.length) {
            if ((field[0].type == "checkbox") || (field[0].type == "radio")) {
                for(j=0;j<field.length;j++) {
                    if (field[j].checked) {
                        checked = true;
                    }
                }
                if (!checked) {
                    alert("Du skal udfylde alle felter markeret med en *");
                    return false;
                }
                checked = false;
            }
            if (field.selectedIndex) {
                // dropdown
                if(field[field.selectedIndex].value == "noSelect") {
                    alert("Du skal udfylde alle felter markeret med en *");
                    eval('aForm.'+field[0].name).focus();
                    return false;
                }
            }
        }
        if ((field.type == "text")||(field.type == "password")||(field.type == "textarea")) {            
            var oEditor = false;
            try { oEditor = FCKeditorAPI.GetInstance(field.name); } catch(e){}
            if (oEditor) field.value = oEditor.GetHTML();
            if (field.value.length == 0) {
                alert("Du skal udfylde alle felter markeret med en *");
                if (oEditor) oEditor.Focus();
                else eval('aForm.'+field.name).focus();
                return false;
            }
        }        
        // if field is radio or checkbox, and only one field exists
        if ((field.type == "radio")||(field.type == "checkbox")) {
            if(!field.checked) {
                alert("Du skal udfylde alle felter markeret med en *");
                return false;
            }
        }
    }
    return true;
}

function isEmptyTextfields(aForm, fields) 
{
	
	
		for(i=0;i<fields.length;i++) 
			{
			field = eval('aForm.'+fields[i]);
							
			if ((field.type == "text") ||(field.type == "password"))
				{
					if (field.value.length == 0) 
						{
                				eval('aForm.'+field.name).focus();
                				return false;	
						}
				}
			}
	return true;
}




/*
kryptering is only used in byggeweb's login
*/

function kryptering()
{

   	var exp = new Date()
	var expire = exp.getTime() + (365 * 24 * 60 * 60 * 1000)
	exp.setTime(expire)

		document.cookie = "Company=; expires=" + exp.toGMTString()+"; path=;";
		document.cookie = "User=; expires=" + exp.toGMTString()+"; path=;";
		document.cookie = "SSL=; expires=" + exp.toGMTString()+"; path=;";
		document.cookie = "Savelogin=; expires=" + exp.toGMTString()+"; path=;";
	/*


	Det undre mig lidt at adresserne er de samme http
	*/
	if (document.login.ssl.checked)
	{
            document.login.action="http://www.byggeweb.dk/cgi-shl/company-login.pl"
        }
	else
	{
	    document.login.action="http://www.byggeweb.dk/cgi-shl/company-login.pl"
	}


}
function checkNumberOfCiffers( inString, numberOfCiffers)
{
   /* If the string contains precise the number of ciffers specified the function returns true
   ** If the string contains any characters besides ciffers and blanks or too many/few ciffers false is returned
   */
   var ciffersRecognized = 0;
   var aChar = '';

   for(i = 0; i < inString.length ; i++)
   {
      aChar = inString.substring(i,i+1);
      if ( ((aChar == "0") || (aChar == "1") || (aChar == "2") || (aChar == "3") || (aChar == "4") || (aChar == "5") || (aChar == "6") || (aChar == "7") || (aChar == "8") || (aChar == "9")) && (ciffersRecognized < numberOfCiffers))
      {
         ciffersRecognized++;
      }else
      {
         if ( aChar ==" ")
         {
            ;
         }else
         {
            alert("CVR nr. skal best? af 8 cifre evt. adskilt af mellemrum");
            return false;
         }
      }
   }
   if (numberOfCiffers == ciffersRecognized)
   {
      return true;
   } else
   {
      alert("CVR nr. skal best? af 8 cifre evt. adskilt af mellemrum");
      return false;
   }
}


function doByggeMailSubmit() {
    document.loginformbyggemail.userid.value = document.loginformbyggemail.userid1.value+'@'+document.loginformbyggemail.domain[document.loginformbyggemail.domain.selectedIndex].value;
    document.loginformbyggemail.submit();
}

function ByggemailKey(evt) {
	var isIE = document.all;
	var isNav = document.layers;
	var theKey = evt.which;

	if (isIE) {
		if (window.event.keyCode == 13) {
	    		doByggeMailSubmit();
		}
	}
	if (isNav) {
		if (theKey == 13) {
			doByggeMailSubmit();
		}
	}
}


function isEmail(elm) {
	
	
	
	
	if( isEmpty( elm.value))
		{
		 return true;
		
		}
	else if 	(elm.value.indexOf("@") + "" != "-1" &&
        		elm.value.indexOf(".") + "" != "-1" )
        	{
    		return true;
    		}
    	else
    		return false;
	
}

/*
*ser om en tekststreng er tom. Hvis cursoren flyttes i et tekstfelt inds?ttes en whitespace karakter  
*s?ledes at feltets value ikke er rigtigt tom men best?r af en streng indeholdende whitespace.
*Derfor er denne funktion n?dvendig. Anvendes i IsEmail(...)
*/
function isEmpty(txt)
{
	for(var i=0;i<txt.length;i++)
		{
		if( txt.charAt(i) != " ")
			return false;		
		}	
	return true
}

function checkform(form, arrayList) 
{
  
      
   for(i=0;i<arrayList.length;i++)
      {
          var field = eval('form.' + arrayList[i]);
         
	   if (isEmail(field) == false) 
	      {
		   alert("Den indtastede emailadresse er ikke gyldig");
		   field.focus();
		   return false;
	      }	   
		
	
   }	
return true;
}

function enableElements(f, radioes)
{
	
	
	for(i=0;i<radioes.length;i++)
		{		
		var tmp	= radioes[i];
		eval('f.' + tmp + '.disabled = false');
		}
	
}
function openForum(_forum){
	openWinParams('/bygnet/go?action=2729&forum='+_forum,'Debatforum',800,600, false, false, false, false, false, true, true);
}

function disableElements(f, radioes)
{
	
	
	for(i=0;i<radioes.length;i++)
		{		
		var tmp	= radioes[i];
		
		eval('f.' + tmp + '.checked = false');
		eval('f.' + tmp + '.value = 0');
		eval('f.' + tmp + '.disabled = true');
		
		
		}
	
}

// hide/show html element 
// author ml
function showElement(_element){
	if( document.getElementById( _element ).style.display == 'none'){
		document.getElementById( _element ).style.display = '';
	}
	else{
		document.getElementById( _element ).style.display = 'none';
	}
}

// add element to html select box
// author ml
function addOption(theSel, theText, theValue){

	var newOpt = new Option(theText, theValue);
	var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
}

// remove element from html select box
// author ml
function deleteOption(theSel, theIndex){	

	var selLength = theSel.length;
	if(selLength>0)
	{
		theSel.options[theIndex] = null;
	}
}

	function saveIpValues(){
	
		if( document.user.listOne != null && document.user.assignedIps != null ){
			var selLength = document.user.listOne.length;
								
			var i;
			var ids = '';
							
			for( i=selLength-1 ; i >= 0 ; i-- ){
				ids += document.user.listOne.options[i].value;
				if( i != 0 )
					ids +=  '|';
			}
			
			document.user.assignedIps.value = ids;
		}

	}
function checkAndSubmitIfNotEmpty(msg, form, value){
	if(value == ''){
		alert(msg);	
	}
	else{
		document.bygnetForm.submit();
	}
}


function resizeBannerWidth(img,maxWidth){
	var width = img.width;
	if( img.width > maxWidth ){
			img.width=maxWidth;
	}
}

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
}

/*
 * view or hide element on page
 */
function view(elementId){
	document.getElementById(elementId).style.display = 'block'; 
}
function hide(elementId){
	document.getElementById(elementId).style.display = 'none'; 
}


// Function to submit a form , and close window, it user answers 'yes'
function conditionalSubmitAndClose(question, info, formtosubmit, windowtoclose)
{
	if(confirm(question))
	{
		alert(info);
		formtosubmit.submit();
		windowtoclose.close();
	}
}