//--------------------------------------------------------------------------------------
//Setup Ajax-Functionality
//--------------------------------------------------------------------------------------
function setUpAjax() {
  $.ajaxSetup ({
      //don't cache the requests, will append a random id to the request,
      cache: false,
      //this function will be called before each request
      beforeSend:function(req) {
        //alert ('before Send');
        ajaxBusy = true;
        $('body').css('cursor', 'wait'); 
      },
      complete:function(req) {
        //alert ('JSon complete');
        ajaxBusy = false;
         $('body').css('cursor', 'default'); 
        //alert (req.responseText);
        if (req.responseText == '{"string":"errorCode=needsLogin"}') {
           alert('Die verbindung ist abgelaufen. Bitte melden Sie sich neu an. Danke');
           location.href = '../login/home.do';
           return false;
        }
      },
    //Timeout after 5000ms, when there is no response to the request
    timeout: 30000,
    //Called if the response-code is an error
    error:function (XMLHttpRequest, textStatus, errorThrown) {
      alert ('Server-Timeout');
      ajaxBusy = false;
      $('body').css('cursor', 'default'); 
    }
  });
}
//--------------------------------------------------------------------------------------
//END Sidebar-Functionality
//--------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------
//Setup Sidebar-Functionality
//--------------------------------------------------------------------------------------

function setupSidebarFunctionality() {
    //----------------------------------------------------------------------------------
    //Setup Search-Form
    //----------------------------------------------------------------------------------
    
    $('#searchForm').submit(function (event) {    
        var sb = $("#suchbegriff").val();
        var href = "../suche/show.do";    
        //abort
        return true; 
        $.get(href, {suchbegriff:sb}, function(data){          
                //move all into a div
                var $response = $('<div />').html(data);
                ///find the relevant part without the embedding header etc.
                var $content = $response.find('#content').html();
                //set the content of the holder
                $("#content").html($content);
        });
    });   
    //----------------------------------------------------------------------------------
    //End Search-Form
    //---------------------------------------------------------------------
    
      $('a[rel="toggleBox"]').click( function() {
         if (!ajaxBusy) {
           var name = $(this).attr('name');
           var p = $(this).find('div').eq(0);
           p.toggleClass('openedBox');
           p.toggleClass('closedBox');
           var show = p.hasClass('openedBox');
           
            var href = '../context/updateBoxState.do?boxName=' + name + '&show=' + show;
            $.getJSON(href, function (data) {
              //alert (data.boxName + ' ' + data.show);
            });
           
           //use the name of the link to find the box that should be toggled;
           $('#' + name).toggle();
           return false;
        }
      });
}

//-----------------------------------------------------------
// Function to show or hide a box
// Takes the boxName and a boolean to indicate if the box should
// be shown or not
//-----------------------------------------------------------
function showHideBox (boxName, show) {
    //alert (boxName + ' ' + show);
    var boxDiv = $('#' + boxName);
    var boxToggle = $('a[rel="toggleBox"][name=' + boxName + ']');
    var boxToggleDiv = boxToggle.find('div').eq(0);
    if (show) {
      boxDiv.show();
      boxToggleDiv.addClass('openedBox');
      boxToggleDiv.removeClass('closedBox');
    } else {
      boxDiv.hide();
      boxToggleDiv.removeClass('openedBox');
      boxToggleDiv.addClass('closedBox');
    }
}


function moveToMerkliste(zeilenr) {
 //alert ("moveToMerkliste: " + zeilenr); 
 location.href = '../warenkorb/moveToMerkliste.do?zeilenr=' + zeilenr;
}

function moveFromMerkliste(zeilenr, artid) {
 var field = 'mkmngznr' + zeilenr;
 location.href = '../warenkorb/moveFromMerkliste.do?zeilenr=' + zeilenr + '&artid=' + artid + '&menge=' + $("#" + field).val();
}
      
//--------------------------------------------------------------------------------------
//End Setup Sidebar-Functionality
//--------------------------------------------------------------------------------------


function setupDirektbestellung () {

		 function addRow (event) {
                    //alert ("new Row");
                    //alert ($("#direktbestForm tr").length);
                    //var template = $("#direktbestForm table tr").eq(2).html();
                    var rownum = $("#direktbestForm #therows :button[class='submitButton']").length;
            
                    var template = $("#content #templateRow").html();
                    
                    $("#direktbestForm #therows").append('<div id="row' + rownum + '" > ' + template + '</div>');
                    var $newRow = $("#direktbestForm #therows div:last");
                    $newRow.find(':text').keydown(onKeyUp).keyup(onKeyUp).blur(onKeyUp).focus(onKeyUp).focus(onFocus);
                    $newRow.hide();
                    $newRow.fadeIn(250);
                    updateButtonsAndHandlers();
		 }
		 
		 function deleteRow(event) {
		 	var id =  ($(this).attr('id'));
			$(this).parent().remove();
			$('#direktbestForm #therows #' + id).remove();
		 }
		 
		 function onKeyUp (event) {
		 	var artnr = $(this).val();
			//var found = artnr.match(/[^\d]/);
			//if (found != null) {
			//	alert (found);
			//}
			var artnr = artnr.replace(/[^\d]*/g, '');
			$(this).val(artnr);
			
		 }
		 
		 function onFocus(event) {
		 	var val = $(this).val();
			if (val == 'Artikelnummer' || val == 'Menge') {
				$(this).val('');
			}
		 }
		 
		 function updateButtonsAndHandlers() {
			var nButtons = $("#direktbestForm #therows :button[class='submitButton']").length;
			$("#direktbestForm #therows :button[class='submitButton']").eq(nButtons-2).attr('name', 'minus').val('-').unbind('click', addRow).click(deleteRow);
			$("#direktbestForm #therows :button[class='submitButton']:last").click(addRow);
		 }
     
      
		 
    $("#direktbestForm input[name='plus']").click(addRow);
    $("#direktbestForm :text").keydown(onKeyUp).keyup(onKeyUp).blur(onKeyUp).focus(onKeyUp);
    
    function formSubmitted (response) {
          fillContent(response);
          setupDirektbestellung();
    }
      
    $("#contentPanel #direktbestForm").submit (function (event) {
        var action = $(this).attr('action');
        var formvals = $(this).serialize();
        $.post (action, formvals, formSubmitted , 'html');
        return false;
    });
}

function fillContent (data) {
  //alert (data);
  var $contentPanel = $("#contentPanel #content");                
  $contentPanel.html( $(data).html());
}

function setupDialogFunctionality(posXY, buttonsAndCallbacks, width, height) {
//------------------------------------------------------------------
    //Setup the dialog. The dialog is stored in a div #dialog
    //------------------------------------------------------------------
    //do not open automatically
    
    //variable to hold the current kg that the rueckruf should be made for
    var ckgrr = -1;
    
    //variable to hold the parent kg of the selected item
     cpkgrr = -1;
    
    $('#dialog').dialog({ autoOpen: false }); 
    //Set the position of the dialog
    $('#dialog').dialog('option', 'position', posXY);
    //Set the widht of the dialog
    $('#dialog').dialog('option', 'width', width);
    //Set the height of the dialog
    $('#dialog').dialog('option', 'height', height);
    //Add Buttons to the dialog and set handlers for the button
    $('#dialog').dialog('option', 'buttons', buttonsAndCallbacks);
    //Let the dialog work in modal mode
    $('#dialog').dialog('option', 'modal', true);
}
    //------------------------------------------------------------------
    //END Setup the dialog. The dialog is stored in a div #dialog
    //------------------------------------------------------------------
function openDialog(msg) {
    var $dialog = $('#dialog');
    $dialog.html(msg);
    $dialog.dialog('open');
}

/**
 * Todo: Make this generic and get rid of the above 
 *
 */
function setupCustomDialogFunctionality(posXY, buttonsAndCallbacks, width, height, dialogId, center, autoCloseTimeout) {
//------------------------------------------------------------------
    //Setup the dialog. The dialog is stored in a div #dialog
    //------------------------------------------------------------------
    //do not open automatically
    
    //variable to hold the current kg that the rueckruf should be made for
    var ckgrr = -1;
    
    //variable to hold the parent kg of the selected item
     cpkgrr = -1;
    
    if ($(center)) {
      var x = 1100/2 - width/2;
      var y = 768/2 - height/2;
      posXY = [x, y];
    }
    
    var dialogHolder = $('#' + dialogId);
    
    $(dialogHolder).dialog({ autoOpen: false }); 
    //Set the position of the dialog
    $(dialogHolder).dialog('option', 'position', posXY);
    //Set the widht of the dialog
    $(dialogHolder).dialog('option', 'width', width);
    //Set the height of the dialog
    $(dialogHolder).dialog('option', 'height', height);
    //Add Buttons to the dialog and set handlers for the button
    $(dialogHolder).dialog('option', 'buttons', buttonsAndCallbacks);
    //Let the dialog work in modal mode
    $(dialogHolder).dialog('option', 'modal', false);
    
    //If autoclose is submitted and a timeout has been set the add the autoClose-Behviour to the dialog
    if($(autoCloseTimeout) && autoCloseTimeout > 0) {
      setTimeout(function(){ $(dialogHolder).dialog('close'); }, autoCloseTimeout);
    }

   
}
    //------------------------------------------------------------------
    //END Setup the dialog. The dialog is stored in a div #dialog
    //------------------------------------------------------------------
function openCustomDialog(msg, dialogId) {
    var $dialog = $('#' + dialogId);
    $dialog.html(msg);
    $dialog.dialog('open');
}
    
function phoneYes(event) {
   $('#dialog').dialog('close');
   
 //do the request and hide the holder when everything is done
   var href = "../mitteilungen/rueckruf.do";
   $.getJSON(href, {pkg:cpkgrr,kg:ckgrr}, function(data){
   });   
}

function phoneNo(event) {
  $('#dialog').dialog('close');
}
  
function doCloseDialog(event) {
  $('#dialog').dialog('close');
}


/* Checks for Mindestverkauufsmengen pwk is the Object with the parsed parameters */
function checkMindestverkaufsmengen (pwk) {
   var hmenge = parseInt(pwk.pmenge);
    var hmindverkmng = parseInt(pwk.pmindverkmng);
    if (isNaN(hmenge) || hmenge < hmindverkmng) {
      $("#itemList #artmng" + pwk.partid).val(parseInt(pwk.pmindverkmng));
      setupDialogFunctionality([400,300],{"OK": doCloseDialog}, 340, 100);  
      openDialog ('<ul><li>Die Mindestabnahme f&uuml;r diesen Artikel ist ' + pwk.pmindverkmng + '</li></ul>', 'Bitte passen Sie Ihre Angaben an...');
      return false;
    } else if ((hmenge % hmindverkmng) > 0) {
       $("#itemList #artmng" + pwk.partid).val(parseInt(pwk.pmindverkmng));
      setupDialogFunctionality([380,300],{"OK": doCloseDialog}, 380, 100);  
      openDialog ('<ul><li>Die Menge muss ein Vielfaches der Mindestabnahme ' + hmindverkmng + ' sein</li></ul>', 'Bitte passen Sie Ihre Angaben an...');
      return false;
    } else {
      return true;
    }
}

function loadImage (url) {
  //alert (url);
  var img = new Image();
  $(img).load(function () {
      $('#imageLoader').html('').removeClass('imageLoading').append(this);
      $('#imageLoader').show().click(function (){
        $(this).hide().html('');
      });
    }).attr('src', url);
}

//--------------------------------------------------------------------------------------
//Setup Einkaufslisten-Functionality
//--------------------------------------------------------------------------------------
function setUpEinkaufslistenFuncs (cntrToOpen, validate) {

        var dxp = 436;
        var dyp = 300;
        var dw = 360;
        var dh = 180;
          
        var containerToOpen = cntrToOpen;
        if (containerToOpen == '') {
          containerToOpen = "ekList";
        }
    
        var activeElement = null;
        $("#content #einkaufslisten div[class!=divider]").hide();
        
        activeElement = $("#content #einkaufslisten #" + containerToOpen);
        activeElement.show();
        
        $("#actionTable a").click(function(event){
          event.preventDefault();
          if (activeElement) {
            activeElement.hide();
          }
          //alert (this.name);
          var elem = $('#einkaufslisten div[id=' + this.name + ']');
          
          elem.show();
          //$('#einkaufslisten div[id=' + this.name + '] input:first').focus();
          activeElement = elem;
          $('#ekMessageText').html('');
        });
        
      $("#ekRename .textInputOff").focus(function(event){
        $(this).addClass('textInputFocus');
        $(this).removeClass('textInputOff');
      });
      
      $("#ekRename .textInputOff").blur(function(event){
        $(this).removeClass('textInputFocus');
        $(this).addClass('textInputOff');
      });
      
      //Start Validation-Setup
      if (validate) {
      
          $("#einkaufslisten #ekCopyToUserForm").submit( function (event) {
           
            var message = "";
            var valid = true;
            
            //select all checked checkboxes, excluding the one for the overwrite flag
            var $list = $("input[type='checkbox']:checked:not([name='overwrite'])", this).val();
          
            if (!$list) {
                 message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus.<\/li>";
                 valid = false;
            }
          
            if (!valid) {
              setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh-40);
              openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
            }
            
            return valid;
          });
          
          $("#einkaufslisten #copyToNewForm").submit( function (event) {
           
            var message = "";
            var valid = true;
            var $list = $("input[type='radio']:checked", this).val();
            var $name = $("input[name='newName']", this).val();
            
            if (!$list) {
                 message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus.<\/li>";
                 valid = false;
            }
            if (!$name.match(/\w/g)) {
                 message += "<li>Bitte geben Sie einen g&uuml;ltigen Namen für die Liste an. Der Name muss mindestens einen Buchstaben oder eine Zahl enthalten.<\/li>";
                 valid = false;
            }
            
            if (!valid) {
              setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh);
              openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
            }
            return valid;
          });
          
           $("#einkaufslisten #moveToWkForm").submit( function (event) {
              var message = "";
              var valid = true;
              var $list = $("input[type='radio']:checked", this).val();
              if (!$list) {
                   message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus.<\/li>";
                   valid = false;
              }
              if (!valid) {
                setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh-40);
                openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
              }
              return valid;
          });
          
           $("#einkaufslisten #deleteEkForm").submit( function (event) {
              var message = "";
              var valid = true;
              var $list = $("input[type='checkbox']:checked", this).val();
              if (!$list) {
                   message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus.<\/li>";
                   valid = false;
              }
              if (!valid) {
                setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh-40);
                openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
              }
              return valid;
          });
          
          //Validation for Creating a new List
          $("#einkaufslisten #createNewForm").submit( function (event) {
       
            var message = "";
            var valid = true;
           
            var $newName = $("input[name='newName']", this).val();
            
            if (!$newName.match(/\w/g)) {
                 message += "<li>Bitte geben Sie einen g&uuml;ltigen Namen für die Liste an. Der Name muss mindestens einen Buchstaben oder eine Zahl enthalten.<\/li>";
                 valid = false;
            }
            
            if (!valid) {
              setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh);
              openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
            }
            
            return valid;
          });
        
         //Validation for the copyFromTo Form
         $("#einkaufslisten #copyFromToForm").submit(function (event) {
            var message = "";
            var valid = true;
            var $from 	= $("input[name='from']:checked", this).val();
            var $to 	= $("input[name='to']:checked", this).val();
            
            if (!$from) {
              message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus<\/li>";
              valid = false;
            }
            
            if (!$to) {
              message += "<li>Bitte w&auml;hlen Sie eine Einkaufsliste aus in die, die Artikel kopiert werden sollen.<\/li>";
              valid = false;
            }
            
            if ($from == $to) {
              message += "<li>Sie m&uuml;ssen zwei verschiedene Einkaufslisten ausw&auml;hlen.<\/li>";
              valid = false;
            }
            
            if (!valid) {
              setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh+20);
              openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
            }
            return valid;
        });
      } //End Validation-Setup
}

//--------------------------------------------------------------------------------------
//End Einkaufslisten-Functionality
//--------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------
//Setup List-Functionality
//--------------------------------------------------------------------------------------
function setupListFunctionality () {
      
    //has the list for the einkaufslisten already been loaded
		var ekLoaded = false;
		
		//The values of all current lists are diplayed here
		var eklist = new Array();
		
		var $eklisterrors = $('#eklisterrors');
		var $eklistSubmitButton = $('#eklistSubmitButton');
		
		//container for einkaufslisten
		var $holder = $("#eklistHolder");
		var $empfHolder = $("#empfHolder");
		var $ekLoader = $("#ekLoader");
		var $ekLoader2 = $("#ekLoader2");
		
		//active popUp
		var $popUp = $holder;
      
		//glass-pane
		var $backgroundPopup = $("#backgroundPopup");
    
    setupDialogFunctionality([400,300],{"NEIN": phoneNo, "JA": phoneYes});
    
   //-----------------------------------
    //Setup Events for click on Rueckruf 
    //-----------------------------------
    $('#itemList a[rel="add2Rr"]').click(function(event) {
      
      var idstr = $(this).attr('id');
      var idvals = idstr.split('-param-');
      var partnr = idvals[1];
      var ppkg = idvals[2];
      var pkg = idvals[3];
      ckgrr = pkg;
      cpkgrr = ppkg;
      
      openDialog ("Sollen wir Sie bez&uuml;glich des Artikels " + partnr + " zur&uuml;ckrufen?");
     
      return false;
    });
    
    //-----------------------------------
    //End Events for click on Rueckruf 
    //-----------------------------------
      
      function createPopupCss(pos, offset, width) {
        var cssObj = {
          'position' : 'absolute',
          'top': pos.top,
          'left': pos.left + offset,
          'width': 400,
          'z-index': 2,
		  'background-color': '#eee'
        }
        return cssObj;
      }
      
      function parseParams (idstr) {
        var idvals = idstr.split('-param-');
        var obj = new Object();
        obj.partid = idvals[1];
        obj.partnr = idvals[2];
        obj.pmngidx = idvals[3];
        obj.pmenge = $("#itemList #artmng" + obj.partid).val();
        obj.pmindverkmng = $("#itemList #mindverkmng" + obj.partid).val();
        obj.pbestellmenge = $("#itemList #bestellmenge" + obj.partid).val();
        return obj;
      }
      
      function setupSplash() {
		 
		 //splash-screen
         $backgroundPopup.css({  
            "opacity": "0.2"  
         });
         
         //fade-in the splash screen
         $backgroundPopup.fadeIn("fast");
         
         //add handler to splash-screen, so when it is clicked, the pop-up is closed
         $backgroundPopup.click(function(){  
            $backgroundPopup.fadeOut("fast");
            $popUp.hide();
         });
		 
      }
      
      
    
      
      //-----------------------------------
      //Setup Events for click on warenkorb 
      //-----------------------------------
      
      //On the menge filed we want to be able to submit by hitting the enter key
      $('#itemList input[name="menge"]').keyup(function(e) {
          if (e.which == 13) {
            //find matching warenkorb button and make a click on it
             var artid = $(this).attr('id').substring("artmng".length);
             //alert (artid);
             //alert ($(this).attr('id')); 
             var key = "add2Wk-param-" + artid;
             var wkbtn = $('#itemList a[rel="add2Wk"][id^="' + key + '"]');
             $(wkbtn).trigger('click');
             return false;
          }
      });
      
      
      //This is called when a user tries to submit an item to the warenkorb that has allready been placed previously
      //In this case a message pops up (invoked from add2wk) where the user is asked to confirm the submition
      var currentThisReference = null;
      
      $('#itemList a[rel="add2Wk"]').click(doInternalAdd2wk); 
       
      function doInternalAdd2wk (event, forceAppendToWk) {
        
        //Keep the reference for the Dialog
        //Overwirte it if the call comes from the wk-button, otherwise use the stored value
        if (!forceAppendToWk) {
          currentThisReference = $(this);
        }
        //alert ("doAdd2Wk called. forceAppendToWk" + forceAppendToWk);
        //alert ($(currentThisReference).attr('id'));
   
        //If there is a request running don't do anything
        if (ajaxBusy == true) {
          //alert ('busy');
          return false;
        }
        
        //Get id  
        var idstr = $(currentThisReference).attr('id');
        //Parse params artid, artnr, menge
        //alert (idstr);
        var pwk = parseParams (idstr);
        //Request
        var pviewName = $('#viewName').val();
        //alert (pwk.pmenge + " - " + pwk.pmindverkmng);
        
        var mindverkmngok = checkMindestverkaufsmengen(pwk);
        if (!mindverkmngok) {
          return false;
        }
        
        //Lets see this item is already in the warenkorb if so, display a confirmation
        //Dialog. If on the Dialog the Button trotzdem hinzufügen is clicked, then the mengen
        //will be added up to the menge that is already in the warenkorb.
        //The Dialog wil clall this function (doInternalAdd2wk) again.
        var hmenge = parseInt(pwk.pmenge);
        var hbestellmenge = parseInt(pwk.pbestellmenge);
        if (!forceAppendToWk && !isNaN(hbestellmenge) && hbestellmenge > 0) {
          currentThisReference = $(this); 
          setupDialogFunctionality([400,300],{"Abbrechen": doCloseDialog, "Mengen hinzufuegen":  function(){doInternalAdd2wk(event, true); doCloseDialog();} }, 340, 100);  
          openDialog ('<ul><li>Artikel liegt bereits mit Menge ' + hbestellmenge + ' im Warenkorb. Menge hinzuf&uuml;gen? </li></ul>', 'Bitte passen Sie Ihre Angaben an...');
          return false;
        } else if (forceAppendToWk && !isNaN(hbestellmenge) && hbestellmenge > 0) {
          pwk.pmenge = hmenge + hbestellmenge;
        }
        
        var $img = $(currentThisReference).find('img').eq(0);
        $img.attr('src', '../ui-images/loader.gif'); 
        var href = "../warenkorb/addOne.do"; 
        if (pwk.pmenge > 0) {
            $('body').css('cursor', 'wait'); 
           $.get(href, {artid:pwk.partid,menge:pwk.pmenge,viewName:pviewName}, function (data) {
                  //put the http-get-response into the miniCart container
                  //move all into a div
                 
                  var $response = $('<div />').html(data);
                 
                  ///find the relevant part without the embedding header etc.
                  var $content = $response.find('#miniCartContent').html();
                  //set the content of the holder
                  var $miniCart = $("#miniCart")
                  $miniCart.html($content);
                  
                   
                   
                  showHideBox ('miniCart', true);
                  
                  var alt = $img.attr('alt');
                  $img.attr('src', '../ui-images/' + alt + '.gif'); 
                  
                  $('body').css('cursor', 'default'); 
                  
                  //Read the Bestellmenge of the submitted row and put the value into the hidden field
                  //This is needed so that we know an item is already in the wk and if so how many
                  $("#itemList #bestellmenge" + pwk.partid).val($response.find('#updatedBestellmenge').html());
                  
                  //alert($response.find('#updatedBestellmenge').html());
                  
          });
        } else {
            var alt = $img.attr('alt');
            $img.attr('src', '../ui-images/' + alt + '.gif'); 
        }
        return false;
      }
      
      //-----------------------------------
      //End Events for click on warenkorb 
      //-----------------------------------
      
      //-----------------------------------
      //Setup Events for click on update or delete for warenkorb 
      //-----------------------------------
      
      function updateWarenkorb (event) {
           //If there is a request running don't do anything
        if (ajaxBusy == true) {
          //alert ('busy');
          return false;
        }
      
        //Get id  
        var idstr = $(this).attr('id');
        //Parse params artid, artnr, menge
        var idvals = idstr.split('-param-');
       
        var paufnr    = idvals[1];
        var pfolgenr  = idvals[2];
        var partid    = idvals[3];
        var partnr    = idvals[4];
        var pmngidx   = idvals[5];
        
        var keyPostfix = paufnr + "_" + pfolgenr + "_" + partid;
        var mengekey = "menge" + keyPostfix;
        
        var $mengeHolder = $('#itemList input[id=' + mengekey + ']');
        var pmenge = $mengeHolder.val();
        
        //Request
        var pviewName = $('#viewName').val();
        
        //holder of the total value, this will be updated if the request is ajax
        var totalKey = "total" + paufnr + "_" + pfolgenr;
        var $totalHolder = $('#itemList span[id=' + totalKey + ']');
        
        //holder of the mwst value, this will be updated if the request is ajax
        var mwstKey = "mwst" + paufnr + "_" + pfolgenr;
        var $mwstHolder = $('#itemList span[id=' + mwstKey + ']');
        
        //holder of the versandkosten value, this will be updated if the request is ajax
        var versandkostenKey = "versandkosten" + paufnr + "_" + pfolgenr;
        var $versandkostenHolder = $('#itemList span[id=' + versandkostenKey + ']');
        
         //holder of the zwischensumme value, this will be updated if the request is ajax
        var zwischensummeKey = "zwischensumme" + paufnr + "_" + pfolgenr;
        var $zwischensummeHolder = $('#itemList span[id=' + zwischensummeKey + ']');
        
         //holder of the warenwertexkl value, this will be updated if the request is ajax
        var warenwertexklKey = "warenwertexkl" + paufnr + "_" + pfolgenr;
        var $warenwertexklHolder = $('#itemList span[id=' + warenwertexklKey + ']');
       
         //holder of the total value, this will be updated if the request is ajax
        var zeilenwertHolderKey = "zeilenwert" + keyPostfix;
        var $zeilenwertHolder = $('#itemList span[id=' + zeilenwertHolderKey + ']');
        
        //Get the associated kundartbez from the list
        var pazkundartbez = $('#itemList #azkundartbez_' + partid).val();
       
        $totalHolder.css('color', 'red');
        $mwstHolder.css('color', 'red');
        $warenwertexklHolder.css('color', 'red');
        $zwischensummeHolder.css('color', 'red');
        $versandkostenHolder.css('color', 'red');
        $zeilenwertHolder.css('color', 'red');
        $mengeHolder.css('color', 'red');
       
        //holder of the image icon
        var $img = $(this).find('img').eq(0);
        $img.attr('src', '../ui-images/loader.gif'); 
        var href = "../warenkorb/addOne.do"; 
        //alert ("addOne: " + $(this).attr('rel') + " Menge:" + pmenge );
        if (pmenge > 0 && ($(this).attr('rel') != 'del2Wk') )  {
           $.get(href, {aufnr:paufnr,folgenr:pfolgenr,artid:partid,menge:pmenge,viewName:pviewName,azkundartbez:pazkundartbez}, function (data) {
                  //put the http-get-response into the miniCart container
                  //move all into a div
                  var $response = $('<div />').html(data);
                  ///find the relevant part without the embedding header etc.
                  var $content = $response.find('#miniCartContent').html();
                  
                  //Set the miniCart to the updated content except for the freigabe detail
                  //which does not work on the users wk
                  if (pviewName != 'freigabenErteilenDetail') {
                    //set the content of the holder, i.e. update the div with the minicart
                    var $miniCart = $("#miniCart")
                    $miniCart.html($content);
                  }
                  
                  //Inside the response we have a section with the total of the update warenkorb
                  //we use this to update the total on the current page
                  var $cartTotal = $response.find('#cartTotal').html();
                  $totalHolder.html($cartTotal);
                  
                  //Inside the response we have a section with the mwst of the update warenkorb
                  //we use this to update the total on the current page
                  var $mwstTotal = $response.find('#cartMwst').html();
                  $mwstHolder.html($mwstTotal);
                  
                  //Inside the response we have a section with the versandkosten of the update warenkorb
                  //we use this to update the total on the current page
                  var $versandkostenTotal = $response.find('#cartVersandkosten').html();
                  $versandkostenHolder.html($versandkostenTotal);
                  
                  //Inside the response we have a section with the zwischensumme of the update warenkorb
                  //we use this to update the total on the current page
                  var $zwischensummeTotal = $response.find('#cartZwischensumme').html();
                  $zwischensummeHolder.html($zwischensummeTotal);
                  
                  //Inside the response we have a section with the total of the update warenkorb
                  //we use this to update the total on the current page
                  var $warenwertexklTotal = $response.find('#cartWarenwertexkl').html();
                  $warenwertexklHolder.html($warenwertexklTotal);
                  
                   //Inside the response we have a section with the total of the update warenkorb
                  //we use this to update the total on the current page
                  var $updatedZeilenwert = $response.find('#updatedZeilenwert').html();
                  $zeilenwertHolder.html($updatedZeilenwert);
                 
                  //Restore the image-icon to its original key
                  var alt = $img.attr('alt');
                  $img.attr('src', '../ui-images/' + alt + '.gif');
                  
                  $warenwertexklHolder.css('color', 'black');
                  $totalHolder.css('color', 'black');
                  $mwstHolder.css('color', 'black');
                  $zwischensummeHolder.css('color', 'black');
                  $versandkostenHolder.css('color', 'black');
                  $zeilenwertHolder.css('color', 'black');
                  $mengeHolder.css('color', 'black');
          });
        } else {
          //be sure not to invoke another request even if its not an ajax one
          ajaxBusy = true;
          location.href = href + '?aufnr=' + paufnr + '&folgenr=' + pfolgenr + '&artid=' + partid + '&menge=0' + '&viewName=' + pviewName;
        }
        return false;
      }
      
      $('#itemList a[rel="del2Wk"]').click(updateWarenkorb); 
     
      $('#itemList a[rel="upd2Wk"]').click(updateWarenkorb); 
    
      //-----------------------------------
      //End Events for click on update or delete for warenkorb 
      //-----------------------------------
      
      //-------------------------------------------------------------------
      //Setup Events for click on Aktualisieren for Einkauflsiten Artikel (WebbenutzerArtListArt)
      //-------------------------------------------------------------------
      $('#itemList a[rel="upd2Ek"]').click(function(event) {
        
        // alert ("upd2Ek");
         
        //If there is a request running don't do anything
        if (ajaxBusy == true) {
          //alert ('busy');
          return false;
        }
        //Get id  
        var idstr = $(this).attr('id');
        
        //Parse params artid, artnr, menge
        var pwk = parseParams (idstr);
      
        //viewName
        var pviewName = $('#viewName').val();
        
        //the current List
        //var ptoList = $('#currentEkListName').val();
        var ptoList = $('#artikelform #listId').val();
        
        var $img = $(this).find('img').eq(0);
        $img.attr('src', '../ui-images/loader.gif'); 
        var href = "../einkaufslisten/placeArticleInList.do"; 
        
       
        
        if (pwk.pmenge > 0) {
           $.get(href, {artidToPlace:pwk.partid,artnrToPlace:pwk.partnr,menge:pwk.pmenge,toList:ptoList,viewName:pviewName,jsAction:'upd2Ek'}, function (data) {
                  //put the http-get-response into the miniCart container
                  //move all into a div
                  $img.attr('src', '../ui-images/aktualisieren.gif'); 
          });
        } else {
          location.href = "../einkaufslisten/placeArticleInList.do?artidToPlace=" + pwk.partid + "&artnrToPlace=" + pwk.partnr + "&menge=" + pwk.pmenge + "&toList=" + ptoList + "&viewName=" + pviewName;
        }
        
        return false;
      });
      //-----------------------------------
      //End Events for click on Aktualisieren 
      //-----------------------------------
      
      //-----------------------------------
      //Setup Events for click on Loeschen for Einkaufslisten 
      //-----------------------------------
      $('#itemList a[rel="del2Ek"]').click(function(event) {
        // Values zwischenspeichern
        //Get id  
        var $idstr = $(this).attr('id');
        
        var $img = $(this).find('img').eq(0);
        setupDialogFunctionality([400,300],{"NEIN": ekdelNo, "JA": function(event,idstr,image) {ekdelYes(event,$idstr,$img);}});
        openDialog("Wollen Sie den Artikel wirklich aus der Liste entfernen?") ; 
      });
      
      function ekdelNo(event) {
        doCloseDialog(event) ;
      }
      
      function ekdelYes(event,idstr,$img) {
        doCloseDialog(event) ; 
        
        //alert ("del2Ek");
        //If there is a request running don't do anything
        if (ajaxBusy == true) {
          //alert ('busy');
          return false;
        }
         //viewName
        var pviewName = $('#viewName').val();

        //Parse params artid, artnr, menge
        var pwk = parseParams (idstr);
        
        //the current List
         //var ptoList = $('#currentEkListName').val();
        var ptoList = $('#artikelform #listId').val();
        
        // 01.07..10 pg: to be able to Navigate to the structartdetail, we need some more paramters
        var ppid = jQuery.url.param('pid') ; 
        var pListName = jQuery.url.param('listName') ;
        var ppName = jQuery.url.param('pName') ;
        var pkgart = jQuery.url.param('kgart') ;

        $img.attr('src', '../ui-images/loader.gif'); 
        var href = "../einkaufslisten/placeArticleInList.do"; 
        
        location.href = "../einkaufslisten/placeArticleInList.do?artidToPlace=" + pwk.partid + "&artnrToPlace=" + pwk.partnr + "&menge=" + 0 + "&toList=" + ptoList + 
          "&listName=" + pListName + "&pid=" + ppid + "&pName=" + ppName + "&kgart=" + pkgart + "&viewName=" + pviewName + "&jsAction=del2Ek";
        
        return false;
      }
      //-----------------------------------
      //End Events for click on Loeschen for Einkaufslisten 
      //-----------------------------------
       
    
	  
    //----------------------------------------------------------------------
    //Setup key-handler for the input field that takes the NEW name of a LIST
    //Check that the name is not equal to a list that already exists
    //----------------------------------------------------------------------
    //get the input-field and setup event-handler
	  $('#toNewList').keyup(function(event) {
      //trim string
			var s = jQuery.trim (this.value);
         
      //check to see if list already exists
			if (jQuery.inArray(s,eklist) >= 0) {
            //there's a hit so let's show a feedback message in place
            $eklisterrors .text('Es gibt bereits eine Liste mit diesem Namen.');
            //make sure the submit button is disabled
            $eklistSubmitButton.attr("disabled", "disabled");
            } else {
              //everything is ok, enable the button and remove any Feedback-Message
              $eklisterrors .text('');
              $eklistSubmitButton.removeAttr("disabled");
            }
      });
      
      //----------------------------------------------------------------------
      //Setup Submit for the form that stores an item to a SELECTED Einkaufsliste
      //----------------------------------------------------------------------
      
      //This is the handler for the Dialog, if there has been an attempt to place an item in an Einkaufsliste
      //but the Einkaufsliste has already such an item in the List. Then the Dialog shows up to confirm that
      //you still want to append the item to the List. This is the handler if in the Dialog-Box someone clicks
      //'TROTZDEM HINZUFUEGEN'
      function forceAppendToEkList(event) {
        //Copy the item to the Einkaufsliste and force an append
        var ok = copyFromTo (event, true);
        doCloseDialog(event);
        return ok;
      }
      
      function htmlEncode(value){ 
      return $('<div/>').text(value).html(); 
    } 
    
    function htmlDecode(value){ 
      return $('<div/>').html(value).text(); 
    }

      
      
      //Place an item to a Einkaufsliste
      function copyFromTo (event, pforceAppendToList) {
        // alert ("copyFromTo"); 
      //get the params
         var partid =  $('#artidToPlaceToList').val();
         var partnr =  $('#artnrToPlaceToList').val();
         var pmenge =  $('#mengeToPlaceToList').val();
         var plist  =  $('#toList').val();
         var plistName  =  $('#toList :selected').text();
         
         //show the loader as feedback while processing
         $ekLoader.show();
         
         //setup the request to place the item into the selected list
         var href = "../einkaufslisten/placeArticleInList.do";
                                   
         //alert (href);
         $.getJSON(href, { artidToPlace: partid, artnrToPlace: partnr, menge: pmenge, toList:plist, toListName:plistName, forceAppendToList:pforceAppendToList }, function(data){
            $holder.hide();
            if (data.isInList) {
              
              // Py: 06/2010 fixing the bad encoding in the text of the buttons
              var cancelLabel = "Abbrechen";
              var saveLabel = data.savebuttonLabel;
              var buttons = {};
              buttons[cancelLabel] = function(event) {doCloseDialog(event);}
              buttons[saveLabel] = function(event) {forceAppendToEkList(event);} 
              
              setupDialogFunctionality([480,300], buttons, 380, 180);               
              // setupDialogFunctionality([480,300],{"Abbrechen": doCloseDialog, "Trotzdem hinzuf&uuml;gen": forceAppendToEkList}, 380, 180);               
              openDialog (data.messageText, 'Bitte passen Sie Ihre Angaben an...');
            } else if(data.messageText) {
                $("#statusTextJson").html("<p>" + data.messageText + "</p>").show();     
            }
            $("#backgroundPopup").fadeOut("fast");
            
         });
         
         //don't do any further processing
         return false;
      }
	
      //get the form with the list selection, that stores an item to the selected list and setup submit handler
      $('#copyFromTo').submit (function (event) {
         //Call the Ajax-Function to store an item in the list but do not force append when the item is already in the list
         //In this case a Confirmation-Dialog is shown, where the user has to confirm that he wants to put the item
         //to the list and the menge is added up.
         return copyFromTo (event, false);
      });
      //----------------------------------------------------------------------
      //End Submit for the form that stores an item to a selected list
      //----------------------------------------------------------------------
      
      //----------------------------------------------------------------------
      //Setup Submit for the form that stores an item to a NEW list
      //----------------------------------------------------------------------
      //get the form for creation of a new list and placement of an item into this list and setup the submit handler
      $('#copyToNew').submit (function (event) {
         //get params in the form
         var partid =  $('#artidToPlaceToNew').val();
         var partnr =  $('#artnrToPlaceToNew').val();
         var pmenge =  $('#mengeToPlaceToNew').val();
         var plist  =  $('#toNewList').val();
         
         //we need a name to create a list
         if (plist == '') {
            $eklisterrors .text('Der Name der Liste darf nicht leer sein.');
            return false;
         }
         
         //show the loader while processing
         $ekLoader2.show();
         
         //do the request and hide the holder when everything is done
         var href = "../einkaufslisten/createNewAndPlaceArticle.do";
         $.getJSON(href, { artidToPlace: partid, artnrToPlace: partnr, menge: pmenge, toList:plist }, function(data){
            $holder.hide();
            $ekLoader2.hide();
            $("#backgroundPopup").fadeOut("fast");
            //clear the input
            $('#toNewList').val('');
         });
         
         //reset the flag for loaded lists, so that they are updated next time
         ekLoaded = false;
         
         //no further processing of the form
         return false;
      });
      //----------------------------------------------------------------------
      //End Submit for the form that stores an item to a new list
      //----------------------------------------------------------------------
      
      $('#empfehlenForm').submit (function (event) {
        
          var pkg =           $('#empfehlenForm #kg2Empf').val();
          var pparent =       $('#empfehlenForm #parent2Empf').val();
          var pemail =        $('#empfehlenForm #email').val();
          var pemailempf =    $('#empfehlenForm #empfaengerEmail').val();
          var pbemerkung =    $('#empfehlenForm #bemerkung').val();
          
          //alert (pkg + " " + pparent + " " + pemail + " " + pemailempf + " " + pbemerkung);
          
          $('#empfehlenForm #empfLoader').show();
        //do the request and hide the holder when everything is done
         var href = "../mitteilungen/saveEmpfehlung.do";
         $.getJSON(href, {fromEmail:pemail, toEmail:pemailempf, pid:pparent, id:pkg, bemerkung:pbemerkung}, function(data){
             var h = $('#empfehlenForm #statusMessage');
            $('#empfehlenForm #empfLoader').hide();
            h.text(data.statusMessage);
            h.show();
            $("#backgroundPopup").hide();
            $popUp.fadeOut(1000);
         });
         
          return false;
      });
   	  //----------------------------------------------------------------------
      //Click-Handler for Empfehlen and Popup
      //---------------------------------------------------------------------- 
      $('#itemList a[rel="add2Empf"]').click(function(event) {
          
			//If there is a request running don't do anything
			if (ajaxBusy == true) {
				return false;
			}
			
			//Get the id of the clicked link and parse the parameters
			var idstr = $(this).attr('id');
      var params = idstr.split('-param-');
      var parent = params[1];
			var kg = params[2];
			
      $('#empfHolder #parent2Empf').val(parent);
			$('#empfHolder #kg2Empf').val(kg);
          
			//gets the position of the target
			//to place the container
			var pos = ($(event.target).position());
			
			//create css class for the popUp container
			var cssObj = createPopupCss(pos, 25, 400);
			
			//Add this css to the container for the Empfehlungen
			$empfHolder.css(cssObj);
			
			//This container is the current popUp
			$popUp = $empfHolder;
      
      //hide holder for the status-message
      var h = $('#empfehlenForm #statusMessage');
      h.hide();
			
			//Fade in the container with the Empfehlungen
			$empfHolder.hide();
			$empfHolder.fadeIn(250);
			
			//Set-Up the splash
			setupSplash();
			
			return false;
          
      });
      //----------------------------------------------------------------------
      //End Click-Handler for Empfehlen and Popup
      //----------------------------------------------------------------------
      
      //----------------------------------------------------------------------
      //Click-Handler for Einkausflisten and Popup
      //----------------------------------------------------------------------
      $('#itemList a[rel="add2Ek"]').click(function(event) {
        
        //alert ("add2Ek");
        //If there is a request running don't do anything
        if (ajaxBusy == true) {
          //alert ("I'm busy");
          return false;
        }
        
        //Get the id of the clicked link and parse the parameters
        var idstr = $(this).attr('id');
        var p = parseParams (idstr);
        
        //Copy the parameters from the id over to the form
        $("#artidToPlaceToList").attr("value", p.partid);
        $("#artnrToPlaceToList").attr("value", p.partnr);
        $("#mengeToPlaceToList").attr("value", p.pmenge);

        $("#artidToPlaceToNew").attr("value", p.partid);
        $("#artnrToPlaceToNew").attr("value", p.partnr);
        $("#mengeToPlaceToNew").attr("value", p.pmenge);
        
        //Make sure the holder of the einkaufslisten-container is hidden so we can fade in
        $holder.hide();
         
        //gets the position of the target
        //to place the container
        var pos = ($(event.target).position());
        
        //create a css-object to add to the container, so that it is shown as popup in the right position
        //at position pos with offset - 415 and width 400;
        var cssObj = createPopupCss (pos, -415, 400);
        
        //show the loader icon
         $ekLoader.show();
         
        //add popup-css to the container
         $holder.css(cssObj);
		 
         //set this as the active popUp;
         $popUp = $holder;
         
         //fade-in container
         $holder.fadeIn(250);
         
         setupSplash();
        
        if (!ekLoaded) {
          //add a placeholder for the list values;
          $("#toList").html('<option value="loading">Listen werden geladen...</option>');
          var href = '../einkaufslisten/getEkLists.do';
          
          //get einkaufslisten and add them to the select list
          $.getJSON(href, function (data) {
            var options = "";
              $.each(data.items.rows, function (i, item) {
              options += '<option value="' + item.key + '">' + item.value + '</option>';
              //alert(options);
              eklist[i] = item.value;
            });
            $("#toList").html(options);
             ekLoaded = true;
             $ekLoader.hide();
             $("#ekToListSubmit").focus();
          });
        } else {
          $ekLoader.hide();
          $("#ekToListSubmit").focus();
        }
        
        /*
        $.get("../einkaufslisten/showAddToListPopup.do", { artid: partid, artnr: partnr },
          function(data){
        //move all into a div
        var $response = $('<div />').html(data);
        ///find the relevant part without the embedding header etc.
        var $content = $response.find('#bodyOnly').html();
        //set the content of the holder
        $("#eklistHolder").html($content);
        //show the holder 
        $("#eklistHolder").show();
          });
          */
       
         /*
         $("#eklistHolder").load("../einkaufslisten/showAddToListPopup.do #bodyOnly", { artid: "22824", artnr: "160009600" });
         $("#eklistHolder").show();
         */
            return false;
        });
}

//

//----------------------------------------------------------------------
// Setup Form-Validation
//----------------------------------------------------------------------

function createErrorMessageLineForObject (prefix, $object, message) {
    
    if (!prefix) {
      prefix = '';
    }
    //Get name of this input field as reference...
    var ref = $object.attr('name');
    //to find the title of the label for this input field, use only the first if ther are many
    var labelTag = $("label[for='" + ref + "'], formRef").eq(0);
    var label = labelTag.attr('title');
    //Use inner Html of the label tag as fallback
    if (!label) {
      label = labelTag.text();
    }
    //Add the label (the title of the label for this input-field) to the message
    var msg = "<li>" + prefix + " " + label + "  " + message + "</li>";
    return msg;
}

function setupFormInputFocusHandlers(form) {

  $("input", form).focus(function(event){
        $(this).addClass('inputFocus');
        $(this).removeClass('inputError');
      });
      
    $("input", form).blur(function(event){
      $(this).removeClass('inputFocus');
    });
}

function setupFormValidation(form, validate) {
    
    if (validate) {
      $(form).submit( function (event) {
        var message = "";
        var formRef = $(this);
        var valid = true;
        var numOfLines = 0;
		
	//Remove all previous errorClasses from the input fields
        $("input").removeClass("inputError");
       
	//Input-fields, that reqiure a not empty String
        $("input.reqString", form).each (function (i) {
                	
                //Get the value of this input-field
                var value = $(this).val();
                
                //If empty add error-message;
                if (!value) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "darf nicht leer sein.");
                  numOfLines++;
		  $(this).addClass('inputError');
                } 
              });
        
        //Input-fields, that reqiure a certain number of characters
        $("input.reqLength", form).each (function (i) {	
          //Get the value of this input-field
          var value = $(this).val();
          
          if (value.length < 5) {
            valid = false;
            message += createErrorMessageLineForObject (null, $(this),  "muss mindestens 5 Zeichen haben.");
            numOfLines++;
            $(this).addClass('inputError');
          } 
        });  
        
        //Input-fields, that require a not empty Number
        $("input.isNumber", form).each (function (i) {
                //get the name of the input-field
                var value = $(this).val();
                if (value.match(/\D/)) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "muss eine Zahl sein.");
                  numOfLines++;
                  $(this).addClass('inputError');
                }
        });
        
        //Input-fields, that require a not empty Number
        $("input.isNumberOrEmpty", form).each (function (i) {
                //get the name of the input-field
                var value = $(this).val();
                if (value && value.match(/\D/)) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "muss eine Zahl sein.");
                  numOfLines++;
                  $(this).addClass('inputError');
                }
        });
        
        
        
        
        //Input-fields, that require a checked box
        $("input.reqChecked", form).each (function (i) {
                //get the name of the input-field
                var value = $(this).attr('checked');
                if (!value) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "muss akzeptiert sein.");
                  numOfLines++;
		  $(this).addClass('inputError');
                }
         });
         
        
         
        //Input-fields, that require a checked box within a group. I start 
        // creating an array with all the elements belonging to the group
        var $cbInGroup    = $("input.reqCheckedOneInGroup", form);
        var $groupName    = $cbInGroup.attr('name');
        if ($groupName) {
          var $isOneChecked = $("input.reqCheckedOneInGroup:checked").val();
          if(!$isOneChecked) {
            valid = false;
            message += createErrorMessageLineForObject ("Mindestens ein ", $cbInGroup,  " muss ausgew&auml;hlt sein.");
            //$("input.reqCheckedOneInGroup", form).parent().parent().addClass('inputError');
            numOfLines++;
          }
        }
        $("input.reqCheckedOneInGroup", form).each (function (i) {
          //get the name of the input-field
          var value = $(this).attr('selected');
          if (value) {
            isOneSelected = true;
          }
      });
         
      // Multiple selection list, that requires a selection, note that before
      // every option is cheched, in order to find if at least one is selected
      // and then the result is stored in a variable. Then only the select element 
      // is selected to display the message (so we have only one instead of many)
      // and to add the errpr element.
      var isOneSelected = false;
      $("select.reqSelected option", form).each (function (i) {
          //get the name of the input-field
          var value = $(this).attr('selected');
          if (value) {
            isOneSelected = true;
          }
      });
      $("select.reqSelected", form).each (function (i) {
        if(!isOneSelected) {
            message += createErrorMessageLineForObject ("Mindestens ein ", $("select.reqSelected"),  " muss ausgew&auml;hlt sein.");
            $("select.reqSelected").addClass('inputError');
            valid = false;
        } else {
            $("select.reqSelected").removeClass('inputError');
        }
      });
		
        //Input-fields, that require a phone-number
        $("input.isPhone", form).each (function (i) {
                //get the name of the input-field
                var value = $(this).val();
                if (value.match(/[^0-9\+\-\*\/\(\)\s]/)) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "darf nur Zahlen [0-9] oder die Zeichen [+-*/()] enthalten");
                  numOfLines++;
		  $(this).addClass('inputError');
                }
         });
			
        //Input-fields, that require an email
        $("input.isEmail", form).each (function (i) {
                //get the name of the input-field
              var value = $(this).val();
              value = jQuery.trim(value);
              if (value) {
                var email = value.match(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,64})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);
                //match, if not, no valid email.
                if (!email) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "muss eine g&uuml;ltige E-Mail enthalten.");
                  numOfLines++;
                  $(this).addClass('inputError');
                }
              }
          });
            
        //Input-fields, that require a phone-number
        $("input.isDate", form).each (function (i) {
                //get the name of the input-field
                var value = $(this).val();
                
                if(value == "") {
                  message += createErrorMessageLineForObject (null, $(this),  "muss ein g&uuml;ltiges Datum (dd.mm.yyyy) enthalten.");
                  valid = false;
                  $(this).addClass('inputError');
                } else
                if (!isDate(value)) {
                  valid = false;
                  message += createErrorMessageLineForObject (null, $(this),  "muss ein g&uuml;ltiges Datum (dd.mm.yyyy) enthalten.");
                  numOfLines++;
		  $(this).addClass('inputError');
                }
         });
         
         //check that the 2 passwords are the same
         var passwords = new Array(2);
         var index = 0;
         $("input.matchPassword", form).each (function (i) {
           passwords[index] = $(this).val();
           index++;
         });
         $("input.matchPassword", form).each (function (i) {
           if (passwords[0] != passwords[1]) {
             valid = false;
             message += createErrorMessageLineForObject (null, $(this),  ": Ihr altes Passwort stimmt nicht mit Ihrem altem Passwort &uuml;berein.");
             numOfLines++;
             $(this).addClass('inputError');
           }
         });
         
         
         // This evaluates if the 2 dates are in the correct chronological order
         // It requires that the css class are set to "isFromDate" and "isToDate"
         var startDate = new Date();
         var endDate = new Date();
         startDate = $("input.isFromDate").val();
         endDate =   $("input.isToDate").val(); 
         if (startDate && endDate) {
           startDate = $("input.isFromDate").datepicker("getDate");
           endDate =   $("input.isToDate").datepicker("getDate");
           if (startDate.getTime() > endDate.getTime()) {
             var toDateRef = $("input.isToDate").attr("name");
             message += createErrorMessageLineForObject (null,  $("input.isFromDate"),  "muss vor der " + $("label[for='" + toDateRef + "']").attr("title") + " sein");
             valid = false;
             $("input.isFromDate").addClass('inputError');
             $("input.isToDate").addClass('inputError');
           }
         }
       

         
          
          var h =  100 + numOfLines * 24;
          
          if (!valid) {
            setupDialogFunctionality([480,300],{"OK": doCloseDialog}, 400, h);  
            openDialog ('<ul>' + message + '</ul>', 'Bitte passen Sie Ihre Angaben an...');
          }
          return valid;
   	});
	}
        
}

//----------------------------------------------------------------------
// End Setup Form-Validation
//----------------------------------------------------------------------
//------------------------------------------------------------------------------
//     DATE VALIDATION (http://codingforums.com/showthread.php?t=14325)
//          modified to match pur format that is dd.mm.yyyy
//------------------------------------------------------------------------------     
function isDate(sDate) {
     var re = /^\d{1,2}\.\d{1,2}\.\d{4}$/
     if (re.test(sDate)) {
        var dArr = sDate.split(".");
        var day = dArr[0];
        var month = dArr[1];
        var year = dArr[2];
        var d = new Date(year,month,day);
        return d.getMonth() == dArr[1] && d.getDate() == dArr[0] && d.getFullYear() == dArr[2];
     }
     else {
        return false;
     }
}

// check if the two dates are in the correct chronological order
function dateFromToValidation(dateFromElementname, 
                              dateToElementname, 
                              formElementname) {
  $("#" + formElementname).submit(function (event) {
    var startDate = new Date();
    var endDate = new Date();
    startDate = $("#" + dateFromElementname).datepicker("getDate");
    alert("Date from= " + startDate);
    var endDate = new Date();
    endDate = $("#" + dateToElementname).datepicker("getDate");
    alert("Date from= " + endDate);
    if (startDate != null && endDate != null) {
      if (startDate.getTime() > endDate.getTime()) {
        message += createErrorMessageLineForObject (null, $("#" + dateFromElementname),  "muss vor dem Bis-Datun sein");
        valid = false;
        $("#" + dateFromElementname).addClass('inputError');
        $("#" + dateToElementname).addClass('inputError');
      }
    }
  });
}

//------------------------------------------------------------------------------
//                            END DATE VALIDATION 
//------------------------------------------------------------------------------ 


//------------------------------------------------------------------------------
//                            FREIGABE ERTEILEN
//------------------------------------------------------------------------------
 //Start Validation-Setup
function validateFreigabenErteilen (form, validate) {
     
      if (validate) {
    
          var dxp = 436;
          var dyp = 300;
          var dw = 360;
          var dh = 180;
          
          var message = "";
          var valid = true;
          var numOfLines = 1;
          
          //Input-fields, that require a checked box
          $("input.reqChecked", form).each (function (i) {
              //get the name of the input-field
              var value = $(this).attr('checked');
              if (!value) {
                valid = false;
                message += createErrorMessageLineForObject (null, $(this),  "muss akzeptiert sein.");
                numOfLines++;
                $(this).addClass('inputError');
              }
          });
       
          //select all checked checkboxes, excluding the one for the overwrite flag
          var $list = $("input[type='checkbox']:checked:not([name='agb'])", form);
        
          if (!$list.val()) {
               message += "<li>Bitte w&auml;hlen Sie eine Bestellung aus.<\/li>";
               numOfLines++;
               valid = false;
          } else {
            var targetwb = null;
            var targetkst = null;
            $list.each(function (i) {
               var key = $(this).val();
               var wbid = $('#wbid_' + key, form).val();
			   var kstid = $('#kst_' + key, form).val();
			   if (targetwb == null) {
				   targetwb = wbid;
			   }
			   if (targetkst == null) {
				   targetkst = kstid;
			   }
			   if ((targetkst != kstid) || (targetwb != wbid)) {
				   message += "<li>Die ausgew&auml;hlten Bestellungen stammen von unterschiedlichen Kostenstelllen und/oder Benutzern<\/li>";
           numOfLines++;
				   valid = false;
				   return valid;
			   }
            });
          }
          
          dh += numOfLines * 12
        
          if (!valid) {
            setupDialogFunctionality([dxp,dyp],{"OK": doCloseDialog}, dw, dh-40);
            openDialog ("<ul>" + message + "<\/ul>", 'Bitte passen Sie Ihre Angaben an...');
          }  
          return valid;
     }
}