function FilterArticleRows(id){
  if (!id) {
      id = "";
  }
  var manufacturerItems;
  var supfiltervalue = $('SupplierFilter'+id).value;
  var posfiltervalue = $('PositionFilter'+id).value;
  var rowitem, classNames, j, i, show;

  var positionfiltersetting = $$('input[name=PositionFilterSetting]');
  for (i=0; i < positionfiltersetting.length; i++) {
      positionfiltersetting[i].value = posfiltervalue;
  }

  if (id != "") {
      manufacturerItems = $$('#'+id+' input[name=RowManufacturer]');
  } else {
      manufacturerItems = $$('input[name=RowManufacturer]');
  }

  if  (posfiltervalue == 'All'){
    for (i=0; i < manufacturerItems.length; i++){
       rowitem = manufacturerItems[i].parentNode.parentNode;
       if ((manufacturerItems[i].value == supfiltervalue) ||  supfiltervalue == ''){
	     rowitem.style.display = '';
	   } else {
	     rowitem.style.display = 'none';
	   }
	}
  } else {
    for (i=0; i < manufacturerItems.length; i++){
       rowitem = manufacturerItems[i].parentNode.parentNode;

       show = false;
       classNames = rowitem.className.split(" ");
       for (j=0; j < classNames.length; j++) {
           if (classNames[j].toLowerCase() == posfiltervalue) {
               show = true;
               break;
           }
       }

       if (((manufacturerItems[i].value == supfiltervalue) ||  supfiltervalue == '') && show == true) {
           rowitem.style.display = '';
       } else {
           rowitem.style.display = 'none';
	   }

    }
  }

}

function changeCarHistoryPositionNew(floating) {
	if (!(AnotherdetectIE6())){
		if ($('CarInformationBox').style.position == 'absolute') {
			$('CarInformationBox').style.position = 'fixed';
			$('CarInfoBoxFloatImage').src = "pictures/vehicle_info_box_float2.gif";
			new Ajax.Updater('FloatInfo', 'ajax.php?PageName=switch_lock', { 
		    	parameters: {newValue: 'fixed'}
	    	});
            if($('carHistory')) {
                $('carHistory').style.position = 'fixed';
            }
		} else {
			$('CarInformationBox').style.position = 'absolute';
			$('CarInfoBoxFloatImage').src = "pictures/vehicle_info_box_nofloat2.gif";
			new Ajax.Updater('FloatInfo', 'ajax.php?PageName=switch_lock', { 
		    	parameters: {newValue: 'absolute'}
	    	});
            if($('carHistory')) {
                $('carHistory').style.position = 'absolute';
            }
		}
	}
}

function openCloseCarHistory(){
  if($('carHistory').style.display != "inline"){
	  new Ajax.Updater('carHistory', 'ajax.php?PageName=CarHistory', {parameters: { }, onComplete: function(transport) {ShowCarHistory();}});
	  
  } else {
	  if (AnotherdetectIE6()) {
		  if ($('PositionFilter')) {
			$('PositionFilter').show();
		  }
		}
    $('carHistory').style.display = "none";
    $('CarInfoVehicleHistoryImage').src = "pictures/car_info_box_icon_blue.gif";
    $('CarInfoVehicleHistoryImage').style.height='38px';
  }
}

function ShowCarHistory() {
    if($('CarInformationBox')) {
        $('carHistory').style.position = $('CarInformationBox').style.position;
    }
	if (AnotherdetectIE6()) {
		if ($('PositionFilter')) {
			$('PositionFilter').hide();
		  }
	}
    $('CarInfoVehicleHistoryImage').style.height='1px';
	$('CarInfoVehicleHistoryImage').src = "";
	$('carHistory').style.display = "inline";
	
}

function changeBackgroundColor(item, color){
  item.style.backgroundColor = color;
}

function changeClass(item, myclass){
	  $(item).className = myclass;
}

function switchClass(item, oldClass, newClass){
    $(item).addClassName(newClass);
    $(item).removeClassName(oldClass);
}

function jsSelect() {

    if ($('searchMethodSelect')) {
        if ($('searchMethodSelect').style.display == 'none') {
            $('searchMethodSelect').style.display = 'block';
        }
        else {
            $('searchMethodSelect').style.display = 'none';
            $('searchString').focus();
        }
    }
}

function changeCar($PlateNr, $VehicleID){
  
  
  var path = window.location.href.split('?');
  var url = path[0];
  
  url = url + "?PageName=checking_plate&VehicleID=" + $VehicleID + "&PlateNr=" + $PlateNr;
  
  window.location = url;
  return;
}

function removeVehicleId() {
	var get_string = document.location.search;
	var return_value = '';
	
	do { //This loop is made to catch all instances of any get variable.
		var name_index = get_string.indexOf('VehicleID=');
		   
		if(name_index != -1)
		{
			var front_string = get_string.substr(0, name_index - 1);
			var end_of_value = get_string.indexOf('&',name_index + 1);
			if(end_of_value != -1)                
				var end_string = get_string.substr(end_of_value);
			else                
				end_string = '';                
			get_string = front_string + end_string;
		}
	} while(name_index != -1)
	return(get_string);        
}

function setVehicleId() {
	var getVars = removeVehicleId();
	window.location.href =  window.location.pathname + getVars + '&VehicleID=' + $('searchString').value;
}

function SearchBoxSubmit() {
	if ($('searchMethod').value == 2){
		setVehicleId();
	}
	else {
		$('searchbox').submit();
	}
}

function MarkPreviousForGenArtAutoComp() {
	if (this.index > 0) {
		this.index--;
	} else {
		this.index = this.entryCount - 1;
	}
	this.getEntry(this.index).scrollIntoView(false);
}

var GenArtAutoComp; 
var RegPlateAutoComp;

function KeyPressForGenArtAutoComp() {
    // do nothing
}

function InitiateGenArtAutoComp(){
    
    if ($('searchString')) {
        $('searchString').setAttribute('autocomplete','off');
    }
    /*
    if ($('submitImageDiv')) {
        $('submitImageDiv').innerHTML = "<input type='image' name='submitImage' id='submitImage' src='pictures/search.gif' width='20px' class='fade'>";
    }
    */
  
  if ($('searchMethod')) {

      if ($('searchMethod').value == 1) {
          if (RegPlateAutoComp != undefined) {
            RegPlateAutoComp.disable();
          }
          if (GenArtAutoComp != undefined) {
              GenArtAutoComp.enable();
          } else {
              GenArtAutoComp = new Ajax.ToggleableAutocompleter("searchString", "searchStringChoices", "ajax/generic_article_search.php", {
              paramName: "SearchCriteria",
              onShow: UserNameAutoCompOnShow,
              minChars: 3});
              //GenArtAutoComp.markPrevious = function () { MarkPreviousForGenArtAutoComp(); };
              GenArtAutoComp.options.afterUpdateElement = function (a1, a2) {if (a2.childNodes[0].href) {window.location.href = a2.childNodes[0].href;}};
              GenArtAutoComp.markPrevious = function () {if (this.index > 0) {this.index--;} else {this.index = this.entryCount - 1;}this.getEntry(this.index).scrollIntoView(false);};
              GenArtAutoComp.enable();
          }
          

        $('searchMethod').className = 'genart_highlight';
        $('searchString').className = 'genart_highlight';
    //    $('searchStringChoices').style.display = 'inline';
        $('submitImage').disabled = true;
        $('searchString').setAttribute('autocomplete','off');
        
        $('searchStringChoices').style.border = 'solid thin #888888';
        if (detectIE()) {
            $('searchStringChoices').style.position = 'relative';
            $('searchStringChoices').style.left = '65px';
            if (AnotherdetectIE6()) {
                $('searchStringChoices').style.top = '1px';
            } else {
                $('searchStringChoices').style.top = '24px';
            }
        }

      } else if ($('searchMethod').value == 4) {
         $('submitImage').disabled = false;
         $('searchMethod').className = 'enginecodesearch_hilight';
         $('searchString').className = 'enginecodesearch_hilight';
         if (GenArtAutoComp != undefined) {
             GenArtAutoComp.disable();
         }
         if (RegPlateAutoComp != undefined) {
            RegPlateAutoComp.disable();
         }
         if ($('searchStringChoices').visible()) {
             $('searchStringChoices').hide();
         }
      } else if ($('searchMethod').value == 5) {
          $('submitImage').disabled = false;
          $('searchMethod').className = 'chassisnrsearch_hilight';
          $('searchString').className = 'chassisnrsearch_hilight';
          if (GenArtAutoComp != undefined) {
             GenArtAutoComp.disable();
          }
          if (RegPlateAutoComp != undefined) {
              RegPlateAutoComp.disable();
          }
          if ($('searchStringChoices').visible()) {
              $('searchStringChoices').hide();
          }
      } else {
          if ($('submitImage')) {
              $('submitImage').disabled = false;
          }
          if ($('searchMethod')) {
              $('searchMethod').className = 'genart';
          }
          if ($('searchString')) {
              $('searchString').className = 'genart';
          }

         if (GenArtAutoComp != undefined) {
            GenArtAutoComp.disable();
         }
         if (RegPlateAutoComp != undefined) {
            RegPlateAutoComp.disable();
         }

         if ($('searchMethod').value == 2){
             //var getVars = removeVehicleId();
             $('submitImageDiv').innerHTML = "<img width='20px' src='pictures/search.gif' class='fade' onclick=\"SearchBoxSubmit();\">";
         }
      }

      if ($('searchMethod').value == 0) {

          if ($('searchString')) {
              $('searchString').addClassName('uppercase');
          }
        
          if ($('searchCountry')) {
              if ($('searchCountry').value == 1) {
                  if (GenArtAutoComp != undefined) {
                      GenArtAutoComp.disable();
                  }
                  if (RegPlateAutoComp != undefined) {
                      RegPlateAutoComp.enable();

                  } else {
                      RegPlateAutoComp = new Ajax.ToggleableAutocompleter("searchString", "searchStringChoices", "ajax.php?PageName=regplate_check", {
                                                              paramName: "SearchCriteria",
                                                              onShow: UserNameAutoCompOnShow,
                                                              minChars: 1}
                                                            );
                      RegPlateAutoComp.onKeyPress = KeyPressForGenArtAutoComp;
                      RegPlateAutoComp.hasFocus = false;
                      RegPlateAutoComp.updateElement = KeyPressForGenArtAutoComp;
                      RegPlateAutoComp.selectEntry = KeyPressForGenArtAutoComp;
                      RegPlateAutoComp.onBlur = KeyPressForGenArtAutoComp;
                      RegPlateAutoComp.enable();
                  }
                  
                  
                    
                  if ($('searchStringChoices')) {
                      $('searchStringChoices').style.border = 'none';
                      if (detectIE()) {
                        $('searchStringChoices').style.position = 'relative';
                        $('searchStringChoices').style.left = '65px';
                        if (AnotherdetectIE6()) {
                            $('searchStringChoices').style.top = '1px';
                            $('searchStringChoices').style.display = 'inline';
                              $('searchStringChoices').style.width = '250px';
                              $('searchStringChoices').style.border = 'none';
                              $('searchStringChoices').style.position = 'relative';
                              $('searchStringChoices').style.left = '65px';
                        }else {
                            $('searchStringChoices').style.top = '24px';
                        }
                      }
                  }

                  if ($('searchString')) {
                      $('searchString').setAttribute('autocomplete','on');
                      //$('searchString').focus();
                  }


              }
          }

      } else {
          if ($('searchString')) {
              $('searchString').removeClassName('uppercase');
          }
      }

  }
    
}

function checkIfEnter(e){
     var key;
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox
     if (key == 13){ //enter key
         return true;
     } else { //other key
         return false;
     }
}

function checkIfCanPostRegPlateWhenEnter(e){
     var key;  
     if(window.event) {
         key = window.event.keyCode; //IE
     } else {
         key = e.which; //firefox
     }

     if (key != 13){
       return true;
     } else if ($('searchMethod').value == 0){
        return true;
     } else if ($('searchMethod').value == 1){
       if ($('searchString').value == ""){
    	   setSearchMethod2(0);
       }
       return false;
     } else if ($('searchMethod').value == 2){
    	 setVehicleId();
    	 return false;
     }else if ((key != 13) || ($('searchMethod').value == 3) ){
    	 return true;
     } else if ($('searchMethod').value == 4 || $('searchMethod').value == 5 || $('searchMethod').value == 6) {
         return true;
     }
     return false;
}

function validateInput() {
         if ($('searchMethod').value == 0){
             var patt=/^[A-Z|a-z|Å|å|Ä|ä|Ö|ö]{3}[ ]*\d{3}$/;
             var patt2=/^[^1]/;
             if (patt.test($('searchString').value) || patt2.test($('searchCountry').value)) {
                return true;
             }
             /*
             //changeBackgroundColor($('searchString'),'red');
             test = $('searchStringSubmit').parentNode;
             newDiv = document.createElement('div');
             newDiv.setAttribute('id','searchErrorText');
             newDiv.setAttribute('style','color:red;background-color:white;position:absolute;top:42px;font-size:8pt;');
             var txtNode = document.createTextNode('Registreringsnummret skall alltid var tre bokstäver följt av tre siffror, t.ex. "ABC123".');
             test.appendChild(newDiv);
             newDiv.appendChild(txtNode);
        */
             return false;
         }else {
            return true;
         }
}

function setSearchMethodsClassName(i) {
	switch(i)
	{
	case 1:
        if ($('searchMethods')) {
            $('searchMethods').className = '';
            $('searchMethods').addClassName('genart_highlight');
        }
		break;
	case 4:
		$('searchMethods').className = '';
		$('searchMethods').addClassName('enginecodesearch_hilight');
		break;
	case 5:
		$('searchMethods').className = '';
		$('searchMethods').addClassName('chassisnrsearch_hilight');
		break;
	default:
        if ($('searchMethods')) {
            $('searchMethods').className = '';
            $('searchMethods').addClassName('genart');
        }
	}
}

function setSearchMethod2(i) {
    var elem;
    
	for (var j=0;j<=6;j++){
		if (i!=j){
			elem = 'searchMethod_' + j;
			if ($(elem)){
				$(elem).style.display = 'none';
			}
		}
	}
	elem = 'searchMethod_' + i;
	if ($(elem)){
        $(elem).style.display = 'block';
    }
	$('searchMethod').value = i;
	setSearchMethodsClassName(i);
	InitiateGenArtAutoComp();
    $('searchString').focus();
    if (i == 6){
      $('searchString').value = '';
    }
}

function setSearchMethod(i) {
	setSearchMethod2(i);
	jsSelect();
}

/* Old function copy-paste from article_browser.php */

function klis(id)
{
	var r="kte"+id;
	$(r).value++;
	kmuuta(id);
}

function kvah(id)
{
	var a = $("kte"+id).value;
	if (a > 0){
	  $("kte"+id).value = a - 1;  
	} 
	
	kmuuta(id);
}
//function kmuuta(t,ksid,ar,h,nh)
function kmuuta(t)
{
	$('koriin').src='fukor2.php?s='+$("kts"+t).value+'&tk='+$("kta"+t).value+'&yh='+$("ktn"+t).value+'&nh='+$("ktnh"+t).value+'&tkpl='+$("kte"+t).value+'&ktsaldo='+Anna("ktsaldo"+t).value;
}

function klis_til(id)
{
	var r="kte_til"+id;
	$(r).value++;
	kmuuta_til(id);
	new Ajax.Updater('FrebellCartMessage', 'ajax/cart_message.php', {parameters: {}, onComplete: function(transport) {UpdateShoppingCartInfoBox();}});
	
}

function kvah_til(id)
{
	var a=$("kte_til"+id).value;
	if (a > 0) {
	  $("kte_til"+id).value = a - 1;  
	}
	kmuuta_til(id);
	new Ajax.Updater('FrebellCartMessage', 'ajax/cart_message.php', {parameters: {}, onComplete: function(transport) {UpdateShoppingCartInfoBox();}});
}
//function kmuuta(t,ksid,ar,h,nh)
function kmuuta_til(t)
{
  var Price;
  if ($("ktn_til"+t) != null){
    Price = $("ktn_til"+t).value;
  } else {
    Price = $("ktn"+t).value
  }
	$('koriin_til').src='fukor_til2.php?s='+$("kts_til"+t).value+'&tk='+$("kta_til"+t).value+'&yh='+Price+'&nh='+$("ktnh"+t).value+'&tkpl='+$("kte_til"+t).value+'&ktsaldo='+Anna("ktsaldo"+t).value+'&ktplate='+Anna("ktplate"+t).value;
}

function sal_kys(a,s)
{
	$('saldoa_kysy').src='saldona_kysy2.php?s='+s+'&a='+a;
}

// old functions from lopusta.php

var hakuoli='------';

function checkSearchAdmin(VehId){
	if(hakuoli!=$('etsit').value)
	{
		hakuoli=$('etsit').value;
		new Ajax.Updater('valinnat', 'ajax_article_browser_linking.php', {parameters: {etsit: $('etsit').value, VehicleID:  VehId}, onComplete: function(transport) {$('valinnatr').show();}});
//		if($('etsit').value!='') $('search_result').hide();
	}
}

function AddArticle(ArticleID, ArticleName, Amount, RowType, Description, RowNumber, blockID, serviceGuideIntervalID, addOperatingSupplies){
    if (blockID>0) {
        Price = $('Price_' + blockID + '_' + RowNumber).value;
        if ($('tpu_' + blockID + '_' + RowNumber + '_quantity')) {
            $('tpu_' + blockID + '_' + RowNumber + '_quantity').value++;
        }
    }
    else {
        Price = $('Price'+RowNumber).value;
    }
	new Ajax.Updater('FrebellCartMessage', 'ajax/cart_message.php',  
		{parameters: {Action: 'AddArticle',ArticleID : ArticleID, ArticleName: ArticleName,
			Price: Price, Amount: Amount, RowType: RowType, Description: Description, ServiceGuideIntervalID: serviceGuideIntervalID, AddOperatingSupplies: addOperatingSupplies},
		 onComplete: function(transport){UpdateShoppingCartInfoBox();}});
}

function RemoveArticle(ArticleID, ArticleName ,Amount, RowType, Description, RowNumber, blockID){
    if (blockID>0) {
        Price = $('Price_' + blockID + '_' + RowNumber).value;
        if ($('tpu_' + blockID + '_' + RowNumber + '_quantity')) {
            if ($('tpu_' + blockID + '_' + RowNumber + '_quantity').value > 1) {
                $('tpu_' + blockID + '_' + RowNumber + '_quantity').value--;
            } else {
                $('tpu_' + blockID + '_' + RowNumber + '_quantity').value = 0;
            }
        }
    } else {
        Price = $('Price'+RowNumber).value;
    }
	new Ajax.Updater('FrebellCartMessage', 'ajax/cart_message.php', {
        parameters: {Action: 'RemoveArticle',ArticleID : ArticleID, ArticleName: ArticleName,
                     Price: Price, Amount: Amount, RowType: RowType, Description: Description},
		 onComplete: function(transport){
             UpdateShoppingCartInfoBox();
         }});
}

function ChangeArticleCount(ArticleID, ArticleName ,Amount, RowType, Description, RowNumber, blockID, serviceGuideIntervalID, mandatoryIncrement){
    var actualAmount;
    if ((Amount % mandatoryIncrement) > 0 ){
            actualAmount = Math.floor(Amount / mandatoryIncrement) * mandatoryIncrement + mandatoryIncrement;
    } else {
    	actualAmount = Amount;
    }
    if (blockID>0) {
        $('kte_til_' + blockID + '_' + RowNumber).value = actualAmount;
        Price = $('Price_' + blockID + '_' + RowNumber).value;
        if ($('tpu_' + blockID + '_' + RowNumber + '_quantity')) {
            $('tpu_' + blockID + '_' + RowNumber + '_quantity').value = actualAmount;
        }
    } else {
        $('kte_til' + RowNumber).value = actualAmount;
        Price = $('Price'+RowNumber).value;
    }
    new Ajax.Updater('FrebellCartMessage', 'ajax/cart_message.php',
            {parameters: {Action: 'ChangeArticleCount',ArticleID : ArticleID, ArticleName: ArticleName,
                    Price: Price, Amount: actualAmount, RowType: RowType, Description: Description, ServiceGuideIntervalID: serviceGuideIntervalID},
             onComplete: function(transport){UpdateShoppingCartInfoBox();}});
   return false; 
}

function changeServiceItemPrice(index, vat, atoy){
    var price =  new Number($("kte_mar" + index).value  * eval("serviceTime" + index));
    var priceToShoppingBasket = $("kte_mar" + index).value;
    priceToShoppingBasket = new Number(parseFloat(priceToShoppingBasket));
    price = new Number(price.toFixed());
    priceToShoppingBasket = new Number(priceToShoppingBasket.toFixed());
    price = price.toFixed(2);
    priceToShoppingBasket = priceToShoppingBasket.toFixed(2);
    if (atoy) {
        var priceNoVat = new Number(price / vat);
        var priceVat = new Number(price);
        var priceToShoppingBasketVat = new Number(priceToShoppingBasket);
    } else {
        priceNoVat = new Number(price);
        priceVat = new Number(price * vat);
        priceToShoppingBasketVat = new Number(priceToShoppingBasket * vat);
    }
    
    priceToShoppingBasketVat = new Number(priceToShoppingBasketVat.toFixed());
    priceVat = new Number(priceVat.toFixed());
    priceNoVat = new Number(priceNoVat.toFixed());
    priceToShoppingBasketVat = priceToShoppingBasketVat.toFixed(2);
    priceVat = priceVat.toFixed(2);
    priceNoVat = priceNoVat.toFixed(2);
    $("Price" + index).value = priceToShoppingBasket;
    if ($("VatPrice" + index)) {
        $("VatPrice" + index).value = priceToShoppingBasketVat;
    }
    $("VPrice" + index).innerHTML = priceVat;
    if (!atoy) {
        if ($("VNoVatPrice" + index)) {
            $("VNoVatPrice" + index).innerHTML = priceNoVat;
        }
    }
}

function changeServiceOilPrice(index, vat){
    var price =  new Number($("kte_mar" + index).value  * eval("serviceTime" + index));
    var priceToShoppingBasket = $("kte_mar" + index).value;
    priceToShoppingBasket = new Number(parseFloat(priceToShoppingBasket));
    price = new Number(price.toFixed());
    priceToShoppingBasket = new Number(priceToShoppingBasket.toFixed());
    price = price.toFixed(2);
    priceToShoppingBasket = priceToShoppingBasket.toFixed(2);
    var priceVat = new Number(price * vat);
    var priceToShoppingBasketVat = new Number(priceToShoppingBasket * vat);
    priceVat = new Number(priceVat.toFixed());
    priceToShoppingBasketVat = new Number(priceToShoppingBasketVat.toFixed());
    priceVat = priceVat.toFixed(2);
    priceToShoppingBasketVat = priceToShoppingBasketVat.toFixed(2);
    $("Price" + index).value = priceToShoppingBasket;
    if ($("VatPrice" + index)) {
        $("VatPrice" + index).value = priceToShoppingBasketVat;
    }
    $("VPrice" + index).innerHTML = price;
    if ($("VVatPrice" + index)) {
        $("VVatPrice" + index).innerHTML = priceVat;
    }
}

function ShowLoading() {
	var loading;
	loading = $('LoadingText');
	loading.style.color	 = '#fff';
	loading.style.position  = 'absolute';
	loading.style.top   = 0;
	loading.style.right	 = 0;
	loading.style.backgroundColor = '#f00';
	loading.style.border		= '1px solid #f99';
	loading.style.width		 = '80px';
	loading.style.padding	   = '4px';
	loading.style.fontFamily	= 'Arial, Helvetica, sans';
	loading.count = 0;
	loading.style.display = 'block';
}

function HideLoading() {
  $('LoadingText').style.display = 'none';
}

function Anna(id) {
  return $(id);
}

function LoadErrorReporter(Url, version){

        if ($('TemotId')) {
            var temotId = '&TemotVehicleId=' + $('TemotId').innerHTML;
        }
        else {
            temotId = '';
        }
        if (version == 3){
	   new Ajax.Updater("ErrorReporterDiv",
			   "ajax.php?PageName=error_reporter2&Technical_assistance_request=1&"+Url+temotId,
			   	{onComplete: function (transport) {
		            ShowInfoDiv("ErrorReporterDiv");
		   	    }
			   	});
        } else {
	   new Ajax.Updater("ErrorReporterDiv",
			   "ajax.php?PageName=error_reporter"+version+"&"+Url+temotId,
			   	{onComplete: function (transport) {
		            ShowInfoDiv("ErrorReporterDiv");
		   	    }
			   	});
        }
}

function ShowInfoDiv(divName){
	  $(divName).style.display = 'none';
	  if (document.body.scrollTop){
	    $(divName).style.top = document.body.scrollTop + 200 + "px";
	  } else if (window.pageYOffset) {
	    $(divName).style.top = window.pageYOffset + 200 +"px";
	  } else if (document.documentElement.scrollTop) {
	    $(divName).style.top = document.documentElement.scrollTop + 200 +"px";  
	  } else {
	    $(divName).style.top = "200px";
	  }
	  $(divName).style.display = 'inline'; 
	  	BrowserDetect.init();
		if (BrowserDetect.browser == 'Safari' && BrowserDetect.version < 4.0) {
			; // do nothing
		} else {
			new Draggable(divName, {scroll: window, zindex: 5000});

		}
}

function togglePurchaseHistory(ArticleVehicleTypeMapID, Article) {
    if($('purchaseHistory'+ArticleVehicleTypeMapID).style.display=='none') {
        if ($('SalesStatistics'+ArticleVehicleTypeMapID)) {
            $('purchaseHistory'+ArticleVehicleTypeMapID).show();
        }
        else {
            $('purchaseHistory'+ArticleVehicleTypeMapID).insert({after: "<img style='clear: left; left: 40%; position: relative;' src='pictures/loading-indicator.gif' id='articleCardLoadingIndicatorPH"+ArticleVehicleTypeMapID+"'/>"});
            var parameters = { PageName: 'GetSalesStatistics', Article: Article, ArticleVehicleTypeMapID: ArticleVehicleTypeMapID };
            new Ajax.Updater(
                'purchaseHistory'+ArticleVehicleTypeMapID,
                'ajax.php',
                { 
                    parameters: parameters, 
                    onComplete: function(response) {
                        $('articleCardLoadingIndicatorPH'+ArticleVehicleTypeMapID).remove();
                        $('purchaseHistory'+ArticleVehicleTypeMapID).show();
                    }
                }
            );
        }
    }
    else {
        $('purchaseHistory'+ArticleVehicleTypeMapID).hide();
    }	
}

function HideArticleDetaildInfoDiv(){
  ArticleDivs = $$('#ArticleDetaildInfo input[name=leave_detailed_info]');
  for (var i = 0; i < ArticleDivs.length; i++){
    if (ArticleDivs[i].checked != true){
      ArticleDiv = ArticleDivs[i].parentNode.parentNode;
      ArticleDiv.parentNode.removeChild(ArticleDiv);
    }
  }
 $('ArticleDetaildInfo').style.display = 'none';
}
 
function GetVehicleModels(sourceItem, aManufacturerID){
    BrowserDetect.init();
    if (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 8) {

    } else {

        if (sourceItem.hasClassName("vehicle_selector_selected") === false) {
            var itemarray = $('VehManufacturerSelection').getElementsByTagName("td");
            for (var i=0; i < itemarray.length; i++){
                if (itemarray[i].hasClassName("vehicle_selector_selected")) {
                    itemarray[i].removeClassName("vehicle_selector_selected");
                    break;
                }
            }
            sourceItem.addClassName("vehicle_selector_selected");
        }

    }
    
    new Ajax.Updater('VehModelSelection', 'ajax/vehicle_models_types.php', {parameters: {ManufacturerID: aManufacturerID, Action: 'Models'}, onComplete: function(transport) {}});
	new Ajax.Updater('VehTypeSelection', 'ajax/vehicle_models_types.php', {parameters: {ModelID: '', Action: ''}, onComplete: function(transport) {}});
}

function GetVehicleTypes(sourceItem, aModelID){
/*    if (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 8) {

    } else {
*/
        Element.extend(sourceItem);
        if (sourceItem.hasClassName("vehicle_selector_selected") === false) {
            var itemarray = $('vehicleSelector_models').getElementsByTagName("td");
            for (var i=0; i < itemarray.length; i++){
                var myItem = itemarray[i];
                Element.extend(myItem);
                if (myItem.hasClassName("vehicle_selector_selected")) {
                    myItem.removeClassName("vehicle_selector_selected");
                    break;
                }
            }
            sourceItem.addClassName("vehicle_selector_selected");
        }

//    }

    new Ajax.Updater('VehTypeSelection', 'ajax/vehicle_models_types.php', {parameters: {ModelID: aModelID, Action: 'Types'}, onComplete: function(transport) {}});
}

function LoadTemotBlock(BlockId, Source, VehicleID, guid, Suppliers, Service, Country, Sid) {
    new Ajax.Updater(
        'temot_articles_' + BlockId,
        'ajax.php?PageName=Temot',
        {
            parameters:
                {
                    BlockId: BlockId,
                    Source: Source,
                    VehicleID: VehicleID,
                    guid: guid,
                    Suppliers: Suppliers,
                    Service: Service
                },
            evalScripts: true,
            onComplete: function(transport) {
                if (Country==3) {
                    GetAjaxLatviaStockValuesTemot($('articles_as_cvs_' + BlockId).innerHTML, Sid, BlockId);
                }
                else if (Country==2) {
                    GetAjaxFrebelStockValuesTemot($('articles_as_cvs_' + BlockId).innerHTML, Sid, 'Finland', BlockId);
                }
                else {
                    GetAjaxFrebelStockValuesTemot($('articles_as_cvs_' + BlockId).innerHTML, Sid, '', BlockId);
                }
                TemotLayoutCheck(BlockId);
            }
        }
    );
}

function hide_temot(block){
    var myNode = 'temot_articles_' + block;
    $(myNode).setStyle({display: 'none'});
}

function show_temot(block){
    var itemarray = $$('div.temot_articles');
    var i;
    var item;
    for (i=0; i < itemarray.length; i++){
        item = itemarray[i];
        Element.extend(item);
        item.setStyle({display: 'none'});
    }
    var myNode = 'temot_articles_' + block;
    $(myNode).setStyle({display: 'block'});
}

function TemotLayoutCheck(block) {
    if ($('temot_articles_' + block).getStyle('display')=='block') {
        if ($('mainBody').getWidth()-$('rightColumn').getWidth() < $('Temot_Img_' + block).getWidth()) {
            $('rightColumn').setStyle({top: $('ArticlesTable_' + block).positionedOffset()[1] + 'px'});
        }
    }
}

function toggle_temot(vehicle, block, choose, goBack){
    TemotPopUpHide();
    var myId = 'temot_selectionHeader_' + vehicle + '_' + block;
    var headerInfoText = $('mySelect_' + vehicle);
    var headerInfoTextArray = $$('td.mySelect');
    var load = 0;
    var item;
    var i;
    var itemarray = $$('tr.temot_selectionHeader');

    if (itemarray.length==1) {
        load = 1;
    }
    else {
        if ($(myId).hasClassName('temot_selected')){
            for (i=0; i < itemarray.length; i++){
                item = itemarray[i];
                Element.extend(item);
                if (item.id != myId){
                    if (item.style.display=='none') {
                        item.style.display='';
                        load = 2;
                    }
                    else{
                        item.style.display='none';
                        load = 1;
                    }
                }
            }
        }
        else{
            for (i=0; i < itemarray.length; i++){
                item = itemarray[i];
                Element.extend(item);
                if (item.id != myId){
                    if (item.hasClassName('temot_selected')) {
                        item.removeClassName('temot_selected');
                        item.addClassName('temot_default');
                    }
                    item.style.display='none';
                }
                else{
                    if (item.hasClassName('temot_default')) {
                        item.removeClassName('temot_default');
                    }
                    item.addClassName('temot_selected');
                    load = 1;
                }
            }
        }
    }
    if (load==1){
        show_temot(block);
        $('TemotId').update(vehicle);
        headerInfoText.innerHTML = goBack;
        if ($('Temot_Img_' + block)) {
            if ($('mainBody').getWidth()-$('rightColumn').getWidth() < $('Temot_Img_' + block).getWidth()) {
                $('rightColumn').setStyle({top: $('ArticlesTable_' + block).positionedOffset()[1] + 'px'});
            }
            else {
                $('rightColumn').setStyle({top: '0'});
            }
        }
        return;
    }
    if (load==2){
        $('TemotId').update('');
        $(myId).removeClassName('temot_selected');
        $(myId).addClassName('temot_default');
        for (i=0; i < headerInfoTextArray.length; i++){
            headerInfoTextArray[i].innerHTML = choose;
        }
        hide_temot(block);
        $('rightColumn').setStyle({top: '0'});
        return;
    }
}

function toggle_nohau_selectionHeader(strip, merk, type){
    var myId;
    var i;
    var load = 0;
    if (merk == ''){
        myId = 'nohau_selectionHeader_' + strip;
    }
    else{
        myId = 'nohau_selectionHeader_' + strip + '_' + merk + '_' + type;
    }
    var item;
    var itemarray = $$('h1.nohau_selectionHeader');
    if ($(myId).hasClassName('nh_selected')){
        for (i=0; i < itemarray.length; i++){
            item = itemarray[i];
            Element.extend(item);
            if (item.id != myId){
                if (item.style.display=='none') {
                    item.style.display='block';
                }
                else{
                    item.style.display='none';
                }
            }
        }
    }
    else{
        for (i=0; i < itemarray.length; i++){
            item = itemarray[i];
            Element.extend(item);
            if (item.id != myId){
                if (item.hasClassName('nh_selected')) {
                    item.removeClassName('nh_selected');
                    item.addClassName('nh_unselected');
                }
                item.style.display='none';
            }
            else{
                item.removeClassName('nh_unselected');
                item.addClassName('nh_selected');
                load = 1;
            }
        }
    }
    if (load==1){
        $('content').innerHTML = "<h1>Loading...</h1>";
        var myPath = location.href.split('?');
        var myUrl = myPath[0];
        var myParams = myPath[1].split('&');
        var service = '';
        var side = '';
        for (i=0; i < myParams.length; i++){
            if (myParams[i].search('PageName') > -1) {
                service = myParams[i];
            }
            if (myParams[i].search('steering_side') > -1) {
                side = '&' + myParams[i];
            }
        }
        myUrl = myUrl + "?" + service + side + "&Strip=" + strip + "&nmerk=" + merk + "&ntype=" + type;

        location.href = myUrl;
        return;
    }
}

function TemotPopUpHide() {
    $$('div.TemotPopUpBox').each(Element.hide);
}

function TemotPopUp_2(BlockId,ArticleName,kiId){

    if (kiId) {
        if (!$('TemotPopUpBox_' + BlockId + '_' + kiId) || $('TemotPopUpBox_' + BlockId + '_' + kiId)=='undefined') {
            var rowId = kiId-1;
            if ($('ape_' + BlockId + '_missing' + rowId)) {
                if ($('Lambda_' + BlockId + '_' + kiId).value) {
                    var popUp = new Element('div', {'style': 'position:relative;z-index: 10;', 'class': 'TemotPopUpBox', 'id': 'TemotPopUpBox_' + BlockId + '_' + kiId}).update($('TemotPopUpBoxLambda').innerHTML.replace(/tpu_/g,"tpu_" + BlockId + "_" + kiId + "_"));
                    $('TemotPopUpContainer').insert(popUp);
                    $('tpu_' + BlockId + '_' + kiId + '_close').observe('click', TemotPopUpHide);
                    $('tpu_' + BlockId + '_' + kiId + '_link').writeAttribute('href', "index.php?PageName=article_browser&nodeInfo=" + $('Lambda_' + BlockId + '_' + kiId).value);
                    $('tpu_' + BlockId + '_' + kiId + '_link').update($('Description_' + BlockId + '_' + kiId).innerHTML);
                }
                else {
                    popUp = new Element('div', {'style': 'position:relative;z-index: 10;', 'class': 'TemotPopUpBox', 'id': 'TemotPopUpBox_' + BlockId + '_' + kiId}).update($('TemotPopUpBoxMissing').innerHTML.replace(/tpu_/g,"tpu_" + BlockId + "_" + kiId + "_"));
                    $('TemotPopUpContainer').insert(popUp);
                    $('tpu_' + BlockId + '_' + kiId + '_close').observe('click', TemotPopUpHide);
                    $('tpu_' + BlockId + '_' + kiId + '_description').innerHTML = $('Description_' + BlockId + '_' + kiId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_no_sale').innerHTML = $('no_sale_' + BlockId + '_' + kiId).innerHTML;
                    if ($('tpu_' + BlockId + '_' + kiId + '_error')) {
                        $('tpu_' + BlockId + '_' + kiId + '_error').observe('click', function(){
                            $$('#article_item_row_' + BlockId + '_' + kiId + ' img')[0].onclick();
                        });
                    }
                }
            }
            else {
                popUp = new Element('div', {'style': 'position:relative;z-index: 10;', 'class': 'TemotPopUpBox', 'id': 'TemotPopUpBox_' + BlockId + '_' + kiId}).update($('TemotPopUpBox').innerHTML.replace(/tpu_/g,"tpu_" + BlockId + "_" + kiId + "_"));
                $('TemotPopUpContainer').insert(popUp);
                $('tpu_' + BlockId + '_' + kiId + '_close').observe('click', TemotPopUpHide);
                var countryId;
                if ($('tpu_code')) {
                    countryId = 1;
                }
                else if ($('tpu_saldo3')) {
                    countryId = 3;
                }
                else {
                    countryId = 2;
                }
                $('tpu_' + BlockId + '_' + kiId + '_article').innerHTML = ArticleName;
                $('tpu_' + BlockId + '_' + kiId + '_description').innerHTML = $('Description_' + BlockId + '_' + kiId).innerHTML;
                $('tpu_' + BlockId + '_' + kiId + '_supplier').innerHTML = $('SupplierName_' + BlockId + '_' + kiId).innerHTML;
                $('tpu_' + BlockId + '_' + kiId + '_no_sale').innerHTML = $('no_sale_' + BlockId + '_' + kiId).innerHTML;
                if ($('tpu_' + BlockId + '_' + kiId + '_error')) {
                    $('tpu_' + BlockId + '_' + kiId + '_error').observe('click', function(){
                        $$('#article_item_row_' + BlockId + '_' + kiId + ' img')[0].onclick();
                    });
                }
                if (countryId==1) {
                    $('tpu_' + BlockId + '_' + kiId + '_price').innerHTML = $('ape_' + BlockId + '_price' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_vat_price').innerHTML = $('ape_' + BlockId + '_vat_price' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_code').innerHTML = $('ape_' + BlockId + '_code' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_c_saldo').innerHTML = $('ape_' + BlockId + '_c_saldo' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_saldo').innerHTML = $('ape_' + BlockId + '_saldo' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').value=$('kte_til_' + BlockId + '_' + kiId).value;
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').observe('blur', function(){ 
                        $('kte_til_' + BlockId + '_' + kiId).value = $('tpu_' + BlockId + '_' + kiId + '_quantity').value;
                        $('kte_til_' + BlockId + '_' + kiId).onblur();
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').observe('change', function(){
                        $('kte_til_' + BlockId + '_' + kiId).value = $('tpu_' + BlockId + '_' + kiId + '_quantity').value;
                        $('kte_til_' + BlockId + '_' + kiId).onchange();
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_up').observe('click', function(){ 
                        $$('#article_item_row_' + BlockId + '_' + kiId + ' img[src$=ylos.gif]')[0].onclick();
                        $('tpu_' + BlockId + '_' + kiId + '_quantity').value = $('kte_til_' + BlockId + '_' + kiId).value;
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_down').observe('click', function(){
                        $$('#article_item_row_' + BlockId + '_' + kiId + ' img[src$=alas.gif]')[0].onclick();
                        $('tpu_' + BlockId + '_' + kiId + '_quantity').value = $('kte_til_' + BlockId + '_' + kiId).value;
                    });
                }
                if (countryId==2) {
                    $('tpu_' + BlockId + '_' + kiId + '_price').innerHTML = $('ape_' + BlockId + '_price' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_vat_price').innerHTML = $('ape_' + BlockId + '_vat_price' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_saldo').innerHTML = $('ape_' + BlockId + '_saldo' + rowId).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').value=$('kte_til_' + BlockId + '_' + kiId).value;
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').observe('blur', function(){
                        $('kte_til_' + BlockId + '_' + kiId).value = $('tpu_' + BlockId + '_' + kiId + '_quantity').value;
                        $('kte_til_' + BlockId + '_' + kiId).onblur();
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_quantity').observe('change', function(){
                        $('kte_til_' + BlockId + '_' + kiId).value = $('tpu_' + BlockId + '_' + kiId + '_quantity').value;
                        $('kte_til_' + BlockId + '_' + kiId).onchange();
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_up').observe('click', function(){
                        $$('#article_item_row_' + BlockId + '_' + kiId + ' img[src$=ylos.gif]')[0].onclick();
                        $('tpu_' + BlockId + '_' + kiId + '_quantity').value = $('kte_til_' + BlockId + '_' + kiId).value;
                    });
                    $('tpu_' + BlockId + '_' + kiId + '_down').observe('click', function(){
                        $$('#article_item_row_' + BlockId + '_' + kiId + ' img[src$=alas.gif]')[0].onclick();
                        $('tpu_' + BlockId + '_' + kiId + '_quantity').value = $('kte_til_' + BlockId + '_' + kiId).value;
                    });
                }
                if (countryId==3) {
                    $('tpu_' + BlockId + '_' + kiId + '_price').innerHTML = $('apelv_' + BlockId + '_price_' + ArticleName).innerHTML;
//                    $('tpu_' + BlockId + '_' + kiId + '_saldo1').innerHTML = $('apelv_' + BlockId + '_saldo1_' + ArticleName).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_saldo2').innerHTML = $('apelv_' + BlockId + '_saldo2_' + ArticleName).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_saldo3').innerHTML = $('apelv_' + BlockId + '_saldo3_' + ArticleName).innerHTML;
                    $('tpu_' + BlockId + '_' + kiId + '_button').observe('click', function(){
                        latvia_buy( ArticleName, 'tpu_' + BlockId + '_' + kiId + '_quantity');
                    });
                }
                if ($$('#article_item_row_' + BlockId + '_' + kiId + ' img[src="pictures/more_information_icon.gif"]')[0]) {
                    var temp = $$('#tpu_' + BlockId + '_' + kiId + '_saldo img[src="pictures/more_information_icon.gif"]')[0].readAttribute('style');
                    $$('#tpu_' + BlockId + '_' + kiId + '_saldo img[src="pictures/more_information_icon.gif"]')[0].writeAttribute('style', 'vertical-align: top;' + temp);
                }
            }
        }
        else {
            $('TemotPopUpBox_' + BlockId + '_' + kiId).show();
        }
    }
    else {
        TemotArticleRows(ArticleName);
        TemotPopUpHide();
        var rows = $$('#temot_articles_' + BlockId + ' td[name="' + ArticleName + '"] input[name="RowNumber"]');
        var numberOfRows = rows.length;
        for (var i=0; i < numberOfRows; i++){
            kiId = rows[i].value;
            TemotPopUp(BlockId,ArticleName,kiId);
        }
    }
}
function TemotPopUp(BlockId,Articles){
    TemotPopUpHide();
//    Articles = new Array(Articles);
    TemotArticleRows(Articles);
    var numberOfArticles = Articles.length;
    for (var i=0; i < numberOfArticles; i++){
        var ArticleName = Articles[i];
        var rows = $$('#temot_articles_' + BlockId + ' td[name="' + ArticleName + '"] input[name="RowNumber"]');
        var numberOfRows = rows.length;
        for (var j=0; j < numberOfRows; j++){
            var kiId = rows[j].value;
            TemotPopUp_2(BlockId,ArticleName,kiId);
        }
    }
}

function NohauPopUp(baseClassName, aTINR){

	var itemarray = document.getElementsByTagName("td");
	var searchString = "nohau_selected";
	
	for (i=0; i < itemarray.length; i++){
		var item = itemarray[i];
		Element.extend(item);
		if (item.hasClassName("nohau_selected")){
			item.removeClassName("nohau_selected");
		}
		if (item.hasClassName(aTINR)){
			item.addClassName("nohau_selected");
		}
	}

	if (AnotherdetectIE6()){
		itemarray = $('NohauPopUpBox').childNodes[0].childNodes;
	}
	else {
		itemarray = $$('div.nohauPopUpDiv');
	}
	for (var i=0; i < itemarray.length; i++){
		itemarray[i].style.display="none";
		if (itemarray[i].id == aTINR){
			itemarray[i].style.display="inline";
		}
	}
	
	itemarray = document.getElementsByName(aTINR);
	for (i=0; i < itemarray.length; i++){
		item = itemarray[i];
		Element.extend(item);
		item.addClassName("nohau_selected");
	}
	$('NohauPopUpBox').appear({duration: 0.5});
}

function TemotArticleRows(Articles){

    var itemarray = $$('td');
    var numberOfArticles = Articles.length;

    for (var i=0; i < itemarray.length; i++){
        var item = itemarray[i];
        Element.extend(item);
        if (item.hasClassName("ArticleTableCellItem_even_green")){
                item.removeClassName("ArticleTableCellItem_even_green");
                item.addClassName("ArticleTableCellItem_even");
        }
        if (item.hasClassName("ArticleTableCellItem_odd_green")){
                item.removeClassName("ArticleTableCellItem_odd_green");
                item.addClassName("ArticleTableCellItem_odd");
        }
        for (var j=0; j < numberOfArticles; j++) {
            if (item.hasClassName(Articles[j])){
                if (item.hasClassName("ArticleTableCellItem_even")){
                        item.addClassName("ArticleTableCellItem_even_green");
                        item.removeClassName("ArticleTableCellItem_even");
                }
                if (item.hasClassName("ArticleTableCellItem_odd")){
                        item.addClassName("ArticleTableCellItem_odd_green");
                        item.removeClassName("ArticleTableCellItem_odd");
                }
            }
        }
    }
    for (j=0; j < numberOfArticles; j++) {
        itemarray = $$('td[name="' + Articles[j] + '"]');
        for (i=0; i < itemarray.length; i++){
            item = itemarray[i];
            Element.extend(item);
            if (item.hasClassName("ArticleTableCellItem_even")){
                    item.addClassName("ArticleTableCellItem_even_green");
                    item.removeClassName("ArticleTableCellItem_even");
            }
            if (item.hasClassName("ArticleTableCellItem_odd")){
                    item.addClassName("ArticleTableCellItem_odd_green");
                    item.removeClassName("ArticleTableCellItem_odd");
            }
        }
    }
}

function Mse(ud,imgid){
 var img=$(imgid);
 img.setStyle({cursor: 'default'});
 if (ud) img.setStyle({cursor: 'pointer'});
}

function nayta(uusi) { 
		$(uusi).style.visibility='visible';
}

function piilota(uusi) { 
		$(uusi).style.visibility='hidden';
}

function UpdateCurrentCarInfo() {
	new Ajax.Updater('carInfo', 'ajax.php?PageName=current_carinfo', {parameters: { }});
}

var basketContentsLoaded = 0;

function HoverBasket(){
    if (basketContentsLoaded == 0) {
        basketContentsLoaded = 1;
        new Ajax.Updater('shopping_basket_hover', 'ajax.php?PageName=ShoppingBasket_content', {parameters: {  }, onComplete: function(transport) {
    	$('hoverBasketNew').show();
    	return true;}});
    }
}

function initGetMouseCursorPosition() {
	if (!detectIE()) {
	  if (window.Event) {
	    document.captureEvents(Event.MOUSEMOVE);
	  }
	  if (document.getElementById('shopping_basket_hover_icon')) {
		  document.onmousemove = CursorOnHoverBasketNew;
	  }
	} else {
		if (document.getElementById('shopping_basket_hover_icon') != undefined) {
            addEvent(document.getElementById('shopping_basket_hover_icon'), 'mouseover', function() {HoverBasket();});
            addEvent(document.getElementById('shopping_basket_hover_icon'), 'mouseout', function() {
			/*
			$('shopping_basket_hover_icon').class="ShoppingCartInfoBoxCartIcon";
			$('shopping_basket_hover_icon').src = "pictures/shopping_cart_infobox_carticon.png"; */
			$('hoverBasketNew').hide();
            basketContentsLoaded = 0;
            });
            
		} 
	}
}


function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

function CursorOnHoverBasketNew(e){
	//get the position of the container, prototype functionality
	var containerLeft = Position.page($('shopping_basket_hover_icon'))[0];
	var containerTop = Position.page($('shopping_basket_hover_icon'))[1];
        var mouseX;
        var mouseY;
	//get the mouse coordinates
	if (e.pageX) mouseX = e.pageX;
	else if (e.clientX)
		mouseX = e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	if (e.pageY) mouseY = e.pageY;
	else if (e.clientY)
		mouseY = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	
	//mouseX = Event.pointerX(e);
	//mouseY = Event.pointerY(e);

	//calculate the absolute mouse position in the div by mouseposition minus left position of the container
	var horizontalPosition = mouseX - containerLeft;
	var verticalPosition = mouseY - containerTop;

	//use prototypes function to get the dimension
	var containerDimensions = $('shopping_basket_hover_icon').getDimensions();
	var height   = containerDimensions.height;
	var width = containerDimensions.width;

	//check if the mouse is out or inside the div
	//this if statement checks if the cursor is inside the div
	if(horizontalPosition < 0 || verticalPosition < 0 || mouseX > (width + containerLeft) || mouseY > (height + containerTop) ){
		if ($('hoverBasketNew').visible()) {
			//$('shopping_basket_hover_icon').className = "ShoppingCartInfoBoxCartIcon";
			//$('shopping_basket_hover_icon').src = "pictures/shopping_cart_infobox_carticon.gif";
			$('hoverBasketNew').hide();
            basketContentsLoaded = 0;
		}
	}else{
		HoverBasket();
		//$("hoverBasketNew").show();
		//$('hoverBasketNew').innerHTML = 'MOUSE IN DIV mouseX:' + horizontalPosition + '-- mouseY:' + verticalPosition;
	}
}

//Not Used
function ToggleUserAdminView(list, userID, companyID){
    new Ajax.Updater('User_Management', 'ajax.php?PageName=um_user_list', {parameters: {list: list, userID: userID, companyID: companyID}, onComplete: function(transport) { }});
}

function ToggleCompanyAdminView(list, uID, pCID){
   var position = Position.positionedOffset($('companyRow'+uID));

    new Ajax.Updater('um_infoedit_content', 'ajax.php?PageName=um_company_list', { 
	    	parameters: {list: list, uID: uID, pCID: pCID}
	    	});
    $('um_infoedit').style.bottom = '';
    $('um_infoedit').style.top = position.top - 100 +'px';
	$('um_infoedit').style.display = 'inline';
}

function ToggleNewCompany(list, uID, pCID){
    new Ajax.Updater('um_infoedit_content', 'ajax.php?PageName=um_company_list', { 
	    	parameters: {list: list, uID: uID, pCID: pCID}
	    	});

	$('um_infoedit').style.display = 'inline';
}

function ToggleAutodataAdminView(request, uID, pCID){
  var position = Position.positionedOffset($('autodataRow'+uID));
  new Ajax.Updater('um_infoedit_content', 'ajax.php?PageName=um_autodata_list', { 
	    	parameters: {request: request, uID: uID, pCID: pCID}
	    	});
    $('um_infoedit').style.bottom = '';
    $('um_infoedit').style.top = position.top - 100 +'px';
	$('um_infoedit').style.display = 'inline';

}

function ToggleVividAdminView(list, uID, pCID){
  var position = Position.positionedOffset($('vividRow'+uID));
  new Ajax.Updater('um_infoedit_content', 'ajax.php?PageName=um_vivid_list', { 
	    	parameters: {list: list, uID: uID, pCID: pCID}
	    	});
    $('um_infoedit').style.bottom = '';
    $('um_infoedit').style.top = position.top - 100 +'px';
	$('um_infoedit').style.display = 'inline';

}

function SubmitUserData(){
	$('um_user_data').request({
		method: 'GET',
		evalJS: false,
		onComplete: function(transport){ 
			var test = $('um_user_data').parentNode.previousSibling;
			insert(test, {after: transport.responseText}); 
		}
	});
}

function AutodataSearch(cID,argument){
	var needle = $('AutodataSearchString').value;
	var options1 = document.getElementsByName('AutodataSearchOptions_1');
	var options2 = document.getElementsByName('AutodataSearchOptions_2');
	var op2disabled=0;
	var toggleheaders=0;
	for (var i=0; i < options1.length; i++)
	{
		if (options1[i].checked)
		{
			var option1 = options1[i].value;
			if (i==2 || i==3)
			{
				op2disabled=1;
				if (i==3)
				{
					toggleheaders=1;
				}
			}
			else
			{
				op2disabled=0;
			}
		}
	}
	for (i=0; i < options2.length; i++)
	{
		if (op2disabled==1)
		{
			options2[i].disabled = "disabled";
			if (i==0){
				options2[i].checked = "checked";
			}
			else
			{
				options2[i].checked = "";
			}
		}
		else
		{
			options2[i].disabled = "";
		}
		if (options2[i].checked)
		{
			var option2 = options2[i].value;
		}
	}
	if (needle.length>=2 || option1 != 2 || option2 != 0 || argument>0){
	    $('AutodataSearchString').style.backgroundColor  = 'white';
		new Ajax.Updater('AutodataContent', 'ajax.php?PageName=um_autodata_search', {parameters: {needle: needle, cID: cID, option1: option1, option2: option2}, onComplete: function(transport) { }});
	} else {
	  $('AutodataContent').innerHTML = '';
	  $('AutodataSearchString').focus();
	  $('AutodataSearchString').style.backgroundColor  = 'yellow';
	}
/*	ToggleAutodataRequest(toggleheaders); */
}

function VividSearch(cID,argument){
	var needle = $('VividSearchString').value;
	var options = document.getElementsByName('VividSearchOptions');
	for (var i=0; i < options.length; i++)
	{
		if (options[i].checked)
		{
			var option = options[i].value;
		}
	}
	if (needle.length>=2 || option != 1 || argument>0)
	{
		new Ajax.Updater('VividContent', 'ajax.php?PageName=um_vivid_search', {parameters: {needle: needle, cID: cID, option: option}, onComplete: function(transport) { }});
	}
}

function CompanyDataSearch(cID,argument){
	var needle = $('um_user_list_searchString').value;
	if (needle.length>=2 || argument>0){
	
		new Ajax.Updater('CompanyDataContent', 'ajax.php?PageName=um_companyData_search', {parameters: {needle: needle, cID: cID}, onComplete: function(transport) { }});
	}
}

function AdminArticleBrowserPopUp(options){
    var db = $('val_DBName').value;
    var avtmID = $('val_ArticleVehicleTypeMapID').value;
    var aID = $('val_ArticleID').value;
    var langID = $('val_LanguageID').value;
    var vehID = $('val_VehicleID').value;
	window.open('admin_article_browser.php?AdminAttributes=true&DBName=' + db + '&ArticleVehicleTypeMapID=' + avtmID + '&ArticleID=' + aID + '&LanguageID=' + langID + '&VehicleID=' + vehID,'','scrollbars=yes,menubar=no,height=600,width=900,top=50,left=50,resizable=yes,toolbar=no,location=no, status=no'); 
		return false;
}

function ShowLoadingIndicator(elementid, loadinggif) {
    $(elementid).innerHTML = "<img style='top: 40%; left: 40%;' src='pictures/" + loadinggif + "' alt='loading...'>";
}

function TailFunction(options){
	if (options['TailFunction'] == 'AdminArticleBrowserPopUp'){
		AdminArticleBrowserPopUp(options);
	}
	if ((options['TailFunction'] == 'LoadPriceStockValue')){
		AfterLoad();
	}
    if ((options['TailFunction'] == 'ShowArticleStockValues')) {
        BrowserDetect.init();
        if (!BrowserDetect.browser == 'Safari') {
            new Draggable('ArticleStockValues', {scroll: window, zindex: 5000});
        }
    }

    if ((options['TailFunction'] == 'loadFrebellArticlePrices')) {
        GetAjaxFrebelStockValues($('ArticlesCommaText').innerHTML, options['session_id'], options['frebellCountry']);
        SetHTMLBodyHeight();
    }

    if (options['TailFunction'] == "changeSearchMethod") {
        if ($('searchMethod')) {
            if ($('searchMethod').value != 0) {
                setSearchMethod2(0);
            }
         }
    } 
    if (options['TailFunction'] == "UpdateShoppingCartInfoBox"){
    	UpdateShoppingCartInfoBox();	
    }
    if (options['TailFunction'] == "MultiSelector2"){
    	 new MultiSelector2('upload_new', -1); 	
    }
    if (options['TailFunction'] == "MultiSelector2AndInitCategory"){
    	 new MultiSelector2('upload_new', -1);
         if ($('select_CategoryID').value > 0){
           loadPrivilegeSelection($('select_CategoryID').value);
         }
    }
    if (options['TailFunction'] == "TemotLayoutCheck"){
        TemotLayoutCheck(options['BlockId']);
    }
 
}

function PreFunction(options) {
    if (options['PreFunction'] == 'ShowArticleStockValues'){
        if ($('ArticleStockValues')) {
            BrowserDetect.init();
            if (BrowserDetect.browser == 'Safari' || BrowserDetect.browser == 'Chrome') {
                $('ArticleStockValues').style.marginTop = "200px";
            }
            $('ArticleStockValuesInitial').innerHTML = "<img style='top: 40%; left: 40%;' src='pictures/loading-indicator.gif' alt='loading...'/>";
            if (!$('ArticleStockValues').visible()) {
                $('ArticleStockValues').style.left = "-650px";
                $('ArticleStockValues').show();
                if ($('CountryID').value == 3) {
                    new Effect.Move('ArticleStockValues', {x:870,y:0,duration:1});                    
                }
                else {
                    new Effect.Move('ArticleStockValues', {x:650,y:0,duration:1});                    
                }
            }
        }
	} else if (options['PreFunction'] == 'loaderMiddleInDiv'){
        if (!$(options['element']).visible()) {
            $(options['element']).appear( {duration: 0.5} );
        }
        $(options['element']).innerHTML = "<img style='top: 40%; left: 40%;' src='pictures/" + options['ajax_loader'] + ".gif'/>";
    } else if (options['PreFunction'] == 'changeBookingArticle') {
        $('changeBookingArticleBG').appear( {duration: 0.4} );
        if (!$(options['element']).visible()) {
            $(options['element']).appear( {duration: 0.4} );
        }
        $(options['element']).innerHTML = "<img style='top: 40%; left: 40%;' src='pictures/" + options['ajax_loader'] + ".gif'/>";
    } else if (options['PreFunction'] == 'changeServiceArticle') {
        $('changeServiceArticleBG').appear( {duration: 0.5} );
        if (!$(options['element']).visible()) {
            $(options['element']).appear( {duration: 0.5} );
        }
        $(options['element']).innerHTML = "<img style='bottom: 20%; left: 20%;' src='pictures/" + options['ajax_loader'] + ".gif'/>";
    }


}

function GetByAjax(options){
	var default_args = {
            'file'	:	"ajax.php",
            'PageName' : "service_search_tree",
            'element' : "SERVICE_search_tree",
            'evalScripts' : false
	}
        var index;
	for(index in default_args) {
		if(typeof options[index] == "undefined") {
			options[index] = default_args[index];
		}
	}
	if(typeof options['ajax_loader'] != "undefined") {
		$(options['element']).innerHTML = "<img src='pictures/" + options['ajax_loader'] + ".gif'/>";
	}
	var link = options['file'] + "?PageName=" + options['PageName'];

    if(typeof options['PreFunction'] != "undefined") {
        PreFunction(options);
    }

	new Ajax.Updater(options['element'], link, {
            parameters: options,
            evalScripts: options['evalScripts'],
            onComplete: function(transport) {
                if(typeof options['TailFunction'] != "undefined") {
                    TailFunction(options);
                }
            }
        });
}

function prCodePDF(e)
{
        window.open('pdf/PR-Koder.pdf', 'prkoder', 'status=1, height=800, width=800');
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function WholesalerAutodata_2(){
	$('VATNumber').value=$('um_ad_VATNumber').innerHTML;
	$('EmailAddress').value=$('um_ad_Email').innerHTML;
	$('AutodataSerialNumber').value=$('um_ad_AutodataSerialNumber').innerHTML;
}

function WholesalerAutodata(){
    if ($('umCompanyInfoDiv')){
        var div = $('umCompanyInfoDiv');
        div.parentNode.removeChild(div);
    }
	var cID=$('CompanyName').value;
	new Ajax.Updater('um_tabscontent', 'ajax.php?PageName=um_fetch_company_data', {parameters: {cID: cID}, insertion: Insertion.After, onComplete: function(transport) {WholesalerAutodata_2()}});
}

function ToggleAutodataBox(requestType)
{
    if (requestType == 1)
    {
        $("AutodataSerialNumber").enable();
    }
    else
    {
        $("AutodataSerialNumber").disable();
    }
}

function UpdateShoppingCartInfoBox() {
	new Ajax.Updater('ShoppingCartInfoBoxArticleCount', 'ajax.php?PageName=shopping_cart_infobox_articlecount',  
		{parameters: {},
		 onComplete: function(transport){}});
	new Ajax.Updater('ShoppingCartInfoBoxArticleTotal', 'ajax.php?PageName=shopping_basket_total',  
		{parameters: {},
		 onComplete: function(transport){}});
}

function AnotherdetectIE6() {

	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer') {
	 var ua = navigator.userAgent;
	 var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	 if (re.exec(ua) != null)
	   rv = parseFloat( RegExp.$1 );
	}
	
	if (rv == -1) {
		return false;
	} else {
		if (rv < 7.0) {
			return true;
		} else {
			return false;
		}
	}
	
}

function detectIE() {
	if (navigator.appName == 'Microsoft Internet Explorer') {
		return true;
	} else {
		return false;
	}

}

function SetHTMLBodyHeight() {
	if (AnotherdetectIE6()) {
		if ($('content').clientHeight) {
			document.body.style.height = $('content').clientHeight + 50 + 'px';
			document.body.style.width = '100%';
		}
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function GetRadioValue(elementid){
	var services;
	$$('#'+elementid).each( 
			function(i) { 
				if ($F(i)) {services = $F(i);} 
			}
		);
	return services;
}

function findPos(obj) {
        var curtop;
	var curleft = curtop = 0;

	if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);

		return [curleft,curtop];
	}
    return null;
}

function setFocus(elementid) {
    document.getElementById(elementid).focus();
    //document.search_by_articlename.elements[0].focus();
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function')
    {
        window.onload = func;
    }
    else
    {
        window.onload = function()
        {
            if (oldonload)
            {
                oldonload();
            }
            func();
        }
    }
}

function OpenInfoMessageLayer(MessageID) {
    if ($('InfoMessagesLayer').visible()) {
        // change only message inside
        LoadInfoMessage(MessageID);
    } else {
        new Effect.toggle('InfoMessagesLayer', 'blind', {scaleX: 'true', scaleY: 'true;', scaleContent: false});
        new Effect.Fade('InfoMessagesLayer', {duration:1.0, from:0.0, to:1.0, afterFinish: function() {
                $('infomessages_messagearea').className = "infomessages_messagearea";
            }});

        LoadInfoMessage(MessageID);
        if (AnotherdetectIE6()) {
            if ($('PositionFilter')) {
                $('PositionFilter').hide();
              }
        }
    }

}

function LoadInfoMessage(MessageID) {
    new Ajax.Updater('infomessages_messagearea', 'ajax.php?PageName=load_infomessage_content',
        {parameters: {InfoMessageID: MessageID},
        onComplete: function(transport){}});

    var topics = $('InfoMessagesLayer').getElementsByTagName('li');
    for(var i=0; i<topics.length; i++) {
        var topicID = topics[i].getAttribute('id');
        if (topicID.indexOf('infoMessage_') != -1) {
            document.getElementById(topicID).style.backgroundColor = "#A4A497";
            document.getElementById(topicID).style.width = "160px";
            document.getElementById(topicID).style.paddingBottom = "0px";
            document.getElementById(topicID).style.paddingTop = "0px";
            document.getElementById(topicID).style.borderTop = "none";
            document.getElementById(topicID).style.borderLeft = "none";
            document.getElementById(topicID).style.borderBottom = "none";
        }
    }
    document.getElementById('infoMessage_' + MessageID).style.backgroundColor = "#9A9A8D";
    document.getElementById('infoMessage_' + MessageID).style.width = "182px";
    document.getElementById('infoMessage_' + MessageID).style.paddingBottom = "1px";
    document.getElementById('infoMessage_' + MessageID).style.paddingTop = "1px";
    document.getElementById('infoMessage_' + MessageID).style.borderTop = "solid thin #868679";
    document.getElementById('infoMessage_' + MessageID).style.borderLeft = "solid thin #868679";
    document.getElementById('infoMessage_' + MessageID).style.borderBottom = "solid thin #868679";
}

function CloseInfoMessageLayer() {
    $('infomessages_messagearea').className = "infomessages_messagearea_hide";
    new Effect.toggle('InfoMessagesLayer', 'blind', {scaleX: 'true', scaleY: 'true;', scaleContent: false});
    new Effect.Fade('InfoMessagesLayer', {duration:1.0, from:1.0, to:0.0});

    if (AnotherdetectIE6()) {
        if ($('PositionFilter')) {
            $('PositionFilter').show();
          }
    }
}

function GoToURL(url) {
    window.location.href = url;
}

function createNewFormAndSubmitIt(action, method, elements, target) {
    var newform = document.createElement("form");
    newform.action = action;
    newform.method = method;
    if (target) {
        newform.target = target;
    }
    var i;
    for (i in elements) {
        var newfield = document.createElement("input");
        newfield.type = "hidden";
        newfield.name = i;
        newfield.value = elements[i];
        newform.appendChild(newfield);
    }

    document.body.appendChild(newform);
    newform.submit();
}

function createNewFormAndSubmitItAjax(action, method, elements, node, position, anchor) {
    var newform = new Element('form', {
                         action: action,
                         method: method
                       });
    var i;
    for (i in elements) {
        var newfield = new Element('input', { name: i, type: "hidden", value: elements[i] });
        newform.appendChild(newfield);
    }
    if (node) {
        if (!position) {
            position = 'replace';
        }
        newform.request({
            onComplete: function(response){
                if (position == 'replace') {
                    $(node).update(response.responseText);
                }
                else if (position == 'before') {
                    $(node).insert({
                        before: response.responseText
                    });
                    
                }
                else if (position == 'after') {
                    $(node).insert({
                        after: response.responseText
                    });
                }
                else if (position == 'bottom') {
                    $(node).insert({
                        bottom: response.responseText
                    });
                }
                else {
                    $(node).insert({
                        top: response.responseText
                    });
                }
                response.responseText.evalScripts();
                if (anchor) {
                    $(anchor).scrollTo();
                }
            }
        });
    }
    else {
        newform.request();
    }
}

function toggleCatalogue(a) {
    if (a=='searchTreeTabExtranet') {
        window.location.href = 'index.php?PageName=extranet&extranet=1';
    }
    if (a=='searchTreeTabAccessories') {
        window.location.href = 'index.php?PageName=article_browser&accNodeInfo=0';
    }
    if (a=='searchTreeTabReplacementParts') {
        window.location.href = 'index.php?PageName=article_browser&NodeInfo=0';
    }
}

function UserNameAutoCompOnShow(element, update) {
    if(!update.style.position || update.style.position=='absolute') {
      update.style.position = 'absolute';
      Position.clone(element, update, {
        setHeight: false,
        setWidth: false,
        offsetTop: element.offsetHeight
      });
    }
    Effect.Appear(update,{duration:0.15});
}

function GetAjaxFrebellSaldo(ArticleNames, SessionID){
     ShowLoading();
     new Ajax.Updater('ape_saldoa', 'ajax.php?PageName=saldo_query',
     {parameters: {ArticleNames: ArticleNames , sid: SessionID}, onComplete: function(transport) {
             HideLoading();
             GetSaldo();
         }
     });
}

function GetSaldo()
{
	var i = 0;
	var ArtId;
	var Saldo;
        var ABCCode;
	var ArtInfo;
        var Class;
	var result_arrays = $('ape_saldoa').innerHTML.split(';');
	while(result_arrays[i] != null){
	  ArtInfo = result_arrays[i].split('$');
	  ArtId = ArtInfo[0];
	  Saldo = ArtInfo[2];
          ABCCode = ArtInfo[5];
          Class = ArtInfo[10];
          if (Saldo.replace(/\s/g,"") == ""){
              Saldo = '0';
          }
	  if ($('saldo_'+ArtId)){
	    $('saldo_'+ArtId).innerHTML = Saldo;
          }
	  if ($('code_'+ArtId)){
	    $('code_'+ArtId).innerHTML = ABCCode;
          }
	  if ($('class_'+ArtId)){
	    $('class_'+ArtId).innerHTML = Class;
          }

	  i++;
	}
}

function ShowDetails(ArticleName)
{
    var myNode = 'ms_detail_table_' + ArticleName;
    if ($(myNode)) {
        $(myNode).toggle();
    }
    else {
        var element = 'missedSales_' + ArticleName;
        new Ajax.Updater(element, 'ajax.php?PageName=MissedSale', {parameters: {ArticleName: ArticleName, getDetails: 1}, insertion: Insertion.After});
    }
}

function shouldCancelbackspace(e) {
     var key;
     if (e){
        key = e.which? e.which : e.keyCode;
        if (key == null || ( key != 8 && key != 13)){ // return when the key is not backspace key.
            return false;
        }
     } else {
        return false;
     }

     if (e.srcElement) { // in IE
         var tag = e.srcElement.tagName.toUpperCase();
         var type = e.srcElement.type;
         var readOnly = e.srcElement.readOnly;
         if (type == null){ // Type is null means the mouse focus on a non-form field. disable backspace button
            //return true;
            return false;
         } else {
            type = e.srcElement.type.toUpperCase();
     }

     } else { // in FF
         tag = e.target.nodeName.toUpperCase();
         type = (e.target.type) ? e.target.type.toUpperCase() : "";
    }

     // we don't want to cancel the keypress (ever) if we are in an input/text area unless it is readonly
     if (tag == 'INPUT' || type == 'TEXT' ||type == 'TEXTAREA') {
         if (readOnly == true ) {
            // if the field has been disabled, disable the back space button
            return true;
         }
         if( ((tag == 'INPUT' && type == 'RADIO') || (tag == 'INPUT' && type == 'CHECKBOX')) && (key == 8 || key == 13) ){
            return true; // the mouse is on the radio button/checkbox, disbale the backspace button
         }
         return false;
     }

    // if we are not in one of the above things, then we want to cancel (true) if backspace
    return (key == 8 || key == 13);
}

function ChangeLanguage(languageID) {
    new Ajax.Updater("LanguageID", 'ajax.php?PageName=change_language', {
        parameters: {LanguageID: languageID},
        onComplete: function(transport) {
            // reload page
            //window.reload();
            var url = window.location.href;
            window.location.href = url;
         }
     });
}

function updateChoicesForArtAutoComp(choices) {
	if (!this.changed && this.hasFocus)	{
		this.update.innerHTML = choices;
		Element.cleanWhitespace(this.update);
		Element.cleanWhitespace(this.update.down());
		if (this.update.firstChild && this.update.down().childNodes) {
			this.entryCount = this.update.down().childNodes.length;
			for (var i = 0; i < this.entryCount; i++) {
				var entry = this.getEntry(i);
				entry.autocompleteIndex = i;
				this.addObservers(entry);
			}
		} else {
			this.entryCount = 0;
		}

		this.stopIndicator();
		this.index = -1;
		if (this.entryCount == 1 && this.options.autoSelect) {
			this.selectEntry();this.hide();
		} else {
			this.render();
		}
	}
}

function disableEnterKey(e) {
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}

function confirmOK(text) {
    var answer = confirm(text);
    if (answer) {
        return true;
    } else {
        return false;
    }
}

function privateLogout(url) {
    if (!url) url='http://bds.se/';
    
    if (confirm('Vill du lämna katalogen? Alla obeställda varor i köpkorgen rensas.'))
        window.top.location.href = 'logout.php?referrer=' + url;
}

var showDisclaimerText = function() {
    $('disclaimerDivBackground').appear( {duration: 0.5} );
    $('disclaimerDiv').appear( {duration: 0.5} );

    GetByAjax( {PageName: 'disclaimer',
                element: 'disclaimerDiv',
                file: 'ajax_view.php',
                Action: 'show_disclaimer',
                'evalScripts' : true } );
}

var enableDisclaimerSubmitButton = function(value) {
    if (value) {
        if ($('submitDisclaimer').hasAttribute('disabled')) {
            $('submitDisclaimer').removeAttribute('disabled');
        }
        $('submitDisclaimer').disabled = false;
        $('submitDisclaimer').focus();
    } else {
        $('submitDisclaimer').setAttribute('disabled', 'disabled');
        $('submitDisclaimer').disabled = true;
    }

}

var acceptDisclaimer = function(value, ajaxPage) {
    new Ajax.Updater("FrebellCartMessage", 'ajax_view.php?PageName=disclaimer', {
        parameters: { Action: 'update_disclaimer_accepted', value: value },
        evalScripts: true,
        onComplete: function(transport) {  }
     });
}

var closeDisclaimerDiv = function() {
    $('disclaimerDivBackground').fade( {duration: 0.5} );
    $('disclaimerDiv').fade( {duration: 0.5} );
}

var showArticleCard = Class.create( {
    initialize: function(options) {
       var default_args = {
            'file'	:	"ajax/article_detaild_info.php",
            'element' : "ArticleDetaildInfo",
            'evalScripts' : false
        }
        var index;
        for(index in default_args) {
            if(typeof options[index] == "undefined") {
                options[index] = default_args[index];
            }
        }
       this.elementname = options['element'];
       this.element = $(this.elementname);
       this.file = options['file'];
       this.parameters = options;       
    },

    show: function() {
        this.hideArticleCard();
        this.element.insert({top: "<img style='left: 40%; position: relative;' src='pictures/loading-indicator.gif' id='articleCardLoadingIndicator'/>"});

        if (this.parameters['type'] == "articleInfo") {
            if (!$('detailedInfoFitsCars'+this.parameters['ArticleID'])){
                this.updateArticleCard();
                this.showArticleCard();
            } else {
                this.showArticleCard();
            }
        } else {
            this.updateArticleCard();
            this.showArticleCard();
        }
        
    },

    updateArticleCard: function(obj) {
        if (typeof this.parameters['type'] != "undefined" && this.parameters['type'] == "accessoryInfo") {

            var articleID =   this.parameters['articleid'];
            var sessionID = this.parameters['SessionID'];
            var countryID = this.parameters['Country'];
            var dontloadPrices = this.parameters['dont_show_prices'];

            if (countryID == "Latvia") {
                var latvia_sid = this.parameters['latvia_sid'];
                var add_to_articlename = this.parameters['add_to_articlename'];
                
                new Ajax.Updater("ArticleDetaildInfo", this.file, {
                                parameters: this.parameters,
                                insertion: Insertion.Bottom,
                                asyncronous: false,
                                evalScripts: this.parameters['evalScripts'],
                                onComplete: function() {
                                    // obj.showArticleCard();
                                    $('articleCardLoadingIndicator').remove();
                                    if (dontloadPrices != 1) {
                                        GetAjaxLatviaStockValues($('AccArticlesCommaText').innerHTML, latvia_sid, add_to_articlename);
                                    }
            	                    
                                    
                                }
                            });
                
            } else {
                new Ajax.Updater("ArticleDetaildInfo", this.file, {
                                parameters: this.parameters,
                                insertion: Insertion.Bottom,
                                asyncronous: false,
                                evalScripts: this.parameters['evalScripts'],
                                onComplete: function() {
                                    // obj.showArticleCard();
                                    if (dontloadPrices != 1) {
                                        GetAjaxFrebelStockValues($('AccArticlesCommaText').innerHTML, sessionID, countryID, 10000);
                                    }
            	                    
                                    $('articleCardLoadingIndicator').remove();
                                }
                            });
            }
            
            
        } else {
            new Ajax.Updater(this.elementname, this.file, {
                                parameters: this.parameters,
                                insertion: Insertion.Bottom,
                                asyncronous: false,
                                evalScripts: this.parameters['evalScripts'],
                                onComplete: function() {
                                    // obj.showArticleCard();
                                    $('articleCardLoadingIndicator').remove();
                                }
                            });

        }
        

    },

    showArticleCard: function(){
	  this.element.style.display = 'none';
	  if (document.body.scrollTop){
	    this.element.style.top = document.body.scrollTop + 100 + "px";
	  } else if (window.pageYOffset) {
	    this.element.style.top = window.pageYOffset + 100 +"px";
	  } else if (document.documentElement.scrollTop) {
	    this.element.style.top = document.documentElement.scrollTop + 100 +"px";
	  } else {
	    this.element.style.top = "100px";
	  }
	  this.element.style.display = 'inline';
	  	BrowserDetect.init();
		if (BrowserDetect.browser == 'Safari' && BrowserDetect.version < 4.0) {

		} else {
			new Draggable(this.elementname, {scroll: window, zindex: 5000});
		}
	},

    hideArticleCard: function(){
        var ArticleDivs = $$('#ArticleDetaildInfo input[name=leave_detailed_info]');
        for (var i = 0; i < ArticleDivs.length; i++){
            if (ArticleDivs[i].checked != true){
                ArticleDiv = ArticleDivs[i].parentNode.parentNode;
                ArticleDiv.parentNode.removeChild(ArticleDiv);
            }
        }
        this.element.style.display = 'none';
    }
});


Ajax.ToggleableAutocompleter = Class.create();
Object.extend(Object.extend(Ajax.ToggleableAutocompleter.prototype, Autocompleter.Base.prototype), {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
    this.blurHandler           = new Array();
    this.keydownHandler        = new Array();
    this.keypressHandler       = new Array();
  },

  disable: function() {
    var el = this.element;
    this.hide();

    if (this.blurHandler.length==0 && this.keydownHandler.length==0 && this.keypressHandler.length==0) {
        this._registerHandlers();
    }

    this.blurHandler.each( function(handler) {
      el.stopObserving('blur', handler);
      el.getStorage().get('prototype_event_registry').unset('blur');
    });

    this.keydownHandler.each( function(handler) {
      el.stopObserving('keydown', handler);
      el.getStorage().get('prototype_event_registry').unset('keydown');
    });

    this.keypressHandler.each( function(handler) {
      el.stopObserving('keypress', handler);
      el.getStorage().get('prototype_event_registry').unset('keypress');
    });
  },

  enable: function() {
    var ele=this.element;
    for (var i = 0; i < this.blurHandler.length; i++) {
      Event.observe(ele, "blur", this.blurHandler[i]);
    }
    for (var i = 0; i < this.keydownHandler.length; i++) {
      Event.observe(ele, "keydown", this.keydownHandler[i]);
    }
    for (var i = 0; i < this.keypressHandler.length; i++) {
      Event.observe(ele, "keypress", this.keypressHandler[i]);
    }
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  _registerHandlers: function() {
    var o = this;
    if ( !o.element.getStorage().get('prototype_event_registry').size() > 0 ) return;
    with( o.element.getStorage().get('prototype_event_registry') ) {
       var blurEvents = get('blur');
       var keypressEvents = get('keypress');
       var keydownEvents = get('keydown');
    }
    if( blurEvents ) blurEvents.each(function(e){
         o.blurHandler.push(e.handler);
    });
    if( keypressEvents ) keypressEvents.each(function(e){
         o.keypressHandler.push(e.handler);
    });
    if( keydownEvents ) keydownEvents.each(function(e){
         o.keydownHandler.push(e.handler);
    });
  }
});

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }

    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;

    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } else {

    }
  },
  update: function(position) {
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});

function article_data_export_download() {
    var ProductGroupID = $('ProductGroupID').value;
    var FileName = $('FileName').value;

    window.open('/file_download.php?ProductGroup=' + ProductGroupID + '&FileName=' + FileName);
}

function article_data_export_check_if_ready() {
    var pidValue = $('pidValue').value;
    var downloadButton = $('downloadButton');

    new Ajax.Request('ajax.php',
    {
        method: 'get',
        parameters: {PageName: 'checkProcess', pid: pidValue},
        onSuccess: function(transport){
            var running = transport.responseText;
            if (running == 100) {
                setTimeout("article_data_export_check_if_ready()", 5000);
            }
            else {
                Element.observe('downloadButton', 'click', article_data_export_download);
                $('ArticleExportFileReady').innerHTML = "The file is ready.";
                downloadButton.disabled = false;
                if (downloadButton.hasAttribute('disabled')) {
                    downloadButton.removeAttribute('disabled');
                }
                downloadButton.focus();
            }
        }
    });
}

function article_data_export() {
    var ProductGroupID = $('ProductGroupID').value;
    var SupplierID = $('SupplierID').value;
    var EmailAddress = $('ExportEmail').value;

    if ($('downloadButton')) {
        var downloadButton = $('downloadButton');
        downloadButton.setAttribute('disabled', 'disabled');
        downloadButton.disabled = true;
    }
    else {
        downloadButton = new Element('input', {id: 'downloadButton', type: 'button', disabled: 'disabled', value: 'Download'});
        Element.insert('ArticleExportFileReady', {
            after: downloadButton
        });
    }

    new Ajax.Request('ajax.php',
    {
        method: 'get',
        parameters: {PageName: 'article_data_export', ProductGroupID: ProductGroupID, SupplierID: SupplierID, EmailAddress: EmailAddress},
        onSuccess: function(transport){
            var pidValue = new Element('input', {id: 'pidValue', type: 'hidden'});
            Element.insert('ArticleExportFileReady', {
                after: pidValue
            });
            pidValue.value = transport.responseText;
            if ("Previous file is still being created!" == pidValue.value) {
                $('ArticleExportFileReady').innerHTML = pidValue.value;
                $('ArticleExportFileReady').style.display = "";
            }
            else {
                $('ArticleExportFileReady').innerHTML = "The file is being generated.";
                $('ArticleExportFileReady').style.display = "";
                article_data_export_check_if_ready();
            }
        }
    });
}

function noSpace(obj) {
     obj.value = obj.value.replace(/\s/g, "");
}
