/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}
function ShowInfo(popupInfo,e,position)
{
        var x = 0;
        var y = 0;

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }

        //alert("position "+position);
        if(position=="left")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 210;
          popupInfo.style.top = y - 60;
        }
        else if(position=="right")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x + 10;
          popupInfo.style.top = y - 60;
        }
        else if(position=="over")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 160;
          popupInfo.style.top = y - 170;
        }
        else if(position=="under")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 180;
          popupInfo.style.top = y + 25;
        }
        else
        {
          //alert("no pos "+position);
          popupInfo.style.display="block";
          popupInfo.style.left = x - 180;
          popupInfo.style.top = y - 180;
        }
}
function HideInfo(popupInfo,e){
        popupInfo.style.display="none";
}


function js_submit_amount(prod_id, amount, e) //kunna trycka enter när man vill ändra antal
{
 if (e.keyCode == 13) //enter har tryckts ner
 {
   ajaxAddProduct(prod_id, amount);
 }
}




var xmlHttp;
var xmlHttp2;
var div_name='';
var div_name2='';

function stateChanged()
{
 //alert(xmlHttp.readyState+" "+xmlHttp.readyState+" "+div_name)
 if ((xmlHttp.readyState==4 || xmlHttp.readyState=="complete") && div_name!='')
 {
   document.getElementById(div_name).innerHTML=xmlHttp.responseText;
 }
}
function stateChanged2()
{
 //alert(xmlHttp.readyState+" "+xmlHttp.readyState+" "+div_name)
 if ((xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") && div_name2!='')
 {
   document.getElementById(div_name2).innerHTML=xmlHttp2.responseText;
 }
}

function GetXmlHttpObject()
{
 var objXMLHttp=null;

 if (window.XMLHttpRequest)
 {
   objXMLHttp=new XMLHttpRequest();
 }
 else if (window.ActiveXObject)
 {
   objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return objXMLHttp;
}

function update_prod_holder(prod_holder, prod_id)
{
 xmlHttp=GetXmlHttpObject()
 div_name=prod_holder;
 if (xmlHttp==null)
 {
   //alert ("Browser does not support HTTP Request")
   return
 }
 var url="aj_update_prodholder.php";
 url=url+"?prod_id=" + prod_id;

 //alert (url + ' ' + div_name);


 xmlHttp.onreadystatechange=stateChanged;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
 //div_name='';
}

function update_tillbehor_holder(tillbehor_holder, prod_id)
{
 xmlHttp2=GetXmlHttpObject()
 div_name2=tillbehor_holder;
 if (xmlHttp2==null)
 {
   //alert ("Browser does not support HTTP Request")
   return
 }
 var url="aj_update_tillbehorholder.php";
 url=url+"?prod_id=" + prod_id;

 //alert (url + ' ' + div_name);


 xmlHttp2.onreadystatechange=stateChanged2;
 xmlHttp2.open("GET",url,true);
 xmlHttp2.send(null);
 //div_name='';
}

          function getexpirydate( nodays){
          var UTCstring;
          Today = new Date();
          nomilli=Date.parse(Today);
          Today.setTime(nomilli+nodays*24*60*60*100);
          UTCstring = Today.toUTCString();
          return UTCstring;
          }

          function getcookie(cookiename) {
           var cookiestring=""+document.cookie;
           var index1=cookiestring.indexOf(cookiename);
           if (index1==-1 || cookiename=="") return "";
           var index2=cookiestring.indexOf(';',index1);
           if (index2==-1) index2=cookiestring.length;
           return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
          }

          function setcookie(name,value,duration){
          cookiestring=name+"="+escape(value)+";EXPIRES="+getexpirydate(duration*1);
          document.cookie=cookiestring;
          if(!getcookie(name)){
          return false;
          }
          else{
          return true;
          }
          }

          function show_rowcolor(elementid)
          {
            gbfamrow='#F4F3F3';

             document.getElementById(elementid).style.background = '#DDDDDD';
             //document.getElementById('mycellid').style.background=bg[i];
          }
          function hide_rowcolor(elementid)
          {
            document.getElementById(elementid).style.background = '';
          }


          function MM_swapImgRestore() { //v3.0
            var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
          }

          function MM_preloadImages() { //v3.0
            var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
              var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
              if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
          }

          function MM_findObj(n, d) { //v4.01
            var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
              d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
            if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
            for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
            if(!x && d.getElementById) x=d.getElementById(n); return x;
          }

          function MM_swapImage() { //v3.0
            var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
             if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
          }






var url_addProductToBasket = 'aj_add_to_cart.php';
var url_removeProductFromBasket = 'remove_from_cart.php';
var txt_totalPrice = 'Total: ';

var ajaxObjects = new Array();

function showAjaxBasketContent(ajaxIndex,amount)
{
        if(amount<1)
        {
         amount=1;
        }

        // referens till varukorgstabellen
        var itemBox = document.getElementById('shopping_cart_items');

        var productItems = ajaxObjects[ajaxIndex].response.split('|||');        // explode ajaxresultatet

        if(document.getElementById('shopping_cart_items_product' + productItems[0]))   // Produkt_id finns redan i varukorgen - plussa på
        {
                var row = document.getElementById('shopping_cart_items_product' + productItems[0]);
                var items = row.cells[0].innerHTML /1;
                items = parseInt(items) + parseInt(amount);
                row.cells[0].innerHTML = items;
        }
        else    // Produkten finns inte i varukorgen, lägg till
        {

                var tr = itemBox.insertRow(-1);
                tr.id = 'shopping_cart_items_product' + productItems[0];
                tr.style.height ='23px';

                var td = tr.insertCell(-1);
                td.innerHTML = amount;         // Antal

                var td = tr.insertCell(-1);
                td.innerHTML = 'x';         // x

                var td = tr.insertCell(-1);
                td.innerHTML = "<a href='products-a-oe.php?id="+productItems[0]+"' class='text_9_verd'>"+productItems[1]+"</a>";         // Namn

                var td = tr.insertCell(-1);
                td.innerHTML = '';         // tomt

                var td = tr.insertCell(-1);
                var a = document.createElement('A');
                td.appendChild(a);
                a.href = '#';
                a.onclick = function(){ removeProductFromBasket(productItems[0]); };
                var img = document.createElement('IMG');
                img.src = 'simg/remove_item_btn.png';
                img.width = "10";
                img.height = "15";
                img.border = "0";
                a.appendChild(img);

                var td = tr.insertCell(-1);
                td.style.textAlign = 'right';
                td.style.display = 'none';
                td.innerHTML = productItems[2];         // Pris

        }


        updateTotalPrice();

        ajaxObjects[ajaxIndex] = false;

        window.setTimeout('hide_cart_progress()',400);

}

function updateTotalPrice()
{
   var itemBox = document.getElementById('shopping_cart_items');
   // Calculating total price and showing it below the table with basket items
   var totalPrice = 0;
   if(document.getElementById('shopping_cart_totalprice'))
   {
      for(var no=0;no<itemBox.rows.length;no++)                                                  //   document.getElementById('cart_price_holder-'+no).value
      {
         totalPrice = totalPrice + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g) * itemBox.rows[no].cells[5].innerHTML);
      }
      document.getElementById('shopping_cart_totalprice').innerHTML = '<b>'+txt_totalPrice + totalPrice.toFixed(2) + '</b>';
   }

}

function removeProductFromBasket(productId)
{
        var productRow = document.getElementById('shopping_cart_items_product' + productId);

        var numberOfItemCell = productRow.cells[0];
        if(numberOfItemCell.innerHTML == '1')
        {
          productRow.parentNode.removeChild(productRow);
        }
        else
        {
          numberOfItemCell.innerHTML = numberOfItemCell.innerHTML/1 - 1;
        }
        updateTotalPrice();
        ajaxRemoveProduct(productId);
}

function ajaxValidateRemovedProduct(ajaxIndex)
{
  if(ajaxObjects[ajaxIndex].response!='OK')alert('Error while removing product from the database');
}

function ajaxRemoveProduct(productId)
{
        var ajaxIndex = ajaxObjects.length;
        ajaxObjects[ajaxIndex] = new sack();
        ajaxObjects[ajaxIndex].requestFile = url_removeProductFromBasket + '?prod_id=' + productId;        // Saving product in this file
        ajaxObjects[ajaxIndex].onCompletion = function(){ ajaxValidateRemovedProduct(ajaxIndex); };        // Specify function that will be executed after file has been found
        ajaxObjects[ajaxIndex].runAJAX();                // Execute AJAX function
}

function ajaxAddProduct(productId,amount)
{
        var ajaxIndex = ajaxObjects.length;
        ajaxObjects[ajaxIndex] = new sack();
        ajaxObjects[ajaxIndex].requestFile = url_addProductToBasket + '?prod_id=' + productId + '&amount=' + amount;        // Saving product in this file
        ajaxObjects[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex, amount); };        // Specify function that will be executed after file has been found
        ajaxObjects[ajaxIndex].runAJAX();                // Execute AJAX function
}


function showSearch(str,click)
{
 if(click=='yes')
 {
  if(str.length<2)
  {
    //alert (str.length+' '+click);
    //document.getElementById("txtHint").innerHTML="";
    return
  }
 }
 else
 {
  if(str.length<8)
  {
    //alert (str.length+' '+click);
    //document.getElementById("txtHint").innerHTML=""
    return
  }
 }

 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
 {
   alert ("Browser does not support HTTP Request")
   return
 }
 var url="aj_products_landscape.php"
 url=url+"?search="+str
 xmlHttp.onreadystatechange=show_search_result
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
}


function show_search_result()
{
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("main_holder").innerHTML=xmlHttp.responseText
 }
}








function Search_Clear(element)
{
  if (element.value.indexOf("Sökord") == 0)
  {
     element.value = "";
  }
}

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

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( name ) {

var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) &&
( name != document.cookie.substring( 0, name.length ) ) )
{
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}

function highlight_row(row, type) {
        if (type == 'off') {
           row.bgColor = '';
        }
        else if (type == 'on') {
           row.bgColor = '#E3E3E3';
        }
}
function highlight_row_under(row, type) {
        if (type == 'off') {
           row.bgColor = '';
        }
        else if (type == 'on') {
           row.bgColor = '#DFF4FA';
        }
}
function highlight_row_prod(row, type, row_number) {
        if (type == 'off') {
           if (row_number%2)
           {
             row.bgColor = '';
           }
           else
           {
            row.bgColor = '#EEEEEE';
           }
        }
        else if (type == 'on') {
           row.bgColor = '#DFF4FA';
        }
}


function show_cart_progress(e)
{
   var x = 0;
   var y = 0;
   //var e = arguments[0];

   var show_div = document.getElementById("cart_progress");

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }

        //popupInfo.style.display="block";



   show_div.style.display = "block";
   show_div.style.left = x - 94;
   show_div.style.top = y + 24;
}
function hide_cart_progress()
{
   var hide_div = document.getElementById("cart_progress");
   hide_div.style.display = "none";
}

function show_click_here(e)
{
   var x = 0;
   var y = 0;
   //var e = arguments[0];

   var show_div = document.getElementById("click_here");

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }

        //popupInfo.style.display="block";



   show_div.style.display = "block";
   show_div.style.left = x + 15;
   show_div.style.top = y - 4;
}
function hide_click_here()
{
   var hide_div = document.getElementById("click_here");
   hide_div.style.display = "none";
}

function update_group_id_holder(tgroup_id, tstype, tsearch, limit, filter, sort, tpage)
{
 xmlHttp=GetXmlHttpObject()
 div_name="group_id_holder_"+tgroup_id;
 if (xmlHttp==null)
 {
   //alert ("Browser does not support HTTP Request")
   return
 }
 var url="aj_products_landscape_type.php";
 url=url+"?tgroup_id=" + tgroup_id + "&tstype=" + tstype + "&tsearch=" + tsearch + '&tlimit=' + limit + '&tfilter=' + filter + '&tsort=' + sort + '&tpage=' + tpage;

 //alert (url + ' ' + div_name);


 xmlHttp.onreadystatechange=stateChanged;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
 //div_name='';
}// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
// Modifications: K.Bra


var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread


// Trim leading/trailing whitespace off string
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};



// Delayed focus setting to get around IE bug
function setFocusDelayed(vfld)
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message))
    dispmessage = String.fromCharCode(nbsp);
  else
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;

  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed),
//         false (validation failed) or
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById)
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "fel");
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "ok");   // OK
      return true;
    }
  }
  return proceed;
}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", "ok");
  return true;
};


// -----------------------------------------
//            validateLevAdress
// Validate if something has been entered
// Returns true if so
// -----------------------------------------

function validateLevAdress(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;

  if(vfld.value.indexOf('box ')>-1 || vfld.value.indexOf('Box ')>-1 || vfld.value.indexOf('BOX ')>-1)
  {
     msg (ifld, "error", "ej box");
     return false;
  }
  else
  {
     msg (ifld, "warn", "ok");
     return true;
  }
};


// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "ej giltig E-post");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld))
  {
    msg (ifld, "warn", "ok");
    return true;
  }
  else
    msg (ifld, "warn", "ok");
  return true;
};


// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "siffror, () eller +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<5) {
    msg (ifld, "error", "" + numdigits + " siffror verkar lite kort?");
    setfocus(vfld);
    return false;
  }

  if (numdigits>15)
    msg (ifld, "warn", numdigits + " siffror, ok?");
  else {
    if (numdigits<10)
      msg (ifld, "warn", "" + numdigits + " siffror, ok");
    else
      msg (ifld, "warn", "ok");
  }
  return true;
};

// -----------------------------------------
//            validateNumber
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------
function validateNumber (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "fel");
    setfocus(vfld);
    return false;
  }


    msg (ifld, "warn", "ok");

  return true;
};

$(document).ready(function()
{
  
});

