function pageOnLoad() {
   //changeColorForLeftMenu();
   setBaggrundForVenstreMenuerPaaUndersider();
};


function  setBaggrundForVenstreMenuerPaaUndersider(sName) {
  var sResult= '';
  try {
    /* STH:  21-01-2008 
       Sætter baggrunden på venstre menuen på undersider.
       Hvilken vælges i backend her stylesheet > ...
    */
    var oUnderMenu = $('UnderMenu');
    if (oUnderMenu) {
      oUnderMenu.style.background = sDwBackgroundColor+' url('+sDwBackgroundImage+') repeat-x -10px -5px';
    }

  } catch(e) {
    sResult+= '\nError in setBaggrundForVenstreMenuerPaaUndersider("'+sName+'"): '+e.message;
  }
  return sResult;
}

function CleanUpText(string) {
	string = CleanUpValue(string);
	string = string.replace(/<a.*?>.*?<\/a>/g, '');
	string = string.replace(/<p.*?>(.*?)<\/p>/g, '$1');
	if (string == '&nbsp;') {
		string='';	
	}
	return (string); 			
}

function CleanUpValue(string) {
	if (string.match(/^<!--/)) {
		return ('');	
	}	
	else {
		return string;
	}		
}



// GLOBAL VARIABLES
var aQuerystring;

/************************* UTILS *************************/

var bAlert = true;
function alert(s)
{
  if (bAlert)
  {
    if (arguments.length>1) {
      for(var i=1; i<arguments.length; i++) {
        s+='\n'+arguments[i]
      }
    }
    bAlert = confirm(s);
  }
}

function getMetaData(sName) {
  var aResult = [];
  try {
    var cMetas = document.getElementsByTagName('META');
    var bShowAll = (arguments.length==0);
    for (var i=0; i<cMetas.length; i++)
    {
      if (cMetas[i].name==sName || bShowAll) {
        aResult[aResult.length] = cMetas[i].getAttribute('CONTENT')+'\n';
      }
    }
  } catch(e) {
    aResult[aResult.length] = 'Error in getMetaData("'+sName+'"): '+e.message;
  }
  return aResult;
}

/* imageNotFound - version 1.1, STH
   V. 1.0
   Routine which should be called "onerror" on a image.
   The image can have an extra attribute "defaultImageSrc", which is a path to an image to use if imagepath in "src" is not valid.
   You can also supply an URL in the 2nd param to this function.
   The syntax is on the HTML part is:
   <img src="myImage.gif" onerror="imageNotFound(this)" defaultImageSrc="/files/billeder/notfound.gif" />
   or
   <img src="myImage.gif" onerror="imageNotFound(this, '/files/billeder/notfound.gif')" />
   V. 1.1
   If an ID exists called: pageName an attempt to locate image using that will be done
*/
function imageNotFound(oElement, sReplaceSrc)
{
  try {
    var iRetries = oElement.getAttribute('retries');
    try {
      iRetries++;
    } catch(e) {
      iRetries = 1;
    }
    oElement.setAttribute('retries', iRetries);
    sReplaceSrc = (sReplaceSrc) ? sReplaceSrc : oElement.getAttribute('defaultImageSrc');
    oElement.title = (oElement.title.indexOf('\u003c\u0021\u002d\u002d\u0040')>-1) ? '' : oElement.title;
    
    // V. 1.1
    var sPageName = '';
    try {
      var oPageName = document.getElementById('pageName');
      sPageName = oPageName.value.strip();
      oPageName.value = '';
    } catch(e) {
    }
    if ((iRetries==1) && sPageName!='') {
      oElement.setAttribute('retries', 0);
      sReplaceSrc = sPageName;
    } 
    
    if (iRetries==1)
    {
      oElement.src = (sReplaceSrc) ;
    } else {
      // Could not find the defaultImageSrc nor a "sReplaceSrc" image, use DW 1x1.gif'
      // And set background to lightgray - you may alter this to other styles.
      oElement.src = '/x.gif';
      oElement.style.backgroundColor = '#efefef';
    }
  } catch(e) {
    alert('Error in imageNotFound('+oElement+','+sReplaceSrc+'):\n'+e.message);
  }
}
  


function copyToClipboard(sText)
{
 if (window.clipboardData) 
   {
   window.clipboardData.setData("Text", sText);
   }
   else if (window.netscape) 
   { 
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;
   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;
   trans.addDataFlavor('text/unicode');
   var str = new Object();
   var len = new Object();
   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
   var copytext=sText;
   str.data=copytext;
   trans.setTransferData("text/unicode",str,copytext.length*2);
   var clipid=Components.interfaces.nsIClipboard;
   if (!clip) return false;
     clip.setData(trans,null,clipid.kGlobalClipboard);
   }
   //alert("Following info was copied to your clipboard:\n\n" + sText);
   return false;
}

function getUniqueNumber()
{
  return ((new Date()-(new Date(1964, 8, 23)))+parseInt(Math.random()*1000));
}

function doesFileExist(url, fFileExist, fFileUnknown)
{
		var xmlhttp = null;
		// code for Mozilla, etc.
		if (window.XMLHttpRequest) {
				xmlhttp = new XMLHttpRequest()
		} else {
				// code for IE
				if (window.ActiveXObject) {
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
				}
		}
		
		if (xmlhttp!=null) {
				xmlhttp.onreadystatechange = function() {doesFileExistState_Change(xmlhttp, fFileExist, fFileUnknown)}
				xmlhttp.open("HEAD",url,true)
				xmlhttp.send(null)
		} else {
				// Your browser does not support XMLHTTP.
				eval('fFileUnknown()');
		}
}

function doesFileExistState_Change(xmlhttp, fFileExist, fFileUnknown) {
		// if xmlhttp shows "loaded"
		if (xmlhttp.readyState==4) {
				// if "OK"
				if (xmlhttp.status==200) {
						eval('fFileExist(xmlhttp)');
						//alert(xmlhttp.getAllResponseHeaders().split(':'))
				} else {
						// Problem retrieving data: + xmlhttp.statusText)
						eval('fFileUnknown()');
				}
		}
}

function getLocationRoot() {
  var sLocation = document.location.toString()
  return sLocation.substr(0, sLocation.indexOf(document.location.pathname))
}
function getPageLocationRoot() {
  var sLocation = document.location.toString()
  var i = sLocation.indexOf('?');
  i = (i==-1) ? sLocation.length : i;
  return sLocation.substr(0, i)
}

/*******
******** ECOM 
*******************************************************/

function wr(s)
{
  document.write(s);
}
function writeVariantNyhedTilbudHTML(sNyhedTrueFalse, sTilbudTrueFalse) {
  writeVariantNyhedTilbudHTMLWithSrc(sNyhedTrueFalse, sTilbudTrueFalse, 'nyhed_list.gif', 'tilbud_list.gif')
}
function writeVariantNyhedTilbudHTMLWithSrc(sNyhedTrueFalse, sTilbudTrueFalse, sNyhedSrc, sTilbudSrc) {
  sNyhedTrueFalse = (sNyhedTrueFalse=='' || typeof(sNyhedTrueFalse)=='undefined') ? 'False' : sNyhedTrueFalse;
  sTilbudTrueFalse = (sTilbudTrueFalse=='' || typeof(sTilbudTrueFalse)=='undefined') ? 'False' : sTilbudTrueFalse;
  wr('<div class="gruppe_nyhedTilbudContainer">');
  wr('<img class="gruppe_nyhed'+sNyhedTrueFalse+'" src="/files/filer/grafik/'+sNyhedSrc+'" border="0" title=""/>');
  wr('<img class="gruppe_tilbud'+sTilbudTrueFalse+'" src="/files/filer/grafik/'+sTilbudSrc+'" border="0" title=""/>');
  wr('</div>');
}

function getVariantURL(sVariantCombination)
{
		var sLocation = document.location+'';
		var sURL = sLocation.substr(0, sLocation.indexOf('?')+1);
		var oTemp = sLocation.toQueryParams();
		oTemp.VariantID = sVariantCombination;
		var oQuerParams = $H(oTemp);
		return sURL+oQuerParams.toQueryString()
}

function doBasketCommand(sCommand, oArguments)
{
		var sLocation = 'default.aspx?id='+sDwPageID+'&purge=true';
		sCommand = sCommand.toLowerCase();
		
		if (sCommand=='emptycart')
		{
				sLocation+='&CartCmd='+sCommand;
		}
		if (sCommand=='delorderline')
		{
				sLocation+='&CartCmd=delorderline';
				sLocation+='&key='+oArguments.key;
		}
		if (sCommand=='setquantity')
		{
				if (parseInt(oArguments.quantity)==0)
				{
						doBasketCommand('delorderline', {'key':oArguments.keyShort});
						return true;
				} else {
						sLocation+='&CartCmd=updateorderlines';
						sLocation+='&'+oArguments.key+'='+oArguments.quantity;
				}
		}
		document.location = sLocation;
}

function toemKurv()
{
  if (confirm('Er du sikker p\u00e5 at du \u00f8nsker at slette alle varer?'))
  {
		doBasketCommand('emptycart');
	}
}

function opdaterAntal(sOrderLineID)
{
  var oOrderLineAntal = $(sOrderLineID);
  var iAntal = parseInt(oOrderLineAntal.value);
  var sKey   = sOrderLineID;
  var sKeyShort = oOrderLineAntal.keyShort;
  doBasketCommand('setquantity', {'quantity':iAntal, 'key':sKey, 'keyShort':sKeyShort});
}

/* FORMULAR DATA CHECK -------------------------------------  START */
var OnlyDigits = {
  generic: function(event) {
    this.action(Event.element(event));
  },
  action: function(oElement) {
    oElement.value = oElement.value.replace(new RegExp('[^0-9]', 'ig'), '');
  },
  isValid: function(oElement) {
    this.action(oElement);
    alert(oElement.maxSize)
    return (oElement.value!='');
  },
  isValidString: function(sString) {
    return (sString.replace(new RegExp('[^0-9]', 'ig'), '')!='');
  }
};


var SubmitForm = {
  generic: function(event) {
  
    if (!checkFormData(true))
    {
      Event.stop(event);
    }
  }
};

function checkFormData(bFormIsOnThisPage, oFormData)
{
    var oElement = '';
    var oForm;
    if (bFormIsOnThisPage)
    {
      oForm = getFormFields();
      for(var i=0; i<oForm.fieldNames.length; i++)
      {
        $(oForm.fieldNames[i]).removeClassName('formularFejl');
      }
    } else
    {
      oForm = oFormData;
    }
    var oResult = checkIfFormDataIsValid(oForm);
    if (bFormIsOnThisPage)
    {
      for(var i=0; i<oResult.notValidFields.length; i++)
      {
        $(oResult.notValidFields[i]).addClassName('formularFejl');
        if (oElement=='') oElement = $(oResult.notValidFields[i]);
      }
    }
    if (oResult.notValidFields.length>0)
    {
      if (bFormIsOnThisPage)
      {
        alert('Formularen er ikke udfyldt korrekt')
        oElement.focus(); 
      }
      return false;
    } else {
      if (!oResult.emailsEqual)
      {
        if (bFormIsOnThisPage)
        {
          $('EcomOrderCustomerEmail').addClassName('formularFejl');
          $('EmailRepeat').addClassName('formularFejl');
          alert('De to e-mail adresser skal v\u00e6re ens');
        }
        return false
      } else
      {
        return true;
      }
    }
}

function getFormFields()
{
  var oForm = {};
  oForm.fieldNames = [];
  var aFields = ['EcomOrderCustomerName', 'EcomOrderCustomerAddress', 'EcomOrderCustomerZip', 'EcomOrderCustomerCity', 'EcomOrderCustomerPhone', 'EcomOrderCustomerEmail'];
  for(var i=0; i<aFields.length; i++)
  {
    oForm[aFields[i]] = $(aFields[i]).value;
    oForm.fieldNames[i] = aFields[i];
  }
  return oForm;
}
function checkIfFormDataIsValid(oForm)
{
    var aNotValid = [];
    var oElement = '';
    var sFejlInfo = 'Formularen er ikke udfyldt korrekt';
    
    // Skal være udfyldt:
    var aNotEmpty = ['EcomOrderCustomerName', 'EcomOrderCustomerAddress', 'EcomOrderCustomerCity'];
    for(var i=0; i<aNotEmpty.length; i++)
    {
      if (oForm[aNotEmpty[i]].strip()=='') {
        aNotValid[aNotValid.length] = aNotEmpty[i];
      }
    }
    
    // Skal være valid e-mail
    var aValidEmail = ['EcomOrderCustomerEmail'];
    for(var i=0; i<aValidEmail.length; i++)
    {
      if (!validEmail(oForm[aValidEmail[i]].strip())) {
        aNotValid[aNotValid.length] = aValidEmail[i];
      }
    }

    // Skal være cifre:
    var aDigits = ['EcomOrderCustomerPhone', 'EcomOrderCustomerZip'];
    for(var i=0; i<aDigits.length; i++)
    {
      var o = $(aDigits[i]);
      
      if (!OnlyDigits.isValidString(oForm[aDigits[i]]) || o.value.length!=o.maxLength) {
        aNotValid[aNotValid.length] = aDigits[i];
      }
    }
    
    return {'notValidFields':aNotValid, 'emailsEqual':true}
}

function validEmail(sEmail) {
     var oRegExp = new RegExp("^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$", 'ig');
     return oRegExp.test(sEmail);
}

function getDemaskedEMail(sEmail)
{
  if (sEmail.substr(0, 2)=='&#' && sEmail.substr(sEmail.length-1, 1)==';')
  {
    sEmail = ';'+sEmail+'&#';
    sEmail = sEmail.split(';&#');
    var ss = '';
    for(var i=0; i<sEmail.length; i++)
    {
      if (sEmail[i]!='') {
        ss+=String.fromCharCode(sEmail[i])
      }
    }
    sEmail = ss;
  }
  return sEmail;
}

/* FORMULAR DATA CHECK -------------------------------------  SLUT */

var oRegExp_LF = new RegExp('\n', 'ig');

function changeColorForLeftMenu()
{
  /* STH: 21/1-2008
     Sætter baggrundsfarven på venstre menuen hvis det er en underside og der 
     er en meta tag der hedder: "venstreMenuBaggrundsFarve". Den sættes på siden
     i backend under Meta.
  */
  return;
  try {
    var oUnderMenu = $('UnderMenu');
    if (oUnderMenu)
    {
      var aVenstreMenuBaggrundsFarve = getMetaData('venstreMenuBaggrundsFarve');
      
      if (aVenstreMenuBaggrundsFarve.length>0)
      {
        oUnderMenu.style.backgroundColor = aVenstreMenuBaggrundsFarve[0].replace(oRegExp_LF, '');
      }
    }
  } catch(e) {
    alert('\nError in changeColorForLeftMenu(): '+e.message);
  }
}

function hasVariants(sEcom_Product_VariantCount, aVariants) {
 var iVariantCount = parseInt(sEcom_Product_VariantCount);
 var bHasVariants = (iVariantCount>0) ? true : false;
 
 // HACK - handles case where sEcom_Product_VariantCount is not correct
  var iHackVariantCount = 0;
  if (aVariants) {
    for(a in aVariants) {
      if (a!='VariantID') {
       iHackVariantCount++;
      }
    }
    bHasVariants = (iHackVariantCount!=iVariantCount) ? (iHackVariantCount>0) : bHasVariants;
  }
 
 return bHasVariants;
}

function getVariantCount(sEcom_Product_VariantCount, aVariants) {
 var iVariantCount = parseInt(sEcom_Product_VariantCount);
 
 // HACK - handles case where sEcom_Product_VariantCount is not correct
  var iHackVariantCount = 0;
  if (aVariants) {
    for(a in aVariants) {
      if (a!='VariantID') {
       iHackVariantCount++;
      }
    }
    iVariantCount = (iHackVariantCount!=iVariantCount) ? iHackVariantCount : iVariantCount;
  }
 
 return iVariantCount;
}

function formatPrice(sPrice) {
  sPrice = (sPrice+'').strip();
  if (sPrice.length==0) return '';
  
  var sDecimal = parseFloat(sPrice.replace(',', '.')).toFixed(2).replace('.', ',');
  sDecimal = sDecimal.substr(sDecimal.indexOf(','), 3);
  var temp = addCommas(sPrice);
  return temp.substr(0, (temp.indexOf(',')>-1) ? temp.indexOf(',') : temp.length)+sDecimal;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}
function showObject(o)
{
  var s = '';
  for(a in o)
  {
    s+=a+'="';
    try
    {
      s+=eval('o.'+a)+'"'
    } catch(e) {
      s+='"'
    }
    s+=', ';
  }
  alert(s);
}

function udskrivDenneSide(sTemplate) {
  var oWin = window.open(document.location+'&template='+sTemplate);
  return oWin;
}							
function visDesigner(sId)
{
  try {
    var sId = (typeof(sId)!='undefined') ? sId : '303'
    showDesignerUsingGroupId(sId, $('produkt_designThumb').getAttribute('designerGroupID'))
  } catch(e) {
    alert('visDesigner('+sId+'): '+e.message);
  }
}
function showDesignerUsingGroupId(sId, groupId)
{
  try {
    var sId = (typeof(sId)!='undefined') ? sId : '303'
	  document.location = 'Default.aspx?id='+sId+'&purge=true&GroupID='+groupId
	} catch(e) {
    alert('showDesignerUsingGroupId('+sId+', '+groupId+'): '+e.message);
  }
}

var oFormatPriceToDk = new RegExp('\\x2e', 'ig');
function writePriceWithoutVAT(sTotalWithoutSymbol, sVat)
{
  var sPrice = '';
  var fTotalPriceInclVAT = parseFloat(sTotalWithoutSymbol.replace(oFormatPriceToDk, ''));
  var fVAT = parseFloat(sVat.replace(oFormatPriceToDk, ''));
  document.write('<div class="todo" title="Ikke 100% f&aelig;rdigt!" style="display: inline;">'+formatPrice(fTotalPriceInclVAT-fVAT)+'</div>');
}

function eComPriceToFloat(sFormattedPrice, sCommaSeperator, sThousandSeperator)
{
  return parseFloat(sFormattedPrice.replace(oFormatPriceToDk, ''))
}

function clickElement(oElement) {
  if (typeof(oElement.dispatchEvent)!='undefined') {
    var clickevent=document.createEvent("MouseEvents")
    clickevent.initEvent("click", true, true)
    oElement.dispatchEvent(clickevent);
  } else {
    if (typeof(oElement.fireEvent)!='undefined') {
      oElement.fireEvent('onclick');
    }
  }
}
function getHost() {
    var url = '' + window.location;
    var end = url.indexOf('/',7);
    var host = url.substring(0,end);
    return host;
}

/*
 * Cookie functions START ------------------- 
 */
/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
/*
 * Cookie functions END ------------------- 
 */

// STH: 2008-04-16: Visning af pris i flere valuta
var iYear = 1000*60*60*24*365;
var bShowPrice_disabled = false;
function showPrice(sId, sPrice, sValuta, e) {
  var oPriceElement = $('price'+sId);
  var oAHrefElement = Event.element(e);
  var sSymbol = getValutaSymbolFromValuta(sValuta);
  if (sPrice!='') {
    oPriceElement.innerHTML = '<span style="float: left;">'+sSymbol+'</span><div class="ProductPriceList">'+sPrice+'</div>'
  }
  if (!bShowPrice_disabled) {
    var oOneYearFromNow = new Date(new Date().getFullYear()+1, new Date().getMonth(), new Date().getDate())
    setCookie('currentValuta', sValuta, oOneYearFromNow)
    selectValutaFromCookie();
  }
}

function selectValutaFromCookie() {
  var sValuta = getCookie('currentValuta');
  if (sValuta!='') {
    try {
      document.getElementsByClassName('currentValuta').each(function(o) {
        o.removeClassName('currentValuta');
      });
    } catch(e) {
    }

    bShowPrice_disabled = true;
    try {
      document.getElementsByClassName(sValuta).each(function(o) {
        o.addClassName('currentValuta');
        clickElement(o);
      });
    } catch(e) {
    }
    bShowPrice_disabled = false;
  }
}

function getValutaSymbolFromValuta(sValuta) {
  var sSymbol = '';
  switch (sValuta)
  {
    case 'USD':
    sSymbol = '$';
    break;
    case 'EUR':
    sSymbol = '\u20ac';
    break;
    case 'GBP':
    sSymbol = '\u00a3';
    break;
    case 'DKR':
    sSymbol = 'kr';
    break;
    case 'NOK':
    sSymbol = 'NOK';
    break;
    case 'SEK':
    sSymbol = 'SEK';
    break;
  }
  return sSymbol;
}


function getValutaSymbolFromCookie(sDefault) {
  var sValuta = getCookie('currentValuta')
  var bValutaEnabled = oEnabledValutaes[getCookie('currentValuta')]
  return (sValuta=='' || !bValutaEnabled) ? sDefault : getValutaSymbolFromValuta(sValuta)
}

function getPriceUsingCookie(sDefaultPrice, sUSD, sEUR, sSEK) {
  var sPrice = sDefaultPrice;
  var sValuta = getCookie('currentValuta');
  var bValutaEnabled = oEnabledValutaes[getCookie('currentValuta')]
  if (sValuta=='' || !bValutaEnabled)
  {
  } else {
    switch (sValuta)
    {
      case 'USD':
      sPrice = sUSD;
      break;
      case 'EUR':
      sPrice = sEUR;
      break;
      case 'SEK':
      sPrice = sSEK;
      break;
    }
  }
  sPrice = (sPrice.indexOf(',')>-1) ? sPrice : formatPrice(sPrice);
  return sPrice;
}

var oEnabledValutaes = {};

