  /** History Jquery Plugin **/
var $j=jQuery.noConflict();
redirectIE6();
(function($){function History(){this._curHash='';this._callback=function(hash){};};$.extend(History.prototype,{init:function(callback){this._callback=callback;this._curHash=location.hash;if($.browser.msie){if(this._curHash==''){this._curHash='#';}$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');var iframe=$("#jQuery_history")[0].contentWindow.document;iframe.open();iframe.close();iframe.location.hash=this._curHash;}else if($.browser.safari){this._historyBackStack=[];this._historyBackStack.length=history.length;this._historyForwardStack=[];this._isFirst=true;this._dontCheck=false;}this._callback(this._curHash.replace(/^#/,''));setInterval(this._check,100);},add:function(hash){this._historyBackStack.push(hash);this._historyForwardStack.length=0;this._isFirst=true;},_check:function(){if($.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash;if(current_hash!=$.history._curHash){location.hash=current_hash;$.history._curHash=current_hash;$.history._callback(current_hash.replace(/^#/,''));}}else if($.browser.safari){if(!$.history._dontCheck){var historyDelta=history.length-$.history._historyBackStack.length;if(historyDelta){$.history._isFirst=false;if(historyDelta<0){for(var i=0;i<Math.abs(historyDelta);i++)$.history._historyForwardStack.unshift($.history._historyBackStack.pop());}else{for(var i=0;i<historyDelta;i++)$.history._historyBackStack.push($.history._historyForwardStack.shift());}var cachedHash=$.history._historyBackStack[$.history._historyBackStack.length-1];if(cachedHash!=undefined){$.history._curHash=location.hash;$.history._callback(cachedHash);}}else if($.history._historyBackStack[$.history._historyBackStack.length-1]==undefined&&!$.history._isFirst){if(document.URL.indexOf('#')>=0){$.history._callback(document.URL.split('#')[1]);}else{$.history._callback('');}$.history._isFirst=true;}}}else{var current_hash=location.hash;if(current_hash!=$.history._curHash){$.history._curHash=current_hash;$.history._callback(current_hash.replace(/^#/,''));}}},load:function(hash){var newhash;if($.browser.safari){newhash=hash;}else{newhash='#'+hash;location.hash=newhash;}this._curHash=newhash;if($.browser.msie){var ihistory=$("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;this._callback(hash);}else if($.browser.safari){this._dontCheck=true;this.add(hash);var fn=function(){$.history._dontCheck=false;};window.setTimeout(fn,200);this._callback(hash);location.hash=newhash;}else{this._callback(hash);}}});$(document).ready(function(){$.history=new History();});})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){element.style.removeAttribute('filter');}
}



/* ------------------------------------------------------------------------
	s3Slider
	
	Developped By: Boban Karišik -> http://www.serie3.info/
        CSS Help: Mészáros Róbert -> http://www.perspectived.com/
	Version: 1.0
	
	Copyright: Feel free to redistribute the script/modify it, as
			   long as you leave my infos at the top.
------------------------------------------------------------------------- */


(function($){  

    $.fn.s3Slider = function(vars) {       
        
        var element     = this;
        var timeOut     = (vars.timeOut != undefined) ? vars.timeOut : 4000;
        var current     = null;
        var timeOutFn   = null;
        var faderStat   = true;
        var mOver       = false;
        var items       = $("#" + element[0].id + "Content ." + element[0].id + "Image");
        var itemsSpan   = $("#" + element[0].id + "Content ." + element[0].id + "Image span");
        
        $j('#slide0').removeClass('hover');
        $j('#slide1').removeClass('hover');
        $j('#slide2').removeClass('hover');
        $j('#slide3').removeClass('hover');
        
        // gestion des bouton slide NAVIGATION : A REFAIRE !!!!  
        function runSlide(n){
            mOver = true;  
            $('.s3sliderImage').hide(); 
            $('#s'+n).fadeIn((timeOut/6));
            $('#spanslide'+n).slideDown((timeOut/6)); 
            // remove class hover des btn $j('#slide1').removeClass('hover');
            $('#slide'+n).addClass('hover');      
        }

        items.each(function(i) {
        
          /*
          $('#slide0').mouseover( function() { runSlide(0); });
          $('#slide0').mouseout( function() {  mOver = false; $('#s0').hide();  $j('#slide0').removeClass('hover'); fadeElement(true); }  );

          $('#slide1').mouseover( function() {  runSlide(1);  });
          $('#slide1').mouseout( function() {  mOver = false; $('#s1').hide();  $j('#slide1').removeClass('hover'); fadeElement(true); }  );
          
          $('#slide2').mouseover( function() {  runSlide(2);  });
          $('#slide2').mouseout( function() {  mOver = false; $('#s2').hide();  $j('#slide2').removeClass('hover'); fadeElement(true); }  );

          $('#slide3').mouseover( function() {  runSlide(3);  });
          $('#slide3').mouseout( function() {  mOver = false; $('#s3').hide();  $j('#slide3').removeClass('hover'); fadeElement(true); }  );
          */
        
            $(items[i]).mouseover(function() {
               mOver = true;
               //alert(items[i]);
            });
            
            $(items[i]).mouseout(function() {
                mOver   = false;
                fadeElement(true);
            });
            
        });
        
        var fadeElement = function(isMouseOut) {
            var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
            thisTimeOut = (faderStat) ? 10 : thisTimeOut;
            if(items.length > 0) {
                
                timeOutFn = setTimeout(makeSlider, thisTimeOut);
                
                
            } else {
                console.log("Poof..");
            }
        }
        
        var makeSlider = function() {
            current = (current != null) ? current : items[(items.length-1)];
            var currNo      = jQuery.inArray(current, items) + 1
            //alert(currNo);
            currNo = (currNo == items.length) ? 0 : (currNo - 1);
            var newMargin   = $(element).width() * currNo;
            if(faderStat == true) {
                if(!mOver) {

                if(currNo==0) var num = 3; //$j('#slide0').addClass('hover');
                else var num = currNo-1;
   
                $j('#slide0').removeClass('hover');
                $j('#slide1').removeClass('hover');
                $j('#slide2').removeClass('hover');
                $j('#slide3').removeClass('hover');
               // var num = currNo+1;
                $('#slide'+currNo).addClass('hover');
                
                    $(items[currNo]).fadeIn((timeOut/6), function() {
                        if($(itemsSpan[currNo]).css('bottom') == 0) {
                            $(itemsSpan[currNo]).slideUp((timeOut/6), function() {
                                faderStat = false;
                                current = items[currNo];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        } else {
                            $(itemsSpan[currNo]).slideDown((timeOut/6), function() {
                                faderStat = false;
                                current = items[currNo];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        }
                    });
                }
            } else {
                if(!mOver) {

                    if($(itemsSpan[currNo]).css('bottom') == 0) {
                        $(itemsSpan[currNo]).slideDown((timeOut/6), function() {
                            $(items[currNo]).fadeOut((timeOut/6), function() {
                                faderStat = true;
                                current = items[(currNo+1)];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        });
                    } else {
                        
                        $(itemsSpan[currNo]).slideUp((timeOut/6), function() {
                        $(items[currNo]).fadeOut((timeOut/6), function() {
                                faderStat = true;
                                current = items[(currNo+1)];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        });
                    }
                }
            }
        }
        
        makeSlider();   

    };  

})(jQuery);  


/* fonction utiles
    * load : utilisé pour charger simplement le contenu d’une page PHP ou HTML.
    * get : utilisé pour charger le contenu d’une page PHP avec la méthode GET.
    * getJSON : utilisé pour charger le contenu d’une page PHP avec la méthode GET et récupéré le json de retour.
    * post : utilisé pour charger le contenu d’une page PHP avec la méthode POST.
    * getScript : utilisé pour charger un fichier javascript en local.
    
    * complete : Exécute une fonction quand la requête AJAX est terminée.
    * error : Exécute une fonction quand la requête AJAX contient une erreur.
    * send : Exécute une fonction quand la requête AJAX va commencer.
    * start : Exécute une fonction quand la requête AJAX commence.
    * stop : Exécute une fonction quand la requête AJAX s’arrête.
    * success : Exécute une fonction quand la requête AJAX est terminé avec succès.
   1. $(document).ready(function () {  
   2.     $.get("test.php", { name: "test", email: "test" },  
   3.     function success(data){  
   4.         alert(data);  
   5.     });  
   6. });  
*/

function redirectIE6(){
    if($j.browser.msie && $j.browser.version<"7.0")
     top.location="/ie6/index.html"; 
}
// surcharge de la box alert
function alertModal(message) {
			// create a modal dialog with the message
			//$j.modal(message);
			$j.modal(message, {
			  containerCss: ({ width: "370px", height: "70px" }),
			  onShow: function modalShow(dialog) {
			    $j.unblockUI();
			  }
			});
}

 function modalAddInPlaylist(id_item){
      $j.blockUI();
      $j.ajax({ 
        type: "GET", 
        url: "playlist/listSelect/id/"+id_item, 
        success: function(retour){ 
          $j.modal(retour, {
			      containerCss: ({ width: "580px", height: "200px" }),
			      onShow: function modalShow(dialog) {
			        $j.unblockUI();
			      }
			    });
        },
        error: function(retour){  alertModal(retour.responseText); }
      }); 
   }
   


function runMediaForPLayer(type_media,id,action){
  document.getElementById("mainplayer").getInfo(id,type_media,action);
}

function runMusicBox(){
  $j("#boxform").submit(function() 
  { 
    $j.blockUI( {message: "<h2>Chargement musique...</h2><img src='loading.gif' />"});
    s = $j(this).serialize(); 
    document.getElementById("mainplayer").getBox(s);
   	refreshPub();
   	runTracker('musicbox');
   	$j.unblockUI();
    return false;  //catch Ajax
   });
}

function runTracker(val){
  pageTracker._trackPageview('/'+val);
}
function refreshPub(){
  var pub_right = '<h2>PUB</h2><iframe height="600" frameborder="0" width="120" scrolling="no" align="top" marginheight="0" marginwidth="0" src="pub/ads/pub_right.html" name="ajaxAd2" id="ajaxAd2">Ad2</iframe>';
  // var pub_right = '<a href="http://www.gambling-affiliation.com/tracking/cpc.php?idv=6673&ids=40571&idc=363&tracklink=" title="Gambling-Affiliation" target="_blank"><img src="http://www.gambling-affiliation.com/tracking/cpm.php?idv=6673&ids=40571&idc=363" width="120" height="600" alt="Gambling-Affiliation" border="0"></a>';
   $j('#pub_right').html(pub_right); 
  /* var pub_top = '<iframe height="90" frameborder="0" width="728" scrolling="no" align="top" marginheight="0" marginwidth="0" src="pub/ads/pub_top.html" name="ajaxAd1" id="ajaxAd1">Ad1</iframe>';*/
   var pub_top = '<a href="http://clic.reussissonsensemble.fr/click.asp?ref=489500&site=4418&type=b66&bnb=66" target="_blank"><img src="http://banniere.reussissonsensemble.fr/view.asp?ref=489500&site=4418&b=66" border="0" alt="Ban été 728x90 n°1" width="728" height="90" /></a><br />';
   /*var pub_top = '<a href="http://www.gambling-affiliation.com/tracking/cpc.php?idv=10366&ids=40571&idc=522&tracklink=" title="Gambling-Affiliation" target="_blank"><img src="http://www.gambling-affiliation.com/tracking/cpm.php?idv=10366&ids=40571&idc=522" width="728" height="90" alt="Gambling-Affiliation" border="0"></a>';*/
   
  // var pub_top = '<iframe src="http://fl01.ct2.comclick.com/aff_frame.ct2?id_regie=1&num_editeur=18685&num_site=1&num_emplacement=6" WIDTH="728" HEIGHT="90" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"></iframe>';
   $j('#pub_top').html(pub_top);
   var pub_left = '<iframe height="250" frameborder="0" width="250" scrolling="no" align="top" marginheight="0" marginwidth="0" src="pub/ads/pub_left.html" name="ajaxAd3" id="ajaxAd3">Ad3</iframe><a href="http://www.gambling-affiliation.com/tracking/cpc.php?idv=10739&ids=40571&idc=549" title="Gambling-Affiliation" target="_blank"><img src="http://www.gambling-affiliation.com/tracking/cpm.php?idv=10739&ids=40571&idc=549" height="1" width="1" alt="Gambling-Affiliation" border="0">Lucky18 Casino</a>';
      //var pub_left = '<a href="http://clic.reussissonsensemble.fr/click.asp?ref=489500&site=4425&type=b91&bnb=91" target="_blank"><img src="http://banniere.reussissonsensemble.fr/view.asp?ref=489500&site=4425&b=91" border="0" alt="Easyflirt" width="234" height="60" /></a><br /><a href="http://clic.reussissonsensemble.fr/click.asp?ref=489500&site=4801&type=b50&bnb=50" target="_blank"><img src="http://banniere.reussissonsensemble.fr/view.asp?ref=489500&site=4801&b=50" border="0" alt="Ulla.com" width="234" height="60" /></a><br />';
      //var pub_left = '<a href="http://clic.reussissonsensemble.fr/click.asp?ref=489500&site=4801&type=text&tnb=1" target="_blank">Venez essayer Ulla.com</a><br /><img src="http://banniere.reussissonsensemble.fr/view.asp?ref=489500&site=4801&type=text&tnb=1&js=1" BORDER="0" WIDTH="1" HEIGHT="1" />';
   $j('#pub_left').html(pub_left);
}

// fonction appelée par le player (btn_info) & link artist
function ficheArtist(slug){
  $j.history.load("artist/"+slug);
}

function updateNavigation(tabName)
{
  $j.ajax({ 
    type: "GET", 
    url: "main/navigation/tab/"+tabName, 
    success: function(retour)
    {     
      if($j("#"+tabName))
      {
        $j("#"+tabName).html(retour);
      }
    },
    error: function()
    { 
      window.location = "http://mynightmusic.com";  
    }
  });
}

function loadUserDataPlaylist()
{
  $j.blockUI();
  $j.ajax({ 
    type: "GET", 
    url: "main/loadUserData", 
    success: function()
    {     
      $j.unblockUI();
    },
    error: function()
    { 
      window.location = "http://mynightmusic.com";  
    }
  });
}

function runAjaxCall(hash,method,element,scroll,pub,tracker,titre)
{
  $j.blockUI();
  $j.ajax({ 
    type: method, 
    url: hash, 
    success: function(retour)
    {     
      if($j(element))
      {
        $j(element).html(retour);
        if(titre)
        {
          var title = $j('#title').html();
          if(title==null)
            document.title = "MyNightMusic | Musique gratuite et illimitée pour tes soirées !";
          else
            document.title = "MyNightMusic | " + title;
        }
        else { document.title = "MyNightMusic | Musique gratuite et illimitée pour tes soirées !"; }
      }
    },
    error: function() { window.location = "http://mynightmusic.com"; },
    complete: function()
    { if(hash=='home') $j("#annonceLegale").show(); else $j("#annonceLegale").hide();
      if(scroll) { $j.scrollTo(element,{duration:300}); }
      if(tracker){ if(hash=='home') runTracker('frontoffice.php');  else runTracker(hash);  }
      if(pub){ refreshPub(); }
      $j.unblockUI();
    }
  });
}// end ajaxCall


// callback function
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
function callback(hash)
{
   if(hash) {  	 
     var hash_action=hash.split('/');
     if(hash.split('=')[0]=='content_search'){
     $j.blockUI();
       $j.ajax({ 
          type: "POST", 
          data: hash, 
          url: $j('#search').attr("action"), 
          success: function(retour){ 
              $j("#content").html(retour); $j.scrollTo( '#player', {duration:300} ); $j('#search_error').fadeOut("fast");
          },
          error: function(){ $j('#search_error').fadeIn("fast"); $j.unblockUI(); },
          complete: function(){  runTracker('search'); refreshPub(); document.title = "MyNightMusic | Recherche"; $j.unblockUI(); $j("#annonceLegale").hide();}
        }); 
     }
     else if(hash_action[0]!='track')
     {
        runAjaxCall(hash,"GET","#content",true,true,true,true);      
     }
     else{
     runAjaxCall("home","GET","#content",false,true,true,false);       
     }
  } //pas de hash ds l'url 
  else 
  {
    // order scroll, pub, tracker
   runAjaxCall("home","GET","#content",false,true,true,false); 
  }
}// end callback


// DOM READY
$j(document).ready(function() 
{

  if(document.location.href.indexOf(".org") != -1)
  {
    //alertModal("Vous êtes actuellement sur la plateforme de développement<br />Merci de vous rendre sur <a href='http://mynightmusic.com'>MyNightMusic.com</a>");
  }
  $j.history.init(callback);
  runMusicBox();
  
   $j('#s3slider').livequery(function(){
     $j(this).s3Slider({
      timeOut: 5000
     });
   });

  // gestion des liens internes utilisant l'historique de navigation
  $j("a[@rel='history']").livequery('click',function(){
    // abstraction du nom de domaine (utile pr le référencement (lien sans #))
    // .COM/ = 5 caracters
    if(this.href.indexOf(".com") != -1)
    {
        var target = this.href.substring(this.href.indexOf(".com")+5,this.href.length);
    }
    else if(this.href.indexOf(".fr") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".fr")+4,this.href.length); 
    }
    else if(this.href.indexOf(".org") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".org")+5,this.href.length); 
    }
    else if(this.href.indexOf(".biz") != -1) var target = this.href.substring(this.href.indexOf(".biz")+5,this.href.length);
    else if(this.href.indexOf(".eu") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".eu")+4,this.href.length); 
    }
    else if(this.href.indexOf(".info") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".info")+6,this.href.length); 
    }
    else if(this.href.indexOf(".net") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".net")+5,this.href.length);
    }
    else if(this.href.indexOf(".us") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".us")+4,this.href.length); 
    }
    else if(this.href.indexOf(".be") != -1)
    {
      var target = this.href.substring(this.href.indexOf(".be")+4,this.href.length); 
    }
	  target = target.replace(/^.*#/, '');
    $j.history.load(target); // appel de callback implicite
    if($j(this).attr("_close")) $j.modal.close(); 
      //alert('debug test');
    return false;
  });
  
  
  
  // binding du moteur de recherche
  $j("#search").submit(function() {    
    $j("#as_content_search").hide();
	  s = $j(this).serialize(); 
    if(s.split('+')[1]!='%3A')
    { 
      $j.history.load(s);
    }
    else  $j('#search_error').fadeIn("fast");
    return false; 
  });
 
  // slide album
  $j("#scrollable").livequery(function() {
    $j(this).scrollable({    
        horizontal:true,  
        size: 1
    }); 
  });

  // gestion des liens de lecture d'une musique
  $j("a[rel='mediaForPlayer']").livequery('click', function() {
 
    var item = this.href.split('#')[1].split('-');
    if(item[0]=="L"){
      var list_idMusic;
       $j(".divDrag").each(function(i){
         if(i==0) list_idMusic = $j(this).attr("id");
         else list_idMusic += ","+$j(this).attr("id");
       });
       runMediaForPLayer(list_idMusic,'0',item[2]);
    }
    else runMediaForPLayer(item[0],item[1],item[2]);
    
    if(item[2]!='A'){
      $j.scrollTo( '#container', {duration:300} );
    }
    else {  $j.blockUI( {message: '<h2>Ajout en cours...</h2><img src="loading.gif" />'}); }
    $j.unblockUI();
    refreshPub();
     //updateNavigation("navPlaylist");
    return false;
  });  
  
  $j("a[rel='addInPlaylist']").livequery('click', function(e) {
    e.preventDefault(); 
    var item = this.href.split('#')[1];
    modalAddInPlaylist(item);
  });  
  
 

  
  // binding du formulaire de connexion

$j("#loginForm").livequery('submit', function(e) {    
    e.preventDefault(); 
        s = $j(this).serialize(); 
        $j.ajax({ 
            type: "POST", 
            data: s, 
            url: $j(this).attr("action"), 
            success: function(retour){ 
                if(retour=='ok') loadUserDataPlaylist();
                else $j("#nav_user").html(retour);  
            }   
        }); 
    });
 
  
  //deconnexion
  $j("#logout").livequery('click',function() {
        $j.blockUI( {message: '<h2>Déconnexion en cours...</h2><img src="loading.gif" />'});
        $j("#magicbox").hide();
        $j("#pl_item_user").empty();
        $j.ajax({ 
            type: "GET", 
            url: "/logout", 
            success: function(retour){ 
                $j("#nav_user").html(retour); 
                $j.unblockUI();
            }   
        }); 
        return false; 
  });
  
  $j("table.datagrid tr").livequery(function() {
  		  $j(this).mouseover(function() {$j(this).addClass("over");}).mouseout(function() {$j(this).removeClass("over");});
        //$j(".stripeMe tr:even").addClass("alt");
 });
 



 $j(".divDrag").livequery(function() { 
    $j(this).draggable({
      helper: function() { return $j(document.createElement('div')).addClass("ui-draggable-helper").attr("id","helperDrag").html("<img id='dragNoOk' src='images/delete.png' alt='' /> Déposez ce titre dans la barre du bas pour l'ajouter à une playlist").appendTo("body")[0]; },
      zIndex: 1000,
      cursor: 'move',
      opacity:0.85,
      revert: true,
      cursorAt: {top: -5, left: -5 }
      
    });
  });
  
 /* panier d'ajout de zik */
  $j("#divDrop").livequery(function() { 
    $j("#divDrop").droppable({
      accept: ".divDrag",
      over: function(ev, ui) { 
      $j("#helperDrag").html("<img id='dragOk' src='images/accept.png' alt='' /> Vous pouvez déposer votre musique ici");
        //$j("#helperDrag").prepend('<img id="dragOk" src="images/accept.png" alt="" />'); 
      },
      out: function(ev, ui) { 
      $j("#helperDrag").html("<img id='dragNoOk' src='images/delete.png' alt='' /> Déposez ce titre dans la barre du bas pour l'ajouter à une playlist");

      }, 
      activeClass: 'droppable-active',
      hoverClass: 'droppable-hover',  
      drop: function(ev, ui) {  
         var id_music = $j(ui.draggable).attr("id");
        // alert('tr#'+id_music+' td:eq(1) div');
         var name_music = $j('#'+id_music+' td:eq(1) div').text();
         //var name_artist = $j('#title').html();
         
         $j(this).append("<li id='"+id_music+"'><a href='#M-"+id_music+"-L' rel='mediaForPlayer'><img alt='Play' src='images/btn_play_min.gif'/></a> - "+name_music+"<li>");
         var id_playlist = $j(this).attr("rel");
        // alert(test);

         //Do your AJAX stuff in here.
         $j.ajax({ 
          type: "GET", 
          data: "id_music="+id_music+"&id_playlist="+id_playlist, 
          url: "playlist/addMusicInPlaylist/", 
          success: function(retour){ 
              $j("#drag_mess_error").html(retour); 
          },
          error: function(retour){ $j("#drag_mess_error").html(retour.responseText);  }
        }); 
        
      }// end drop
    }); 
  });
  

  // binding du formulaire de choix des PL (cart)
  $j("#cart_playlist").livequery(function() {
     $j(this).submit(function() {    
        s = $j(this).serialize(); 
        value_option = s.split('=')[1];
        id_pl = value_option.split('%23')[0];
        name_pl = value_option.split('%23')[1];
        $j("#divDrop").remove();
        //$j("#divDropTrash").remove();
        $j("#cart_playlist").after('<div rel="'+id_pl+'" id="divDrop"><ul></ul></div>');
        //$j("#divDrop").after('<div id="divDropTrash">Déposez ici pour supprimer</div>');
       // $j("#divDrop").attr("rel",id_pl);
        $j("#drag_mess2").html("Déposez une musique ci-dessous");
        $j("#drag_mess1").html('Playlist <'+name_pl+'> sélectionné <a href="#playlist_edit/'+id_pl+'">(Voir)</a>');
        return false;
    });
  });
  
  
  $j("form#registerForm").livequery('submit', function(e) {    
    e.preventDefault();
    $j.blockUI( {message: '<h2>Envoi en cours...</h2><img src="loading.gif" />'});
    s = $j(this).serialize(); 
    $j.ajax({ 
        type: "POST", 
        data: s, 
        url: $j(this).attr("action"),
        success: function(retour){ 
            $j("#content").empty().append(retour); 
            $j.unblockUI();
        }         
    }); 
  });
  
  
  $j("form#editProfilForm").livequery('submit', function(e) {    
    e.preventDefault();
    $j.blockUI( {message: '<h2>Envoi en cours...</h2><img src="loading.gif" />'});
    s = $j(this).serialize(); 
    $j.ajax({ 
        type: "POST", 
        data: s, 
        url: $j(this).attr("action"),
        success: function(retour){ 
            $j("#content").empty().append(retour); 
            $j.unblockUI();
        }         
    }); 
  });
  
	$j("#createPlaylistForm").livequery('submit', function(e) {    
    	 //alert("test");
    	  e.preventDefault();
        $j.blockUI( {message: '<h2>Envoi en cours...</h2><img src="loading.gif" />'});
        s = $j(this).serialize(); 
        $j.ajax({ 
            type: "POST", 
            data: s, 
            url: $j(this).attr("action"),
            success: function(retour){ 
                if(retour=="success"){ $j.modal.close(); loadUserDataPlaylist(); $j.unblockUI(); }
                else{
                $j(".simplemodal-data").empty().append(retour); 
                $j.unblockUI();
                //$j.modal.close();
                }
            }         
        });   
      });
  
	function modalCreatePlaylist(){
  	$j.blockUI();
		// load the create form using ajax
		$j.get("playlist/create", function(data){
			// create a modal dialog with the data
			$j.modal(data, {
			  containerCss: ({ width: "580px", height: "200px" }),
			  onShow: function modalShow(dialog) {
			    $j.unblockUI();
			  }
			});
		});	
	}

  $j("#selectPlaylistForm").livequery('submit', function(e) {    
    e.preventDefault(); 
    $j.blockUI( {message: '<h2>Ajout en cours...</h2><img src="loading.gif" />'});
      s = $j(this).serialize(); 
      $j.ajax({ 
          type: "POST", 
          data: s, 
          url: $j(this).attr("action"), 
          success: function(retour){ 
              $j.modal.close(); $j.unblockUI();
          },
          error: function(retour){ $j.modal.close(); $j.unblockUI(); alertModal(retour.responseText); }
      }); 
  });

	// modifier par #createPlPanier
  $j('#drag_mess2 a').click(function (e) {
		e.preventDefault();
		modalCreatePlaylist();
	});

 $j('#createPlNav').livequery('click', function (e) {
		e.preventDefault();
		modalCreatePlaylist();
	});
	
	/* forgot password */
	$j('#forgotPassword').livequery('click', function (e) {
		e.preventDefault();
		modalForgotPassword();
	});
  function modalForgotPassword(){
  	$j.blockUI();
		// load the create form using ajax
		$j.get("forgot_password", function(data){
			// create a modal dialog with the data
			$j.modal(data, {
			  containerCss: ({ width: "580px", height: "200px" }),
			  onShow: function modalShow(dialog) {
			    $j.unblockUI();
			  }
			});
		});	
	}

	$j("#forgotPasswordForm").livequery('submit', function(e) {    
    	 //alert("test");
    	  e.preventDefault();
        $j.blockUI( {message: '<h2>Envoi en cours...</h2><img src="loading.gif" />'});
        s = $j(this).serialize(); 
        $j.ajax({ 
            type: "POST", 
            data: s, 
            url: $j(this).attr("action"),
            success: function(retour){ 
                    $j.modal.close(); $j.unblockUI();  alertModal(retour); 
            },
            error: function(retour){
              $j.unblockUI(); 
            }
        });   
    });
      
 // gestion upload mp3
 $j("#btn_upload_mp3").livequery(function(){
    var allowed = ['mp3', 'wave', 'wmv', 'wma'];
 		$j.ajax_upload(this, {
			action: '/music/upload/',
			name: 'musicfile',
			onSubmit: function(file, ext) 
			{  
			    if ($j.inArray(ext, allowed ) === -1){
				    // extension is not allowed
  				  $j('#error_upload_mp3').html('Seul les formats suivant sont acceptés: MP3, WMA, WAVE et WMV');
				    return false;
			    }
			    $j.blockUI( {message: '<h2>Import en cours...</h2>Ceci peut prendre un moment<img src="loading.gif" />'});  
			},
			onSuccess: function(file){ $j.unblockUI(); $j('#error_upload_mp3').remove(); $j('#list_upload_mp3').append("<li>"+file+"</li>"); },
			onError: function(file, response){ $j.unblockUI(); $j('#error_upload_mp3').html(response);  }
	 });
 });
 
 	$j("#searchAsk").livequery('submit', function(e) {    
			    	 //alert("test");
			    	  e.preventDefault();
			    	  var music_name = $j("input[@id=ask_music_name]").val();
			    	  var artist_name = $j("input[@id=ask_artist_name]").val();
			    	  if(music_name=='' && artist_name==''){ alertModal('Merci de saisir au moins un des deux champs.'); return false; }
              $j.blockUI( {message: '<h2>Envoi en cours...</h2><img src="loading.gif" />'});
              s = $j(this).serialize(); 
              $j.ajax({ 
                  type: "POST", 
                  data: s, 
                  url: $j(this).attr("action"),
                  success: function(retour){ 
                      if(retour=="success"){ $j.modal.close(); $j.unblockUI(); $j("input[@id=ask_music_name]").val(''); $j("input[@id=ask_artist_name]").val(''); alertModal('Merci ! <br /> Votre proposition a bien été prise en compte. <br /> Elle sera traitée dans les plus bref délais'); }
                      else{
                      $j("search_ask").html(retour); 
                      $j.unblockUI();
                      //$j.modal.close();
                      }
                  }         
              });       
   });
   
   /*pl edit*/
   $j("a[rel='editPlaylist']").livequery('click', function(e) {
      e.preventDefault();
      //$j.blockUI();
      alertModal("Cette fonctionnalité sera très prochainement disponible, merci de patienter encore un peu !");
      var item = this.href.split('#')[1].split('-');
      /*if(item[2] != null)
         deleteMediaForFavorite(item[0],item[1]);
      else
        addMediaForFavorite(item[0],item[1]);*/
   });
   
   
   /*favorite*/
   $j("a[rel='mediaForFavorite']").livequery('click', function(e) {
      e.preventDefault();
      $j.blockUI();
      var item = this.href.split('#')[1].split('-');
      if(item[2] != null)
         deleteMediaForFavorite(item[0],item[1]);
      else
        addMediaForFavorite(item[0],item[1]);
   });
   
   function deleteMediaForFavorite(type_media,id_media){
      $j.ajax({ 
        type: "GET", 
        url: "favorite/delFavorite/id_media/"+id_media+"/type_media/"+type_media, 
        success: function(retour){ 
            alertModal(retour); 
            if(type_media=="A")
              $j.history.load("my_favorites_artists");
            else 
              $j.history.load("my_favorites_playlists");
        },
        error: function(retour){  alertModal(retour.responseText); }
      }); 
   }
   
   function addMediaForFavorite(type_media,id_media){
      $j.ajax({ 
        type: "GET", 
        url: "favorite/addFavorite/id_media/"+id_media+"/type_media/"+type_media, 
        success: function(retour){ 
            alertModal(retour); 
        },
        error: function(XMLHttpRequest, error, exception){  
         /*for (var i in XMLHttpRequest){
            alert('name:'+i+' -- value:'+XMLHttpRequest[i]);
         }*/

        /*alert(XMLHttpRequest.status); */ alertModal(retour.responseText); }
      }); 
   }
   
   
   /* droppable zone player zik */
  $j("#player").livequery(function() { 
    $j(this).droppable({
      accept: ".divDrag",
      over: function(ev, ui) { 
        $j("#helperDrag").html("<img id='dragOk' src='images/accept.png' alt='' /> Vous pouvez déposer votre musique dans le player");
      },
      out: function(ev, ui) { 
        $j("#helperDrag").html("<img id='dragNoOk' src='images/delete.png' alt='' /> Déposez ce titre dans la barre du bas pour l'ajouter à une playlist");
      }, 
      activeClass: 'droppable-active',
      hoverClass: 'droppable-hover',  
      drop: function(ev, ui) {  
         var id_music = $j(ui.draggable).attr("id");
         runMediaForPLayer("M",id_music,"A");
      }// end drop
    }); 
  });

  
}); // end DOM READY


/**
 * TableDnD plug-in for JQuery, allows you to drag and drop table rows
 * You can set up various options to control how the system will work
 * Copyright (c) Denis Howlett <denish@isocra.com>
 * Licensed like jQuery, see http://docs.jquery.com/License.
 *
 * Configuration options:
 * 
 * onDragStyle
 *     This is the style that is assigned to the row during drag. There are limitations to the styles that can be
 *     associated with a row (such as you can't assign a border--well you can, but it won't be
 *     displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
 *     a map (as used in the jQuery css(...) function).
 * onDropStyle
 *     This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
 *     to what you can do. Also this replaces the original style, so again consider using onDragClass which
 *     is simply added and then removed on drop.
 * onDragClass
 *     This class is added for the duration of the drag and then removed when the row is dropped. It is more
 *     flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
 *     is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
 *     stylesheet.
 * onDrop
 *     Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
 *     and the row that was dropped. You can work out the new order of the rows by using
 *     table.rows.
 * onDragStart
 *     Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
 *     table and the row which the user has started to drag.
 * onAllowDrop
 *     Pass a function that will be called as a row is over another row. If the function returns true, allow 
 *     dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
 *     the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
 * scrollAmount
 *     This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
 *     window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
 *     FF3 beta
 * dragHandle
 *     This is the name of a class that you assign to one or more cells in each row that is draggable. If you
 *     specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
 *     will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
 *     the whole row is draggable.
 * 
 * Other ways to control behaviour:
 *
 * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
 * that you don't want to be draggable.
 *
 * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
 * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
 * an ID as must all the rows.
 *
 * Other methods:
 *
 * $("...").tableDnDUpdate() 
 * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
 * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
 * The table maintains the original configuration (so you don't have to specify it again).
 *
 * $("...").tableDnDSerialize()
 * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
 * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
 *
 * Known problems:
 * - Auto-scoll has some problems with IE7  (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
 * 
 * Version 0.2: 2008-02-20 First public version
 * Version 0.3: 2008-02-07 Added onDragStart option
 *                         Made the scroll amount configurable (default is 5 as before)
 * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
 *                         Added onAllowDrop to control dropping
 *                         Fixed a bug which meant that you couldn't set the scroll amount in both directions
 *                         Added serialize method
 * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
 *                         draggable
 *                         Improved the serialize method to use a default (and settable) regular expression.
 *                         Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
 */
jQuery.tableDnD = {
    /** Keep hold of the current table being dragged */
    currentTable : null,
    /** Keep hold of the current drag object if any */
    dragObject: null,
    /** The current mouse offset */
    mouseOffset: null,
    /** Remember the old value of Y so that we don't do too much processing */
    oldY: 0,

    /** Actually build the structure */
    build: function(options) {
        // Set up the defaults if any

        this.each(function() {
            // This is bound to each matching table, set up the defaults and override with user options
            this.tableDnDConfig = jQuery.extend({
                onDragStyle: null,
                onDropStyle: null,
				// Add in the default class for whileDragging
				onDragClass: "tDnD_whileDrag",
                onDrop: null,
                onDragStart: null,
                scrollAmount: 5,
				serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
				serializeParamName: null, // If you want to specify another parameter name instead of the table ID
                dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
            }, options || {});
            // Now make the rows draggable
            jQuery.tableDnD.makeDraggable(this);
        });

        // Now we need to capture the mouse up and mouse move event
        // We can use bind so that we don't interfere with other event handlers
        jQuery(document)
            .bind('mousemove', jQuery.tableDnD.mousemove)
            .bind('mouseup', jQuery.tableDnD.mouseup);

        // Don't break the chain
        return this;
    },

    /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
    makeDraggable: function(table) {
        var config = table.tableDnDConfig;
		if (table.tableDnDConfig.dragHandle) {
			// We only need to add the event to the specified cells
			var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
			cells.each(function() {
				// The cell is bound to "this"
                jQuery(this).mousedown(function(ev) {
                    jQuery.tableDnD.dragObject = this.parentNode;
                    jQuery.tableDnD.currentTable = table;
                    jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                    if (config.onDragStart) {
                        // Call the onDrop method if there is one
                        config.onDragStart(table, this);
                    }
                    return false;
                });
			})
		} else {
			// For backwards compatibility, we add the event to the whole row
	        var rows = jQuery("tr", table); // get all the rows as a wrapped set
	        rows.each(function() {
				// Iterate through each row, the row is bound to "this"
				var row = jQuery(this);
				if (! row.hasClass("nodrag")) {
	                row.mousedown(function(ev) {
	                    if (ev.target.tagName == "TD") {
	                        jQuery.tableDnD.dragObject = this;
	                        jQuery.tableDnD.currentTable = table;
	                        jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
	                        if (config.onDragStart) {
	                            // Call the onDrop method if there is one
	                            config.onDragStart(table, this);
	                        }
	                        return false;
	                    }
	                }).css("cursor", "move"); // Store the tableDnD object
				}
			});
		}
	},

	updateTables: function() {
		this.each(function() {
			// this is now bound to each matching table
			if (this.tableDnDConfig) {
				jQuery.tableDnD.makeDraggable(this);
			}
		})
	},

    /** Get the mouse coordinates from the event (allowing for browser differences) */
    mouseCoords: function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    },

    /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
    getMouseOffset: function(target, ev) {
        ev = ev || window.event;

        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    },

    /** Get the position of an element by going up the DOM tree and adding up all the offsets */
    getPosition: function(e){
        var left = 0;
        var top  = 0;
        /** Safari fix -- thanks to Luis Chato for this! */
        if (e.offsetHeight == 0) {
            /** Safari 2 doesn't correctly grab the offsetTop of a table row
            this is detailed here:
            http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
            the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
            note that firefox will return a text node as a first child, so designing a more thorough
            solution may need to take that into account, for now this seems to work in firefox, safari, ie */
            e = e.firstChild; // a table cell
        }

        while (e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e     = e.offsetParent;
        }

        left += e.offsetLeft;
        top  += e.offsetTop;

        return {x:left, y:top};
    },

    mousemove: function(ev) {
        if (jQuery.tableDnD.dragObject == null) {
            return;
        }

        var dragObj = jQuery(jQuery.tableDnD.dragObject);
        var config = jQuery.tableDnD.currentTable.tableDnDConfig;
        var mousePos = jQuery.tableDnD.mouseCoords(ev);
        var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
        //auto scroll the window
	    var yOffset = window.pageYOffset;
	 	if (document.all) {
	        // Windows version
	        //yOffset=document.body.scrollTop;
	        if (typeof document.compatMode != 'undefined' &&
	             document.compatMode != 'BackCompat') {
	           yOffset = document.documentElement.scrollTop;
	        }
	        else if (typeof document.body != 'undefined') {
	           yOffset=document.body.scrollTop;
	        }

	    }
		    
		if (mousePos.y-yOffset < config.scrollAmount) {
	    	window.scrollBy(0, -config.scrollAmount);
	    } else {
            var windowHeight = window.innerHeight ? window.innerHeight
                    : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
            if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
                window.scrollBy(0, config.scrollAmount);
            }
        }


        if (y != jQuery.tableDnD.oldY) {
            // work out if we're going up or down...
            var movingDown = y > jQuery.tableDnD.oldY;
            // update the old value
            jQuery.tableDnD.oldY = y;
            // update the style to show we're dragging
			if (config.onDragClass) {
				dragObj.addClass(config.onDragClass);
			} else {
	            dragObj.css(config.onDragStyle);
			}
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
            if (currentRow) {
                // TODO worry about what happens when there are multiple TBODIES
                if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
                } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
                }
            }
        }

        return false;
    },

    /** We're only worried about the y position really, because we can only move rows up and down */
    findDropTargetRow: function(draggedRow, y) {
        var rows = jQuery.tableDnD.currentTable.rows;
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            var rowY    = this.getPosition(row).y;
            var rowHeight = parseInt(row.offsetHeight)/2;
            if (row.offsetHeight == 0) {
                rowY = this.getPosition(row.firstChild).y;
                rowHeight = parseInt(row.firstChild.offsetHeight)/2;
            }
            // Because we always have to insert before, we need to offset the height a bit
            if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                // that's the row we're over
				// If it's the same as the current row, ignore it
				if (row == draggedRow) {return null;}
                var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                if (config.onAllowDrop) {
                    if (config.onAllowDrop(draggedRow, row)) {
                        return row;
                    } else {
                        return null;
                    }
                } else {
					// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
                    var nodrop = jQuery(row).hasClass("nodrop");
                    if (! nodrop) {
                        return row;
                    } else {
                        return null;
                    }
                }
                return row;
            }
        }
        return null;
    },

    mouseup: function(e) {
        if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
            var droppedRow = jQuery.tableDnD.dragObject;
            var config = jQuery.tableDnD.currentTable.tableDnDConfig;
            // If we have a dragObject, then we need to release it,
            // The row will already have been moved to the right place so we just reset stuff
			if (config.onDragClass) {
	            jQuery(droppedRow).removeClass(config.onDragClass);
			} else {
	            jQuery(droppedRow).css(config.onDropStyle);
			}
            jQuery.tableDnD.dragObject   = null;
            if (config.onDrop) {
                // Call the onDrop method if there is one
                config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
            }
            jQuery.tableDnD.currentTable = null; // let go of the table too
        }
    },

    serialize: function() {
        if (jQuery.tableDnD.currentTable) {
            return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
        } else {
            return "Error: No Table id set, you need to set an id on your table and every row";
        }
    },

	serializeTable: function(table) {
        var result = "";
        var tableId = table.id;
        var rows = table.rows;
        for (var i=0; i<rows.length; i++) {
            if (result.length > 0) result += "&";
            var rowId = rows[i].id;
            if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
                rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
            }

            result += tableId + '[]=' + rowId;
        }
        return result;
	},

	serializeTables: function() {
        var result = "";
        this.each(function() {
			// this is now bound to each matching table
			result += jQuery.tableDnD.serializeTable(this);
		});
        return result;
    }

}

jQuery.fn.extend(
	{
		tableDnD : jQuery.tableDnD.build,
		tableDnDUpdate : jQuery.tableDnD.updateTables,
		tableDnDSerialize: jQuery.tableDnD.serializeTables
	}
);
 
 
 /* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * LiveQuery
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);
 
  
  /** Watermark Packed JS Use for search engine **/
(function($){var map=new Array();$.Watermark={ShowAll:function(){for(var i=0;i<map.length;i++){if(map[i].obj.val()==""){map[i].obj.val(map[i].text);map[i].obj.css("color",map[i].WatermarkColor);}else{map[i].obj.css("color",map[i].DefaultColor);}}},HideAll:function(){for(var i=0;i<map.length;i++){if(map[i].obj.val()==map[i].text)map[i].obj.val("");}}};$.fn.Watermark=function(text,color){if(!color)color="#cccccc";return this.each(function(){var input=$(this);var defaultColor=input.css("color");map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};function clearMessage(){if(input.val()==text)input.val("");input.css("color",defaultColor);}function insertMessage(){if(input.val().length==0||input.val()==text){input.val(text);input.css("color",color);}else
input.css("color",defaultColor);}input.focus(clearMessage);input.blur(insertMessage);input.change(insertMessage);insertMessage();});};})(jQuery);
  
  /** AutoSuggest Packed JS **/
if(typeof(bsn)=="undefined")_b=bsn={};if(typeof(_b.Autosuggest)=="undefined")_b.Autosuggest={};else alert("Autosuggest is already set!");_b.AutoSuggest=function(id,param){if(!document.getElementById)return 0;this.fld=_b.DOM.gE(id);if(!this.fld)return 0;this.sInp="";this.nInpC=0;this.aSug=[];this.iHigh=0;this.oP=param?param:{};var k,def={minchars:1,meth:"get",varname:"input",className:"autosuggest",timeout:2500,delay:500,offsety:-5,shownoresults:true,noresults:"No results!",maxheight:250,cache:true,maxentries:25};for(k in def){if(typeof(this.oP[k])!=typeof(def[k]))this.oP[k]=def[k]}var p=this;this.fld.onkeypress=function(ev){return p.onKeyPress(ev)};this.fld.onkeyup=function(ev){return p.onKeyUp(ev)};this.fld.setAttribute("autocomplete","off")};_b.AutoSuggest.prototype.onKeyPress=function(ev){var key=(window.event)?window.event.keyCode:ev.keyCode;var RETURN=13;var TAB=9;var ESC=27;var bubble=1;switch(key){case RETURN:this.setHighlightedValue();bubble=0;break;case ESC:this.clearSuggestions();break}return bubble};_b.AutoSuggest.prototype.onKeyUp=function(ev){var key=(window.event)?window.event.keyCode:ev.keyCode;var ARRUP=38;var ARRDN=40;var bubble=1;switch(key){case ARRUP:this.changeHighlight(key);bubble=0;break;case ARRDN:this.changeHighlight(key);bubble=0;break;default:this.getSuggestions(this.fld.value)}return bubble};_b.AutoSuggest.prototype.getSuggestions=function(val){if(val==this.sInp)return 0;_b.DOM.remE(this.idAs);this.sInp=val;if(val.length<this.oP.minchars){this.aSug=[];this.nInpC=val.length;return 0}var ol=this.nInpC;this.nInpC=val.length?val.length:0;var l=this.aSug.length;if(this.nInpC>ol&&l&&l<this.oP.maxentries&&this.oP.cache){var arr=[];for(var i=0;i<l;i++){if(this.aSug[i].value.substr(0,val.length).toLowerCase()==val.toLowerCase()||this.aSug[i].info=='as_header')arr.push(this.aSug[i])}this.aSug=arr;this.createList(this.aSug);return false}else{var pointer=this;var input=this.sInp;clearTimeout(this.ajID);this.ajID=setTimeout(function(){pointer.doAjaxRequest(input)},this.oP.delay)}return false};_b.AutoSuggest.prototype.doAjaxRequest=function(input){if(input!=this.fld.value)return false;var pointer=this;if(typeof(this.oP.script)=="function")var url=this.oP.script(encodeURIComponent(this.sInp));else var url=this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);if(!url)return false;var meth=this.oP.meth;var input=this.sInp;var onSuccessFunc=function(req){pointer.setSuggestions(req,input)};var onErrorFunc=function(status){alert("AJAX error: "+status)};var myAjax=new _b.Ajax();myAjax.makeRequest(url,meth,onSuccessFunc,onErrorFunc)};_b.AutoSuggest.prototype.setSuggestions=function(req,input){if(input!=this.fld.value)return false;this.aSug=[];if(this.oP.json){var jsondata=eval('('+req.responseText+')');for(var i=0;i<jsondata.results.length;i++){this.aSug.push({'id':jsondata.results[i].id,'value':jsondata.results[i].value,'info':jsondata.results[i].info})}}else{var xml=req.responseXML;var results=xml.getElementsByTagName('results')[0].childNodes;for(var i=0;i<results.length;i++){if(results[i].hasChildNodes())this.aSug.push({'id':results[i].getAttribute('id'),'value':results[i].childNodes[0].nodeValue,'info':results[i].getAttribute('info')})}}this.idAs="as_"+this.fld.id;this.createList(this.aSug)};_b.AutoSuggest.prototype.createList=function(arr){var pointer=this;_b.DOM.remE(this.idAs);this.killTimeout();if(arr.length==0&&!this.oP.shownoresults)return false;var div=_b.DOM.cE("div",{id:this.idAs,className:this.oP.className});var hcorner=_b.DOM.cE("div",{className:"as_corner"});var hbar=_b.DOM.cE("div",{className:"as_bar"});var header=_b.DOM.cE("div",{className:"as_header"});header.appendChild(hcorner);header.appendChild(hbar);div.appendChild(header);var ul=_b.DOM.cE("ul",{id:"as_ul"});for(var i=0;i<arr.length;i++){if(arr[i].info=="plugin_header"){var li=_b.DOM.cE("li",{className:"as_header"},arr[i].value);ul.appendChild(li);i++}var val=arr[i].value;var st=val.toLowerCase().indexOf(this.sInp.toLowerCase());var output=val.substring(0,st)+"<em>"+val.substring(st,st+this.sInp.length)+"</em>"+val.substring(st+this.sInp.length);var span=_b.DOM.cE("span",{},output,true);if(arr[i].info!=""){var br=_b.DOM.cE("br",{});span.appendChild(br);var small=_b.DOM.cE("small",{},arr[i].info);span.appendChild(small)}var a=_b.DOM.cE("a",{href:"#"});var tl=_b.DOM.cE("span",{className:"tl"}," ");var tr=_b.DOM.cE("span",{className:"tr"}," ");a.appendChild(tl);a.appendChild(tr);a.appendChild(span);a.name=i+1;a.onclick=function(){pointer.setHighlightedValue();return false};a.onmouseover=function(){pointer.setHighlight(this.name)};var li=_b.DOM.cE("li",{},a);ul.appendChild(li)}if(arr.length==0&&this.oP.shownoresults){var li=_b.DOM.cE("li",{className:"as_warning"},this.oP.noresults);ul.appendChild(li)}div.appendChild(ul);var fcorner=_b.DOM.cE("div",{className:"as_corner"});var fbar=_b.DOM.cE("div",{className:"as_bar"});var footer=_b.DOM.cE("div",{className:"as_footer"});footer.appendChild(fcorner);footer.appendChild(fbar);div.appendChild(footer);var pos=_b.DOM.getPos(this.fld);div.style.left=pos.x+"px";div.style.top=(pos.y+this.fld.offsetHeight+this.oP.offsety)+"px";div.style.width=this.fld.offsetWidth+"px";div.onmouseover=function(){pointer.killTimeout()};div.onmouseout=function(){pointer.resetTimeout()};document.getElementsByTagName("body")[0].appendChild(div);this.iHigh=0;var pointer=this;this.toID=setTimeout(function(){pointer.clearSuggestions()},this.oP.timeout)};_b.AutoSuggest.prototype.changeHighlight=function(key){var list=_b.DOM.gE("as_ul");if(!list)return false;var n;if(key==40)n=this.iHigh+1;else if(key==38)n=this.iHigh-1;if(n>list.childNodes.length)n=list.childNodes.length;if(n<1)n=1;this.setHighlight(n)};_b.AutoSuggest.prototype.setHighlight=function(n){var list=_b.DOM.gE("as_ul");if(!list)return false;if(this.iHigh>0)this.clearHighlight();this.iHigh=Number(n);if(list.childNodes[this.iHigh-1].className!="as_header")list.childNodes[this.iHigh-1].className="as_highlight";this.killTimeout()};_b.AutoSuggest.prototype.clearHighlight=function(){var list=_b.DOM.gE("as_ul");if(!list)return false;if(this.iHigh>0){if(list.childNodes[this.iHigh-1].className!="as_header")list.childNodes[this.iHigh-1].className="";this.iHigh=0}};_b.AutoSuggest.prototype.setHighlightedValue=function(){if(this.iHigh){this.sInp=this.fld.value=this.aSug[this.iHigh-1].value;this.fld.focus();if(this.fld.selectionStart)this.fld.setSelectionRange(this.sInp.length,this.sInp.length);this.clearSuggestions();if(typeof(this.oP.callback)=="function")this.oP.callback(this.aSug[this.iHigh-1])}};_b.AutoSuggest.prototype.killTimeout=function(){clearTimeout(this.toID)};_b.AutoSuggest.prototype.resetTimeout=function(){clearTimeout(this.toID);var pointer=this;this.toID=setTimeout(function(){pointer.clearSuggestions()},1000)};_b.AutoSuggest.prototype.clearSuggestions=function(){this.killTimeout();var ele=_b.DOM.gE(this.idAs);var pointer=this;if(ele){var fade=new _b.Fader(ele,1,0,250,function(){_b.DOM.remE(pointer.idAs)})}};if(typeof(_b.Ajax)=="undefined")_b.Ajax={};_b.Ajax=function(){this.req={};this.isIE=false};_b.Ajax.prototype.makeRequest=function(url,meth,onComp,onErr){if(meth!="POST")meth="GET";this.onComplete=onComp;this.onError=onErr;var pointer=this;if(window.XMLHttpRequest){this.req=new XMLHttpRequest();this.req.onreadystatechange=function(){pointer.processReqChange()};this.req.open("GET",url,true);this.req.send(null)}else if(window.ActiveXObject){this.req=new ActiveXObject("Microsoft.XMLHTTP");if(this.req){this.req.onreadystatechange=function(){pointer.processReqChange()};this.req.open(meth,url,true);this.req.send()}}};_b.Ajax.prototype.processReqChange=function(){if(this.req.readyState==4){if(this.req.status==200){this.onComplete(this.req)}else{this.onError(this.req.status)}}};if(typeof(_b.DOM)=="undefined")_b.DOM={};_b.DOM.cE=function(type,attr,cont,html){var ne=document.createElement(type);if(!ne)return 0;for(var a in attr)ne[a]=attr[a];var t=typeof(cont);if(t=="string"&&!html)ne.appendChild(document.createTextNode(cont));else if(t=="string"&&html)ne.innerHTML=cont;else if(t=="object")ne.appendChild(cont);return ne};_b.DOM.gE=function(e){var t=typeof(e);if(t=="undefined")return 0;else if(t=="string"){var re=document.getElementById(e);if(!re)return 0;else if(typeof(re.appendChild)!="undefined")return re;else return 0}else if(typeof(e.appendChild)!="undefined")return e;else return 0};_b.DOM.remE=function(ele){var e=this.gE(ele);if(!e)return 0;else if(e.parentNode.removeChild(e))return true;else return 0};_b.DOM.getPos=function(e){var e=this.gE(e);var obj=e;var curleft=0;if(obj.offsetParent){while(obj.offsetParent){curleft+=obj.offsetLeft;obj=obj.offsetParent}}else if(obj.x)curleft+=obj.x;var obj=e;var curtop=0;if(obj.offsetParent){while(obj.offsetParent){curtop+=obj.offsetTop;obj=obj.offsetParent}}else if(obj.y)curtop+=obj.y;return{x:curleft,y:curtop}};if(typeof(_b.Fader)=="undefined")_b.Fader={};_b.Fader=function(ele,from,to,fadetime,callback){if(!ele)return 0;this.e=ele;this.from=from;this.to=to;this.cb=callback;this.nDur=fadetime;this.nInt=50;this.nTime=0;var p=this;this.nID=setInterval(function(){p._fade()},this.nInt)};_b.Fader.prototype._fade=function(){this.nTime+=this.nInt;var ieop=Math.round(this._tween(this.nTime,this.from,this.to,this.nDur)*100);var op=ieop/100;if(this.e.filters){try{this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity=ieop}catch(e){this.e.style.filter='progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')'}}else{this.e.style.opacity=op}if(this.nTime==this.nDur){clearInterval(this.nID);if(this.cb!=undefined)this.cb()}};_b.Fader.prototype._tween=function(t,b,c,d){return b+((c-b)*(t/d))};

/** Init autosuggest on Search Input **/
jQuery(function() {
	//==================== Search With all plugins =================================================
	// Unbind form submit
	//$j('#search').bind('submit', function() { return false;} ) ;	
	// Set autosuggest options with all plugins activated
	var options = {
		script:"search/autocomplete/json/true/limit/200/input/",
		varname:"", json:true,
		shownoresults:true,				// If disable, display nothing if no results
		noresults:"Aucun résultat",			// String displayed when no results
		maxresults:200,					// Max num results displayed
		cache:false,					// To enable cache
		minchars:2,						// Start AJAX request with at leat 2 chars
		timeout:3000,					// AutoHide in XX ms
		callback: function (obj) { 		// Callback after click or selection
			$j('#search').submit(); 
			$j('#as_content_search').hide(); 
		}
	};
	// Init autosuggest
	var as_json = new bsn.AutoSuggest('content_search', options);
	// Display a little watermak	
	$j("#content_search").Watermark("ex : Guetta, Always is love...");
});

// AJAX FILE UPLOAD
// Copyright (c) 2008 Andris Valums, http://valums.com
// Licensed under the MIT license (http://valums.com/mit-license/)
(function(C){if(!C){return }C.ajax_upload=function(E,D){E=C(E);if(E.size()!=1){console.error("You passed ",E.size()," elements to ajax_upload at once");return false}return new A(E,D)};var B=function(){var D=0;return function(){return D++}}();var A=function(E,D){this.button=E;this.wrapper=null;this.form=null;this.input=null;this.iframe=null;this.disabled=false;this.submitting=false;this.settings={action:"upload.php",name:"userfile",data:{},onSubmit:function(F,G){},onComplete:function(G,F){},onSuccess:function(F){},onError:function(G,F){}};C.extend(this.settings,D);this.create_wrapper();this.create_input();if(jQuery.browser.msie){this.make_parent_opaque()}this.create_iframe()};A.prototype={set_data:function(D){this.settings.data=D},disable:function(){this.disabled=true;if(!this.submitting){this.input.attr("disabled",true)}},enable:function(){this.disabled=false;this.input.attr("disabled",false)},create_wrapper:function(){var E=this.button,F;F=this.wrapper=C("<div></div>").insertAfter(E).append(E);setTimeout(function(){F.css({position:"relative",display:"block",overflow:"hidden",height:E.outerHeight(true),width:E.outerWidth(true)})},1);var D=this;F.mousemove(function(G){if(!D.input){return }D.input.css({top:G.pageY-F.offset().top-5+"px",left:G.pageX-F.offset().left-170+"px"})})},create_input:function(){var D=this;this.input=C('<input type="file" />').attr("name",this.settings.name).css({position:"absolute",margin:0,padding:0,width:"220px",heigth:"10px",opacity:0}).change(function(){if(C(this).val()==""){return }D.submitting=true;D.submit();D.submitting=false}).appendTo(this.wrapper).hover(function(){D.button.addClass("hover")},function(){D.button.removeClass("hover")});if(this.disabled){this.input.attr("disabled",true)}},create_iframe:function(){var D="iframe_au"+B();this.iframe=C('<iframe name="'+D+'"></iframe>').css("display","none").appendTo("body")},submit:function(){var D=this,G=this.settings;var E=this.file_from_path(this.input.val());if(G.onSubmit.call(this,E,this.get_ext(E))===false){if(D.disabled){this.input.attr("disabled",true)}return }this.create_form();this.input.appendTo(this.form);this.form.submit();this.input.remove();this.input=null;this.form.remove();this.form=null;this.submitting=false;this.create_input();var F=this.iframe;F.load(function(){var H=F.contents().find("body").html();G.onComplete.call(D,E,H);if(H=="success"){G.onSuccess.call(D,E)}else{G.onError.call(D,E,H)}setTimeout(function(){F.remove()},1)});this.create_iframe()},create_form:function(){this.form=C('<form method="post" enctype="multipart/form-data"></form>').appendTo("body").attr({action:this.settings.action,target:this.iframe.attr("name")});for(var D in this.settings.data){C('<input type="hidden" />').appendTo(this.form).attr({name:D,value:this.settings.data[D]})}},file_from_path:function(E){var D=E.lastIndexOf("\\");if(D!==-1){return E.slice(D+1)}return E},get_ext:function(E){var D=E.lastIndexOf(".");if(D!==-1){return E.slice(D+1)}return""},make_parent_opaque:function(){this.button.add(this.button.parents()).each(function(){var D=C(this).css("backgroundColor");var E=C(this).css("backgroundImage");if(D!="transparent"||E!="none"){C(this).css("opacity",1);return false}})}}})(jQuery);

  /**  Innerface Packed JS use for register message **/
(function($){$.fn.innerfade=function(options){return this.each(function(){$.innerfade(this,options);});};$.innerfade=function(container,options){var settings={'animationtype':'fade','speed':'normal','type':'sequence','timeout':2000,'containerheight':'auto','runningclass':'innerfade','children':null};if(options)$.extend(settings,options);if(settings.children===null)var elements=$(container).children();else
var elements=$(container).children(settings.children);if(elements.length>1){$(container).css('height',settings.containerheight).addClass(settings.runningclass);for(var i=0;i<elements.length;i++){$(elements[i]).css('z-index',String(elements.length-i)).css('position','absolute').hide();};if(settings.type=="sequence"){setTimeout(function(){$.innerfade.next(elements,settings,1,0);},settings.timeout);$(elements[0]).show();}else if(settings.type=="random"){var last=Math.floor(Math.random()*(elements.length));setTimeout(function(){do{current=Math.floor(Math.random()*(elements.length));}while(last==current);$.innerfade.next(elements,settings,current,last);},settings.timeout);$(elements[last]).show();}else if(settings.type=='random_start'){settings.type='sequence';var current=Math.floor(Math.random()*(elements.length));setTimeout(function(){$.innerfade.next(elements,settings,(current+1)%elements.length,current);},settings.timeout);$(elements[current]).show();}else{alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');}}};$.innerfade.next=function(elements,settings,current,last){if(settings.animationtype=='slide'){$(elements[last]).slideUp(settings.speed);$(elements[current]).slideDown(settings.speed);}else if(settings.animationtype=='fade'){$(elements[last]).fadeOut(settings.speed);$(elements[current]).fadeIn(settings.speed,function(){removeFilter($(this)[0]);});}else
alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');if(settings.type=="sequence"){if((current+1)<elements.length){current=current+1;last=current-1;}else{current=0;last=elements.length-1;}}else if(settings.type=="random"){last=current;while(current==last)current=Math.floor(Math.random()*elements.length);}else
alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');setTimeout((function(){$.innerfade.next(elements,settings,current,last);}),settings.timeout);};})(jQuery); 

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 */
(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/**
 * jquery.scrollable 0.13. Put your HTML scroll.
 * 
 * http://flowplayer.org/tools/scrollable.html
 *
 * Copyright (c) 2008 Tero Piirainen (support@flowplayer.org)
 *
 * Released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * >> Basically you can do anything you want but leave this header as is <<
 *
 * Since  : 0.10 - 03/01/2008
 * Version: 0.13 - Fri Nov 07 2008 16:50:33 GMT-0000 (GMT+00:00)
 */
(function($){function Scrollable(el,config){var self=this;if(!Scrollable.current){Scrollable.current=this;}var opts={size:5,vertical:false,activeClass:'active',speed:300,onSeek:null,clickable:true,items:'.items',prev:'.prev',next:'.next',navi:'.navi',naviItem:'span',loop:false};this.opts=$.extend(opts,config);this.opts.horizontal=!opts.vertical;this.root=$(el);var root=this.root;var itemRoot=$(opts.items,root);if(!itemRoot.length){itemRoot=root;}itemRoot.css({position:'relative',overflow:'hidden',visibility:'visible'});itemRoot.children().wrapAll('<div class="__scrollable" style="position:absolute"/>');this.wrap=itemRoot.find(":first");this.wrap.css(opts.horizontal?"width":"height","200000em").after('<br clear="all" />');this.items=this.wrap.children();this.index=0;if(opts.horizontal){itemRoot.width(opts.size*(this.items.eq(1).offset().left-this.items.eq(0).offset().left)-2);}else{itemRoot.height(opts.size*(this.items.eq(1).offset().top-this.items.eq(0).offset().top)-2);}if($.isFunction($.fn.mousewheel)){root.bind("mousewheel.scrollable",function(e,delta){self.move(-delta,50);return false;});}if(opts.clickable){this.items.each(function(index,arg){$(this).bind("click.scrollable",function(){self.click(index);});});}this.activeIndex=0;$(opts.prev,root).click(function(){self.prev();});$(opts.next,root).click(function(){self.next();});$(opts.navi,root).each(function(){var navi=$(this);var status=self.getStatus();if(navi.is(":empty")){for(var i=0;i<status.pages;i++){var item=$("<"+opts.naviItem+"/>").attr("page",i).click(function(e){var el=$(this);el.parent().children().removeClass(opts.activeClass);el.addClass(opts.activeClass);self.setPage(el.attr("page"));e.preventDefault();});if(i===0){item.addClass(opts.activeClass);}navi.append(item);}}else{var els=navi.find("a");if(!els.length){els=navi.children();}els.each(function(i){var item=$(this);item.attr("page",i);if(i===0){item.addClass(opts.activeClass);}item.click(function(){navi.find("."+opts.activeClass).removeClass(opts.activeClass);item.addClass(opts.activeClass);self.setPage(item.attr("page"));});});}});}$.extend(Scrollable.prototype,{getVersion:function(){return'@VERSION';},click:function(index){var item=this.items.eq(index);var klass=this.opts.activeClass;if(!item.hasClass(klass)&&(index>=0||index<this.items.size())){this.items.removeClass(klass);item.addClass(klass);var delta=Math.floor(this.opts.size/2);var to=index-delta;if(to!==this.activeIndex){this.seekTo(to);}}},getStatus:function(){var len=this.items.size();return{size:this.opts.size,total:len,index:this.index,pages:Math.ceil(len/this.opts.size),page:Math.ceil(this.index/this.opts.size)};},seekTo:function(index,time){if(index<0){index=0;}var max=Math.min(index,this.items.length-this.opts.size);if(index<=max){var item=this.items.eq(index);this.index=index;if(this.opts.horizontal){var left=this.wrap.offset().left-item.offset().left;this.wrap.animate({left:left},time||this.opts.speed);}else{var top=this.wrap.offset().top-item.offset().top;this.wrap.animate({top:top},time||this.opts.speed);}Scrollable.current=this;}if($.isFunction(this.opts.onSeek)){this.opts.onSeek.call(this);}var navi=$(this.opts.navi,this.root);if(navi.length){var klass=this.opts.activeClass;var page=Math.ceil(index/this.opts.size);page=Math.min(page,navi.children().length-1);navi.children().removeClass(klass).eq(page).addClass(klass);}this.activeIndex=index;return true;},move:function(offset,time){var to=this.index+offset;if(this.opts.loop&&to>(this.items.length-this.opts.size)){to=0;}this.seekTo(to,time);},next:function(time){this.move(1,time);},prev:function(time){this.move(-1,time);},movePage:function(offset,time){this.move(this.opts.size*offset,time);},setPage:function(page,time){var size=this.opts.size;var index=size*page;var lastPage=index+size>=this.items.size();if(lastPage){index=this.items.size()-this.opts.size;}this.seekTo(index,time);},prevPage:function(time){this.setPage(this.getStatus().page-1,time);},nextPage:function(time){this.setPage(this.getStatus().page+1,time);},begin:function(time){this.seekTo(0,time);},end:function(time){this.seekTo(this.items.size()-this.opts.size,time);}});$(window).bind("keypress.scrollable",function(evt){var el=Scrollable.current;if(!el){return;}if(el.opts.horizontal&&(evt.keyCode==37||evt.keyCode==39)){el.move(evt.keyCode==37?-1:1);return evt.preventDefault();}if(!el.opts.horizontal&&(evt.keyCode==38||evt.keyCode==40)){el.move(evt.keyCode==38?-1:1);return evt.preventDefault();}return true;});jQuery.prototype.scrollable=function(opts,arg0,arg1){if(!opts||typeof opts=='number'){var index=opts||0;var el=$.data(this.get()[index],"scrollable");if(el){return el;}}this.each(function(){if(typeof opts=="string"){var el=$.data(this,"scrollable");el[opts].apply(el,[arg0,arg1]);}else{var instance=new Scrollable(this,opts);$.data(this,"scrollable",instance);}});return this;};})(jQuery);


/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-14 23:57:10 -0600 (Fri, 14 Dec 2007) $
 * $Rev: 4163 $
 * mousewheel
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+

(function($){$.event.special.mousewheel={setup:function(){var handler=$.event.special.mousewheel.handler;if($.browser.mozilla)$(this).bind('mousemove.mousewheel',function(event){$.data(this,'mwcursorposdata',{pageX:event.pageX,pageY:event.pageY,clientX:event.clientX,clientY:event.clientY});});if(this.addEventListener)this.addEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),handler,false);else
this.onmousewheel=handler;},teardown:function(){var handler=$.event.special.mousewheel.handler;$(this).unbind('mousemove.mousewheel');if(this.removeEventListener)this.removeEventListener(($.browser.mozilla?'DOMMouseScroll':'mousewheel'),handler,false);else
this.onmousewheel=function(){};$.removeData(this,'mwcursorposdata');},handler:function(event){var args=Array.prototype.slice.call(arguments,1);event=$.event.fix(event||window.event);$.extend(event,$.data(this,'mwcursorposdata')||{});var delta=0,returnValue=true;if(event.wheelDelta)delta=event.wheelDelta/120;if(event.detail)delta=-event.detail/3;if($.browser.opera)delta=-event.wheelDelta;event.data=event.data||{};event.type="mousewheel";args.unshift(delta);args.unshift(event);return $.event.handle.apply(this,args);}};$.fn.extend({mousewheel:function(fn){return fn?this.bind("mousewheel",fn):this.trigger("mousewheel");},unmousewheel:function(fn){return this.unbind("mousewheel",fn);}});})(jQuery); 
 */

/**
 * Cookie plugin
 * @example $.cookie('the_cookie', 'the_value');
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @example $.cookie('the_cookie', null);
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/* barre bottom fix */
/**
 * Menu fixé et transparent - http://www.webinventif.fr/barre-de-navigation-fixe-depliable-et-transparente/
 * 
 * Copyright (c) 2008 Julien Chauvin (webinventif.fr)
 * Licensed under the Creative Commons License:
 * http://creativecommons.org/licenses/by/3.0/
 *
 * Date: 2008-02-25
 */
function fixed_bottom(select,offS){return Number(-offS+document.documentElement.clientHeight-select.offsetHeight+document.documentElement.scrollTop+document.body.scrollTop)+'px';}$j(document).ready(function(){$j("#magicmenu").show();if($j.browser.msie){if($j.browser.version=="6.0"){$j("#magicmini").hide();$j("#magicmaxi").hide();$j("#magicbox").css('position','absolute');}else if($j.browser.version>"7.0"){$j("#magicbox").css('position','fixed');$j("#magicmini").hide();$j("#magicmaxi").hide();}}else{$j("#magicbox").css('position','fixed');$j("#magicmini").hide();$j("#magicmaxi").hide();}$j("#magicmenu .magic1").click(function(){$j.cookie('selectmenu','close');$j("#magiccontent").slideUp("slow",function(){$j("#magicmaxi").hide();$j("#magicmini").hide();$j(this).show();});toggleselect(this);return false;});$j("#magicmenu .magic3").click(function(){$j.cookie('selectmenu','light');if($j("#magicmini").css("display")=="none"&&$j("#magicmaxi").css("display")=="none"){$j("#magiccontent").hide();$j("#magicmini").show();}if($j("#magiccontent").css("display")=="none"){$j("#magicmaxi").hide();$j("#magiccontent").slideDown("slow");}else if($j("#magicmaxi").css("display")=="block"){$j("#magicmaxi").slideUp("slow");}toggleselect(this);return false;});$j("#magicmenu .magic2").click(function(){$j.cookie('selectmenu','full');if($j("#magicmini").css("display")=="none"&&$j("#magicmaxi").css("display")=="none"){$j("#magiccontent").hide();$j("#magicmini").show();}if($j("#magiccontent").css("display")=="none"){$j("#magicmaxi").show();$j("#magiccontent").slideDown("slow");}else if($j("#magicmaxi").css("display")=="none"){$j("#magicmaxi").slideDown("slow");}toggleselect(this);return false;});$j("#magiccontent").fadeTo("fast",0.95);$j("#magicmenu ul li a").each(function(i){$j(this).fadeTo("fast",0.95);this.colback=$j(this).css('background-color');this.tempcol=false;$j(this).hover(function(){$j(this).css('background-color',$j("#magiccontent").css('background-color'))},function(){if(this.tempcol){$j(this).css('background-color',$j("#magiccontent").css('background-color'));}else{$j(this).css('background-color',this.colback);}});});function toggleselect(ele){$j("#magicmenu ul li a").each(function(i){$j(this).css('background-color',this.colback);this.tempcol=false;});$j(ele).css('background-color',$j("#magiccontent").css('background-color'));ele.tempcol=true;}if($j.cookie('selectmenu')){if($j.cookie('selectmenu')=="full"){$j("#magicmini").show();$j("#magicmaxi").show();$j("#magicmenu .magic2").each(function(){toggleselect(this);});}else if($j.cookie('selectmenu')=="light"){$j("#magicmini").show();$j("#magicmenu .magic3").each(function(){toggleselect(this);});}else if($j.cookie('selectmenu')=="close"){$j("#magicmenu .magic1").each(function(){toggleselect(this);});}}else{$j("#magicmini").show();toggleselect("#magicmenu .magic3");}});

/* UI Draggable & dropable 1.5 stable  */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(6(C){C.b={U:{16:6(E,D,H){c G=C.b[E].2m;2h(c F 4z H){G.1T[F]=G.1T[F]||[];G.1T[F].2x([D,H[F]])}},v:6(D,F,E){c H=D.1T[F];5(!H){f}2h(c G=0;G<H.1o;G++){5(D.7[H[G][0]]){H[G][1].27(D.e,E)}}}},2l:{},g:6(D){5(C.b.2l[D]){f C.b.2l[D]}c E=C(\'<2s 3H="b-4A">\').1z(D).g({k:"S",8:"-3y",a:"-3y",3v:"4y"}).1I("1a");C.b.2l[D]=!!((!(/25|3U/).17(E.g("1K"))||(/^[1-9]/).17(E.g("r"))||(/^[1-9]/).17(E.g("t"))||!(/2X/).17(E.g("4x"))||!(/4v|4w\\(0, 0, 0, 0\\)/).17(E.g("4C"))));4E{C("1a").3S(0).3M(E.3S(0))}4u(F){}f C.b.2l[D]},4l:6(D){C(D).2b("2f","3O").g("3V","2X")},4i:6(D){C(D).2b("2f","4J").g("3V","")},58:6(G,D){c F=/8/.17(D||"8")?"V":"W",E=l;5(G[F]>0){f q}G[F]=1;E=G[F]>0?q:l;G[F]=0;f E}};c A=C.2W.1J;C.2W.1J=6(){C("*",4).16(4).1w("1J");f A.27(4,3R)};6 B(F,D,G){c E=C[F][D].56||[];E=(38 E=="39"?E.3m(/,?\\s+/):E);f(C.5a(G,E)!=-1)}C.1H=6(D,E){c F=D.3m(".")[0];D=D.3m(".")[1];C.2W[D]=6(J){c H=(38 J=="39"),I=4P.2m.4I.v(3R,1);5(H&&B(F,D,J)){c G=C.Y(4[0],D);f(G?G[J].27(G,I):26)}f 4.19(6(){c K=C.Y(4,D);5(H&&K&&C.3w(K[J])){K[J].27(K,I)}1V{5(!H){C.Y(4,D,42 C[F][D](4,J))}}})};C[F][D]=6(H,I){c G=4;4.1u=D;4.3o=F+"-"+D;4.7=C.1v({},C.1H.1O,C[F][D].1O,I);4.e=C(H).1L("2e."+D,6(L,J,K){f G.2e(J,K)}).1L("2N."+D,6(K,J){f G.2N(J)}).1L("1J",6(){f G.2u()});4.2w()};C[F][D].2m=C.1v({},C.1H.2m,E)};C.1H.2m={2w:6(){},2u:6(){4.e.3f(4.1u)},2N:6(D){f 4.7[D]},2e:6(D,E){4.7[D]=E;5(D=="12"){4.e[E?"1z":"1y"](4.3o+"-12")}},47:6(){4.2e("12",l)},46:6(){4.2e("12",q)}};C.1H.1O={12:l};C.b.3k={3Q:6(){c D=4;4.e.1L("4d."+4.1u,6(E){f D.3p(E)});5(C.2z.3j){4.3r=4.e.2b("2f");4.e.2b("2f","3O")}4.43=l},3q:6(){4.e.2n("."+4.1u);(C.2z.3j&&4.e.2b("2f",4.3r))},3p:6(F){(4.1r&&4.2k(F));4.2I=F;c D=4,G=(F.4a==1),E=(38 4.7.2H=="39"?C(F.24).2Z().16(F.24).3Y(4.7.2H).1o:l);5(!G||E||!4.3a(F)){f q}4.2r=!4.7.2J;5(!4.2r){4.45=4c(6(){D.2r=q},4.7.2J)}5(4.3i(F)&&4.3l(F)){4.1r=(4.23(F)!==l);5(!4.1r){F.49();f q}}4.3g=6(H){f D.3u(H)};4.3h=6(H){f D.2k(H)};C(j).1L("3C."+4.1u,4.3g).1L("3B."+4.1u,4.3h);f l},3u:6(D){5(C.2z.3j&&!D.4b){f 4.2k(D)}5(4.1r){4.1U(D);f l}5(4.3i(D)&&4.3l(D)){4.1r=(4.23(4.2I,D)!==l);(4.1r?4.1U(D):4.2k(D))}f!4.1r},2k:6(D){C(j).2n("3C."+4.1u,4.3g).2n("3B."+4.1u,4.3h);5(4.1r){4.1r=l;4.21(D)}f l},3i:6(D){f(Z.2M(Z.1h(4.2I.1t-D.1t),Z.1h(4.2I.1A-D.1A))>=4.7.2O)},3l:6(D){f 4.2r},23:6(D){},1U:6(D){},21:6(D){},3a:6(D){f q}};C.b.3k.1O={2H:2d,2O:1,2J:0}})(3n);(6(A){A.1H("b.m",A.1v({},A.b.3k,{2w:6(){c B=4.7;5(B.h=="2R"&&!(/(p|S|1i)/).17(4.e.g("k"))){4.e.g("k","p")}4.e.1z("b-m");(B.12&&4.e.1z("b-m-12"));4.3Q()},23:6(F){c H=4.7;5(4.h||H.12||A(F.24).3A(".b-40-2B")){f l}c B=!4.7.2B||!A(4.7.2B,4.e).1o?q:l;A(4.7.2B,4.e).3x("*").3Z().19(6(){5(4==F.24){B=q}});5(!B){f l}5(A.b.u){A.b.u.1B=4}4.h=A.3w(H.h)?A(H.h.27(4.e[0],[F])):(H.h=="3c"?4.e.3c():4.e);5(!4.h.2Z("1a").1o){4.h.1I((H.1I=="o"?4.e[0].1Y:H.1I))}5(4.h[0]!=4.e[0]&&!(/(1i|S)/).17(4.h.g("k"))){4.h.g("k","S")}4.18={a:(T(4.e.g("4e"),10)||0),8:(T(4.e.g("44"),10)||0)};4.11=4.h.g("k");4.d=4.e.d();4.d={8:4.d.8-4.18.8,a:4.d.a-4.18.a};4.d.z={a:F.1t-4.d.a,8:F.1A-4.d.8};4.X=4.h.X();c C=4.X.d();5(4.X[0]==j.1a&&A.2z.48){C={8:0,a:0}}4.d.o={8:C.8+(T(4.X.g("32"),10)||0),a:C.a+(T(4.X.g("31"),10)||0)};c E=4.e.k();4.d.p=4.11=="p"?{8:E.8-(T(4.h.g("8"),10)||0)+4.X[0].V,a:E.a-(T(4.h.g("a"),10)||0)+4.X[0].W}:{8:0,a:0};4.1F=4.2Y(F);4.w={t:4.h.2S(),r:4.h.37()};5(H.1n){5(H.1n.a!=26){4.d.z.a=H.1n.a+4.18.a}5(H.1n.3T!=26){4.d.z.a=4.w.t-H.1n.3T+4.18.a}5(H.1n.8!=26){4.d.z.8=H.1n.8+4.18.8}5(H.1n.3G!=26){4.d.z.8=4.w.r-H.1n.3G+4.18.8}}5(H.n){5(H.n=="o"){H.n=4.h[0].1Y}5(H.n=="j"||H.n=="1Z"){4.n=[0-4.d.p.a-4.d.o.a,0-4.d.p.8-4.d.o.8,A(H.n=="j"?j:1Z).t()-4.d.p.a-4.d.o.a-4.w.t-4.18.a-(T(4.e.g("3s"),10)||0),(A(H.n=="j"?j:1Z).r()||j.1a.1Y.3D)-4.d.p.8-4.d.o.8-4.w.r-4.18.8-(T(4.e.g("3E"),10)||0)]}5(!(/^(j|1Z|o)$/).17(H.n)){c D=A(H.n)[0];c G=A(H.n).d();4.n=[G.a+(T(A(D).g("31"),10)||0)-4.d.p.a-4.d.o.a,G.8+(T(A(D).g("32"),10)||0)-4.d.p.8-4.d.o.8,G.a+Z.2M(D.41,D.2i)-(T(A(D).g("31"),10)||0)-4.d.p.a-4.d.o.a-4.w.t-4.18.a-(T(4.e.g("3s"),10)||0),G.8+Z.2M(D.3D,D.2g)-(T(A(D).g("32"),10)||0)-4.d.p.8-4.d.o.8-4.w.r-4.18.8-(T(4.e.g("3E"),10)||0)]}}4.1l("1s",F);4.w={t:4.h.2S(),r:4.h.37()};5(A.b.u&&!H.3F){A.b.u.35(4,F)}4.h.1z("b-m-3e");4.1U(F);f q},1d:6(C,D){5(!D){D=4.k}c B=C=="S"?1:-1;f{8:(D.8+4.d.p.8*B+4.d.o.8*B-(4.11=="1i"||(4.11=="S"&&4.X[0]==j.1a)?0:4.X[0].V)*B+(4.11=="1i"?A(j).V():0)*B+4.18.8*B),a:(D.a+4.d.p.a*B+4.d.o.a*B-(4.11=="1i"||(4.11=="S"&&4.X[0]==j.1a)?0:4.X[0].W)*B+(4.11=="1i"?A(j).W():0)*B+4.18.a*B)}},2Y:6(E){c F=4.7;c B={8:(E.1A-4.d.z.8-4.d.p.8-4.d.o.8+(4.11=="1i"||(4.11=="S"&&4.X[0]==j.1a)?0:4.X[0].V)-(4.11=="1i"?A(j).V():0)),a:(E.1t-4.d.z.a-4.d.p.a-4.d.o.a+(4.11=="1i"||(4.11=="S"&&4.X[0]==j.1a)?0:4.X[0].W)-(4.11=="1i"?A(j).W():0))};5(!4.1F){f B}5(4.n){5(B.a<4.n[0]){B.a=4.n[0]}5(B.8<4.n[1]){B.8=4.n[1]}5(B.a>4.n[2]){B.a=4.n[2]}5(B.8>4.n[3]){B.8=4.n[3]}}5(F.1p){c D=4.1F.8+Z.3z((B.8-4.1F.8)/F.1p[1])*F.1p[1];B.8=4.n?(!(D<4.n[1]||D>4.n[3])?D:(!(D<4.n[1])?D-F.1p[1]:D+F.1p[1])):D;c C=4.1F.a+Z.3z((B.a-4.1F.a)/F.1p[0])*F.1p[0];B.a=4.n?(!(C<4.n[0]||C>4.n[2])?C:(!(C<4.n[0])?C-F.1p[0]:C+F.1p[0])):C}f B},1U:6(B){4.k=4.2Y(B);4.13=4.1d("S");4.k=4.1l("1m",B)||4.k;5(!4.7.29||4.7.29!="y"){4.h[0].2a.a=4.k.a+"2L"}5(!4.7.29||4.7.29!="x"){4.h[0].2a.8=4.k.8+"2L"}5(A.b.u){A.b.u.1m(4,B)}f l},21:6(C){c D=l;5(A.b.u&&!4.7.3F){c D=A.b.u.1q(4,C)}5((4.7.1E=="4T"&&!D)||(4.7.1E=="4S"&&D)||4.7.1E===q){c B=4;A(4.h).4U(4.1F,T(4.7.1E,10)||4V,6(){B.1l("1C",C);B.2P()})}1V{4.1l("1C",C);4.2P()}f l},2P:6(){4.h.1y("b-m-3e");5(4.7.h!="2R"&&!4.28){4.h.1J()}4.h=2d;4.28=l},1T:{},2Q:6(B){f{h:4.h,k:4.k,2y:4.13,7:4.7}},1l:6(C,B){A.b.U.v(4,C,[B,4.2Q()]);5(C=="1m"){4.13=4.1d("S")}f 4.e.1w(C=="1m"?C:"1m"+C,[B,4.2Q()],4.7[C])},2u:6(){5(!4.e.Y("m")){f}4.e.3f("m").2n(".m").1y("b-m");4.3q()}}));A.1v(A.b.m,{1O:{1I:"o",29:l,2H:":4W",2J:0,2O:1,h:"2R"}});A.b.U.16("m","1K",{1s:6(D,C){c B=A("1a");5(B.g("1K")){C.7.36=B.g("1K")}B.g("1K",C.7.1K)},1C:6(C,B){5(B.7.36){A("1a").g("1K",B.7.36)}}});A.b.U.16("m","1b",{1s:6(D,C){c B=A(C.h);5(B.g("1b")){C.7.33=B.g("1b")}B.g("1b",C.7.1b)},1C:6(C,B){5(B.7.33){A(B.h).g("1b",B.7.33)}}});A.b.U.16("m","1D",{1s:6(D,C){c B=A(C.h);5(B.g("1D")){C.7.34=B.g("1D")}B.g("1D",C.7.1D)},1C:6(C,B){5(B.7.34){A(B.h).g("1D",B.7.34)}}});A.b.U.16("m","2G",{1s:6(C,B){A(B.7.2G===q?"4R":B.7.2G).19(6(){A(\'<2s 3H="b-m-2G" 2a="4Q: #4L;"></2s>\').g({t:4.2i+"2L",r:4.2g+"2L",k:"S",1D:"0.4K",1b:4M}).g(A(4).d()).1I("1a")})},1C:6(C,B){A("2s.4N").19(6(){4.1Y.3M(4)})}});A.b.U.16("m","22",{1s:6(D,C){c E=C.7;c B=A(4).Y("m");E.1g=E.1g||20;E.1j=E.1j||20;B.1f=6(F){3L{5(/25|22/.17(F.g("2F"))||(/25|22/).17(F.g("2F-y"))){f F}F=F.o()}3N(F[0].1Y);f A(j)}(4);B.1c=6(F){3L{5(/25|22/.17(F.g("2F"))||(/25|22/).17(F.g("2F-x"))){f F}F=F.o()}3N(F[0].1Y);f A(j)}(4);5(B.1f[0]!=j&&B.1f[0].2p!="2o"){B.30=B.1f.d()}5(B.1c[0]!=j&&B.1c[0].2p!="2o"){B.2V=B.1c.d()}},1m:6(D,C){c E=C.7;c B=A(4).Y("m");5(B.1f[0]!=j&&B.1f[0].2p!="2o"){5((B.30.8+B.1f[0].2g)-D.1A<E.1g){B.1f[0].V=B.1f[0].V+E.1j}5(D.1A-B.30.8<E.1g){B.1f[0].V=B.1f[0].V-E.1j}}1V{5(D.1A-A(j).V()<E.1g){A(j).V(A(j).V()-E.1j)}5(A(1Z).r()-(D.1A-A(j).V())<E.1g){A(j).V(A(j).V()+E.1j)}}5(B.1c[0]!=j&&B.1c[0].2p!="2o"){5((B.2V.a+B.1c[0].2i)-D.1t<E.1g){B.1c[0].W=B.1c[0].W+E.1j}5(D.1t-B.2V.a<E.1g){B.1c[0].W=B.1c[0].W-E.1j}}1V{5(D.1t-A(j).W()<E.1g){A(j).W(A(j).W()-E.1j)}5(A(1Z).t()-(D.1t-A(j).W())<E.1g){A(j).W(A(j).W()+E.1j)}}}});A.b.U.16("m","2U",{1s:6(D,C){c B=A(4).Y("m");B.1G=[];A(C.7.2U===q?".b-m":C.7.2U).19(6(){c F=A(4);c E=F.d();5(4!=B.e[0]){B.1G.2x({3I:4,t:F.2S(),r:F.37(),8:E.8,a:E.a})}})},1m:6(J,O){c I=A(4).Y("m");c L=O.7.4O||20;c D=O.2y.a,C=D+I.w.t,P=O.2y.8,N=P+I.w.r;2h(c H=I.1G.1o-1;H>=0;H--){c E=I.1G[H].a,B=E+I.1G[H].t,R=I.1G[H].8,M=R+I.1G[H].r;5(!((E-L<D&&D<B+L&&R-L<P&&P<M+L)||(E-L<D&&D<B+L&&R-L<N&&N<M+L)||(E-L<C&&C<B+L&&R-L<P&&P<M+L)||(E-L<C&&C<B+L&&R-L<N&&N<M+L))){2T}5(O.7.3W!="4Y"){c K=Z.1h(R-N)<=20;c Q=Z.1h(M-P)<=20;c G=Z.1h(E-C)<=20;c F=Z.1h(B-D)<=20;5(K){O.k.8=I.1d("p",{8:R-I.w.r,a:0}).8}5(Q){O.k.8=I.1d("p",{8:M,a:0}).8}5(G){O.k.a=I.1d("p",{8:0,a:E-I.w.t}).a}5(F){O.k.a=I.1d("p",{8:0,a:B}).a}}5(O.7.3W!="57"){c K=Z.1h(R-P)<=20;c Q=Z.1h(M-N)<=20;c G=Z.1h(E-D)<=20;c F=Z.1h(B-C)<=20;5(K){O.k.8=I.1d("p",{8:R,a:0}).8}5(Q){O.k.8=I.1d("p",{8:M-I.w.r,a:0}).8}5(G){O.k.a=I.1d("p",{8:0,a:E}).a}5(F){O.k.a=I.1d("p",{8:0,a:B-I.w.t}).a}}}}});A.b.U.16("m","3J",{1s:6(D,C){c B=A(4).Y("m");B.2v=[];A(C.7.3J).19(6(){5(A.Y(4,"3b")){c E=A.Y(4,"3b");B.2v.2x({i:E,3P:E.7.1E});E.59();E.1l("1W",D,B)}})},1C:6(D,C){c B=A(4).Y("m");A.19(B.2v,6(){5(4.i.1P){4.i.1P=0;B.28=q;4.i.28=l;5(4.3P){4.i.7.1E=q}4.i.21(D);4.i.e.1w("55",[D,A.1v(4.i.b(),{54:B.e})],4.i.7.4f);4.i.7.h=4.i.7.3d}1V{4.i.1l("1Q",D,B)}})},1m:6(F,E){c D=A(4).Y("m"),B=4;c C=6(K){c H=K.a,J=H+K.t,I=K.8,G=I+K.r;f(H<(4.13.a+4.d.z.a)&&(4.13.a+4.d.z.a)<J&&I<(4.13.8+4.d.z.8)&&(4.13.8+4.d.z.8)<G)};A.19(D.2v,6(G){5(C.v(D,4.i.50)){5(!4.i.1P){4.i.1P=1;4.i.14=A(B).3c().1I(4.i.e).Y("3b-3I",q);4.i.7.3d=4.i.7.h;4.i.7.h=6(){f E.h[0]};F.24=4.i.14[0];4.i.3a(F,q);4.i.23(F,q,q);4.i.d.z.8=D.d.z.8;4.i.d.z.a=D.d.z.a;4.i.d.o.a-=D.d.o.a-4.i.d.o.a;4.i.d.o.8-=D.d.o.8-4.i.d.o.8;D.1l("4Z",F)}5(4.i.14){4.i.1U(F)}}1V{5(4.i.1P){4.i.1P=0;4.i.28=q;4.i.7.1E=l;4.i.21(F,q);4.i.7.h=4.i.7.3d;4.i.14.1J();5(4.i.3t){4.i.3t.1J()}D.1l("51",F)}}})}});A.b.U.16("m","1R",{1s:6(D,B){c C=A.52(A(B.7.1R.53)).4X(6(F,E){f(T(A(F).g("1b"),10)||B.7.1R.2q)-(T(A(E).g("1b"),10)||B.7.1R.2q)});A(C).19(6(E){4.2a.1b=B.7.1R.2q+E});4[0].2a.1b=B.7.1R.2q+C.1o}})})(3n);(6(A){A.1H("b.15",{2w:6(){4.e.1z("b-15");4.1e=0;4.1x=1;c C=4.7,B=C.1k;C=A.1v(C,{1k:C.1k&&C.1k.4p==4o?C.1k:6(D){f A(D).3A(B)}});4.2A={t:4.e[0].2i,r:4.e[0].2g};A.b.u.1N.2x(4)},1T:{},b:6(B){f{m:(B.14||B.e),h:B.h,k:B.k,2y:B.13,7:4.7,e:4.e}},2u:6(){c B=A.b.u.1N;2h(c C=0;C<B.1o;C++){5(B[C]==4){B.4q(C,1)}}4.e.1y("b-15 b-15-12").3f("15").2n(".15")},1S:6(C){c B=A.b.u.1B;5(!B||(B.14||B.e)[0]==4.e[0]){f}5(4.7.1k.v(4.e,(B.14||B.e))){A.b.U.v(4,"1S",[C,4.b(B)]);4.e.1w("4r",[C,4.b(B)],4.7.1S)}},1M:6(C){c B=A.b.u.1B;5(!B||(B.14||B.e)[0]==4.e[0]){f}5(4.7.1k.v(4.e,(B.14||B.e))){A.b.U.v(4,"1M",[C,4.b(B)]);4.e.1w("4s",[C,4.b(B)],4.7.1M)}},1q:6(E,B){c C=B||A.b.u.1B;5(!C||(C.14||C.e)[0]==4.e[0]){f l}c D=l;4.e.3x(".b-15").4n(".b-m-3e").19(6(){c F=A.Y(4,"15");5(F.7.3K&&A.b.1X(C,A.1v(F,{d:F.e.d()}),F.7.2t)){D=q;f l}});5(D){f l}5(4.7.1k.v(4.e,(C.14||C.e))){A.b.U.v(4,"1q",[E,4.b(C)]);4.e.1w("1q",[E,4.b(C)],4.7.1q);f q}f l},1W:6(C){c B=A.b.u.1B;A.b.U.v(4,"1W",[C,4.b(B)]);5(B){4.e.1w("4m",[C,4.b(B)],4.7.1W)}},1Q:6(C){c B=A.b.u.1B;A.b.U.v(4,"1Q",[C,4.b(B)]);5(B){4.e.1w("4h",[C,4.b(B)],4.7.1Q)}}});A.1v(A.b.15,{1O:{12:l,2t:"1X"}});A.b.1X=6(I,E,J){5(!E.d){f l}c D=(I.13||I.k.S).a,C=D+I.w.t,K=(I.13||I.k.S).8,H=K+I.w.r;c F=E.d.a,B=F+E.2A.t,L=E.d.8,G=L+E.2A.r;4g(J){2E"4j":f(F<D&&C<B&&L<K&&H<G);2j;2E"1X":f(F<D+(I.w.t/2)&&C-(I.w.t/2)<B&&L<K+(I.w.r/2)&&H-(I.w.r/2)<G);2j;2E"4k":f(F<((I.13||I.k.S).a+(I.2K||I.d.z).a)&&((I.13||I.k.S).a+(I.2K||I.d.z).a)<B&&L<((I.13||I.k.S).8+(I.2K||I.d.z).8)&&((I.13||I.k.S).8+(I.2K||I.d.z).8)<G);2j;2E"4t":f((K>=L&&K<=G)||(H>=L&&H<=G)||(K<L&&H>G))&&((D>=F&&D<=B)||(C>=F&&C<=B)||(D<F&&C>B));2j;3U:f l;2j}};A.b.u={1B:2d,1N:[],35:6(D,F){c B=A.b.u.1N;c E=F?F.4D:2d;2h(c C=0;C<B.1o;C++){5(B[C].7.12||(D&&!B[C].7.1k.v(B[C].e,(D.14||D.e)))){2T}B[C].2c=B[C].e.g("3v")!="2X";5(!B[C].2c){2T}B[C].d=B[C].e.d();B[C].2A={t:B[C].e[0].2i,r:B[C].e[0].2g};5(E=="4F"||E=="4G"){B[C].1W.v(B[C],F)}}},1q:6(B,C){c D=l;A.19(A.b.u.1N,6(){5(!4.7){f}5(!4.7.12&&4.2c&&A.b.1X(B,4,4.7.2t)){D=4.1q.v(4,C)}5(!4.7.12&&4.2c&&4.7.1k.v(4.e,(B.14||B.e))){4.1x=1;4.1e=0;4.1Q.v(4,C)}});f D},1m:6(B,C){5(B.7.4H){A.b.u.35(B,C)}A.19(A.b.u.1N,6(){5(4.7.12||4.3X||!4.2c){f}c D=A.b.1X(B,4,4.7.2t);c G=!D&&4.1e==1?"1x":(D&&4.1e==0?"1e":2d);5(!G){f}c F;5(4.7.3K){c E=4.e.2Z(".b-15:4B(0)");5(E.1o){F=A.Y(E[0],"15");F.3X=(G=="1e"?1:0)}}5(F&&G=="1e"){F.1e=0;F.1x=1;F.1M.v(F,C)}4[G]=1;4[G=="1x"?"1e":"1x"]=0;4[G=="1e"?"1S":"1M"].v(4,C);5(F&&G=="1x"){F.1x=0;F.1e=1;F.1S.v(F,C)}})}};A.b.U.16("15","2C",{1W:6(C,B){A(4).1z(B.7.2C)},1Q:6(C,B){A(4).1y(B.7.2C)},1q:6(C,B){A(4).1y(B.7.2C)}});A.b.U.16("15","2D",{1S:6(C,B){A(4).1z(B.7.2D)},1M:6(C,B){A(4).1y(B.7.2D)},1q:6(C,B){A(4).1y(B.7.2D)}})})(3n);',62,321,'||||this|if|function|options|top||left|ui|var|offset|element|return|css|helper|instance|document|position|false|draggable|containment|parent|relative|true|height||width|ddmanager|call|helperProportions|||click|||||||||||||||||||absolute|parseInt|plugin|scrollTop|scrollLeft|offsetParent|data|Math||cssPosition|disabled|positionAbs|currentItem|droppable|add|test|margins|each|body|zIndex|overflowX|convertPositionTo|isover|overflowY|scrollSensitivity|abs|fixed|scrollSpeed|accept|propagate|drag|cursorAt|length|grid|drop|_mouseStarted|start|pageX|widgetName|extend|triggerHandler|isout|removeClass|addClass|pageY|current|stop|opacity|revert|originalPosition|snapElements|widget|appendTo|remove|cursor|bind|out|droppables|defaults|isOver|deactivate|stack|over|plugins|mouseDrag|else|activate|intersect|parentNode|window||mouseStop|scroll|mouseStart|target|auto|undefined|apply|cancelHelperRemoval|axis|style|attr|visible|null|setData|unselectable|offsetHeight|for|offsetWidth|break|mouseUp|cssCache|prototype|unbind|HTML|tagName|min|_mouseDelayMet|div|tolerance|destroy|sortables|init|push|absolutePosition|browser|proportions|handle|activeClass|hoverClass|case|overflow|iframeFix|cancel|_mouseDownEvent|delay|clickOffset|px|max|getData|distance|clear|uiHash|original|outerWidth|continue|snap|overflowXOffset|fn|none|generatePosition|parents|overflowYOffset|borderLeftWidth|borderTopWidth|_zIndex|_opacity|prepareOffsets|_cursor|outerHeight|typeof|string|mouseCapture|sortable|clone|_helper|dragging|removeData|_mouseMoveDelegate|_mouseUpDelegate|mouseDistanceMet|msie|mouse|mouseDelayMet|split|jQuery|widgetBaseClass|mouseDown|mouseDestroy|_mouseUnselectable|marginRight|placeholder|mouseMove|display|isFunction|find|5000px|round|is|mouseup|mousemove|scrollHeight|marginBottom|dropBehaviour|bottom|class|item|connectToSortable|greedy|do|removeChild|while|on|shouldRevert|mouseInit|arguments|get|right|default|MozUserSelect|snapMode|greedyChild|filter|andSelf|resizable|scrollWidth|new|started|marginTop|_mouseDelayTimer|disable|enable|mozilla|preventDefault|which|button|setTimeout|mousedown|marginLeft|receive|switch|dropdeactivate|enableSelection|fit|pointer|disableSelection|dropactivate|not|Function|constructor|splice|dropover|dropout|touch|catch|transparent|rgba|backgroundImage|block|in|gen|eq|backgroundColor|type|try|dragstart|sortactivate|refreshPositions|slice|off|001|fff|1000|DragDropIframeFix|snapTolerance|Array|background|iframe|valid|invalid|animate|500|input|sort|inner|toSortable|containerCache|fromSortable|makeArray|group|sender|sortreceive|getter|outer|hasScroll|refreshItems|inArray'.split('|'),0,{}))


/**
 * Ingrid : JQuery Datagrid Control
 * @jarod : 2 bug fixed
 * Copyright (c) 2007 Matthew Knight (http://www.reconstrukt.com http://slu.sh)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * @requires jQuery v1.2
 *
 * Revision: $Id: jquery.ingrid.js,v 1.00 2007/10/02 09:00:00 mknight Exp $
 * Version: .1
 *
 * Some notes... 
 * using dimensions plugin, the call to width() temporarily styles the element to 
 * have 0px padding, border, margin, measures width() -- then removes these inline styles.
 * This sometimes causes the element to BLINK - as all those margins/widths are updated!
 *
 * removed dependency on dimensions plugin
 *
 * need to support a "row selection" model - either single-select, or multi-select (checkboxes)
 *
 * need to implement loading JSON data
 *
 */

jQuery.fn.ingrid = function(o){

	var cfg = {
		height: 200, 										// height of our datagrid (scrolling body area)
		
		savedStateLoad : false,					// when Ingrid is initialized, should it load data from a previously saved state?
		initialLoad : false,						// when Ingrid is initialized, should it load data immediately?

		colWidths: [225,225,225,225],		// width of each column
		minColWidth: 60,								// minimum column width
		headerHeight: 30,								// height of our header
		headerClass: 'grid-header-bg',	// header bg
		resizableCols: true,						// make columns resizable via drag + drop
		
		gridClass: 'datagrid',							// class of head & body
		rowClasses: [],
		colClasses: [],													// array of classes : i.e. ['','grid-col-2','','']
		rowHoverClass: 'grid-row-hover',				// hovering over a row? use this class
		rowSelection: true,											// allow row selection?
		rowSelectedClass: 'grid-row-sel',				// hovering over a row? use this class
		onRowSelect: function(tr, selected){},	// function to call when row is clicked
		
		/* sorting */
		sorting: true,
		colSortParams: [],								// value to pass as sort param when header clicked (i.e. '&sort=param') ex: ['col1','col2','col3','col4']
		sortAscParam: 'asc',							// param passed on ascending sort (i.e. '&dir=asc)
		sortDescParam: 'desc',						// param passed on ascending sort (i.e. '&dir=desc)
		sortedCol: 'col1',								// current data's sorted column (can be a key from 'colSortParams', or an int 0-n (for n columns)
		sortedColDir: 'desc',							// current data's sorted dorections
		sortDefaultDir: 'desc',						// on 1st click, sort tihs direction
		sortAscClass: 'grid-sort-asc',		// class for ascending sorted col
		sortDescClass: 'grid-sort-desc',	// class for descending sorted col
		sortNoneClass: 'grid-sort-none',	// ... not sorted? use this class
		
		/* paging */
		paging: true,											// create a paging toolbar
		pageNumber: 1,
		recordsPerPage: 0,
		totalRecords: 0,
		pageToolbarHeight: 25,
		pageToolbarClass: 'grid-page-toolbar',
		pageStartClass: 'grid-page-start',
		pagePrevClass: 'grid-page-prev',
		pageInfoClass: 'grid-page-info',
		pageInputClass: 'grid-page-input',
		pageNextClass: 'grid-page-next',
		pageEndClass: 'grid-page-end',
		pageLoadingClass: 'grid-page-loading',
		pageLoadingDoneClass: 'grid-page-loading-done',
		pageViewingRecordsInfoClass: 'grid-page-viewing-records-info',

		/* ajax stuff */
		url: 'remote.html',							// url to fetch data
		type: 'GET',										// 'POST' or 'GET'
		dataType: 'html',								// 'html' or 'json' - expected dataType returned
		extraParams: {},								// a map of extra params to send to the server 				
		loadingClass: 'grid-loading',		// loading modalmask div
		loadingHtml: '<div>&nbsp;</div>',			
		
		/* should seldom change */
		resizeHandleHtml: '',									// resize handle html + css
		resizeHandleClass: 'grid-col-resize',
		scrollbarW: 17,									// width allocated for scrollbar
		columnIDAttr: '_colid',					// attribute name used to groups TDs in columns
		ingridIDPrefix: '_ingrid',			// prefix used to create unique IDs for Ingrid
		
		/* cookie, for saving state */
		cookieExpiresDays: 360,
		cookiePath: '/',
		
		/* not yet implemented */
		minHeight: 100,
		resizableGrid: true,
		dragDropCols: true,
		sortType: 'server|client|none'
		
	};
	jQuery.extend(cfg, o);

	// break into 2 tables: header, body.
	// create header table
	var cols = new Array();
	var h = jQuery('<table cellpadding="0" cellspacing="0"></table>')
					.html(this.find('thead'))
					.addClass(cfg.gridClass)
					.addClass(cfg.headerClass)
					.height(cfg.headerHeight)
					.extend({
						cols : cols
					});
	// initialize columns
	h.find('th').each(function(i){
														 
		// init width
		jQuery(this).width(cfg.colWidths[i]);
		
		// put column text in a div, make unselectable
		var col_label = jQuery('<div />')
										.html(jQuery(this).html())
										.css({float: 'left', display: 'block'})
										.css('-moz-user-select', 'none')
										.css('-khtml-user-select', 'none')
										.css('user-select', 'none')
										.attr('unselectable', 'on');

		// column sorting?
		// @jarod column 0 isn't sort
		if (cfg.sorting && i!=0) {
			
			var key = cfg.colSortParams[i] ? cfg.colSortParams[i] : i;
			//alert(i);
			// is this column the default sorted column?
			var cls = (key == cfg.sortedCol || i == cfg.sortedCol) ? 
									( cfg.sortedColDir == cfg.sortAscParam ? cfg.sortAscClass : cfg.sortDescClass ) :
									( cfg.sortNoneClass );

			col_label.addClass(cls).click(function(){
				var dir = col_label.hasClass(cfg.sortNoneClass) ? 
										cfg.sortDefaultDir : ( col_label.hasClass(cfg.sortAscClass) ? cfg.sortDescParam : cfg.sortAscParam );

				var params = { sort : key, dir : dir };					
				if (p) jQuery.extend(params, { page : p.getPage() } );
				
				g.load( params, function(){						
					var cls = col_label.hasClass(cfg.sortNoneClass) ? 
											( cfg.sortDefaultDir == cfg.sortAscParam ? cfg.sortAscClass : cfg.sortDescClass ) :
											( col_label.hasClass(cfg.sortAscClass) ? cfg.sortDescClass : cfg.sortAscClass );

					g.getHeaders(function(col){
					// @jarod pb // A OPTIMISER
						jQuery("th.sort").find("div:first").addClass(cfg.sortNoneClass).removeClass(cfg.sortAscClass).removeClass(cfg.sortDescClass);
					});
					col_label.removeClass(cfg.sortAscClass).removeClass(cfg.sortDescClass).addClass(cls).removeClass(cfg.sortNoneClass);

				});
			});
		}
		
		// replace contents of <th>
		jQuery(this).html(col_label);
		
		// bind an event to easily resize columns
		jQuery(this).bind('resizeColumn', {col_num : i}, function(e, w){
			jQuery(this).width(w);				
			// set body cells to this width
			g.resize();
			g.getColumn(e.data.col_num).each(function(){
				jQuery(this).width(w);
			});
		});
		
		// append resize handle?
		if (cfg.resizableCols) {
			// make column headers resizable
			var handle = jQuery('<div />').html(cfg.resizeHandleHtml == '' ? '-' : cfg.resizeHandleHtml).addClass(cfg.resizeHandleClass);
			handle.bind('mousedown', function(e){
				// start resize drag
				var th 		= jQuery(this).parent();
				var left  = e.clientX;
				z.resizeStart(th, left);
			});
			jQuery(this).append(handle);
		}
	});
	
	// create body table. surround body with container div for scrolling
	// setting width on first row keeps it from "blinking"
	var row = this.find('tr:first')
	jQuery(row).find('td').each(function(i){
		jQuery(this).width( cfg.colWidths[i] )								
	});
	var b = jQuery('<div />')
					.html( jQuery('<table cellpadding="0" cellspacing="0"></table>').html( this.find('tbody') ).width( h.width() ).addClass(cfg.gridClass) )
					.css('overflow', 'hidden') /* @ jarod */
					.height(cfg.height);
			
	
	// resizable cols?
	// if so create a vertical resize divider, with unique ID
	if (cfg.resizableCols) {
		var z_sel = 'vertical-resize-divider' + new Date().getTime();
		var z	= jQuery('<div id="' + z_sel + '"></div>')
						.css({
							backgroundColor: '#ababab', 
							height: (cfg.headerHeight + cfg.height),
							width: '4px',
							position: 'absolute',
							zIndex: '10',
							display: 'block'
						})
						.extend({
							resizeStart : function(th, eventX){
								// this is fired onmousedown of the column's resize handle 						
								var pos	= th.offset();
								jQuery(this).show().css({
									top: pos.top,
									left: eventX
								})
								// when resizing, bind some listeners for mousemove & mouseup events
								jQuery('body').bind('mousemove', {col : th}, function(e){		
									// on mousemove, move the vertical-resize-divider
									var th 		= e.data.col;
									var pos		= th.offset();
									var col_w	= e.clientX - pos.left;
									// make sure cursor isn't trying to make column smaller than minimum
									if (col_w > cfg.minColWidth) {
										jQuery('#' + z_sel).css('left', e.clientX);										
									}																		
								})
								jQuery('body').bind('mouseup', {col : th}, function(e){
									// on mouseup, 
									// 1.) unbind resize listener events from body
									// 2.) hide the vertical-resize-divider
									// 3.) trigger the resize event on the column
									jQuery(this).unbind('mousemove').unbind('mouseup');
									jQuery('#' + z_sel).hide();
									var th 		= e.data.col;
									var pos		= th.offset();
									var col_w	= e.clientX - pos.left;
									if (col_w > cfg.minColWidth) {
										th.trigger('resizeColumn', [col_w]);
									} else {
										th.trigger('resizeColumn', [cfg.minColWidth]);
									}
								})
							}
						});
	}
	// paging?
	// if so create a paging toolbar
	if (cfg.paging) {
	
		// create a paging toolbar
		var totr  = cfg.recordsPerPage > 0 ? cfg.recordsPerPage : b.find('tr').length;
		
		// total records viewing message (if we know total records)
		// total record count might not be passed in config, it's sometimes an expensive hit to the DB
		var pv;
		if (cfg.totalRecords > 0) {
		
			pv = jQuery('<div />')
						.addClass(cfg.pageViewingRecordsInfoClass)
						.extend({
							updateViewInfo : function(loaded_rows, page){
							//alert(loaded_rows);
							/* @jarod (bug fixed) loaded_rows => cfg.recordsPerPage */
								var _start = ( (cfg.recordsPerPage * (page - 1) + 1) );
								var _end   = ( (cfg.recordsPerPage * page) > cfg.totalRecords ? cfg.totalRecords : loaded_rows * page );
								this.html('Musiques ' + _start + ' - ' + _end + ' / ' + cfg.totalRecords);
								return this;
							}
						});
			// update the "viewing x of y" record info
			pv.updateViewInfo(totr, cfg.pageNumber);
		}
		
		// create our paging control container
		var p 		= jQuery('<div />')
								.addClass(cfg.pageToolbarClass)
								.height(cfg.pageToolbarHeight)
								.width(b.width())
								.extend({										
										setPage : function(p){
											var input = this.find('input.' + cfg.pageInputClass);
											pload.removeClass(cfg.pageLoadingDoneClass);
											g.load( {page : p}, function(){
												input.val(p);
												if (cfg.totalRecords > 0) {
													var totr = b.find('tr').length;
													pv.updateViewInfo(totr, p);
												}
												pload.addClass(cfg.pageLoadingDoneClass);
											});
											return this;
										},
										getPage : function(){
											var p = Number(this.find('input.' + cfg.pageInputClass).val());
											return p;
										}
								});
	
		// start page button
		var pb1		= jQuery('<span>&laquo;</span>').addClass(cfg.pageStartClass).click(function(){
		              /* @jarod test conditionnel rajouté */
				          var _p = p.getPage();																															
									if (_p > 1) {
										p.setPage(1);
									}										

								});
	
		// prev page button
		var pb2		= jQuery('<span>&lt;</span>').addClass(cfg.pagePrevClass).click(function(){
									var _p = p.getPage();																															
									if (_p > 1) {
										_p--;
										p.setPage(_p);
									}										
								});
	
		// next page button
		if (cfg.totalRecords > 0) {
			var totp = Math.ceil(cfg.totalRecords / totr);
			//alert("test");
		}
		var pb3		= jQuery('<span>&gt;</span>').addClass(cfg.pageNextClass).click(function(){
									var _p = p.getPage(); _p++;
									if (totp) {
										if (_p <= totp) p.setPage(_p);
									} else {
										p.setPage(_p);
									}
								});
		
		// loading indicator
		var pload	= jQuery('<div />').addClass(cfg.pageLoadingClass).addClass(cfg.pageLoadingDoneClass);
		
		// page field & form
		var pfld  = jQuery('<input type="text" value="' + cfg.pageNumber + '"/>').addClass(cfg.pageInputClass);
		var pinfo = jQuery('<div />')
								.addClass(cfg.pageInfoClass)
								.append(pfld);
		var pform = jQuery('<form></form>').append(pinfo).submit(function(){
									var _p = parseInt(p.getPage());
									if (_p) {
										if (totp) {
											if (_p <= totp) p.setPage(_p);
										} else if (_p > 0) {
											p.setPage(_p);
										}
									} else {
										alert('Please Enter a Valid Page Number.');
									}
									return false;
								});
		
		// last page button & info (if we know total records)
		var pb4;
		if (cfg.totalRecords > 0) {
		
			pinfo.html('Page ' + pinfo.html() + ' / <span id="maxPageGrid">' + totp +'</span>');
			var pb4		= jQuery('<span>&raquo;</span>').addClass(cfg.pageEndClass).click(function(){
			              /* @jarod fixed bug _p++ deleted */
										var _p = p.getPage(); 
										if (totp) {
											 if (_p < totp){ p.setPage(totp); }
											 //p.setPage(totp); 
										}
									});
		} else {
			pinfo.html('Page ' + pinfo.html());
		}
		
		p.append(pb1).append(pb2).append(pform).append(pb3).append(pb4).append(pload).append(pv);
	}

	// create a container div to for our main grid object
	// append & extend grid {g} with header {h}, body {b}, paging {p}, resize handle {z}
	//var p2 = p.clone(); + un append(p2) avec p2: P2 pr afficher la barre en haut
	var g = jQuery('<div />').append(h).append(b).append(p).extend({
		h : h,
		b : b
	});
	if (cfg.paging) {
		g.append(p).extend({ p : p });
	}
	if (cfg.resizableCols) {
		g.append(z.hide()).extend({ z : z });
	}

	// create some other piece-parts, like
	// ...a gap filler to fill gap over scrollport		
	var gap = jQuery('<div />').width(cfg.scrollbarW).addClass(cfg.headerClass).height(cfg.headerHeight).css({
		position: 'absolute',
		zIndex: '0',
		display: 'none' /* @jarod */
	}).appendTo(g);
	// ...a loading modal mask

	var modalmask = jQuery('<div />').html(cfg.loadingHtml).addClass(cfg.loadingClass).css({
		position: 'absolute',		
		zIndex: '1000'
	}).appendTo(g).hide();
	


	// create methods on our grid object
	g.extend({
		load : function(params, cb, total) {
			var data = jQuery.extend(cfg.extraParams, params);
			if(total)
			{
			  totr  = cfg.recordsPerPage > 0 ? cfg.recordsPerPage : b.find('tr').length;
			  totp = Math.ceil(total / totr);
        cfg.totalRecords = total;

		    if (cfg.totalRecords > 0) {
		    //alert('Bientot Dispo');
			
								    var _start = ( (cfg.recordsPerPage * (cfg.pageNumber - 1) + 1) );
								    var _end   = ( (cfg.recordsPerPage * cfg.pageNumber) > cfg.totalRecords ? cfg.totalRecords : totr * cfg.pageNumber );
								    jQuery('.'+cfg.pageViewingRecordsInfoClass).html('Musiques ' + _start + ' - ' + _end + ' / ' + cfg.totalRecords);
								    jQuery("#maxPageGrid").html(totp);

		    }
		    
			  	
			}
			/*
			alert(this + ' ...is jQuery')
			alert(this[0] + ' ...is the div, id="' + this.attr('id') + '"')
			*/
			
			// show loading canvas
			modalmask.width("580").show();
			
			
			// save selected rows
			g.saveSelectedRows();
			
			jQuery.ajax({
				type: cfg.type.toUpperCase(),
				url: cfg.url,
				data: data,
				success: function(result){						
					// for JSON return type
					if (cfg.dataType == 'json') {
						var rows  = eval( '(' + result + ')' );
						alert('json = ' + rows);
					}
					// for HTML (Table) return type
					if (cfg.dataType == 'html') {
						var $tbl = jQuery(result);
						var row  = $tbl.find('tr:first');
						if ( jQuery(row).find('td').length == cfg.colWidths.length ) {
							// setting width on first row keeps it from "blinking"
							jQuery(row).find('td').each(function(i){
								// don't use width() - makes column headers jitter																									 
								// g.getHeader(i).width()
								jQuery(this).width( g.getHeader(i).css('width') )								
							});
							// now swap the tbody's
							b.find('tbody').html($tbl.find('tbody').html());
							g.initStylesAndWidths();
							
							// remember the last loaded state for this grid?
							g.saveState(data);
							
						} else if (row.length < 1) {
							// no rows returned
							alert('Error: No Rows Returned.');
						} else {
							// inconsistent results... too many (or too few) columns returned
							alert('Error: Total columns returned [' + $tbl.find('tbody tr:first td').length + '] do not match Ingrid ['+ cfg.colWidths.length +'].');
						}
					}
					if (cb) cb();
				},
				error: function(){
					alert('Error: Could not load "' + cfg.url + '". Please check the URL and try again. ');
				},
				complete: function(){
					modalmask.hide();
				}
			});
			return this;
		},
		
		// returns JSON
		getState : function() {
			
			/*
			alert(this + ' ...is jQuery')
			alert(this[0] + ' ...is the div, id="' + this.attr('id') + '"')
			*/
			var props = {
				url : 'nothing'				
			}
			return props;
		},
		
		saveState : function(data){

			// how can we deserialize the 'data' object from JSON, to a string, like: "{page:3}"
			//   we could then save this JSON string into a cookie, 
			//   and eval() it back out again when initStylesAndWidths() is called
			
			/*
			I think I need the JSON lib?
			JSON.toString(json_object)
			
			so, like
			JSON.toString(props)
			
			would be nice to combine JSON & jQuery's cookie plugin, call it something like "cache"
			which would let you serialize JSON objects as strings, for storage in cookies, and eval() them back out from a cookie later
			
			so you could call like: 
			
				jQuery.toCache(json_object, 'key')
				json_object = eval( jQuery.fromCache('key') );
				jQuery.clearCache('key')
				
			...u could get creative and call it "save", "remember", "recall", "read", "store", "forget" or whatever
			*/
			
			if (jQuery.cookie) {
				// save page #, column sort & dir
				var g_id  		= this.attr('id');
				var param_str = 'page=' + data.page + ',sort=' + data.sort + ',dir=' + data.dir;
				jQuery.cookie(g_id, param_str, {expires: cfg.cookieExpiresDays, path: cfg.cookiePath});
			}
			
			/*
			props.url = data;
			alert( data.toString() );
			alert( props.toString() );
			*/
			
		},
		
		saveSelectedRows : function() {
			if (jQuery.cookie) {
				var row_ids		= g.getSelectedRowIds();
				if (row_ids.length > 0) {
					jQuery.cookie( this.attr('id') + '_rows', row_ids.join(','), {expires: cfg.cookieExpiresDays, path: cfg.cookiePath});
				}				
			}
		},
		
		// returns <th> els
		getHeaders : function(cb) {
			var ths = this.find('th');
			if (cb) {
				ths.each(function(){
					cb(jQuery(this));							 
				});
				return this;
			} else {
				return ths;
			}
		},
		
		// returns single <th> el
		getHeader : function(i, cb) {
			var th = this.find('th').slice(i, i+1);
			if (cb) {
				cb(jQuery(this));
				return this;
			} else {
				return th;
			}
		},
		
		// returns <td> els in column i
		getColumn : function(i, cb) {
			var tds = this.find("tbody td[@" + cfg.columnIDAttr + "='" + i + "']");
			if (cb) {
				tds.each(function(){
					cb(jQuery(this));							 
				});
				return this;
			} else {
				return tds;							 
			}
		},
		
		// returns <tr> els
		getRows : function(cb) {
			var trs = this.find("tbody tr");
			if (cb) {
				trs.each(function(){
					cb(jQuery(this));							 
				});
				return this;
			} else {
				return trs;							 
			}
		},
				
		// returns <tr> els
		getSelectedRows : function() {
			return this.find("tbody tr[@_selected='true']");
		},
		
		// returns an array of IDs (current view)
		getSelectedRowIds : function() {
			var rows 			= g.getSelectedRows();
			var row_ids		= [];
			for (i=0; i<rows.length; i++) {
				if ( jQuery(rows[i]).attr('id') ) row_ids.push( jQuery(rows[i]).attr('id') );
			}
			return row_ids;
		},
		
		// returns an array of IDs (saved in cookie)		
		getSavedRowIds : function() {
			var row_ids = [];
			if (jQuery.cookie) {
				var str_ids = jQuery.cookie( this.attr('id') + '_rows' );
				if (str_ids) row_ids = str_ids.split(',');
			}			
			return row_ids;
		},
		
		resize : function() {
			// set body table width based on header table 
			// minimize calls to width() and offset()
			var outer_w = h.width() + cfg.scrollbarW;
			b.width(outer_w);

			if (p) p.width(outer_w);
			
			if (gap) {
				var pos = h.offset();
				gap.css('left', outer_w - cfg.scrollbarW + pos.left).css('top', pos.top);
			}
		},
		
		initStylesAndWidths : function() {
			
			// alert('setting styles and widths')
			
			var colWidths = new Array();
			this.getHeaders().each(function(i){
				// don't use width() - makes column headers jitter
				// colWidths[i] = jQuery(this).width();
				colWidths[i] = jQuery(this).css('width');
			});

			// make one pass of the grid, 
			// initialize properties on rows & columns
			var str_ids = '|' + g.getSavedRowIds().join('|') + '|';
			this.getRows().each(function(r){
				
				// custom row styles (striping, etc) & hover
				if (cfg.rowClasses.length > 0) {
					var cursor = (r == 0 ? 0 : r % cfg.rowClasses.length);
					if (cfg.rowClasses[cursor] != '') {
						// custom row class
						jQuery(this).addClass(cfg.rowClasses[cursor]);							
					}
					if (cfg.rowHoverClass != '') {
					
					  alert('hover class');
						// hover class
						jQuery(this).hover(
							function() { if (jQuery(this).attr('_selected') != 'true') jQuery(this).removeClass(cfg.rowClasses[cursor]).addClass(cfg.rowHoverClass); },
							function() { if (jQuery(this).attr('_selected') != 'true') jQuery(this).removeClass(cfg.rowHoverClass).addClass(cfg.rowClasses[cursor]); }
						);
					}
					// bind row selection behaviors
					if (cfg.rowSelection == true) {
						jQuery(this).click(function(){
							if (jQuery(this).attr('_selected')) {
								jQuery(this).attr('_selected') == 'true' ?
									jQuery(this).attr('_selected', 'false').removeClass(cfg.rowSelectedClass) :
									jQuery(this).attr('_selected', 'true').addClass(cfg.rowSelectedClass);
								
							} else {
								jQuery(this).attr('_selected', 'true').addClass(cfg.rowSelectedClass);
							}
							if (cfg.onRowSelect) {
								cfg.onRowSelect(this, (jQuery(this).attr('_selected') == 'true' ? true : false) );
							}
						});
						// was this row Id previously selected?
						if (str_ids.indexOf( '|' + jQuery(this).attr('id') + '|' ) != -1) {
							jQuery(this).attr('_selected', 'true').addClass(cfg.rowSelectedClass);
						}
					}
				}
				
				// setup column IDs & classes on row's cells
				jQuery(this).find('td').each(function(i){
					// column IDs & width
					// wrap the cell text in a div with overflow hidden, so cells aren't stretched wider by long text
					var txt = jQuery(this).html();
					jQuery(this).attr(cfg.columnIDAttr, i)
											.width(colWidths[i])
											.html( jQuery('<div />').html(txt).css('overflow', 'hidden') );
					// column colors
					if (cfg.colClasses.length > 0) {
						if (cfg.colClasses[i] != '') {
							jQuery(this).addClass(cfg.colClasses[i]);
						}
					}
				});
			});
		}			
	});
	
	// don't break the chain
	// return a modified & extended jQ table object.
	// here,
	// 	this     ...is jQuery
	// 	this[0]  ...is a table
	
	/*
			alert(this + ' ...is jQuery')
			alert(this[0] + ' ...is a table')
			alert(this.length + ' = total tables matched to selector')
	*/

	return this.each(function(tblIter){
		// fires for each table[tblIter].
		// for each one,
		// 	this     ...is a table

		/*
		alert(this + ' ...is a table [' + tblIter + '] , id="' + jQuery(this).attr('id') + '"')
		alert(g[0] + ' ...is the grid div html');
		*/

		// append to doc
		var g_id = 	cfg.ingridIDPrefix + '_' + jQuery( this ).attr('id') + '_' + tblIter;
		g.attr( 'id', g_id );
		jQuery( this ).replaceWith( g[0] )

		// init grid styles, etc
		g.initStylesAndWidths();
		
		// sync grid size to headers
		g.resize();
		
		// place the mask accordingly
		modalmask.width( h.width() + cfg.scrollbarW ).height( b.height()).css({
			top: b.offset().top,
			left: b.offset().left
		});

		// load it up?
		if (cfg.savedStateLoad && jQuery.cookie) {
			var param_str = jQuery.cookie(g_id);
			if (!param_str) {
				g.load();
				cfg.initialLoad = false;
			} else {
				// we have a saved state for this grid_id
				var pairs  	= param_str.split(',');
				var params 	= {};
				var hash  	= [];
				for (i=0; i<pairs.length; i++) {
					var prop = pairs[i].split('=');
					hash[prop[0]] = prop[1];
				}
				if (hash['page'].toLowerCase() != 'undefined' && cfg.paging) {
					params.page = hash['page'];
					p.find('input.' + cfg.pageInputClass).val(params.page);
				}
				if (hash['sort'].toLowerCase() != 'undefined' && 
						hash['dir'].toLowerCase() != 'undefined') {
					
					params.sort = hash['sort'];
					params.dir 	= hash['dir'];
					var colid = params.sort;
					// perhaps the sort param is a key, if so, get the id for that key
					if (cfg.colSortParams.length > 0) {
						for (i=0; i<cfg.colSortParams; i++) {
							if (cfg.colSortParams[i] == params.sort) {
								colid = i;
								break;
							}
						}
					}
					
					// set appropriate style on sorted column
					// perhaps we should bind an event to the column <th>, like setSort()?
					g.getHeaders(function(th){
						th.find('div:first').addClass(cfg.sortNoneClass).removeClass(cfg.sortAscClass).removeClass(cfg.sortDescClass);
					});
					// all this prevents the column from being style-less (and blinking)
					g.getHeader(parseInt(colid)).find('div:first').addClass(cfg.sortNoneClass)
																												.removeClass(cfg.sortAscClass).removeClass(cfg.sortDescClass)
																												.addClass( params.dir == cfg.sortAscParam ? cfg.sortAscClass : cfg.sortDescClass )
																												.removeClass(cfg.sortNoneClass);
				}					
				if ( params.page || params.sort || params.dir ) {
					g.load(params);
					cfg.initialLoad = false;
				}
			}
		}
		
		if (cfg.initialLoad) {
			g.load();
		}
		else {
		  //@jarod fix bug webkit
		  modalmask.width("580").show();
	    modalmask.hide(); 
	 }

	}).extend({

		g : g

	});

};



/*
 * jQuery blockUI plugin
 * Version 2.10 (10/22/2008)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
    return;
}

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// plugin method for blocking element content
$.fn.block = function(opts) {
    return this.each(function() {
        if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
        if ($.browser.msie) 
            this.style.zoom = 1; // force 'hasLayout'
        install(this, opts);
    });
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
    return this.each(function() {
        remove(this, opts);
    });
};

$.blockUI.version = 2.09; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
    // message displayed when blocking (use null for no message)
    message:  '<h2>Chargement en cours...</h2><img src="loading.gif" />',
    
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: { 
        padding:        0,
        margin:'-50px 0 0 -125px',
        width:          '250px', 
        top:            '50%', 
        left:           '50%', 
        textAlign:      'center', 
        color:          '#4BDEF9', 
        border:         '3px solid #aaa',
        backgroundColor:'#161F29',
        cursor:         'wait',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        height:'auto',
        'padding-top':'8px',
        'padding-bottom':'8px',
        'font-size':    '0.9em'
    },
    
    // styles for the overlay
    overlayCSS:  { 
        backgroundColor:'#000', 
        opacity:        '0.9' 
    },
    
    // z-index for the blocking overlay
    baseZ: 4000,
    
    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,
    
    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,
    
    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,
    
    // fadeOut time in millis; set to 0 to disable fadeout on unblock
    fadeOut:  400,
    
    // if true, focus will be placed in the first available input field when
    // page blocking
    focusInput: true,
    
    // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
    applyPlatformOpacityRules: false,
    
    // callback method invoked when unblocking has completed; the callback is
    // passed the element that has been unblocked (which is the window object for page
    // blocks) and the options that were passed to the unblock call:
    //     onUnblock(element, options)
    onUnblock: null,
    
    // don't ask (if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493)
    quirksmodeOffsetHack: 4
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
    var full = (el == window);
    var msg = opts && opts.message !== undefined ? opts.message : undefined;
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
    var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
    msg = msg === undefined ? opts.message : msg;

    // remove the current block (if there is one)
    if (full && pageBlock) 
        remove(window, {fadeOut:0}); 
    
    // if an existing element is being used as the blocking content then we capture
    // its current place in the DOM (and current display style) so we can restore
    // it when we unblock
    if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
        var node = msg.jquery ? msg[0] : msg;
        var data = {};
        $(el).data('blockUI.history', data);
        data.el = node;
        data.parent = node.parentNode;
        data.display = node.style.display;
        data.position = node.style.position;
        data.parent.removeChild(node);
    }
    
    var z = opts.baseZ;
    
    // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
    // layer1 is the iframe layer which is used to supress bleed through of underlying content
    // layer2 is the overlay layer which has opacity and a wait cursor
    // layer3 is the message content that is displayed while blocking
    
    var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:'+ z++ +';border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
    var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ z++ +';cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
    var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');

    // if we have a message, style it
    if (msg) 
        lyr3.css(css);

    // style the overlay
    if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))) 
        lyr2.css(opts.overlayCSS);
    lyr2.css('position', full ? 'fixed' : 'absolute');
    
    // make iframe layer transparent in IE
    if ($.browser.msie) 
        lyr1.css('opacity','0.0');

    $([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
    
    // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
    var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
 /*   if (ie6 || expr) {
        // give body 100% height
        if (full && opts.allowBodyStretch && $.boxModel)
            $('html,body').css('height','100%');

        // fix ie6 issue when blocked element has a border width
        if ((ie6 || !$.boxModel) && !full) {
            var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
            var fixT = t ? '(0 - '+t+')' : 0;
            var fixL = l ? '(0 - '+l+')' : 0;
        }

        // simulate fixed position
        $.each([lyr1,lyr2,lyr3], function(i,o) {
            var s = o[0].style;
            s.position = 'absolute';
            if (i < 2) {
                full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
                     : s.setExpression('height','this.parentNode.offsetHeight + "px"');
                full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                if (fixL) s.setExpression('left', fixL);
                if (fixT) s.setExpression('top', fixT);
            }
            else if (opts.centerY) {
                if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                s.marginTop = 0;
            }
        });
    }*/
    
    // show the message
    lyr3.append(msg).show();
    if (msg && (msg.jquery || msg.nodeType))
        $(msg).show();

    // bind key and mouse events
    bind(1, el, opts);
        
    if (full) {
        pageBlock = lyr3[0];
        pageBlockEls = $(':input:enabled:visible',pageBlock);
        if (opts.focusInput)
            setTimeout(focus, 20);
    }
    else
        center(lyr3[0], opts.centerX, opts.centerY);
};

// remove the block
function remove(el, opts) {
    var full = el == window;
    var data = $(el).data('blockUI.history');
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    bind(0, el, opts); // unbind events
    var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);
    
    if (full) 
        pageBlock = pageBlockEls = null;

    if (opts.fadeOut) {
        els.fadeOut(opts.fadeOut);
        setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
    }
    else
        reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
    els.each(function(i,o) {
        // remove via DOM calls so we don't lose event handlers
        if (this.parentNode) 
            this.parentNode.removeChild(this);
    });
    if (data && data.el) {
        data.el.style.display = data.display;
        data.el.style.position = data.position;
        data.parent.appendChild(data.el);
        $(data.el).removeData('blockUI.history');
    }
    if (typeof opts.onUnblock == 'function')
        opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
    var full = el == window, $el = $(el);
    
    // don't bother unbinding if there is nothing to unbind
    if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) 
        return;
    if (!full) 
        $el.data('blockUI.isBlocked', b);
        
    // bind anchors and inputs for mouse and key events
    var events = 'mousedown mouseup keydown keypress click';
    b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//    var $e = $('a,:input');
//    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
    // allow tab navigation (conditionally)
    if (e.keyCode && e.keyCode == 9) {
        if (pageBlock && e.data.constrainTabKey) {
            var els = pageBlockEls;
            var fwd = !e.shiftKey && e.target == els[els.length-1];
            var back = e.shiftKey && e.target == els[0];
            if (fwd || back) {
                setTimeout(function(){focus(back)},10);
                return false;
            }
        }
    }
    // allow events within the message content
    if ($(e.target).parents('div.blockMsg').length > 0)
        return true;
        
    // allow events for content that is not being blocked
    return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
    if (!pageBlockEls) 
        return;
    var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
    if (e) 
        e.focus();
};

function center(el, x, y) {
    var p = el.parentNode, s = el.style;
    var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
    var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
    if (x) s.left = l > 0 ? (l+'px') : '0';
    if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};

})(jQuery);


/*
 * jQuery Taconite plugin - A port of the Taconite framework by Ryan Asleson and
 *     Nathaniel T. Schutta: http://taconite.sourceforge.net/
 *
 * Examples and documentation at: http://malsup.com/jquery/taconite/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Thanks to Kenton Simpson for contributing many good ideas!
 *
 * $Id$
 * @version: 3.03  10/22/2008
 * @requires jQuery v1.2.3 or later
 */

(function($) {

$.taconite = function(xml) { processDoc(xml); };

$.taconite.debug = 0;  // set to true to enable debug logging to Firebug
$.taconite.version = '3.03';
$.taconite.defaults = {
    cdataWrap: 'div'
};

// add 'replace' and 'replaceContent' plugins (conditionally)
if (typeof $.fn.replace == 'undefined')
    $.fn.replace = function(a) { return this.after(a).remove(); };
if (typeof $.fn.replaceContent == 'undefined')
    $.fn.replaceContent = function(a) { return this.empty().append(a); };

$.expr[':'].taconiteTag = 'a.taconiteTag';

$.taconite._httpData = $.httpData; // original jQuery httpData function

// replace jQuery's httpData method
$.httpData = $.taconite.detect = function(xhr, type) {
    var ct = xhr.getResponseHeader('content-type');
    if ($.taconite.debug) {
        log('[AJAX response] content-type: ', ct, ';  status: ', xhr.status, ' ', xhr.statusText, ';  has responseXML: ', xhr.responseXML != null);
        log('type: ' + type);
        log('responseXML: ' + xhr.responseXML);
    }
    var data = $.taconite._httpData(xhr, type); // call original method
    if (data && data.documentElement) {
        var root = data.documentElement.tagName;
        log('XML document root: ', root);
        if (root == 'taconite') {
            log('taconite command document detected');
            $.taconite(data);
        }
    }
    else { 
        log('jQuery core httpData returned: ' + data);
        log('httpData: response is not XML (or not "valid" XML)');
    }
    return data;
};

// allow auto-detection to be enabled/disabled on-demand
$.taconite.enableAutoDetection = function(b) {
    $.httpData = b ? $.taconite.detect : $.taconite._httpData;
};

var logCount = 0;
function log() {
    if (!$.taconite.debug || !window.console || !window.console.log) return;
    if (!logCount++)
        log('Plugin Version: ' + $.taconite.version);
    window.console.log('[taconite] ' + [].join.call(arguments,''));
};

function processDoc(xml) { 
    var status = true, ex;
    try {
        $.event.trigger('taconite-begin-notify', [xml])
        status = go(xml); 
    } catch(e) {
        status = ex = e;
    }
    $.event.trigger('taconite-complete-notify', [xml, !!status, status === true ? null : status]);
    if (ex) throw ex;
};

function go(xml) {
    var trimHash = { wrap: 1 };

    if (typeof xml == 'string')
        xml = convert(xml);
    if (!xml || !xml.documentElement) {
        log('$.taconite invoked without valid document; nothing to process');
        return false;
    }
    try {
        var t = new Date().getTime();
        // process the document
        process(xml.documentElement.childNodes);
        $.taconite.lastTime = (new Date().getTime()) - t;
        log('time to process response: ' + $.taconite.lastTime + 'ms');
    } catch(e) {
        if (window.console && window.console.error)
            window.console.error('[taconite] ERROR processing document: ' + e);
        throw e;
    }
    return true;
    
// convert string to xml document
    function convert(s) {
        var doc;
        log('attempting string to document conversion');
        try {
            if($.browser.msie) {
                doc = $("<xml>")[0];
                doc.async = 'false';
                doc.loadXML(s);
            }
            else {
                var parser = new DOMParser();
                doc = parser.parseFromString(s, 'text/xml');
            }
        }
        catch(e) {
            if (window.console && window.console.error)
                window.console.error('[taconite] ERROR parsing XML string for conversion: ' + e);
            throw e;
        }
        var ok = doc && doc.documentElement && doc.documentElement.tagName != 'parsererror';
        log('conversion ', ok ? 'successful!' : 'FAILED');
        return doc;
    };

// process the taconite commands    
    function process(commands) {
        var doPostProcess = 0;
        for(var i=0; i < commands.length; i++) {
            if (commands[i].nodeType != 1)
                continue; // commands are elements
            var cmdNode = commands[i], cmd = cmdNode.tagName;
            if (cmd == 'eval') {
                var js = (cmdNode.firstChild ? cmdNode.firstChild.nodeValue : null);
                log('invoking "eval" command: ', js);
                if (js) $.globalEval(js);
                continue;
            }
            var q = cmdNode.getAttribute('select');
            var jq = $(q);
            if (!jq[0]) {
                log('No matching targets for selector: ', q);
                continue;
            }
            var cdataWrap = cmdNode.getAttribute('cdataWrap') || $.taconite.defaults.cdataWrap;

            var a = [];
            if (cmdNode.childNodes.length > 0) {
                doPostProcess = 1;
                for (var j=0,els=[]; j < cmdNode.childNodes.length; j++)
                    els[j] = createNode(cmdNode.childNodes[j]);
                a.push(trimHash[cmd] ? cleanse(els) : els);
            }

            // remain backward compat with pre 2.0.9 versions
            var n = cmdNode.getAttribute('name');
            var v = cmdNode.getAttribute('value');
            if (n !== null) a.push(n);
            if (v !== null) a.push(v);

            // @since: 2.0.9: support arg1, arg2, arg3...
            for (var j=1; true; j++) {
                v = cmdNode.getAttribute('arg'+j);
                if (v === null)
                    break;
                a.push(v);
            }

            if ($.taconite.debug) {
                var arg = els ? '...' : a.join(',');
                log("invoking command: $('", q, "').", cmd, '('+ arg +')');
            }
            jq[cmd].apply(jq,a);
        }
        // apply dynamic fixes
        if (doPostProcess) 
            postProcess();
    
        function postProcess() {
            if ($.browser.mozilla) return; 
            // post processing fixes go here; currently there is only one:
            // fix1: opera, IE6, Safari/Win don't maintain selected options in all cases (thanks to Karel Fucík for this!)
            $('select:taconiteTag').each(function() {
                var sel = this;
                $('option:taconiteTag', this).each(function() {
                    this.setAttribute('selected','selected');
                    this.taconiteTag = null;
                    if (sel.type == 'select-one') {
                        var idx = $('option',sel).index(this);
                        sel.selectedIndex = idx;
                    }
                });
                this.taconiteTag = null;
            });
        };
        
        function cleanse(els) {
            for (var i=0, a=[]; i < els.length; i++)
                if (els[i].nodeType == 1) a.push(els[i]);
            return a;
        };
        
        function createNode(node) {
            var type = node.nodeType;
            if (type == 1) return createElement(node);
            if (type == 3) return fixTextNode(node.nodeValue);
            if (type == 4) return handleCDATA(node.nodeValue);
            return null;
        };
        
        function handleCDATA(s) {
            var el = document.createElement(cdataWrap);
            el.innerHTML = s;
            return el;
        };
        
        function fixTextNode(s) {
            if ($.browser.msie) s = s.replace(/\n/g, '\r').replace(/\s+/g, ' ');
            return document.createTextNode(s);
        };
        
        function createElement(node) {
            var e, tag = node.tagName.toLowerCase();
            // some elements in IE need to be created with attrs inline
            if ($.browser.msie) {
                var type = node.getAttribute('type');
                if (tag == 'table' || type == 'radio' || type == 'checkbox' || tag == 'button' || 
                    (tag == 'select' && node.getAttribute('multiple'))) {
                    e = document.createElement('<' + tag + ' ' + copyAttrs(null, node, true) + '>');
                }
            }
            if (!e) {
                e = document.createElement(tag);
                copyAttrs(e, node, tag == 'option' && $.browser.safari);
            }
            
            // IE fix; colspan must be explicitly set
            if ($.browser.msie && tag == 'td') {
                var colspan = node.getAttribute('colspan');
                if (colspan) e.colSpan = parseInt(colspan);
            }

            // IE fix; script tag not allowed to have children
            if($.browser.msie && !e.canHaveChildren) {
                if(node.childNodes.length > 0)
                    e.text = node.text;
            }
            else {
                for(var i=0, max=node.childNodes.length; i < max; i++) {
                    var child = createNode (node.childNodes[i]);
                    if(child) e.appendChild(child);
                }
            }
            if (! $.browser.mozilla) {
                if (tag == 'select' || (tag == 'option' && node.getAttribute('selected')))
                    e.taconiteTag = 1;
            }
            return e;
        };
        
        function copyAttrs(dest, src, inline) {
            for (var i=0, attr=''; i < src.attributes.length; i++) {
                var a = src.attributes[i], n = $.trim(a.name), v = $.trim(a.value);
                if (inline) attr += (n + '="' + v + '" ');
                else if (n == 'style') { // IE workaround
                    dest.style.cssText = v;
                    dest.setAttribute(n, v);
                }
                else $.attr(dest, n, v);
            }
            return attr;
        };
    };
};

})(jQuery);


/*
 * SimpleModal 1.2.2 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2008 Eric Martin
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 181 2008-12-16 16:51:44Z emartin24 $
 */

/**
 * SimpleModal is a lightweight jQuery plugin that provides a simple
 * interface to create a modal dialog.
 *
 * The goal of SimpleModal is to provide developers with a cross-browser 
 * overlay and container that will be populated with data provided to
 * SimpleModal.
 *
 * There are two ways to call SimpleModal:
 * 1) As a chained function on a jQuery object, like $('#myDiv').modal();.
 * This call would place the DOM object, #myDiv, inside a modal dialog.
 * Chaining requires a jQuery object. An optional options object can be
 * passed as a parameter.
 *
 * @example $('<div>my data</div>').modal({options});
 * @example $('#myDiv').modal({options});
 * @example jQueryObject.modal({options});
 *
 * 2) As a stand-alone function, like $.modal(data). The data parameter
 * is required and an optional options object can be passed as a second
 * parameter. This method provides more flexibility in the types of data 
 * that are allowed. The data could be a DOM object, a jQuery object, HTML
 * or a string.
 * 
 * @example $.modal('<div>my data</div>', {options});
 * @example $.modal('my data', {options});
 * @example $.modal($('#myDiv'), {options});
 * @example $.modal(jQueryObject, {options});
 * @example $.modal(document.getElementById('myDiv'), {options}); 
 * 
 * A SimpleModal call can contain multiple elements, but only one modal 
 * dialog can be created at a time. Which means that all of the matched
 * elements will be displayed within the modal container.
 * 
 * SimpleModal internally sets the CSS needed to display the modal dialog
 * properly in all browsers, yet provides the developer with the flexibility
 * to easily control the look and feel. The styling for SimpleModal can be 
 * done through external stylesheets, or through SimpleModal, using the
 * overlayCss and/or containerCss options.
 *
 * SimpleModal has been tested in the following browsers:
 * - IE 6, 7
 * - Firefox 2, 3
 * - Opera 9
 * - Safari 3
 *
 * @name SimpleModal
 * @type jQuery
 * @requires jQuery v1.2.2
 * @cat Plugins/Windows and Overlays
 * @author Eric Martin (http://ericmmartin.com)
 * @version 1.2.2
 */
(function ($) {
	var ie6 = $.browser.msie && parseInt($.browser.version) == 6 && !window['XMLHttpRequest'],
		ieQuirks = $.browser.msie && !$.boxModel,
		w = [];

	/*
	 * Stand-alone function to create a modal dialog.
	 * 
	 * @param {string, object} data A string, jQuery object or DOM object
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.modal = function (data, options) {
		return $.modal.impl.init(data, options);
	};

	/*
	 * Stand-alone close function to close the modal dialog
	 */
	$.modal.close = function () {
		$.modal.impl.close();
	};

	/*
	 * Chained function to create a modal dialog.
	 * 
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.fn.modal = function (options) {
		return $.modal.impl.init(this, options);
	};

	/*
	 * SimpleModal default options
	 * 
	 * opacity: (Number:50) The opacity value for the overlay div, from 0 - 100
	 * overlayId: (String:'simplemodal-overlay') The DOM element id for the overlay div
	 * overlayCss: (Object:{}) The CSS styling for the overlay div
	 * containerId: (String:'simplemodal-container') The DOM element id for the container div
	 * containerCss: (Object:{}) The CSS styling for the container div
	 * dataCss: (Object:{}) The CSS styling for the data div
	 * zIndex: (Number: 1000) Starting z-index value
	 * close: (Boolean:true) Show closeHTML?
	 * closeHTML: (String:'<a class="modalCloseImg" title="Close"></a>') The HTML for the 
	              default close link. SimpleModal will automatically add the closeClass to this element.
	 * closeClass: (String:'simplemodal-close') The CSS class used to bind to the close event
	 * position: (Array:null) Position of container [top, left]. Can be number of pixels or percentage
	 * persist: (Boolean:false) Persist the data across modal calls? Only used for existing
	            DOM elements. If true, the data will be maintained across modal calls, if false,
				   the data will be reverted to its original state.
	 * onOpen: (Function:null) The callback function used in place of SimpleModal's open
	 * onShow: (Function:null) The callback function used after the modal dialog has opened
	 * onClose: (Function:null) The callback function used in place of SimpleModal's close
	 */
	$.modal.defaults = {
		opacity: 50,
		overlayId: 'simplemodal-overlay',
		overlayCss: {},
		containerId: 'simplemodal-container',
		containerCss: {},
		dataCss: {},
		zIndex: 1000,
		close: true,
		closeHTML: '<a class="modalCloseImg" title="Close"></a>',
		closeClass: 'simplemodal-close',
		position: null,
		persist: false,
		onOpen: null,
		onShow: null,
		onClose: null
	};

	/*
	 * Main modal object
	 */
	$.modal.impl = {
		/*
		 * Modal dialog options
		 */
		opts: null,
		/*
		 * Contains the modal dialog elements and is the object passed 
		 * back to the callback (onOpen, onShow, onClose) functions
		 */
		dialog: {},
		/*
		 * Initialize the modal dialog
		 */
		init: function (data, options) {
			// don't allow multiple calls
			if (this.dialog.data) {
				return false;
			}

			// merge defaults and user options
			this.opts = $.extend({}, $.modal.defaults, options);

			// keep track of z-index
			this.zIndex = this.opts.zIndex;

			// set the onClose callback flag
			this.occb = false;

			// determine how to handle the data based on its type
			if (typeof data == 'object') {
				// convert DOM object to a jQuery object
				data = data instanceof jQuery ? data : $(data);

				// if the object came from the DOM, keep track of its parent
				if (data.parent().parent().size() > 0) {
					this.dialog.parentNode = data.parent();

					// persist changes? if not, make a clone of the element
					if (!this.opts.persist) {
						this.dialog.orig = data.clone(true);
					}
				}
			}
			else if (typeof data == 'string' || typeof data == 'number') {
				// just insert the data as innerHTML
				data = $('<div/>').html(data);
			}
			else {
				// unsupported data type!
				alert('SimpleModal Error: Unsupported data type: ' + typeof data);
				return false;
			}
			this.dialog.data = data.addClass('simplemodal-data').css(this.opts.dataCss);
			data = null;

			// create the modal overlay, container and, if necessary, iframe
			this.create();

			// display the modal dialog
			this.open();

			// useful for adding events/manipulating data in the modal dialog
			if ($.isFunction(this.opts.onShow)) {
				this.opts.onShow.apply(this, [this.dialog]);
			}

			// don't break the chain =)
			return this;
		},
		/*
		 * Create and add the modal overlay and container to the page
		 */
		create: function () {
			// get the window properties
			w = this.getDimensions();

			// add an iframe to prevent select options from bleeding through
			if (ie6) {
				this.dialog.iframe = $('<iframe src="javascript:false;"/>')
					.css($.extend(this.opts.iframeCss, {
						display: 'none',
						opacity: 0, 
						position: 'fixed',
						height: w[0],
						width: w[1],
						zIndex: this.opts.zIndex,
						top: 0,
						left: 0
					}))
					.appendTo('body');
			}

			// create the overlay
			this.dialog.overlay = $('<div/>')
				.attr('id', this.opts.overlayId)
				.addClass('simplemodal-overlay')
				.css($.extend(this.opts.overlayCss, {
					display: 'none',
					opacity: this.opts.opacity / 100,
					height: w[0],
					width: w[1],
					position: 'fixed',
					left: 0,
					top: 0,
					zIndex: this.opts.zIndex + 1
				}))
				.appendTo('body');

			// create the container
			this.dialog.container = $('<div/>')
				.attr('id', this.opts.containerId)
				.addClass('simplemodal-container')
				.css($.extend(this.opts.containerCss, {
					display: 'none',
					position: 'fixed', 
					zIndex: this.opts.zIndex + 2
				}))
				.append(this.opts.close 
					? $(this.opts.closeHTML).addClass(this.opts.closeClass)
					: '')
				.appendTo('body');

			this.setPosition();

			// fix issues with IE
			if (ie6 || ieQuirks) {
				this.fixIE();
			}

			// hide the data and add it to the container
			this.dialog.container.append(this.dialog.data.hide());
		},
		/*
		 * Bind events
		 */
		bindEvents: function () {
			var self = this;

			// bind the close event to any element with the closeClass class
			$('.' + this.opts.closeClass).bind('click.simplemodal', function (e) {
				e.preventDefault();
				self.close();
			});

			// update window size
			$(window).bind('resize.simplemodal', function () {
				// redetermine the window width/height
				w = self.getDimensions();

				// reposition the dialog
				self.setPosition();
	
				if (ie6 || ieQuirks) {
					self.fixIE();
				}
				else {
					// update the iframe & overlay
					self.dialog.iframe && self.dialog.iframe.css({height: w[0], width: w[1]});
					self.dialog.overlay.css({height: w[0], width: w[1]});
				}
			});
		},
		/*
		 * Unbind events
		 */
		unbindEvents: function () {
			$('.' + this.opts.closeClass).unbind('click.simplemodal');
			$(window).unbind('resize.simplemodal');
		},
		/*
		 * Fix issues in IE6 and IE7 in quirks mode
		 */
		fixIE: function () {
			var p = this.opts.position;

			// simulate fixed position - adapted from BlockUI
			$.each([this.dialog.iframe || null, this.dialog.overlay, this.dialog.container], function (i, el) {
				if (el) {
					var bch = 'document.body.clientHeight', bcw = 'document.body.clientWidth',
						bsh = 'document.body.scrollHeight', bsl = 'document.body.scrollLeft',
						bst = 'document.body.scrollTop', bsw = 'document.body.scrollWidth',
						ch = 'document.documentElement.clientHeight', cw = 'document.documentElement.clientWidth',
						sl = 'document.documentElement.scrollLeft', st = 'document.documentElement.scrollTop',
						s = el[0].style;

					s.position = 'absolute';
					if (i < 2) {
						s.removeExpression('height');
						s.removeExpression('width');
						s.setExpression('height','' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + "px"');
						s.setExpression('width','' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + "px"');
					}
					else {
						var te, le;
						if (p && p.constructor == Array) {
							if (p[0]) {
								var top = typeof p[0] == 'number' ? p[0].toString() : p[0].replace(/px/, '');
								te = top.indexOf('%') == -1 
									? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'
									: parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
							}
							if (p[1]) {
								var left = typeof p[1] == 'number' ? p[1].toString() : p[1].replace(/px/, '');
								le = left.indexOf('%') == -1 
									? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'
									: parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
							}
						}
						else {
							te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
							le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
						}
						s.removeExpression('top');
						s.removeExpression('left');
						s.setExpression('top', te);
						s.setExpression('left', le);
					}
				}
			});
		},
		getDimensions: function () {
			var el = $(window);

			// fix a jQuery/Opera bug with determining the window height
			var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery <= '1.2.6' ?
				document.documentElement['clientHeight'] : 
				el.height();

			return [h, el.width()];
		},
		setPosition: function () {
			var top, left,
				hCenter = (w[0]/2) - ((this.dialog.container.height() || this.dialog.data.height())/2),
				vCenter = (w[1]/2) - ((this.dialog.container.width() || this.dialog.data.width())/2);

			if (this.opts.position && this.opts.position.constructor == Array) {
				top = this.opts.position[0] || hCenter;
				left = this.opts.position[1] || vCenter;
			} else {
				top = hCenter;
				left = vCenter;
			}
			this.dialog.container.css({left: left, top: top});
		},
		/*
		 * Open the modal dialog elements
		 * - Note: If you use the onOpen callback, you must "show" the 
		 *	        overlay and container elements manually 
		 *         (the iframe will be handled by SimpleModal)
		 */
		open: function () {
			// display the iframe
			this.dialog.iframe && this.dialog.iframe.show();

			if ($.isFunction(this.opts.onOpen)) {
				// execute the onOpen callback 
				this.opts.onOpen.apply(this, [this.dialog]);
			}
			else {
				// display the remaining elements
				this.dialog.overlay.show();
				this.dialog.container.show();
				this.dialog.data.show();
			}

			// bind default events
			this.bindEvents();
		},
		/*
		 * Close the modal dialog
		 * - Note: If you use an onClose callback, you must remove the 
		 *         overlay, container and iframe elements manually
		 *
		 * @param {boolean} external Indicates whether the call to this
		 *     function was internal or external. If it was external, the
		 *     onClose callback will be ignored
		 */
		close: function () {
			// prevent close when dialog does not exist
			if (!this.dialog.data) {
				return false;
			}

			if ($.isFunction(this.opts.onClose) && !this.occb) {
				// set the onClose callback flag
				this.occb = true;

				// execute the onClose callback
				this.opts.onClose.apply(this, [this.dialog]);
			}
			else {
				// if the data came from the DOM, put it back
				if (this.dialog.parentNode) {
					// save changes to the data?
					if (this.opts.persist) {
						// insert the (possibly) modified data back into the DOM
						this.dialog.data.hide().appendTo(this.dialog.parentNode);
					}
					else {
						// remove the current and insert the original, 
						// unmodified data back into the DOM
						this.dialog.data.remove();
						this.dialog.orig.appendTo(this.dialog.parentNode);
					}
				}
				else {
					// otherwise, remove it
					this.dialog.data.remove();
				}

				// remove the remaining elements
				this.dialog.container.remove();
				this.dialog.overlay.remove();
				this.dialog.iframe && this.dialog.iframe.remove();

				// reset the dialog object
				this.dialog = {};
			}

			// remove the default events
			this.unbindEvents();
		}
	};
})(jQuery);



