//**************************************************************************************************************
var innerItemSeparator = "|";
var itemSeparator = "###";
var basketAddressSeparator = "_$_";
// basket str format... 
// fieldValue[0][0]|fieldValue[0][1]###fieldValue[n][0]|fieldValue[n][1]_$_userData[0]|userData[1]|userData[n]
//**************************************************************************************************************//

function Basket() {
  
  function messageHandler(message, params) {
  switch(message) {
    case "Add":
    if(belenusHome.shoppingEnabled != true) return;
//      alert("AddToBasket: " + params);
      
      if(getQueryField(params,"AddBy") == "PartData") {
        var paramArr =  belenusHome.queryStringToArray(params);
        var p = belenusHome.queryStringToArray(paramArr['PartData']);
       	
       	if(belenusHome.useInternalBasket) {
	        if(p['PartsURI'])  addItem(getQueryField(/*unescape*/(paramArr['PartData']),"PartData"),false,false);
	        else { // no 'PartsURI'
	          var partsURI = belenusHome.getProperty("Global","PartsURI", "ItemPath="+p['DeviceID']+"/"+p['ItemContextID']);
	          addItem(/*unescape*/(paramArr['PartData'])+"&PartsURI="+partsURI,"PartData",false);
	        }
        } else { // salesman section follows
             var addUrl = 'method=keys';
             if(typeof belenusHome.transferParameters['interparts_catalogue'] != "undefined" && belenusHome.transferParameters['interparts_catalogue'] != null && belenusHome.transferParameters['interparts_catalogue'] != "")
             	addUrl += "&distributor="+belenusHome.transferParameters['interparts_catalogue'];
             addUrl += '&criteria='+encodeURI(getQueryField(unescape(params),belenusHome.partnoField));
             if((null != belenusHome.getQueryField(unescape(params),'Sender') && belenusHome.getQueryField(unescape(params),'Sender') != "SearchResult")) {
	             var treepath = belenusHome.currentTreePath;
	             treepath = treepath.split("/");
	             var twoStepsAbove = treepath.slice(useTheLabelXStepsHigherThanCurrentlySelected,treepath.length-1);
	             var data = this.getItemDataFromGlobalModule(twoStepsAbove.join("/"));
	             var treeDataArr = queryStringToArray(data);
	             var mlabel = treeDataArr["Label"];
	             addUrl += "&ctx="+encodeURI(mlabel);
            } else {
             	// order comes from search result
             	var ctx = belenusHome.getQueryField(unescape(params),'context');
             	if(ctx != null) {
             		addUrl += "&ctx="+ ctx;
             	}        
	        }

	        var window = belenusHome.WM.getWindowReference('salesmanPartInfo');
	        if (window) {
	            try {
		        	window.location.href = belenusHome.belenusHomeRootPath+"../order/articleQuery?"+addUrl;
		        } catch (e) {
		        	try {
				    	belenusHome.WM.openWindow('salesmanPartInfo',addUrl,false);
				    } catch (e) {
					    belenusHome.doPopupBlockerTest();
				    }
		        }
	        } else {
	        	try {
			    	belenusHome.WM.openWindow('salesmanPartInfo',addUrl,false);
			    } catch (e) {
				    belenusHome.doPopupBlockerTest();
			    }
	        }
        }
        
      } else if(getQueryField(params, "AddBy") == "ItemPaths") {
        // handle a possible multiselection...
        basketMultiSelectionHandler(params, "ItemPath");
      } else {
        alert("Module: Basket\nMessage: AddToBasket\nParams: " + params + "\n\nUnable to handle this kind of data set yet!");
      }
    break;
    
    case "Show":
      if(belenusHome.openCartWindowEnabled == true) {
      	if(belenusHome.useInternalBasket)
	      	belenusHome.WM.openWindow('basket','',true);
	    else {
	    	var addUrl = "";
             if(typeof belenusHome.transferParameters['interparts_catalogue'] != "undefined" && belenusHome.transferParameters['interparts_catalogue'] != null && belenusHome.transferParameters['interparts_catalogue'] != "")
             	addUrl += "distributor="+belenusHome.transferParameters['interparts_catalogue'];	    
		    belenusHome.WM.openWindow('salesman',addUrl,false);
		}
      }
    break;
    
    default:
      alert("message =>" + message +"\nunknown");
    break;
  }
  }
  
  function getProperty(property, params) { 
    //alert(property +"\n"+ params +"\n\ngetProperty of Basket module") 
    if (property == "BasketEnabled") return "" + belenusHome.shoppingEnabled;
    return ""; 
  }
  
	function getItemDataFromGlobalModule(ip) {
		return belenusHome.getProperty("Global", "ItemData", "ItemPath=" + ip);
	}  

  
	this.messageHandler = messageHandler;
	this.getProperty = getProperty;
	this.getItemDataFromGlobalModule = getItemDataFromGlobalModule;
}
// register the basket module...
setTimeout('registerThisModule()',1);

function registerThisModule() {
	if(belenusHome.shoppingEnabled == true) {
	  try {
	    belenusHome.registerModule("Basket", new Basket());    
	  } catch(e) {
	    alert("Error occurred\n-Error-nr.: 05\n-Can not register module: <Basket>!\n\nError description: "+e.toString());
	  }
	}
}

/**
 basket = new Array()
 basket[0] = new Array() <-- quantity
 basket[1] = new Array() <-- partno....
**/


function initBasket() {
	belenusHome.belenusBasket = new Array();
	belenusHome.belenusBasketUserDatas = new Array();
	for(i in belenusHome.basketFields) {
		belenusHome.belenusBasket[i] = new Array();
	}
	if(belenusHome.saveCartOnExit || belenusHome.cookieActivate) {
		if(belenusHome.saveCartOnExit) {
			if(belenusHome.getXCookie("daBasket") != null) {
				strToArray(belenusHome.getXCookie("daBasket"));
			}
		}
	}
    
  /* 
    looks at the startup for the param 'HOOK_URL'
    if it was available, the default address to where the basket will be send 'sendBasketTo' (<-- defined at preferences.js)
    will be overwritten.
  */
  var hookUrl = getQueryField(belenusHome.location.search, 'HOOK_URL');
  belenusHome.sendBasketTo = (hookUrl != null) ? hookUrl : belenusHome.sendBasketTo;
}


function strToArray(str) {
//	alert("strToArray:"+str);
	var basketValue = null;
	var addressValue = null;
	
	if(str.indexOf(basketAddressSeparator) != -1) {
		basketValue = str.split(basketAddressSeparator)[0];	
		addressValue= str.split(basketAddressSeparator)[1];
		
		if(basketValue != "") {
			if(basketValue.indexOf(itemSeparator) != -1) {
				var items = basketValue.split(itemSeparator);
				for(i in items) {
					var itemCache = items[i].split(innerItemSeparator);
					if(itemCache.length == belenusHome.basketFields.length) {
						for(j in belenusHome.basketFields) {
							belenusHome.belenusBasket[j][i] = itemCache[j];
						}
					}
				}
			} else {
				if(basketValue.indexOf(innerItemSeparator) != -1) {
					var itemCache = basketValue.split(innerItemSeparator);
					if(itemCache.length == belenusHome.basketFields.length) {
						for(j in belenusHome.basketFields) {
							belenusHome.belenusBasket[j][0] = itemCache[j];
						}
					}
				}
			}
		}
		if(addressValue != "") {
			if(addressValue.indexOf(innerItemSeparator) != -1) {
				addressValue = addressValue.split(innerItemSeparator);
				for(k in belenusHome.basketAddressFields) {
          belenusHome.belenusBasketUserDatas[k] = belenusHome.checkValue(addressValue[k]);
				}
			}
		} else {
			for(k in belenusHome.basketAddressFields) {
				belenusHome.belenusBasketUserDatas[k] = "";
			}
		}
	}
}


function arrayToStr() {
	//alert("arrayToStr:"+belenusHome.belenusBasket);
	var bItems="";
	var aFields="";
	var undef;
	if((belenusHome.saveCartOnExit || belenusHome.cookieActivate) && (belenusHome.belenusBasket[0].length > 0)){

		for(i in belenusHome.belenusBasket[0]) { // run through the items...
		
			for(j in belenusHome.belenusBasket) {// run through the basketFields...
				var dash = (belenusHome.belenusBasket.length-1 == j) ? "" : innerItemSeparator;
				if(belenusHome.belenusBasket[j][i] != undef && belenusHome.basketFields[j] != belenusHome.jumpToCatalog[0]) {
					bItems += belenusHome.belenusBasket[j][i];
					bItems += dash;
				} else {
					bItems += dash;
				}
			}	
				var itemsDash = (belenusHome.belenusBasket[0].length-1 == i) ? "" : itemSeparator;
				bItems += itemsDash;
		}
		for(k in belenusHome.basketAddressFields) {
			var dash = (belenusHome.basketAddressFields.length-1 == k) ? "" : innerItemSeparator;
			if(belenusHome.belenusBasketUserDatas[k] != undef) {
				aFields += belenusHome.belenusBasketUserDatas[k];
				aFields += dash;
			} else {
				aFields += dash;
			}
		}

	}	
	belenusHome.cookieReset("daBasket");
	belenusHome.setXCookie("daBasket", bItems.concat(basketAddressSeparator).concat(aFields), belenusHome.basketCookieDurationTimeOfValidity);
	return bItems.concat(basketAddressSeparator).concat(aFields);
}



function belOrderItem(itemdata) {
  // for downward compatibility 
	addItem(itemdata,false,false);
}

function basketMultiSelectionHandler(params,handlingType) {
  var paramArr = belenusHome.queryStringToArray(params);
  var token = 0;
  var itemDataSets = new Array();
  while(paramArr[handlingType+""+token]) {
    var PartsURI = null;
    if(handlingType == "HotspotID") {
      PartsURI = getProperty("Global","PartsURI", "ItemPath"+"="+belenusHome.getProperty("Table","ItemListPath","HotspotID="+paramArr[handlingType+""+token]));
    } else if(handlingType == "ItemPath") {
      PartsURI = getProperty("Global","PartsURI", handlingType+"="+paramArr[handlingType+""+token]);
    }
    //alert(handlingType + "\nPartsURI:"+PartsURI);
    itemDataSets[itemDataSets.length] = belenusHome.getProperty("Table","PartData",handlingType+"="+paramArr[handlingType+""+token++]) + "&PartsURI="+PartsURI;
  }
  var partNOs = new Array();
  for(items in itemDataSets) {
    var multiSelection = (itemDataSets.length > 1) ? true : false;
    if(belenusHome.useInternalBasket) 
    	addItem(itemDataSets[items], multiSelection, false);
    else 
	    partNOs[partNOs.length] = belenusHome.getQueryField(itemDataSets[items],belenusHome.partnoField);
  }
  if(!belenusHome.useInternalBasket) {
   var addUrl = 'method=keys';
	if(typeof belenusHome.transferParameters['interparts_catalogue'] != "undefined" && belenusHome.transferParameters['interparts_catalogue'] != null && belenusHome.transferParameters['interparts_catalogue'] != "")
		addUrl += "&distributor="+belenusHome.transferParameters['interparts_catalogue'];	    
    addUrl += '&criteria='+partNOs.join(",");
	if(null != (belenusHome.getQueryField(unescape(params),'AddBy')) || (null != belenusHome.getQueryField(unescape(params),'Sender') && belenusHome.getQueryField(unescape(params),'Sender') != "SearchResult")) {   
		var treepath = belenusHome.currentTreePath;
		treepath = treepath.split("/");
		var twoStepsAbove = treepath.slice(useTheLabelXStepsHigherThanCurrentlySelected,treepath.length-1);
		var data = belenusHome.getModule("Basket").getItemDataFromGlobalModule(twoStepsAbove.join("/"));		
		var treeDataArr = queryStringToArray(data);
		var mlabel = treeDataArr["Label"];
		addUrl += "&ctx="+encodeURI(mlabel);  
	}
	try {
    	belenusHome.WM.openWindow('salesmanPartInfo',addUrl,false);
    } catch(e) {
	    belenusHome.doPopupBlockerTest();
    }
  }
}

function addItem(itemdata, multiSelection, adoptedByPartslinkObj) {
	//alert("itemdata:"+itemdata+"\n\nmultiSelection:"+multiSelection+"\n\nadoptedByPartslinkObj:"+adoptedByPartslinkObj);
	if(adoptedByPartslinkObj == false && belenusHome.usePartslinkConnector == true) { // send it to the partslink obj for verifying
		PLBH.pLGetPartInfo(itemdata);
		return;
	} 
	if(itemdata != "null" && belenusHome.shoppingEnabled == true) {
		var itemData = new Array(); // a temp array
		for(iBindex in belenusHome.basketFields) { // get itemdata.....
			if(belenusHome.basketFields[iBindex] == belenusHome.ociMasternum) {
				// at using oci_interface get MasterNumber...
				itemData[iBindex] = (helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex].concat(belenusHome.supNo)) == null) ? "" : helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex].concat(belenusHome.supNo));
			} else {
				if(belenusHome.basketFields[iBindex] == belenusHome.quantityField) { // if the quantity field is
					if(helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]) == undef || // undef
							helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]) == null ||  // null
							helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]) == "" ||  // ""
							helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]) == "null" || // "null"
							isNaN(parseFloat(Math.abs(helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex])))) || // isNan
							helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]) <= 0) { // <= 0
						itemData[iBindex] = "1"; // then set it to 1
					} else { 
						itemData[iBindex] = helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]);
					}
				} else {
					itemData[iBindex] = helpGettingRightFieldValue(itemdata, belenusHome.basketFields[iBindex]);
				}
			}
		}
		//		alert("controllItem(itemData):"+controllItem(itemData));
		var detectItem = controllItem(itemData);
		for(n in itemData) { // delete entries with null or "null" value... a CLEAN UP
			if(itemData[n] == "null" || itemData[n] == null) {
				itemData[n] = "";
			}
		}
		//		if(belenusHome.multiselection == true || belenusHome.belenusBasketConfirmPopupWindow == false) {
		if(multiSelection == true || belenusBasketConfirmPopupWindow == false || adoptedByPartslinkObj == true) {
			nowFinallyAddTheItem(itemData, detectItem);
		} else {
			popup(itemData, detectItem);
		}
	} 
}
//the follow two function are used by addItem... see above..

//this function opens a popup window
//@itemData is the current set of data which should be added to the basket....
//@detectItem if the item is already available in the basket, than it means the position (index)... if it doesn't exists than it is "false"
function popup(itemData, detectItem) {
	var keyValuePairs = "";
	for(keys in belenusHome.basketFields) {
		keyValuePairs += belenusHome.basketFields[keys] + "=" + itemData[keys] + "&";
	}
	this.basketCache = itemData; // using for editing from the popup (quantity...)
	belenusHome.WM.openWindow("basketPopup", "detectItem="+detectItem, true);
}

//this function will be called by the popup window... the function above handle the popup...
//@param also see above
function nowFinallyAddTheItem(itemData, detectItem) {
	//alert("nowFinallyAddTheItem(itemData, detectItem)\n\n-itemData: "+itemData+"\n-detectItem: "+detectItem);
	detectItem = controllItem(itemData);
	if(detectItem == "false") {
		for(i in belenusHome.belenusBasket) {
			belenusHome.belenusBasket[i][belenusHome.belenusBasket[i].length] = itemData[i];
		}
	} else {
		detectItem = parseInt(detectItem);
		for(k in belenusHome.basketFields) {
			if(belenusHome.basketFields[k] == belenusHome.quantityField) { // <-- FOUND QUANTITY FIELD
				belenusHome.belenusBasket[k][detectItem] = parseInt(belenusHome.belenusBasket[k][detectItem])+parseInt(itemData[k]); // add together the amount... 
			}
		}	
	}
	// if the basket window is open... refresh it.. so that it will be updated
	try {
		if(belenusHome.WM.getWindowReference("basket") != null) { // is the window avialable?
			if(belenusHome.useTabManager && Windows["basket"][5] != "") {
				var fProps = belenusHome.document.getElementById('MainFrameSet').getAttribute("Rows").split(","); //frame properties
				var tabPos = (belenusHome.showVersionAlert) ? fProps.length-2 : fProps.length-1;
				if(parseInt(fProps[tabPos]) > 0) belenusHome.WM.getWindowReference("basket").location.reload();
			} else {
				if(belenusHome.WM.getWindowReference("basket").closed == false) { // is the window open?
					belenusHome.WM.getWindowReference("basket").location.reload(); // it's open... reload...
				}
			}
		}
	} catch(e) {
		//catched a non remote server computer error -> winparts&popups
	}
	arrayToStr();
	set_gui_basket_status();
}
	
	
function delItem(itemIndex, askForIt) { // @askForIt boolean
  var delIt = true;
  if(belenusHome.delConfirmDialog && askForIt) {
    if(belenusHome.WM.getWindowReference("basket") != undef || belenusHome.WM.getWindowReference("basket") != null)
    delIt = belenusHome.WM.getWindowReference("basket").confirm(belenusHome.ld["del_art"]);
    else {
      delIt = confirm(belenusHome.ld["del_art"]);
      belenusHome.blur();    
    }
  }
  if(delIt) {
	var arrayLength = belenusHome.belenusBasket.length;
	for(var i = 0; i < arrayLength; i++) {
		var cache = new Array();
		var k = 0;
		for(j in belenusHome.belenusBasket[i]) {
			if(j != itemIndex) {
				cache[k++] = belenusHome.belenusBasket[i][j];
			}
		}
		belenusHome.belenusBasket[i] = cache;
	}
	arrayToStr();
	set_gui_basket_status();
  }
}


function delAllItems(askForIt) { // @askForIt boolean
  if(belenusHome.belenusBasket[0].length > 0) {
    var delAll = true;
    if(belenusHome.delAllConfirmDialog && askForIt) {
      if(belenusHome.WM.getWindowReference("basket") != undef || belenusHome.WM.getWindowReference("basket") != null)
      delAll = belenusHome.WM.getWindowReference("basket").confirm(belenusHome.ld["del_all"]);
      else {
        delAll = confirm(belenusHome.ld["del_all"]);
        belenusHome.blur();
      }
    }
    if(delAll) {
    	for(i in belenusHome.belenusBasket[0]) {
    		delItem(belenusHome.belenusBasket[0].length-1,false);
    	}
      belenusHome.cookieReset("daBasket"); // also delete user input
    }
	}
}


function editItem(fieldName, itemIndex, value) {
	var detectedField = "notDetected";
	for(i in belenusHome.basketFields) { // get right field index
		if(fieldName == belenusHome.basketFields[i]) detectedField = i;
	}

	if(detectedField != "notDetected") { // go on...
  
        var cacheDataSet = new Array();
        for(dub in belenusHome.basketFields) {
          if(detectedField == dub)
            cacheDataSet[dub] = value;
          else cacheDataSet[dub] = belenusHome.belenusBasket[dub][itemIndex];
        }
        var aSameIsExisting = controllItem(cacheDataSet);  
        
        if(aSameIsExisting != "NotFound" && itemIndex != aSameIsExisting) {
          nowFinallyAddTheItem(cacheDataSet, aSameIsExisting)
          delItem(itemIndex,false);
        } else {
    
    var Komma = false;
    if(fieldName == belenusHome.quantityField) {
      Komma = value+="";
      Komma = (value.indexOf(",") != -1) ? true : false;
      value = parseFloat(value.replace(/,/,"."));
    }
    
		if(fieldName == belenusHome.quantityField && (value == 0 || isNaN(value))) { //if someone change the quantity to 0.... delete item
      			delItem(itemIndex,false);
		} else {
			if(fieldName == belenusHome.quantityField) { // save as right value... if it is the quantity field....
        if(Komma) {
          value +="";
          value = value.replace(/\./,",");
        }
				belenusHome.belenusBasket[detectedField][itemIndex] = value;
			} else {
				belenusHome.belenusBasket[detectedField][itemIndex] = value;
			}
			arrayToStr();
		}
        } // aSameIsExisting after editing an item
        
	} else { // field not found
		alert("The field, that U want to change is not defined in belenusHome.basketFields");
	}
}

/****************************************************************************************************************\
|** secondary basket functions																				   **|
|** e.g. addresse and other user datas																		   **|
\****************************************************************************************************************/


function getUserData(key) { // e.g. Name, Street, City....
	var	fieldIndex = "NotFound";
	for(i in belenusHome.basketAddressFields) {
		if(belenusHome.basketAddressFields[i] == key) {
			 fieldIndex = i;
		}
	}
//	alert("getUserData("+key+"):"+fieldIndex);
	if(fieldIndex != "NotFound") {
    var undef;
    if(belenusHome.belenusBasketUserDatas[fieldIndex] != undef) {
      return belenusHome.belenusBasketUserDatas[fieldIndex];
    } else {
		  return "";
    }
	} else {
		return fieldIndex;
	}
}


function setUserData(key, value) {
	var	fieldIndex = "NotFound";
	for(i in belenusHome.basketAddressFields) {
		if(belenusHome.basketAddressFields[i] == key) {
			 fieldIndex = i;
		}
	}
	if(fieldIndex != "NotFound") {
		belenusHome.belenusBasketUserDatas[fieldIndex] = value;
	}
	arrayToStr();
}

var checkInput = new Array();
function checkUserInput(inputWinRef) {
  checkInput = new Array();
  var doc = inputWinRef.document;
  for(var bAF = 0; bAF < belenusHome.basketAddressFields.length; bAF++) {
    var controllThisItem = true;
    for(var bN4VAF = 0; bN4VAF < belenusHome.basketNot4VerifyAddressFields.length; bN4VAF++) {
      if(belenusHome.basketAddressFields[bAF] == belenusHome.basketNot4VerifyAddressFields[bN4VAF]) {
        controllThisItem = false;
        break;
      }
    }
    if(controllThisItem) {
      if(getUserData(belenusHome.basketAddressFields[bAF]) == "") checkInput[checkInput.length] = belenusHome.basketAddressFields[bAF];
    }
  }
  if(checkInput.length != 0) {
    for(all in belenusHome.basketAddressFields) {
      if(doc.getElementById(belenusHome.basketAddressFields[all]+"_label")) {
        doc.getElementById(belenusHome.basketAddressFields[all]+"_label").className = "FineUserInput";
      }
    }
    for(f in checkInput) {
      if(doc.getElementById(checkInput[f]+"_label")) {
        doc.getElementById(checkInput[f]+"_label").className = "MissingUserInput";
      }
    }
  }
}


/****************************************************************************************************************\
|** internal functions....																					   **|
\****************************************************************************************************************/

// return false if no entry was found, which was equal.... else it returns the position where it was found....
function controllItem(itemDataArray) {
	var controllingFields = new Array();
	for(i in belenusHome.basketFields) {
		for(j in belenusHome.basketItemIDFields) {
			if(belenusHome.basketFields[i] == belenusHome.basketItemIDFields[j]) {
				controllingFields[controllingFields.length] = i;
			}
		}
	}
var foundedEqualKeys = -1;
	for(i in belenusHome.belenusBasket[0]) {
		for(j in controllingFields) {
			if(belenusHome.belenusBasket[controllingFields[j]][i] == itemDataArray[controllingFields[j]]) { // if an entry was found which doesn't have to exisit twice....
				foundedEqualKeys++;
			}
		}
	  if(foundedEqualKeys == j) return i;
    foundedEqualKeys = -1;    
	}
	return "false";
}


function helpGettingRightFieldValue(itemdata, normalFieldName) {
	var subSign = belenusHome.subTableFieldsIdentifier;
	var returningValue = belenusHome.getQueryField(itemdata, subSign.concat(normalFieldName));
	if(returningValue != null) {
		return returningValue;	
	} else {
		var temp = belenusHome.getQueryField(itemdata, normalFieldName);
		if(temp == null) {
			//alert("!! Field \""+normalFieldName+"\" or subfield contains no data, or not exists");
			return null;
		} else {
			return temp;
		}
	}
}


/****************************************************************************************************************\
|** sort functions....																				   		   **|
\****************************************************************************************************************/

	      function numCompare(a,b) {
    	      return a.substring(0, a.lastIndexOf(':')) - b.substring(0, b.lastIndexOf(':'));
	      }
	      
	      function addColon(arr) {
		      for (var i = 0; i < arr.length; i++) arr[i] = arr[i] + ':' + i;
	      }
	      
	      function duplicateArray(arr) {
		      var newArr = new Array();
		      for (var i = 0; i < arr.length; i++) newArr[i] = arr[i];
		      return newArr;
	      }
	      
	      function removeColon(arr) {
		      for (var i = 0; i < arr.length; i++) arr[i] = arr[i].substring(arr[i].lastIndexOf(':') + 1);
	      }
	
			function reorganizeAllArrays(newArrangement) {
				var cache = new Array();
				for(i in belenusHome.belenusBasket) {
					for(j in belenusHome.belenusBasket[0]) {
						cache[j] = belenusHome.belenusBasket[i][newArrangement[j]]
					}
					belenusHome.belenusBasket[i] = cache;
					cache = new Array();
				}
			}
		

function sortBasket(fieldName, strOrInt) {
	if(fieldName != null) {
		var fieldIndex = getFieldPos(belenusHome.basketFields, fieldName);
		if(fieldIndex == null) {
			alert("Error: in basket.js --> sortBasket(), field for sorting not found\nHave a look at the preferences.js");
		} else {
			var tempArray = belenusHome.belenusBasket[fieldIndex];
			var copy = duplicateArray(tempArray);
			addColon(copy);
			if(strOrInt == "string") {
				copy.sort();
			} else {
				copy.sort(numCompare);
			}
			removeColon(copy);
			reorganizeAllArrays(copy);
		}
	}
}


/****************************************************************************************************************\
|** inti basket....																					   		   **|
\****************************************************************************************************************/

initBasket();


/****************************************************************************************************************\
|** GUI functions....																					   	   **|
\****************************************************************************************************************/

// sets the red point before the basket label in the header bar... 
// use the function which is defined in the header_lib.js (onOrderImgChange)...

function set_gui_basket_status() {
  var filled = (belenusHome.belenusBasket[0].length>0) ? "true" : "false";
  belenusHome.eventHandler("ChangedBasketContent","Filled="+filled);
}


var mozControlAmount = new Array(belenusHome.belenusBasket[0].length);
//paintBasket(..)
//@alterable true|false . if true the quantity field is alterable else it's not alterable
function paintBasket(windowReference, alterable) {
	belenusHome.sortBasket(basketSortField, basketSortMode);
	var d = windowReference.document; // get the document...

    if(alterable && belenusHome.usePartslinkConnector) {
      d.write('<form style="width:99%" onsubmit="if(document.getElementById(\'partno\').value != \'\') {belenusHome.PLBH.pLGetPartInfo(\''+belenusHome.partnoField+'=\'+document.getElementById(\'partno\').value);document.getElementById(\'partno\').value=\'\'}; return false;">');
      d.write('<table width="100%" border="0" cellpadding="0" cellspacing="0">');
      d.write('<tr>');
      d.write('<td colspan="4">&nbsp;</td>');
      d.write('</tr>');
      d.write('<tr class="header">');
      d.write('  <td colspan="3" style="border: 0px solid #E8EBED;border-left-width:0px;">');
      d.write('  <table border="0" cellpadding="0" cellspacing="0">');
      d.write('		<tr>');
      d.write('			<td id="'+belenusHome.addLKey("a38"+Math.random(),windowReference,"","directInputTxt0")+'">&nbsp;'+belenusHome.ld['directInputTxt0']+'</td>');
      d.write(' 			<td><input type="text" value="" id="partno" size="12"></td><td>&nbsp;</td>');
      d.write('			<td valign="middle"><input type="button" class="tab" id="'+belenusHome.addLKey("a39"+Math.random(),windowReference,"inputButton","directInputTxt1")+'" value="'+belenusHome.ld['directInputTxt1']+'" ');
      d.write(' 						onclick="javascript:if(document.getElementById(\'partno\').value != \'\') {belenusHome.PLBH.pLGetPartInfo(\''+belenusHome.partnoField+'=\'+document.getElementById(\'partno\').value);document.getElementById(\'partno\').value=\'\';}">');
      d.write('			</td>');
      d.write('		</tr>');
      d.write('	</table>');
      d.write(  '<td valign="top" align="right"><table width="8" height="26" border="0" cellpadding="0" cellspacing="0"><tr><td height="8"><img src="'+belenusHome.getPath('custom/images/top_gradient.gif')+'"></td></tr><tr height="10"><td></td></tr><tr><td><img src="'+belenusHome.getPath('custom/images/bottom_gradient.gif')+'"></td></tr></table></td>');
      d.write('</tr>');
      d.write('</table><image type="submit" src="../images/html/i.gif" width="1" height="1">');
      d.write('</form><br>');
    }  
  
	if(belenusHome.belenusBasket[0].length < 1) {
		d.write('<br>&nbsp;<div style="margin-top:30px" align="center" id="'+belenusHome.addLKey("a40"+Math.random(),windowReference,"","wkleer")+'">'+belenusHome.ld['wkleer']+'</div>');
	} else {
		var commonSumPrice = 0;
		d.write('<form name="basketCanvas" onsubmit="return false;">');
		d.write('<table width="100%" border="0" cellpadding="2" cellspacing="1">');
		
		// paint table header.....
		d.write('<tr>'); 
		d.write('<th align="left" id="'+belenusHome.addLKey("a41"+Math.random(),windowReference,"","basketHeader_consecutiveNumber")+'">'+belenusHome.ld['basketHeader_consecutiveNumber']+'</th>');
		for(tdHeader in belenusHome.visibleBasketFields) {
			if(belenusHome.visibleBasketFields[tdHeader] == belenusHome.priceField) {
				d.write('<th id="'+belenusHome.addLKey("a42"+Math.random(),windowReference,"",'basketHeader_'+belenusHome.visibleBasketFields[tdHeader])+'">'+belenusHome.ld['basketHeader_'+belenusHome.visibleBasketFields[tdHeader]]+'</th>');
				d.write('<th id="'+belenusHome.addLKey("a43"+Math.random(),windowReference,"",'basketHeader_sumPrice')+'">'+belenusHome.ld['basketHeader_sumPrice']+'</th>');
			} else {
				if(belenusHome.visibleBasketFields[tdHeader] != belenusHome.priceField) {
					d.write('<th align="left" id="'+belenusHome.addLKey("a44"+Math.random(),windowReference,"",'basketHeader_'+belenusHome.visibleBasketFields[tdHeader])+'">'+belenusHome.ld['basketHeader_'+belenusHome.visibleBasketFields[tdHeader]]+'</th>');
				}
			}
		}
		d.write('</tr>');
		
		// paint basket items
		for(i in belenusHome.belenusBasket[0]) { // runs through every entry in the basket
			d.write('<tr class="basket_row'+i%2+'">');
			if(typeof belenusHome.runningNumberFormat != "undefined" && belenusHome.runningNumberFormat == "style1") {
				var runningNum = "";
				var numX = parseInt(i)+1;
				if(numX < 10) runningNum = "00"+numX;
				else if(numX < 100) runningNum = "0"+numX;
				else runningNum = numX;
				
				d.write('<td valign="top">'+runningNum+'&nbsp;&nbsp;</td>');
			} else
				d.write('<td valign="top">'+eval(parseInt(i)+1)+')&nbsp;&nbsp;</td>');
			var amount=null;		
			for(j in belenusHome.visibleBasketFields) {	// 
				if(belenusHome.visibleBasketFields[j] == belenusHome.quantityField) { 
					//quantityProperties BLOCK....
					amount = belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.visibleBasketFields[j])][i];
					var Komma = amount+="";
					Komma = (Komma.indexOf(",") != -1) ? true : false;
					var shownAmount = amount = parseFloat(amount.replace(/,/,"."));
					if(Komma) {
						shownAmount+="";
						shownAmount = shownAmount.replace(/\./,",");
						//alert("amount:"+amount+"\nshownAmount:"+shownAmount);
					}
					if(alterable) {
						mozControlAmount[i] = shownAmount;
						d.write('<td nowrap valign="middle" id="tdRow'+i+'">');
						d.write('<input type="text" size="5" id="quantityField'+i+'" oldValue="'+amount+'" style="text-align:right" value="'+shownAmount+'" ');
						d.write(' onkeydown="var keY = (event.keyCode) ? event.keyCode : event.which; if(keY==13)if(!isNaN(this.value) && this.value != \'\') { belenusHome.editItem(belenusHome.quantityField, '+i+', Math.abs(this.value));self.location.href=self.location.href;} else { alert(belenusHome.ld[\'error1\']);this.value=this.getAttribute(\'oldValue\')}";" ');
						d.write(' onchange="if(!isNaN(this.value) && this.value != \'\') { belenusHome.editItem(belenusHome.quantityField, '+i+', Math.abs(this.value));self.location.href=self.location.href;} else { alert(belenusHome.ld[\'error1\']);this.value=this.getAttribute(\'oldValue\')}"></input>');
						d.write(' <a href="javascript:belenusHome.delItem('+i+',true);self.location.href=self.location.href"  title="'+belenusHome.ld["p_tt_delete"]+'" alt="'+belenusHome.ld["p_tt_delete"]+'" id="'+belenusHome.addLKey("a45"+Math.random(),windowReference,"title",'p_tt_delete')+'"><img src="../custom/images/delete.gif" border="0"></a>&nbsp;');
					} else {
						d.write('<td valign="top">'+shownAmount+'</td>');
					}
					d.write('</td>');
					
				} else { // no quantity block
					if(belenusHome.visibleBasketFields[j] == belenusHome.priceField) {
						//priceField BLOCK
						var singlePrice = belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.visibleBasketFields[j])][i];
						var itemSumPrice = getItemSumPrice(singlePrice, amount);
						commonSumPrice += itemSumPrice; // summate
						
						d.write('<td align="right" valign="top">');
						d.write(priceParser(singlePrice));
						d.write('</td>');
						
						d.write('<td align="right" valign="top">');
						d.write(priceParser(itemSumPrice));
						d.write('</td>');					
						
					} else { // no quantity & no price block
						//other fields...
						if(belenusHome.visibleBasketFields[j] != belenusHome.priceField && belenusHome.visibleBasketFields[j] != belenusHome.quantityField) {
							
							var isLink = "NO"; // "NO" because if i use false, js thinks that 0 & false is the same! And so it ignores the first entry...
							for(linkFields in belenusHome.jumpToCatalog[2]) { // look if the field should have a link propertie.....
								if(	belenusHome.visibleBasketFields[j] == belenusHome.jumpToCatalog[2][linkFields] &&
										belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.jumpToCatalog[0])][i] != "") isLink = linkFields;
							}
							
							if(belenusHome.jumpToCatalog[1] == true && isLink != "NO") {
								//do generate a <a href=""...> tag around the field....
								d.write('<td valign="top">');
								d.write('<a href="javascript:if(belenusHome.autoTabMinimize)belenusHome.minimizeTab();void(belenusHome.eventHandler(\'OpenLink\',\'URL=parts:'+belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.jumpToCatalog[0])][i]+'\'))">'+belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.visibleBasketFields[j])][i]+'</a>');
								d.write('</td>');									
							} else {
								//without a link
								d.write('<td valign="top">');
								d.write(belenusHome.belenusBasket[getFieldPos(belenusHome.basketFields, belenusHome.visibleBasketFields[j])][i]);
								d.write('</td>');									
							}
						}			
					}
				}
			}
			d.write('</tr>');
		} // end of looping through the items (for)
		d.write('</table>');
		
		if(belenusHome.priceField != null && belenusHome.basketTax != null) {
			var inclTax;
			if(belenusHome.basketTax.search(/\./) == -1) {
				inclTax=eval('1.'+belenusHome.basketTax);
			} else {
				inclTax=eval('1.'+belenusHome.basketTax.replace(/\./, ""));
			}		
			d.write('<table>');
			
			if(belenusHome.usePartslinkConnector && belenusHome.tp("accountType") == "guest") {
				belenusHome.shipCost = parseFloat(belenusHome.shipCost);
				d.write('<tr>');
				d.write('<td width="100%" valign="top" id="'+belenusHome.addLKey("a46"+Math.random(),windowReference,"",'tdLabel_shipCost')+'">'+belenusHome.ld['tdLabel_shipCost']+'</td>');
				d.write('<td align="right" valign="top">'+priceParser(belenusHome.shipCost)+"".replace(/\./,",")+'</td>');
				d.write('</tr>');
			} else {
				belenusHome.shipCost = 0;
			}       
			d.write('<tr>');
			d.write('<td width="100%" valign="top" id="'+belenusHome.addLKey("a47"+Math.random(),windowReference,"",'basketHeader_LSP_netto')+'">'+belenusHome.ld['basketHeader_LSP_netto']+'</td>');
			d.write('<td align="right" valign="top">'+priceParser(priceRound(commonSumPrice+belenusHome.shipCost))+'</td>');
			d.write('</tr>');
			d.write('<tr>');
			d.write('<td valign="top"><span id="'+belenusHome.addLKey("a48"+Math.random(),windowReference,"",'basketHeader_Tax')+'">'+belenusHome.ld['basketHeader_Tax']+'</span> '+belenusHome.basketTax+'</span>%</td>');
			d.write('<td align="right" valign="top">'+priceParser(priceRound(((commonSumPrice+belenusHome.shipCost)/100)*belenusHome.basketTax))+'</td>');
			d.write('</tr>');			
			d.write('<tr>');
			d.write('<td valign="top" id="'+belenusHome.addLKey("a49"+Math.random(),windowReference,"",'basketHeader_LSPIncludeTax')+'">'+belenusHome.ld['basketHeader_LSPIncludeTax']+'</td>');
			d.write('<td align="right" valign="top">'+priceParser(priceRound((commonSumPrice+belenusHome.shipCost)*inclTax))+'</td>');
			d.write('</tr>');
			d.write('</table>');      
			
		} else if(belenusHome.priceField != null && belenusHome.basketTax == null) {
			d.write('<table>');
			
			if(belenusHome.usePartslinkConnector && belenusHome.tp("accountType") == "guest") {
				belenusHome.shipCost = parseFloat(belenusHome.shipCost);
				if(belenusHome.shipCost > 0) {
					d.write('<tr>');
					d.write('<td width="100%" valign="top" id="'+belenusHome.addLKey("a50"+Math.random(),windowReference,"",'tdLabel_shipCost')+'">'+belenusHome.ld['tdLabel_shipCost']+'</td>');
					d.write('<td align="right" valign="top">'+priceParser(belenusHome.shipCost)+"".replace(/\./,",")+'</td>');
					d.write('</tr>');
				}
			} else {
				belenusHome.shipCost = 0;
			}       
			if(belenusHome.priceField != null) {
				d.write('<tr>');
				d.write('<td width="100%" valign="top" id="'+belenusHome.addLKey("a51"+Math.random(),windowReference,"",'basketHeader_LSP_netto')+'">'+belenusHome.ld['basketHeader_LSP_netto']+'</td>');
				d.write('<td align="right" valign="top">'+priceParser(priceRound(commonSumPrice+belenusHome.shipCost))+'</td>');
				d.write('</tr>');
			}
			d.write('</table>');      		
		}
		
		// end paint table for items content
		d.write('</form>');
	}
	if(alterable && belenusHome.browserName != "Internet Explorer") { 
		for(var moz = 0; moz < mozControlAmount.length; moz++) {
			var newTxtField = windowReference.document.createElement("input");
			newTxtField.setAttribute("id","quantityField"+moz);
			newTxtField.setAttribute("value",mozControlAmount[moz]);
			newTxtField.setAttribute("oldValue",windowReference.document.getElementById("quantityField"+moz).getAttribute("oldValue"));
			newTxtField.setAttribute("style",windowReference.document.getElementById("quantityField"+moz).getAttribute("style"));
			newTxtField.setAttribute("onChange",windowReference.document.getElementById("quantityField"+moz).getAttribute("onchange"));
			newTxtField.setAttribute("size",windowReference.document.getElementById("quantityField"+moz).getAttribute("size"));
			newTxtField.setAttribute("type",windowReference.document.getElementById("quantityField"+moz).getAttribute("type"));
			windowReference.document.getElementById("tdRow"+moz).replaceChild(newTxtField,windowReference.document.getElementById("quantityField"+moz));
		}		
	}
    if(alterable && belenusHome.usePartslinkConnector)
      windowReference.document.getElementById('partno').focus();	
}


function writeDate(){
	var monat = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
	var heute=new Date();
	return heute.getDate()+ "." +monat[heute.getMonth()]+ "." +heute.getYear();
}


//**************************************************************************************************************************************************
// -submit basket &-paint submit fields methodes
//**************************************************************************************************************************************************/

function sendBasket(mode) { // allowed params "server" & "email"
	if(belenusHome.belenusBasket[0].length>0) {
    if(mode == "server") {
  		if(belenusHome.oci_interface) {
  			belenusHome.sendOCIBasket(); // calls an other method which handels the way of sending to the sap interface, defined in oci_generator.js...
  		} else {
  			belenusHome.whereIsTheForm.document.forms['standardBasketForm4ServerSubmit'].submit();
  			belenusHome.delAllItems(false);
        
          var fProps = belenusHome.document.getElementById('MainFrameSet').getAttribute("Rows").split(","); //frame properties
          var tabPos = (belenusHome.showVersionAlert) ? fProps.length-2 : fProps.length-1;
          if(parseInt(fProps[tabPos]) > 0) belenusHome.WM.getWindowReference("basket").location.reload();        
        
  			belenusHome.WM.closeWindow('printPopup');
        //belenusHome.WM.closeWindow('basketPopup');
        if(!belenusHome.includedOrPopupBasket) setTimeout("belenusHome.WM.closeWindow(belenusHome.basketWinName)",1);
        else setTimeout("belenusHome.WM.closeWindow(belenusHome.basketWinName+'Extra')",1);
  		}
  	} else {
      if(mode == "email") {
        belenusHome.whereIsTheForm.document.forms['standardBasketForm4EmailSubmit'].submit();
        belenusHome.delAllItems(false);
        
          var fProps = belenusHome.document.getElementById('MainFrameSet').getAttribute("Rows").split(","); //frame properties
          var tabPos = (belenusHome.showVersionAlert) ? fProps.length-2 : fProps.length-1;
          if(parseInt(fProps[tabPos]) > 0) belenusHome.WM.getWindowReference("basket").location.reload();
                  
        belenusHome.WM.closeWindow('printPopup');
        belenusHome.WM.closeWindow('basketPopup');
        if(!belenusHome.includedOrPopupBasket) setTimeout("belenusHome.WM.closeWindow(belenusHome.basketWinName)",1000);
        else setTimeout("belenusHome.WM.closeWindow(belenusHome.basketWinName+'Extra')",1000);
        //if(belenusHome.includedOrPopupBasket) belenusHome.document.getElementById("basketFrame").setAttribute("src",belenusHome.document.getElementById("basketFrame").getAttribute("src"));
      }
    } // no server submit
  } // empty basket
}


//**************************************************************************************************************************************************
// helping methodes 
//**************************************************************************************************************************************************

function getItemSumPrice(singlePrice, amount) {
	singlePrice = (singlePrice == null) ? 0 : parseFloat(singlePrice.replace(/,/,"."));
	amount = (amount == null) ? 1 : parseFloat(amount);
	return priceRound(singlePrice * amount);
}


function priceRound(value){
	return (Math.round(value*100) / 100);
}


function priceParser(value) {
	value+="";
	value = value.replace(/\./,",");
	var point = value.indexOf(",");
	if(point == -1) {
		value+=",00";
	} else {
		if(value.length-value.substring(0,point).length == 2) {
			value += "0";
		}
		if(value.length-value.substring(0,point).length > 2) {
			value = value.substring(0, point+3);
		}
	}
	return value;
}


function getFieldPos(atArray, fieldName) {
	for(kcuf in atArray) {
		if(atArray[kcuf] == fieldName) {
			return kcuf;
		}
	}
	return null;
}

 function usrInputCheck(winRef,type,value) {
  var internalWinRef = (winRef == "none") ? self : winRef;
  switch(type) {
    case("num"):
      if(isNaN(Math.abs(value))) {
        internalWinRef.alert(belenusHome.ld['error1']);
         return false;
      }
      else return true;
    break;
    
    case("alphaNum"):
      var undef;
      if(value != undef && value != "") return true;
      else return false;      
    break;
    
    case("notEmpty"):
      var undef;
      if(value != undef && value != "") return true;
      else {
        return false;
      }
    break;
  
    default: return false;
  }
}