/*
 * Draeger Job Selector 
 * created by Christian Beyer (e7)
 * 091001
 */

// LH URL (Proxy zum lokalen Testen)
var proxy=false;
var actHost=draeger.SEND_PATH;

// globale Variablen
var ajaxLocationFinished=true;
var ajaxCategoryFinished=true;
var historyAction=false;
var historykeys=new Array();
var lastQuery='';
var selectHtml=new Array("","","");
var selectSelected=new Array("","","");
var reqType="";
var scope="ext";


// Servlet URLs von LH
var urlLocation="";
var urlCategory="";
var urlOffers="";
var urlSearchOffers="";

// Servlet URLS werden gesetzt    
if (proxy){
  urlLocation="../../Proxy?mimeType=text/plain&url="+actHost+"hr/getLocationFilterJSON.action";
  urlCategory="../../Proxy?mimeType=text/plain&url="+actHost+"hr/getCategoryFilterJSON.action";
  urlOffers="../../Proxy?mimeType=text/plain&url="+actHost+"hr/filterOfferListJSON.action";
  urlSearchOffers="../../Proxy?mimeType=text/plain&url="+actHost+"hr/searchOfferListJSON.action";
} else {
  urlLocation=actHost+"hr/getLocationFilterJSON.action";
  urlCategory=actHost+"hr/getCategoryFilterJSON.action";
  urlOffers=actHost+"hr/filterOfferListJSON.action";
  urlSearchOffers=actHost+"hr/searchOfferListJSON.action";
}

/*
 *  Ajax Eventhandler (mit Requesturl und Callbackfunktion als Parameter)
 */  
function ajaxEventHandler(url,params,callbackFunc) {
    $.ajax({
           type: "GET",
           url: encodeURI(url+params),
           dataType: "json",
           timeout: 20000,
           error: function (XMLHttpRequest, textStatus, errorThrown) {noResult("The Webservice is temporarily not available.","Error");hideOverlay();},
           success: function(data,textStatus){
                if (textStatus!="error"){
                      // Bei fehlerhafter Suche
                      if (data.Message && data.Message.Type =="error"){
                          noResult(data.Message.Value,lastQuery);
                          if (query!=""){
                             searchTracking('false',lastQuery);
                          }
                          hideOverlay();
                      } else {   
                         $(".prodControls div").attr("style","display:block;");
                         if (query!=""){
                             searchTracking('true',lastQuery);
                          }
                         callbackFunc(data);            
                      }
                            
                   }
           },
           complete: function (XMLHttpRequest, textStatus) { }
     });
}

/*
 * URL für Ajax Request wird anhand von Parametern gesetzt und zurückgegeben
 */
function getParams(qType){
    var params='';  
    switch (qType) {
       case "location"  : params="?country="+country+"&scope="+getScope()+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "category"  : params="?country="+country+"&scope="+getScope()+"&location="+loc+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "offers"    : params="?country="+country+"&scope="+getScope()+"&category="+cat+"&location="+loc+"&page="+page+"&pageSize="+size+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "search"    : lastQuery=query;
                          params='?search='+query+'&scope='+getScope()+'&page='+page+'&pageSize='+size+'&lang='+draeger.LANGUAGE+'&'+Math.random(9999);
                          break;
       case "scope"  :    params="?country="+country+"&scope="+getScope()+"&category="+cat+"&location="+loc+"&page="+page+"&pageSize="+size+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
    }
    return params;   
}

/*
 * Vorstufe vor dem Ajaxcall
 * 
 * Per Parameter werden Aufrufe und Callbackfunktionen gesetzt 
 */
function updateJobSelector(params){
    // Overlay wird angezeigt
    showOverlay();
    //for history last Request Typ
    reqType=params;
    // Wenn Suchfeld befüllt, wird Suchwort eingelesen
    if (params=="search" || (params=="offers" && $("#search input").attr("value")!="") ){
        params="search";
        query= $("#search input").attr("value");
        //neues Suchwort
        if ((query!=lastQuery)&& !historyAction ){
            page=1;
        }
    }
    ajaxLocationFinished=true;
    ajaxCategoryFinished=true;
    // Parameter regelt den Aufruf
     switch (params) {
       case "location" :    ajaxLocationFinished=false; ajaxCategoryFinished=false;
                            ajaxEventHandler(urlLocation,getParams("location"),updateLocation);
                            ajaxEventHandler(urlCategory,getParams("category"),updateCategory);
                            ajaxEventHandler(urlOffers,getParams("offers"),updateOffers);
                            break;
       case "category" :    ajaxCategoryFinished=false;
                            ajaxEventHandler(urlCategory,getParams("category"),updateCategory);
                            ajaxEventHandler(urlOffers,getParams("offers"),updateOffers);
                            break;                            
       case "offers"   :    ajaxEventHandler(urlOffers,getParams("offers"),updateOffers);
                            break;
       case "search"   :    lastQuery=query;
                            country="all";
                            loc="all";
                            cat="all";
                            ajaxCategoryFinished=false;
                            ajaxEventHandler(urlCategory,getParams("category"),updateCategory);
                            ajaxEventHandler(urlSearchOffers,getParams("search"),updateOffers);
                            setStateSearchSelector();
                            break;
       case "scope"     :   ajaxEventHandler(urlOffers,getParams("scope"),updateOffers);
                            break;
     }
    //"Selected" Options in Selects werden entfernt
    jQuery.each($(".cats select option"), function() {
        $(this).removeAttr("selected");
        }); 
}            

/*
 * Inhalte der Dropdowns werden gespeichert und ins Historyobjekt eingetragen
 */
function saveDropdownsHistory(){
       jQuery.each($(".selectCat").children("div").children("p"),function(index){
               selectSelected[index]="";
               selectSelected[index]=$(this).attr("class");
      });

      // Historyobjekt mit aktuellen Parametern befüllt
      addHistoryEvent();
}

/*
 * Country gewählt, Locationdropdown wird gesetzt
 */
function updateLocation(jsonObj){
     //Dropdownfeld Location wird gesetzt
     $("#cat2 .selectCat").remove();
     //location enabled
     $("#cat2 div").html('<select class="cat2" name="cat2"><option id="allLocation">'+draeger.LABEL_ALL_LOCATIONOPTION+'</option></select>');
     var actSelect= $(".cat2");
     // Daten aus JSON Objekt eingesetzt
     $.each(jsonObj.Locations, function(j,value){
              //bei History Back/Forward  wird select gesetzt
              if (historyAction && (selectSelected[1]==value.Id)){
                  actSelect.append("<option selected='selected' id='"+value.Id+"'>"+value.Name+"</option>");
              } else {
                actSelect.append("<option id='"+value.Id+"'>"+value.Name+"</option>");
              }
     });
     // abschliesend wieder neuinitialisiert     
     actSelect.selectBox({css:'selectCat'});  
     $("#cat2 .selectCat ul").click(function(){whichDropdown($(this));return false;});
     ajaxLocationFinished=true;
}

/*
 * Gelieferte Jobkategorien vom Ajax Request werden ausgegeben
 */
function updateCategory(jsonObj){
      //Dropdownfeld Category wird gelöscht
      $("#cat3 .selectCat").remove();
      $("#cat3 div").html('<select class="cat3" name="cat3"><option id="allCategory">'+draeger.LABEL_ALL_CATEGORYOPTION+'</option></select>');
      var actSelect= $(".cat3");
      // Daten aus JSON Objekt eingesetzt
      $.each(jsonObj.Categories, function(j,value){
              //bei History Back/Forward  wird select gesetzt
              if (historyAction && (selectSelected[2]==value.Id)){
                actSelect.append("<option selected='selected' id='"+value.Id+"'>"+value.Name+"</option>");
              } else {
                actSelect.append("<option id='"+value.Id+"'>"+value.Name+"</option>");
              }
      });
      // abschliesend wieder neuinitialisiert
      $(".cat3").selectBox({css:'selectCat'});  
      $("#cat3 .selectCat ul").click(function(){whichDropdown($(this));return false;});
      ajaxCategoryFinished=true;
}


/*
 * Gelieferte Jobangebote vom Ajax Request werden ausgegeben
 */
function updateOffers(jsonObj){
   // Jobliste wird geleert
   $(".prodList").html("");  
   // Html für die einzelnen Angebote(aus JSON) wird erstellt und an die Ergebnisliste angehängt
   $.each(jsonObj.Offers, function(i,job){
       var jobCats="";
       //Kategorien gelesen
       $.each(job.Categories, function(i,cats){
           jobCats+='<p>Cat ID: '+cats.Id+' Name: '+cats.Name+'</p>';
       });
       // Angebots HTML mit Daten aus JSON versehen 
       var actJob='<div class="select m-resultjobsearch clearfix">\n\
                      <p class="date">'+job.Createdate+'</p>\n\
                      <h3 class="sl"><a href="getOfferDetail.action?country='+country+'&location='+loc+'&category='+cat+'&scope='+getScope()+'&search='+encodeURI(query)+'&pageSize='+size+'&page='+page+'&jobnumber='+job.Jobnumber+'&selectorHitIndex='+i+'" >'+job.Title+'</a></h3>\n\
                      <p class="txsmall shortmargin">'+job.Country+', '+job.Location+'</p>\n\
                  </div>';
       
       //Result an Liste angehängt
       $(".prodList").append(actJob);     
   });
   // Event für "Clipboard Hinzufügen" setzen -> Toolbox.js
   $("a.addJob").click(function(){addJob($(this));this.blur();return false;});
   //Jobanzahl aus JSON Objekt übernommen
   jobCounter=jsonObj.Count;
   //Produktanzahl ins HTML geschrieben
   $(".prodCounter").html(jobCounter);
   // Anzahl Ergebniseiten ermittelt
   pageCounter=Math.ceil((parseInt(jobCounter)/parseInt(size))); 
   
   // Anzeige gehighlightet für derzeit angeklickte Auswahl
   $(".prodSize a").removeClass("active");
   $(".prodSize"+size).addClass("active");
   // Pagecontrol aktualisieren
   pageControl();

    // wait finishing all Ajax Events to go further
   var time=0;
   var ajaxInterval=window.setInterval(function(){
                                         if (ajaxLocationFinished&&ajaxCategoryFinished){
                                               // Historypunkt gesetzt, wenn Browser Back/Forwardbutton nicht gerade gedrückt wurde
                                               if (!historyAction){
                                                    saveDropdownsHistory();
                                               } else {
                                                    historyAction=false;
                                               }
                                               // Ajax Overlay verstecken
                                               hideOverlay();
                                               window.clearInterval(ajaxInterval);
                                         }
                                         time+=100;
                                         //timeout 30 sec
                                         if (time>=20000){
                                                window.clearInterval(calInterval);
                                         }
                                     }, 100);

}



/*
 * Pagingmechanismus für die Seitenauswahl
 */
function pageControl(){
   $(".prodControls .disabled").removeClass("disabled");
   // aktuelle Seitenzahl wird ausgelesen
   page=parseInt(page);
   pageCounter=parseInt(pageCounter);
   // HTML Seitenzahlen werden aktualisiert
   $(".minus2Page").html(page-2);
   $(".minus1Page").html(page-1);
   $(".actPage").html(page);
   $(".plus1Page").html(page+1);
   $(".plus2Page").html(page+2);
   // Wenn man sich auf der letzten Seite befindet, werden Forwardbutton, nächste Seite usw. disabled
   if (page==pageCounter){
       $(".plus1Page").addClass('disabled');
       $(".plus2Page").addClass('disabled');
       $(".plus1Page").html('');
       $(".plus2Page").html('');
       $(".lastPage").addClass('disabled');
       $(".nextPage").addClass('disabled');
   }
    // Wenn man sich auf der vorletzten Seite befindet,... 
   if (page+1==pageCounter){      
       $(".plus2Page").addClass('disabled');
       $(".plus2Page").html('');     
   }   
   // Wenn man sich auf Seite 1 befindet,... 
   if (page==1){
       $(".firstPage").addClass('disabled');
       $(".prevPage").addClass('disabled');
       $(".minus2Page").addClass('disabled');
       $(".minus2Page").html('');
       $(".minus1Page").addClass('disabled');
       $(".minus1Page").html('');
   } 
   // Wenn man sich auf Seite 2 befindet,...
   if (page==2){
       $(".minus2Page").addClass('disabled');
       $(".minus2Page").html('');
   } 
}   


/*
 *  "Ajax" Overlay wird angezeigt
 */
function showOverlay(){
  var height=$("#contentContainer").innerHeight();
  $("#wait").children().css({ display:"block"});
  $("#wait").css({ opacity: "0.5",left:"0px",height:height});
}

/*
 *  "Ajax" Overlay wird wieder versteckt
 */
function hideOverlay(){
    $("#wait").css({ left:"-2000px",height:"1px"});
    $("#wait").children().css({ display:"none"});
}

/*
 *  Zusätzlicher Ajax-Param für interne/externe User
 */
function getScope(){
    scope = $("div#cat4 p").attr("class");

    if(scope == "" || scope == undefined){
        scope = "ext";
    }
    return scope;
}

/*
 * Callback bei Klick auf Kategorie Dropdown
 */
function whichDropdown(elem){
    // Suchfeld wird geleert bei Selektorclick
    $("#search input").attr("value","");
    query="";
    lastQuery="";
    //zurück zu Seite 1
    page="1";
    // gewünschte ID der Kategorie wird ermittelt
    var actCat= elem.parent().prev("div").children("p").attr("class");
    var actSelect=elem.parent().prevAll("select");
    jQuery.each(actSelect.children("option"),function(){
           if ($(this).attr("id")==actCat){
               // welches Dropdown wurde geklickt?
               switch (actSelect.attr("class")){
                     case "cat1"    : country=$(this).attr("id");
                                      loc="all";
                                      cat="all";
                                      if (country=="allCountry" || country==""){
                                          country="all";                                   
                                          // Jobselektor wird aktualisiert (Ajax)
                                          updateJobSelector("category"); 
                                          disableLocationSelector();

                                      } else {
                                          // Jobselektor wird aktualisiert (Ajax)
                                          updateJobSelector("location");
                                      }
                                      // Tracking
                                      clickTracking('false','cat1');
                                      break;
                     case "cat2"    : loc=$(this).attr("id");
                                      cat="all";
                                      if (loc=="allLocation" || loc==""){
                                          loc="all";
                                      }
                                      // Jobselektor wird aktualisiert (Ajax)
                                      updateJobSelector("category");
                                      // Tracking
                                      clickTracking('false','cat2');
                                      break;
                     case "cat3"    : cat=$(this).attr("id");
                                      if (cat=="allCategory" || cat==""){
                                          cat="all";
                                      }
                                      // Jobselektor wird aktualisiert (Ajax)
                                      updateJobSelector("offers");
                                      // Tracking
                                      clickTracking('false','cat3');
                                      break;
                    case "cat4"    :  // Jobselektor wird aktualisiert (Ajax)
                                      updateJobSelector("scope");
                                      // Tracking
                                      clickTracking('false','cat4');
                                      break;
               }
           }
    });     
    
    // aktuelle Active Selection wird gespeichert
    jQuery.each($(".selectCat").children("div").children("p"),function(index){
           selectSelected[index]=""; 
           selectSelected[index]=$(this).attr("class");
    });    
}

/*
 * Callback für Klick auf Anzahl angezeigter Resultate
 */
function whichSize(elem){   
    // aktuelle Anzahl ermittelt und gesetzt
    size=elem.html();
    //zurück zu Seite 1
    page="1";
    // Jobselektor wird aktualisiert (Ajax)
    updateJobSelector('offers');
}

/*
 * Callback für Pagingbuttons
 */
function whichControl(elem){    
  if (!elem.hasClass("disabled")){
      var pageType=elem.attr("class");
      page=parseInt(page);
      // Je nach Auswahl wird Page neugesetzt
      switch (pageType) {
       case "firstPage" : page=1;
                          break;
       case "prevPage"  : page=page-1;
                          break;
       case "minus2Page": page=page-2; 
                          break;
       case "minus1Page": page=page-1; 
                          break;
       case "plus1Page" : page=page+1; 
                          break;
       case "plus2Page" : page=page+2;  
                          break;
       case "nextPage"  : page=page+1; 
                          break; 
       case "lastPage"  : page=pageCounter;
                         break;
    }
    // Produktselektor wird aktualisiert (Ajax)
    updateJobSelector('offers');
  }
}

 /*
 *   Ausgabe bei keinen gefundenen Jobresultaten
 */        
function noResult(message,headline){
    // Controls werden ausgeblendet
    $(".prodControls div").attr("style","display:none;");
    // Counter genullt
    $(".prodCounter").html("0");
    // Errortext ausgegeben
    if (headline==""){headline="Error";}
    $(".prodList").html("<div class='noresult'><h2>"+headline+"</h2><p class='txtext'>"+message+"</p></div>");
     // Historypunkt gesetzt, wenn Browser Back/Forwardbutton nicht gerade gefrückt wurde
   if (!historyAction){
        saveDropdownsHistory();
   } else {
        historyAction=false;
   }
}

/*
 * Selektoren werden in Initialisierungszustand gebracht
 */
function setStateSearchSelector(){
     
     // bei Suche werden die Dropdowns in den Ausgangszustand gebracht
      for (var i = 1; i <= 2; i++){
        var delAct= $(".cat"+i);   
        delAct.clone().insertBefore(delAct.parent());
        delAct.parent().remove();
      }
      //Dropdownfeld Location wird geleert
      $("#cat1 div select").children().removeAttr("selected");
      $(".cat1").selectBox({css:'selectCat'});
      $("#cat1 .selectCat ul").click(function(){ whichDropdown($(this));return false;});
      disableLocationSelector();
}

/*
 * Leeres Location "Dropdown" wird disabled 
 */
function disableLocationSelector(){
      //Dropdownfeld Location wird gelöscht/neuinitialisiert
      $("#cat2 .selectCat").remove();
      $("#cat2 div").html('<select class="cat2" name="cat2"><option id="allLocation">'+draeger.LABEL_ALL_LOCATIONOPTION+'</option></select>');
      $(".cat2").selectBox({css:'selectCat'});
      var temp=$(".cat2").next('div');
      temp.children('p').html(draeger.LABEL_EMPTY_LOCATIONDROPDOWN);
      temp.css({'background-color':'#fff'});
}

/*
 * Selektoren werden per Javascript initialisert und mit Events versehen
 */
function initSelectors(){
    $(".cat1").selectBox({css:'selectCat'});
    $(".cat2").selectBox({css:'selectCat'});
    $(".cat3").selectBox({css:'selectCat'});
    $(".cat4").selectBox({css:'selectCat'});
    //Category Dropdowns disablen
    if (country=="all"){
           //location disabled
           var temp=$(".cat2").next('div');
           temp.children('p').html(draeger.LABEL_EMPTY_LOCATIONDROPDOWN);
           temp.css({'background-color':'#fff'});
           $("#cat1 .selectCat ul").click(function(){ whichDropdown($(this));return false;});
           $("#cat3 .selectCat ul").click(function(){ whichDropdown($(this));return false;});
           $("#cat4 .selectCat ul").click(function(){ whichDropdown($(this));return false;});
    } else {
        $(".selectCat ul").click(function(){ whichDropdown($(this));return false;});
    }
}

/* 
 * Event Handler für die Historyfunktion
 */
addHistoryEvent = function() {
         // JSON Objekt zuordbar mittels Millisekunden seit 1970 an URL
        var time = new Date();
        var hKey="e"+time.getTime();
        // aktuelle Parameter werden als JSON Objekt im Historyobjekt gespeichert
        var jsonobj={"reqType":reqType,"scope":scope,"country":country,"location":loc,"cat":cat,"query":query,"page":page,"size":size,"selectSelected":[selectSelected[0],selectSelected[1],selectSelected[2]]};
        dhtmlHistory.add(hKey,jsonobj);
}



function historyChange(newLocation, historyData) {
      // Wenn Historyobjekt befüllt...
      if (historyData){
          //JSON Objekt wird ausgelesen und Parameter befüllt
          country=historyData.country;
          loc=historyData.location;
          cat=historyData.cat;
          query=historyData.query;
          scope=historyData.scope;
          lastQuery=query;
          page=historyData.page;
          size=historyData.size;
          selectSelected[0]=historyData.selectSelected[0];
          selectSelected[1]=historyData.selectSelected[1];
          selectSelected[2]=historyData.selectSelected[2];
          // Historyvariable auf true, damit beim Update kein erneuter Historypunkt im Browser gesetzt wird
          historyAction=true;
          // Wenn es sich um eine Suche handelt, wird der Suchbegriff wieder ins Suchfeld eingetragen
          if (query!=""){
              $("#search input").attr("value",query);
              updateJobSelector("search");
          } else {
              $("#search input").attr("value","");
              //first dropdown new initialized
              var firstSelect=$(".cat1");
              firstSelect.clone().insertBefore(firstSelect.parent());
              firstSelect.parent().remove();
              firstSelect=$(".cat1");
              if (selectSelected[0]!=""){
                firstSelect.children().each(function (i) {
                    $(this).removeAttr("selected");
                    if ($(this).attr("id")==selectSelected[0]){
                        $(this).attr("selected","selected");
                    }
                });
              }
              firstSelect.selectBox({css:'selectCat'});
              $("#cat1 .selectCat ul").click(function(){whichDropdown($(this));return false;});
              if (country=="all"){
                       updateJobSelector("category");
                       disableLocationSelector();
              } else {
                      // Jobselektor wird aktualisiert (Ajax)
                      updateJobSelector("location");
              }
        }
      }
};

/*
 *   Init Application Job Selector
 */
$().ready(function() {
        $(".cats").removeClass("jsdisplay");
        //Applikation aktiv
        draeger.HRSELECTOR_ACTIVE=true;
        lastQuery=query;
        // Kategorieselektor wird initialisiert
        initSelectors();
        // Events an Links gehängt   
        // Bestimmung Anzahl gezeigter Jobangebote
        $(".prodSize a").click(function(){whichSize($(this));return false;});
        // Pagingmechanismus
        $(".pageControl a").click(function(){whichControl($(this));return false;});
        // Suchfeld (Mausklick und Enter)
        $("#search a").click(function(){
            updateJobSelector('search');
            /*addHistoryEvent();*/
            return false;
        });
        $("#search input").keydown(function(event){
            if(event.keyCode=="13"){
                updateJobSelector('search');
                /*addHistoryEvent();*/
                return false;
            }
            return true;
        });
        // Initialisierung der History Funktion
        dhtmlHistory.initialize();
        //Subscribe Listener für Browser Back/Forward
        dhtmlHistory.addListener(historyChange);
        // erster Historypunkt wird gesetzt (unter Umständen nicht nötig)
        if (location.href.match("#e")==null){
             // erster Historypunkt wird gesetzt (unter Umständen nicht nötig)
            saveDropdownsHistory();
        }
        //Ausfaden des Sichtschutzes vor dem Selektor
        $(".blocker").fadeOut(1000);     
});

/*
 * Tracking-Variablen befüllen und abschicken
 * success = true/false -> Suche war erfolgreich oder nicht
 * lastQuery = Suchbegriff
 */
function searchTracking(success,lastQuery) {

    var searchTerm = lastQuery.toLowerCase();

    if(success == 'false') { /* Suche nicht erfolgreich */
        s.prop1 = "";
        s.prop2 = searchTerm;
        s.prop3 = searchTerm;
        s.prop9 = 'job search';
        s.prop13 = $('.prodSize .active').html()+':one column';
        s.eVar2 = ""; // = s.prop1
        s.eVar3 = searchTerm; // = s.prop2
        s.eVar12 = 'job search'; // = s.prop9
    } else { /* Suche erfolgreich */
        s.prop1 = searchTerm;
        s.prop2 = "";
        s.prop3 = searchTerm;
        s.prop9 = 'job search';
        s.prop13 = $('.prodSize .active').html()+':one column';
        s.eVar2 = searchTerm; // = s.prop1
        s.eVar3 = ""; // = s.prop2
        s.eVar12 = 'job search'; // = s.prop9
    }

    s.linkTrackVars = 'prop1,prop2,prop3,prop9,prop13,eVar2,eVar3,eVar12';
    // true -> Standard wäre "this", was dem href eines Links entsprechen würde. Gibt es kein href, wäre this=null.
    // 'o' -> normaler Link wird getrackt (kein Download- oder Exit-Link)
    s.tl(true,'o','job selector');
}

/*
 * Tracking-Variablen befüllen und abschicken
 * element = HTML-Object oder Element-ID
 * type = "cat1", "cat2", "cat3", "search"
 */
function clickTracking(element, type){

    var trackPath = buildTrackPath(type);

    s.prop1 = trackPath;
    s.prop2 = "";
    s.prop3 = trackPath;
    s.prop9 = 'job selector';
    s.prop13 = $('.prodSize .active').html()+':one column';
    s.eVar2 = trackPath; // = s.prop1
    s.eVar3 = ""; // = s.prop2
    s.eVar12 = 'job selector'; // = s.prop9

    s.linkTrackVars = 'prop1,prop2,prop3,prop9,prop13,eVar2,eVar3,eVar12';
    // true -> Standard wäre "this", was dem href eines Links entsprechen würde. Gibt es kein href, wäre this=null.
    // 'o' -> normaler Link wird getrackt (kein Download- oder Exit-Link)
    s.tl(true,'o', 'job selector');
    
}

function buildTrackPath(elemId){

    var trackingTitles = new Array();
    // vorherige Dropdown-Container finden und ihre Inhalte ins Array
    var prevCatElems = $('#'+elemId).prevAll('div');
    $(prevCatElems).each(function(j){
    
        trackingTitles.unshift($(prevCatElems[j]).find('p').html());

    });

    // Kategorietitel des angeklickten Elements hinten anhängen
    trackingTitles.push($('#'+elemId).find('p').html());

    // Leerzeichen am Anfang und Ende wegtrimmen
    var trimmedTrackingTitles = new Array();
    $(trackingTitles).each(function(i){
        trimmedTrackingTitles.push(trackingTitles[i].match(/^\s*(.+?)\s*$/)[1]);
    });

    // Omniture-String zusammen bauen
    var trackingTitlesString = trimmedTrackingTitles.join(':');

    return trackingTitlesString;
}
    
   
/*
 *
 * Modified Selectbox for Job Selector (Hilfsklasse nicht direkt relevant)
 * 
 */
/*jQuery.fn.selectBox = function(o) {
        
	return this.each(function() {
        var oThis = this;
		var oSelected = null;
		var state = 'closed';
		var iSelectedIndex = 0;
               
		

		// wrap div around the select element
		jQuery(this).wrap('<div></div>').css({top:'-1000px',left:'-1000px',position: 'absolute'})//hide();
		var oContainer = jQuery(this).parent().addClass(o.css);
        // append html inside the container
		oContainer.append('<div><p></p></div><ul class="scroll-pane"></ul>');
		jQuery("div",oContainer).toggle(function() {
                   
                  if($(this).prev("select").children("option").length>1){
                     
                      state = 'opened';
                      var actElem=jQuery("ul",oContainer);
                      var actHeight=0;
                      jQuery.each(actElem.children(), function() {
                             actHeight+=parseInt($(this).height().replace('px',""))+3;//+3;
                      });   
                      if (actHeight <= 200){
                          actElem.height(actHeight);
                      }                                          
                      actElem.slideDown(5,function(){
                                                            if (!$(this).parent().hasClass('jScrollPaneContainer')){
                                                               $(this).jScrollPane({scrollbarWidth : 15,showArrows : true,arrowSize : 15});
                                                            } else {
                                                                $(this).parent().slideDown('fast');
                                                            } 
                                                            $(this).css({left:"0px"});
                                                            $(this).css({top:"0px"}); 
                                                            if (actHeight <= 200){
                                                               $(this).parent().css({"height":actHeight});
                                                            } else {
                                                                $(this).css({width:"426px"});   
                                                            }
                                                          });
                      jQuery("li",oContainer).removeClass('active');                      
                      if(oSelected == null) {
                    	jQuery("li:eq(0)",oContainer).addClass('active');
                    	oSelected = jQuery("li:eq(0)",oContainer);
                      } else {
                        oSelected.addClass('active');
                      }
                   }  
		//jQuery(oThis)[0].focus();
		},function() {
                   if($(this).prev("select").children("option").length>1){
                       state = 'closed';
                       var ul= $(this).parent().children().children("ul");
                       var scrollPane= $(this).parent().children(".jScrollPaneContainer");
                       ul.slideUp('fast',function() {});
                       scrollPane.slideUp('fast',function() {});
                   }
		});

        jQuery("ul",oContainer).parent().bind("mouseleave",function(){
                        window.setTimeout(function(){  
                          if(state == 'opened') {
                            jQuery("div",oContainer).trigger("click");
                          } 
                        }, 400);  
        });
                
			
		// get values from the option elements and set them in the ul list.
		jQuery(this).keyup(function() {
			setValue();
		});

		jQuery('option',this).each(function(i) {
			var o = this;
			jQuery(this).click(function() {
				this.selected = true;
			});

			jQuery("ul",oContainer).append('<li>' +  jQuery(this).text() + '</li>');

			jQuery("li:eq(" + i + ")",oContainer).click(function() {
				jQuery(o).click();
				jQuery("div",oContainer).trigger("click");
                                jQuery("div p",oContainer).html(jQuery(o).text());
                                jQuery("div p",oContainer).removeClass();
                                jQuery("div p",oContainer).addClass(jQuery(o).attr("id"));
                                oSelected = $(this)
			}).mouseover(function() {
				jQuery(this).addClass('active');
				//jQuery(oThis)[0].focus();
			}).mouseout(function() {
				jQuery(this).removeClass('active');
				//jQuery(oThis)[0].blur();
			});
		});

		// set ul list position	
		jQuery("ul",oContainer).hide();

		var positionListElement = function() {
           //window.setTimeout(function(){
                       //var oOffset = jQuery("div",oContainer).offset('.jobSelector');
                        // set ul list position
                        
                        jQuery("ul",oContainer).css({
                            //left: (oOffset.left )+ 'px',
                        	//top: oOffset.top + parseInt(oOffset.height) + 'px',
                        	position: 'absolute' ,
                        	width: '425px'
                        });
             //}, 10);
		};
		var setValue = function() {
                        var elem =jQuery(":selected",oThis);
			var val = elem.text();
                        jQuery("div p",oContainer).html(val);
                        if (jQuery(oThis)[0].selectedIndex>0){
                          jQuery("div p",oContainer).attr("class",elem.attr("id"));
                        }
			oSelected = jQuery("li:eq(" + jQuery(oThis)[0].selectedIndex + ")",oContainer);                  
			jQuery("li",oContainer).removeClass('active');
			oSelected.addClass('active');
                        
		};

		setValue();
		positionListElement();
		
		//jQuery(window).resize(positionListElement);
	});
};
*/

jQuery.fn.selectBox = function(o) {
	return this.each(function() {

        var oThis = this;
		var oSelected = null;
		var state = 'closed';
                var actHeight=0;

        //wierd
     //   var oSelectOffset = jQuery(this).offset('HTML');

                // Safari gibts keine Tastatursteuerung, deshalb, Selects verstecken
                if(jQuery.browser.safari){
                    jQuery(this).wrap('<div></div>').hide();
                } else {
                    jQuery(this).wrap('<div></div>').css({left:'-1000px',position: 'absolute'});
                }

		var oContainer = jQuery(this).parent().addClass(o.css);
                // append html inside the container
		oContainer.append('<div><p></p></div><ul class="scroll-pane"></ul>');

		jQuery("div",oContainer).toggle(function() {

                         if($(this).prev("select").children("option").length>1){

                                  state = 'opened';
                                  reentered=false;
                                  var actElem=jQuery("ul",oContainer);
                                  actHeight=0;
                                  jQuery.each(actElem.children(), function() {

                                         actHeight+=parseInt($(this).height().replace('px',""))+3;//+3;
                                  });
                                  if (actHeight <= 200){
                                      actElem.height(actHeight);
                                  }
                                  actElem.slideDown(5,function(){
                                                                       if (!$(this).parent().hasClass('jScrollPaneContainer')){
                                                                           $(this).jScrollPane({scrollbarWidth : 15,showArrows : true,arrowSize : 15});
                                                                           // ick brauch den drag scroller focus für IE6 !!!
                                                                            jQuery(".jScrollPaneTrack,.jScrollArrowUp,.jScrollArrowDown",oContainer).mouseup(function() {
                                                                                        jQuery(oThis)[0].focus();
                                                                            });

                                                                        } else {
                                                                            $(this).parent().slideDown('fast');
                                                                        }
                                                                        $(this).css({left:"0px"});
                                                                        $(this).css({top:"0px"});
                                                                        if (actHeight <= 200){
                                                                           $(this).parent().css({"height":actHeight});
                                                                        } else {
                                                                            $(this).css({width:"410px"});
                                                                        }
                                                                      });
                                  jQuery("li",oContainer).removeClass('active');
                                  if(oSelected == null) {
                                        jQuery("li:eq(0)",oContainer).addClass('active');
                                        oSelected = jQuery("li:eq(0)",oContainer);
                                  } else {
                                        oSelected.addClass('active');
                                  }
                       }

                 jQuery(oThis)[0].focus();

		},function() {

                       if($(this).prev("select").children("option").length>1){
                                   state = 'closed';
                                   reentered=false;
                                   var ul= $(this).parent().children().children("ul");


                                  var scrollPane= $(this).parent().children(".jScrollPaneContainer");
                                  ul.slideUp('fast',function() {});
                                  scrollPane.slideUp('fast',function() {});
                       }
		});

        jQuery("ul",oContainer).parent().bind("mouseleave",function(){
                        reentered=false;
                        window.setTimeout(function(){
                          //console.log("mouseleave: "+reentered+" state: "+state);
                          if(!reentered && state == 'opened') {
                                reentered=false;
                                jQuery("div",oContainer).trigger("click");
                          }
                        }, 1000);

        });

        jQuery("ul",oContainer).parent().bind("mouseenter",function(){
                          reentered=false;
                          if(state == 'opened') {
                                reentered=true;
                          }
        });

                // get values from the option elements and set them in the ul list.
		jQuery(this).keydown(function(e) {
                        var key = e.charCode || e.keyCode || 0;
                        // bei tab oder esc schliessen
                        if(state == 'opened' &&(key=="27"||key=="9")){
                            jQuery("div",oContainer).trigger("click");
                            return false;
                        }
		});

                // ie 6 manuell scroll
               jQuery(this).mousewheel(function(e,delta) {
                            jQuery("ul",oContainer)[0].scrollBy(-(event.wheelDelta /120)*25);//(e.wheelDelta)*((delta<=-1)?-delta:(1+delta))
                            return false;
                        }
		);


		// get values from the option elements and set them in the ul list.
		jQuery(this).keyup(function(e) {

                        var key = e.charCode || e.keyCode || 0;
                        //tab highlighting
                        if(key=="9"){
                           // console.log("element: "+$(this).html());
                            $(this).parent().parent().animate({backgroundColor: "#dadddf"}, 500, function(){$(this).animate({backgroundColor: "#EDF0F2"},500);});
                        }
                        // liste öffnen
                        if(state == 'closed' &&(key=="40"||key=="38"||key=="39"||key=="37")){
                             jQuery("div",oContainer).trigger("click");
                              setValue(key=="13",false);
                        } else if(state == 'opened'){
                                    setValue(key=="13",false);
                                }
		});

		jQuery('option',this).each(function(i) {
			var o = this;
			jQuery(this).click(function() {
				this.selected = true;
			});

			jQuery("ul",oContainer).append('<li>' +  jQuery(this).text() + '</li>');

			jQuery("li:eq(" + i + ")",oContainer).click(function() {
				jQuery(o).click();
				jQuery("div",oContainer).trigger("click");
                                jQuery("div p",oContainer).html(jQuery(o).text());
                                jQuery("div p",oContainer).removeClass();
                                jQuery("div p",oContainer).addClass(jQuery(o).attr("id"));
                                oSelected = $(this)
			}).mouseover(function() {
				jQuery(this).addClass('active');
                                // ie 6 ohne focus, dann geht scrolling nicht mehr
                                jQuery(oThis)[0].focus();

			}).mouseout(function() {
				jQuery(this).removeClass('active');
                                //jQuery(oThis)[0].blur();

			});
		});

		// set ul list position
		jQuery("ul",oContainer).hide();

		var positionListElement = function() {

                // set ul list position
                jQuery("ul",oContainer).css({
                    //left: (oOffset.left )+ 'px',
                    //top: oOffset.top + parseInt(oOffset.height) + 'px',
                    position: 'absolute',
                    width: '425px'//oOffset.width + 'px'
                });

		};
		var setValue = function(enterPressed,init) {
                        var elem =$(oThis).children("option[selected]");
                        var val = elem.text();
                        oldSelectedPos=0;
                        if (init){
                           jQuery("div p",oContainer).html(val);
                            if (jQuery(oThis)[0].selectedIndex>0){
                              jQuery("div p",oContainer).attr("class",elem.attr("id"));
                            }
                        } else {
                           /* if(oSelected.html()==null){
                                oldSelectedPos=0;
                            } else {
                                oldSelectedPos=oSelected.offset().top;
                            }*/
                        }


                        oSelected = jQuery("li:eq(" + jQuery(oThis)[0].selectedIndex + ")",oContainer);

                      /*  if(oSelected.html()==null){
                            newSelectedPos=0;
                        } else {
                            newSelectedPos=oSelected.offset().top;
                        }*/

                        if(actHeight > 200 && jQuery("ul",oContainer).parent().hasClass('jScrollPaneContainer')){
                                 //console.log("aktuelle Höhe: "+actHeight+" selected: ");
                                if(jQuery(oThis)[0].selectedIndex>1){
                                    //jQuery("ul",oContainer)[0].scrollBy(newSelectedPos-oldSelectedPos);
                                    jQuery("ul",oContainer)[0].scrollTo(jQuery(oThis)[0].selectedIndex*20);
                                } else {
                                    //console.log("index: "+jQuery(oThis)[0].selectedIndex);
                                    jQuery("ul",oContainer)[0].scrollTo(0);

                                }
                        }

			jQuery("li",oContainer).removeClass('active');
			oSelected.addClass('active');
                        if (enterPressed){
                             jQuery("div p",oContainer).html(val);
                                if (jQuery(oThis)[0].selectedIndex>=0){ // hier vorher > , wegen tastatursteuerng muss hier auch erster abgecdeckt werden
                                  jQuery("div p",oContainer).attr("class",elem.attr("id"));
                                }
                            //console.log(oSelected);
                            oSelected.parent().click();
                            jQuery("div",oContainer).trigger("click");
                        }

		};

		setValue(false,true);

		positionListElement();

		//jQuery(window).resize(positionListElement);

	});
};

