/*
 * Draeger Event Selector 
 * created by Christian Beyer (e7)
 * 
 */

// LH URL (Proxy zum lokalen Testen)
var proxy=false;
var actHost=draeger.SEND_PATH;

// globale Variablen
var lastQuery='';
var selectHtml=new Array("","");
var selectSelected=new Array("","");
var reqType="";
var ajaxCalendarFinished=true;
var ajaxIndustryFinished=true;
var historyAction=false;

// Servlet URLs von LH
var urlIndustry="";
var urlCalendar="";
var urlEvents="";
var urlSearchEvents="";

// Servlet URLS werden gesetzt    
if (proxy){
  urlIndustry="../../Proxy?mimeType=text/plain&url="+actHost+"es/getIndustryFilterJSON.action";
  urlCalendar="../../Proxy?mimeType=text/plain&url="+actHost+"es/getCalendarJSON.action";
  urlEvents="../../Proxy?mimeType=text/plain&url="+actHost+"es/getEventsJSON.action";
  urlSearchEvents="../../Proxy?mimeType=text/plain&url="+actHost+"es/getEventsJSON.action";
} else {
  urlIndustry=actHost+"es/getIndustryFilterJSON.action";
  urlCalendar=actHost+"es/getCalendarJSON.action";
  urlEvents=actHost+"es/getEventsJSON.action";
  urlSearchEvents=actHost+"es/getEventsJSON.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);
                          hideOverlay();
                      } else {   
                         $(".prodControls div").attr("style","display:block;"); 
                        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 "industry"  : params="?country="+country+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "calendar"  : params="?country="+country+"&industry="+industry+"&year="+year+"&month="+month+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "events"    : params="?country="+country+"&industry="+industry+"&year="+year+"&month="+month+"&page="+page+"&pagesize="+size+"&lang="+draeger.LANGUAGE+"&"+Math.random(9999);
                          break;
       case "search"    : params="?query="+query+"&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 updateEventSelector(params){
    // Overlay wird angezeigt
    showOverlay();
    //for history last Request Typ
    reqType=params;
    // Wenn Suchfeld befüllt, wird Suchwort eingelesen
    if (params=="search" || (params=="events" && $("#search input").attr("value")!="")|| (params=="calendar" && $("#search input").attr("value")!="") ){
        params="search";
        query= $("#search input").attr("value");
        //neues Suchwort
        if ((query!=lastQuery)&& !historyAction ){
            page=1;
        }
        
    }
    //Flag for Dependency of updateCalendar and updateEvents
    ajaxCalendarFinished=true;
    ajaxIndustryFinished=true;
    // Parameter regelt den Aufruf
     switch (params) {
       case "industry" :    //Flag for Dependency of updateCalendar and updateEvents
                            ajaxCalendarFinished=false;ajaxIndustryFinished=false;
                            ajaxEventHandler(urlIndustry,getParams("industry"),updateIndustry);
                            ajaxEventHandler(urlCalendar,getParams("calendar"),updateCalendar);
                            ajaxEventHandler(urlEvents,getParams("events"),updateEvents);
                            break;
       case "calendar" :    //Flag for Dependency of updateCalendar and updateEvents
                            ajaxCalendarFinished=false;
                            ajaxEventHandler(urlCalendar,getParams("calendar"),updateCalendar);
                            ajaxEventHandler(urlEvents,getParams("events"),updateEvents);
                            
                            break;                            
       case "events"   :    ajaxEventHandler(urlEvents,getParams("events"),updateEvents);
                            break;
       case "search"   :    country="all";
                            industry="all";
                            lastQuery=query;
                            ajaxEventHandler(urlSearchEvents,getParams("search"),updateEvents);
                            setStateSearchSelector();
                            break;    
     }                             
}            

/*
 * Country gewählt, Industrydropdown wird gesetzt
 */
function updateIndustry(jsonObj){
     //Dropdownfeld Industry wird gesetzt
     $("#cat2 .selectCat").remove();
     //industry enabled
     $("#cat2 div").html('<select class="cat2" name="cat2"><option id="allIndustry">'+draeger.LABEL_ALL_INDUSTRYOPTION+'</option></select>');
     var actSelect= $(".cat2");
     // Daten aus JSON Objekt eingesetzt
     $.each(jsonObj.Industries, function(j,value){
              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;});
     //set flag update finished for eventUpdate function
     ajaxIndustryFinished=true;
}                

/*
 * Kalenderblatt wird aktualisiert
 */ 
function updateCalendar(jsonObj){
    var jIndex=0;  
    var calendarMonth="";
    //Kalenderblatt wird durchlaufen
    for (var row=1;row<=6;row++){
        for (var col=1;col<=7;col++){
            var eventActive="";
            //wenn es an diesem Tag einen Event gibt, wird die Klasse 'dateactive' gesetzt
            if (jsonObj.Calendar[jIndex].Events.length!=0){
                eventActive="dateactive";
            }
            var day=jsonObj.Calendar[jIndex].day;
            if (day==null){
                day="";
            }
            day='<li id="day'+row+col+'" class="calendarcell '+eventActive+'">'+day;
            if (eventActive!=""){
              day+='<ul style="display: none;" id="dayd'+row+col+'">';
               // Events aus JSON Objekt durchlaufen und gesetzt
              $.each(jsonObj.Calendar[jIndex].Events, function(j,event){ 
                 day+='<li class="event'+event.id+'"><h6>'+event.title+'</h6><p class="datetime">'+event.startDate+' - '+event.endDate+'</p><p class="event">'+event.text+'<a target="_blank" href="http://'+event.eventLink+'">'+event.eventLinkText+'</a></p></li>';
               }); 
              day+='</ul>'; 
            } else {
                day+='</li>'
            }
            calendarMonth+=day;
            jIndex++;
        }
    }
    year=jsonObj.Year;
    month=jsonObj.Month;
    $("#calendarnav strong").html(jsonObj.MonthText+" "+year);
    // wenn Suche nicht aktiv
    if (query==""){
           $(".dateMonth").html(draeger.LABEL_EVENT_RESULTS+" <span>"+jsonObj.MonthText+", "+year+"</span>");
    }
    $("#days").html(calendarMonth);
    //set flag update finished for eventUpdate function
    ajaxCalendarFinished=true;
    
}


/*
 * Gelieferte Events vom Ajax Request werden ausgegeben
 */
function updateEvents(jsonObj){
  // wenn Suche aktiv
   if (query!=""){
           $(".dateMonth").html(draeger.LABEL_EVENTSEARCH_RESULTS+" <span>\""+query+"\"</span>");
   }
   // Eventliste wird geleert
   $(".eventResults").html("");  
   // Html für die einzelnen Angebote(aus JSON) wird erstellt und an die Ergebnisliste angehängt
   $.each(jsonObj.Events, function(i,event){
       var media='<div class="content no-media">'
       if (event.logo!=null){
          media='<div class="image"><img height="95" width="110" src="'+draeger.DOCROOT+'/media/eventSelector/'+event.logo+'" alt="Logo"/></div><div class="content">';
       }
       // Event HTML mit Daten aus JSON versehen 
       var actEvent='<div id="event'+event.id+'" class="m-art clearfix">\n\
                        '+media+'\n\
                          <p class="date">'+event.startDate+' - '+event.endDate+'</p>\n\
                          <h3>'+event.title+'</h3>\n\
                          <div class="richtext">\n\
                            <p>'+event.city+', '+event.country+'<br/>'+event.text+'<br/>\n\
                                <a class="lnkinternal" target="_blank" href="http://'+event.eventLink+'">'+event.eventLinkText+'</a>\n\
                            </p>\n\
                          </div>\n\
                        </div>\n\
                     </div>';
       
       //Result an Liste angehängt
       $(".eventResults").append(actEvent);     
   }); 
   //Eventanzahl aus JSON Objekt übernommen
   eventCounter=jsonObj.Size;
   //Produktanzahl ins HTML geschrieben
   $(".prodCounter").html(eventCounter);
   // Anzahl Ergebniseiten ermittelt
   pageCounter=Math.ceil((parseInt(eventCounter)/parseInt(size))); 
   
   // Anzeige gehighlightet für derzeit angeklickte Auswahl
   $(".prodSize a").removeClass("active");
   $(".prodSize"+size).addClass("active");
   // Pagecontrol aktualisieren
   pageControl();
  
   var time=0; 
  // wait for Calendar Ajaxupdate to set Events
  var calInterval=window.setInterval(function(){
                                         if (ajaxCalendarFinished&&ajaxIndustryFinished){
                                               initCalendar();
                                               // Historypunkt gesetzt, wenn Browser Back/Forwardbutton nicht gerade gedrückt wurde
                                               if (!historyAction){
                                                    saveHistory();
                                               } else {
                                                    historyAction=false;
                                               }
                                               // Ajax Overlay verstecken
                                               hideOverlay();
                                               window.clearInterval(calInterval);
                                         }
                                         time+=100;
                                         //timeout 20 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"});
}

/*
 * Callback bei Klick auf Kategorie Dropdown
 */
function whichDropdown(elem){
    // Suchfeld geleert
    $("#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");
    //console.log(actCat);
    var actSelect=elem.parent().prevAll("select");
             // welches Dropdown wurde geklickt?
               switch (actSelect.attr("class")){
                     case "cat1"    : country=actCat;
                                      industry="all";
                                      if (country=="allCountry"){
                                          country="all";
                                          // Eventselektor wird aktualisiert (Ajax)
                                          updateEventSelector("calendar"); 
                                          disableIndustrySelector();
                                      } else {
                                          // Eventselektor wird aktualisiert (Ajax)
                                          updateEventSelector("industry"); 
                                      }               
                                      break;
                     case "cat2"    : industry=actCat;
                                      if (industry=="allIndustry"){
                                          industry="all";
                                      }
                                      // Jobselektor wird aktualisiert (Ajax)
                                      updateEventSelector("calendar");
                                      break;
               }                       
}

/*
 * Callback bei Klick auf Kalender
 */
function whichCalendarDirection(elem){
  // Suchfeld geleert
  $("#search input").attr("value","");
  query="";
  lastQuery="";
  //previous month
  if (elem.attr("class")=="arrow_left_two"){
    --month;
    //was January
    if (month<="0"){
        month="12";
        --year;
    }
  // next month  
  } else {
      ++month;
    //was December
    if (month>="13"){
        month="1";
        ++year;
    }
  }
  //zurück zu Seite 1
  page="1";
  // Eventselektor wird aktualisiert (Ajax)
  updateEventSelector('calendar');
}

/*
 * 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";
    // Eventselektor wird aktualisiert (Ajax)
    updateEventSelector('events');
}

/*
 * 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;
    }
    // Eventselektor wird aktualisiert (Ajax)
    updateEventSelector('events');
  }
}       

/*
 * Inhalte der Applikation werden gespeichert und ins Historyobjekt eingetragen
 */
function saveHistory(){
      jQuery.each($(".selectCat").children("div").children("p"),function(index){
               selectSelected[index]=""; 
               selectSelected[index]=$(this).attr("class");
      });
    /*  jQuery.each($(".selectCat").children("select"),function(index){
               selectHtml[index]="<select class='cat"+(index+1)+"'>"+$(this).html().replace(/\"/g,"\'")+"</select>"; 
      });*/
      // Historyobjekt mit aktuellen Parametern befüllt
      addHistoryEvent();
}                                
                                
/* 
 * 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,"country":country,"industry":industry,"year":year,"month":month,"query":query,"page":page,"size":size,"selectSelected":[selectSelected[0],selectSelected[1]]};
        // JSON Objekt zuordbar mittels Millisekunden seit 1970 an URL 
       dhtmlHistory.add(hKey,jsonobj);
}

/*
 * Callback für Browser Back/Forward
 * 
 * Event Selektor wird wieder mit dem vorherigen Zustand befüllt
 * 
 */
function historyChange(newLocation, historyData) {
      // Wenn Historyobjekt befüllt...  
      if (historyData){
          //JSON Objekt wird ausgelesen und Parameter befüllt
          country=historyData.country;
          industry=historyData.industry;
          year=historyData.year;
          month=historyData.month;   
          query=historyData.query;
          lastQuery=query;
          page=historyData.page;
          size=historyData.size;
          selectSelected[0]=historyData.selectSelected[0];
          selectSelected[1]=historyData.selectSelected[1];
          // Historyvariable auf true, damit beim Update kein erneuter ein 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);
              updateEventSelector("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"){
                       // Selektor wird aktualisiert (Ajax)
                       updateEventSelector("calendar");
                       disableIndustrySelector();
              } else {
                      // Selektor wird aktualisiert (Ajax)
                      updateEventSelector("industry");
              }
        }
      }
};                                
                                
 /*
 *   Ausgabe bei keinen gefundenen Eventresultaten
 */        
function noResult(message,headline){
    // Counter genullt
    $(".prodCounter").html("0");
    // wenn Suche aktiv
    if (query!=""){
        $(".dateMonth").html(draeger.LABEL_EVENTSEARCH_RESULTS+" <span>\""+query+"\"</span>");
    }
    // Errortext ausgegeben
    $(".eventResults").html("<div class='noresult'><h2>"+headline+"</h2><p class='txtext'>"+message+"</p></div>");
    // Historypunkt gesetzt, wenn Browser Back/Forwardbutton nicht gerade gedrückt wurde
   if (!historyAction){
        saveHistory();
   } else {
        historyAction=false;
   }
}

/*
 * Selektoren werden bei Suche 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 Industry wird geleert
      $("#cat2 div").html('<select class="cat2" name="cat2"></select>');
      initSelectors();
}

/*
 * Leeres Industry "Dropdown" wird disabled 
 */
function disableIndustrySelector(){
      //Dropdownfeld Industry wird gelöscht/neuinitialisiert
      $("#cat2 .selectCat").remove();
      $("#cat2 div").html('<select class="cat2" name="cat2"></select>');
      $(".cat2").selectBox({css:'selectCat'});
      var temp=$(".cat2").next('div');
      temp.children('p').html(draeger.LABEL_EMPTY_INDUSTRYDROPDOWN);
      temp.css({'background-color':'#fff'});
}

/*
 * Selektoren werden per Javascript initialisert und mit Events versehen
 */
function initSelectors(){
    $(".cat1").selectBox({css:'selectCat'});
    $(".cat2").selectBox({css:'selectCat'});
    //Category Dropdowns disablen
    if (country=="all"){
           //location disabled
           var temp=$(".cat2").next('div');
           temp.children('p').html(draeger.LABEL_EMPTY_INDUSTRYDROPDOWN);
           temp.css({'background-color':'#fff'});
           $("#cat1 .selectCat ul").click(function(){ whichDropdown($(this));return false;});
    } else {
        $(".selectCat ul").click(function(){ whichDropdown($(this));return false;});
    }
}

/*
 * Calendar wird initialisert und mit Events versehen
 */
function initCalendar(){
  var activeDates= $(".dateactive");
  activeDates.css({cursor:"pointer"});
  activeDates.hoverIntent(function () {$(this).children("ul").fadeIn("fast");
                                           jQuery.each($(this).children("ul").children("li"), function() { //#FEFF9F
                                               $(".eventResults #"+$(this).attr("class")).animate({backgroundColor: "#FEFF9F"}, 1000, function(){$(this).animate({backgroundColor: "#fff"},1000);});
                                           });
                                },
                               function () {$(this).children("ul").fadeOut("fast");}
                               );
}

/*
 *   Init Application Event Selector
 */
$().ready(function() {
        $("#calendar").removeClass("jsdisplay");
        $("#search").removeClass("jsdisplay");
        $(".cats").removeClass("jsdisplay");
        //Applikation aktiv
        draeger.EVENTSELECTOR_ACTIVE=true;
       // $(".dateactive")
        //Kalender wird initialisiert
        initCalendar();
        // Kategorieselektor wird initialisiert
        initSelectors();
        lastQuery=query;
        // Events an Links gehängt   
        // Kalendersteuerung
        $("#calendarnav a").click(function(){whichCalendarDirection($(this));return false;});
        // Bestimmung Anzahl gezeigter Events
        $(".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(){updateEventSelector('search');return false;});
        $("#search input").keydown(function(event){if(event.keyCode=="13"){updateEventSelector('search');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)
            saveHistory();
        }
        //Ausfaden des Sichtschutzes vor dem Selektor
        $(".blocker").fadeOut(1000);            
});

    
    
   
/*
 *
 * Modified Selectbox for Event 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>');
                //alert(jQuery("div",oContainer).parent().html());
		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).css({width:"263px"}); 
                                                               $(this).parent().css({"height":actHeight});
                                                            } else {
                                                                $(this).css({width:"263px"});   
                                                            }
                                                          });
                      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('.eventSelector');
                   //alert(oOffset.top + parseInt(oOffset.height));
                    // set ul list position
                    jQuery("ul",oContainer).css({
                    	//todo left: (oOffset.left )+ 'px',
                        //left: 226+ 'px',
                        //top: '9px', //oOffset.top + parseInt(oOffset.height) + 'px',
                        position: 'absolute' ,
                        width: 263 + 'px'
                    });
          //}, 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);
	});
};