//Jquery URL Plugin
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

//custom
$(function(){
   
    var bgImageTotal=4;

    var randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;

    var imgPath=("http://"+window.location.hostname+"/images/header_graphic-"+randomNumber+'.jpg');

    $('#container').css('background-image', ('url("'+imgPath+'")'));
    

    
    var currentfile = jQuery.url.attr("file");
    var currentaction = jQuery.url.param("a");
     var currentdir = jQuery.url.attr("directory");
     //highlight selected link
     //if(currentfile != "login.php" ){
         $("#navigation li a").each(function (i) {
            if ($(this).attr('href') == "http://"+window.location.hostname+currentdir) {
                $(this).parents("li").addClass('selectednav');          
            }else if($(this).attr('href') == "http://"+window.location.hostname+"/"+currentfile) {
                 $(this).parents("li").addClass('selectednav');
            }
           /* if (!currentfile) {
                $("#navigation li:first").addClass('selectednav');
            }*/ 
          });
      //}
	  
	  //don't display empty column
	  if($(".lacnewscolumn #lac_content_loader").html()==""){
		$(".lacnewscolumn").hide();  
	  }
      $("#subnavhorizontal li a").not("#subnavhorizontal li li a").each(function (i) {
            if ($(this).attr('href') == "http://"+window.location.hostname+currentdir) {
                $(this).parents("li").addClass('selectednav');          
            }else if($(this).attr('href') == "http://"+window.location.hostname+"/"+currentfile) {
                 $(this).parents("li").addClass('selectednav');
            }
      });
        
        
        //all hover and click logic for buttons
        $(".fg-button:not(.ui-state-disabled)").hover(
            function(){ 
                $(this).addClass("ui-state-hover"); 
            },
            function(){ 
                $(this).removeClass("ui-state-hover"); 
            }
        ).mousedown(function(){
                $(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
                if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
                else { $(this).addClass("ui-state-active"); }   
        }).mouseup(function(){
            if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
                $(this).removeClass("ui-state-active");
            }
        });
        
        $(".accordion").accordion();
        
        $("#subnavhorizontal li").hover(
            function(){
                $(this).children("ul").show();
                /*$(this).children("ul").stop().animate(
                {opacity: 1}, 
                {duration:300});*/
            },
            function(){
                $(this).children("ul").hide();
               /* $(this).children("ul").stop().animate(
                {opacity: 0}, 
                {duration:300});*/
            }
        );
        
        //inline date picker
        $(".datepickerinline").datepicker({onSelect: function(dateText, inst) {
                                                               
                                                              
                                                              }
                                                              });
        
        
        
        //members filter
/*      $(".catname").next("ul").hide();
        $(".catname").click(function(){
            $(".catname").next("ul").slideUp(100);
            $(this).next("ul").slideDown(100);
        });*/


        //calendar tabs
        $("#calendartabs").tabs({
         add: function(event, ui) { 
                //select newely opened tab
                 $("#calendartabs").tabs('select', ui.index);
                //load function to close tab
                removetabs(ui.index);
                return false;
           },
           show: function(event, ui) { 
                //load function to close tab
                removetabs(ui.index);
           }
        });
        
        //CALENDAR 
        //$(".calendar_thismonth").datepicker();
        
        //END CALENDAR
        
        //zebra table
        $("tbody:nth-child(odd)").addClass("odd");
        
        //clear search box
        $("#search").click(function(){$(this).val('');});
        
        //set todays date for calendar
        $(".todaysdate").text(todaysdate());
        
        //category navigation for home page
        $(".ajaxlist a").unbind("click").click(function(){
        $(".eventcolumn").fadeOut('fast'); //html('LOADING...');                                                    
           var href = $(this).attr("href");
           var category = href.split("category/");
           var cat =category[1];
         //var cat = href.replace(/..\/category.php\?/, "");
         if(href != "#"){
             $(".eventcolumn").load('http://'+window.location.hostname+'/ajax.php?action=latesteventshome&c='+cat).fadeIn('fast');
             //$(".widecolumn").load(href+" .widecolumn > *").fadeIn('fast');
             $(".categorylist li").removeClass('currentcategory');
             $(this).parents("li").addClass('currentcategory');
         }
         return false;
                                                         
        });
        
        //ADD TAGS
        $("#addtag").click(function(){
            var selected = $("#taglist").val()+",";
            var currenttags = $('#tags').val();
            var cat = currenttags.replace(selected, "");
            var tags = $("#taglist").val()+","+cat;
            $("#tags").val(tags);
            return false;                           
        });
        
        //ERROR
        var e = $('.error'); 
        e.fadeIn(); 
        e.queue(function(){ 
          setTimeout(function(){ 
            e.dequeue(); 
          }, 8000 ); 
        }); 
        e.fadeOut('slow');  
        
        //TOOLTIPS
        /*$(".sm-link").simpletip({ fixed: true, 
                                position: 'top',
                                showEffect:'none',
                                onBeforeShow: function(){
                                    var contemt = this.getParent().attr("title");
                                    this.update(contemt); 
                                }}); */
        
        
      
       //cycle
       if($(".promo").length > 0){
           if($('#promoslides').length > 0){
               $('#promoslides').after('<div id="lac_promos_nav">').cycle({ 
                fx:     'fade', 
                pager: '#lac_promos_nav',
                delay:  -2000,
                timeout: 8000
                });
            }
       }else{
            $("#wrapper .promo p").css({'top':'90px','left':'0px'});   
       }
       //Cycle DATES
       if($(".eventdate").length > 0){
           $(".eventdate").cycle({ 
                    fx:     'fade', 
                    speed:  'fast', 
                    timeout: 0, 
                    next:   '#next2', 
                    prev:   '#prev2'
           });
       }
       //FAQ's
        //style all questions as closed
        $(".question").addClass("closed"); 
        //make sure first question is styled as open
            $(".question:first").removeClass("closed").addClass("opened"); 
        $(".answer").hide(); //hide answers
        $(".answer:first").show(); //show first answer
        //question click
        $(".question").click(function() {
            $(".answer").slideUp("fast");
            $(".question").removeClass("opened").addClass("closed");
    
            if ($(this).next(".answer").is(":hidden")) {
                $(this).next(".answer").slideDown("fast");
                $(this).removeClass("closed").addClass("opened");
            }              
        });
        //LOGIN FORM
        $("#loginforms").accordion({
            autoHeight: false,
            collapsible: false
         });
        if(currentaction == "register"){
            $('#loginforms').accordion( 'activate' , 1 );
        }
        
        //GALLERY
        //gallery
     $('ol.gallery').galleria({
            history   : true, // activates the history object for bookmarking, back-button etc.
            clickNext : true, // helper for making the image clickable
            insert    : '#main_image', // the containing selector for our main image
            onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
                
                // fade in the image & caption
                if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
                    image.css('display','none').fadeIn(1000);
                }
                caption.css('display','none').fadeIn(1000);
                
                // fetch the thumbnail container
                var _li = thumb.parents('li');
                
                // fade out inactive thumbnail
                _li.siblings().children('img.selected').fadeTo(500,0.3);
                
                // fade in active thumbnail
                thumb.fadeTo('fast',1).addClass('selected');
                
                // add a title for the clickable image
                image.attr('title','Next image >>');
            },
            onThumb : function(thumb) { // thumbnail effects goes here
                
                // fetch the thumbnail container
                var _li = thumb.parents('li');
                
                // if thumbnail is active, fade all the way.
                var _fadeTo = _li.is('.active') ? '1' : '0.3';
                
                // fade in the thumbnail when finnished loading
                thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
                
                // hover effects
                thumb.hover(
                    function() { thumb.fadeTo('fast',1); },
                    function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
                )
            }
        });
     
     //Load contact form
     if($("#contact_us_form").length > 0){
        $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=getcontactform",
          success: function(frm){
              $("#contact_us_form").html(frm);
          }
               
          });    
     }
     
     //MODAL EMAIL DIALOG
    $(".opendialog").click(function(){
        var email = $(this).attr("href").replace("#", "");
        $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=getcontactform&email="+email,
          success: function(frm){
              $("#modal_dialog").html(frm);
          }
               
          });                           
        $("#modal_dialog").dialog({
            title: "Contact",
            width: 540,
            height:400,
            modal: true,
            close: function(){
                $("#modal_dialog").dialog('destroy');
            }
        });
        return false;
    });
    
    //inappropriate content
    $(".inappropriate").click(function(){
        var urls = $(this).attr('href');
        $.ajax({
          url: urls,
          success: function(frm){
              $("#modal_dialog").html(frm);
              $("#modal_dialog").dialog({
                title: "Flag this as inappropriate",
                width: 400,
                height:250,
                modal: true,
                async: false,
                close: function(){
                    $("#modal_dialog").dialog('destroy');
                }
            });
          }
        });
        
        
        return false;
    });
    
    /*jQuery.expr[':'].Contains = function(a,i,m){
     return jQuery(a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
    };*/
    

    
    //find article by filename
    //ensure case in-sensitive search
    jQuery.extend(
        jQuery.expr[':'].contains = function(a,i,m){
        return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
    });
    $(".search_calendar_events").keyup(function(){
            var elem = $(this).parent("div").next(".eventstable");
            //$(this).parent("div").next(".eventstable").children("tbody").hide();
            $(elem).children("tbody").hide();
            $(elem).children("tbody").removeClass("odd");
            
            var findarticle = $(this).val();
            if(findarticle != ""){
                $(elem).children("tbody:contains("+findarticle+")").show();
            }else{
                $(elem).children("tbody").show();
            }
    }).blur(function(){
        if($(this).val() == ""){
            $(elem).children("tbody").show();   
        }   
        
    });
     
     
});
    
/*    function multicals(){
        $('#multiplecalendars').datepicker({
            numberOfMonths: [3, 4],
            showCurrentAtPos: 0,
            onSelect: function(dateText, inst) { 
             var index=$("#calendartabs").tabs('length');
             $("#calendartabs").tabs( 'add' , 'http://'+window.location.hostname+'/ajax.php?action=calendar&date='+dateText , dateText+' <span id="'+index+'" class="removetab ui-icon ui-icon-circle-close" style="float:right; margin: -1px -16px 0px 0px; cursor:pointer;"></span>');
             removetabs(index);
            }
        });
        
    }*/
    function submitcontactform(formid){
        $('#contact_form').ajaxForm({target: "#contact_form"}); 
        //$("#modal_dialog").dialog('destroy');
    }
    function removetabs(index) {
        
        $(".removetab").click(function(){
            try{
                var index = $(this).attr("id");
                $("#calendartabs").tabs('remove',index);
                //reset tab nuber
                var i=5;
                $("#calendartabs .removetab").each(function(){
                    
                    $(this).attr('id', i);
                    i++;
                });
                /*var newindex = index -1;
                if(newindex == 3){
                    index = 2;  
                }*/
                $("#calendartabs").tabs('select', 2);
            }catch(e){}
        });
     };
     
    /*function calendar_filter(){
        $(".calendar_thismonth").datepicker();
    }*/
     
    function selectdates(){

        $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=getyearevents",
          dataType: "json",
          success: function(calendarEvents){ 
                   //$("#calendartabs").tabs( 'add' , 'http://"+window.location.hostname+"/ajax.php?action=calendar&date='+dateText , dateText);
                 
                   $("#multiplecalendars").datepicker({                        
                       numberOfMonths: [3, 4],
                       showCurrentAtPos: 0,
                       beforeShowDay: function (date){
                           
                            for (i = 0; i < calendarEvents.length; i++) {
                                  if (date.getMonth() == calendarEvents[i][0] - 1 
                                  && date.getDate() == calendarEvents[i][1]
                                  && date.getFullYear() == calendarEvents[i][2]) {
                                  //[disable/enable, class for styling appearance, tool tip]
                                  return [true,"ui-state-highlight tooltip","Click for more"]; 
                                  }
                               }
                               return [false, ""];//enable all other days
                        },
                        onSelect: function(dateText, inst) { 
                             var index=$("#calendartabs").tabs('length');
                             $("#calendartabs").tabs( 'add' , 'http://'+window.location.hostname+'/ajax.php?action=calendar&range=singleday&date='+dateText , '<span id="'+index+'" class="removetab ui-icon ui-icon-circle-close" style="position:absolute; z-index:100; right:2px; margin: 0px 0px 0px 0px; cursor:pointer;"> </span>'+dateText);
                             
                             removetabs(index);
                        }
                    });
                    
            }
        });
        
    }
    
    function zebratable(){
        $("tbody:nth-child(odd)").addClass("odd");
        jQuery.extend(
        jQuery.expr[':'].contains = function(a,i,m){
        return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
        });
        $(".search_calendar_events").keyup(function(){
                var elem = $(this).parent("div").next(".eventstable");
                //$(this).parent("div").next(".eventstable").children("tbody").hide();
                $(elem).children("tbody").hide();
                $(elem).children("tbody").removeClass("odd");
                
                var findarticle = $(this).val();
                if(findarticle != ""){
                    $(elem).children("tbody:contains("+findarticle+")").show();
                }else{
                    $(elem).children("tbody").show();
                }
        }).blur(function(){
            if($(this).val() == ""){
                $(elem).children("tbody").show();   
            }   
            
        });
    }
    
    function todaysdate(){
    // Array of day names
        var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday",
                        "Thursday","Friday","Saturday");
        
        // Array of month Names
        var monthNames = new Array(
        "January","February","March","April","May","June","July",
        "August","September","October","November","December");
        
        var now = new Date();
        var today = dayNames[now.getDay()] + ", " + 
        monthNames[now.getMonth()] + " " + 
        now.getDate() + ", " + now.getFullYear();
        return today;
    }
    
    function sponsors(){
        var slider_minamount;
        var slider_maxamount; 
        $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=loadamounts",
          dataType: "json",
          success: function(amountsarray){
              if(amountsarray.minamount != ""){
                  slider_minamount = parseInt(amountsarray.minamount);
              }else{
                  slider_minamount = 1000;
              }
              if(amountsarray.maxamount != ""){
                  slider_maxamount = parseInt(amountsarray.maxamount);
              }else{
                  slider_maxamount = 20000;
              }
              $("#slider").slider({
                    range: true,
                    step: 250,
                    slide: function(event, ui) {
                        $("#amount").text('$' + ui.values[0] + ' - $' + ui.values[1]);
                        $(".sponsorimages p").not(".ctaright").each(
                        function(intIndex){
                            var amount = parseInt($(this).attr("class"));
                                if(amount >= ui.values[0] && amount <= ui.values[1]){
                                    $(this).show(); 
                                }else{
                                    $(this).hide(); 
                                }
                            }                                              
                        );
                    }
                }); 
                $("#slider").slider('option', 'min', 0);
                $("#slider").slider('option', 'max', slider_maxamount);
                $('#slider').slider('option', 'values', [slider_minamount, slider_maxamount]);
                $('#slider').slider( 'enable' ); 
              
          }
          });
          

        $(".sponsorimages p").each(
            function(intIndex){
                var amount = parseInt($(this).attr("class"));
                if(amount >= 2750){
                    $(this).show(); 
                }
            }                                              
        );
    }  
    //highlight dates  
  function highlightdates(filename, article){   
    $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=getevents&filename="+filename+"&article="+article,
          dataType: "json",
          success: function(natDays){
                     var monthLocale = new Array(12);
                                        monthLocale[1] = "January";
                                        monthLocale[2] = "February";
                                        monthLocale[3] = "March";
                                        monthLocale[4] = "April";
                                        monthLocale[5] = "May";
                                        monthLocale[6] = "June";
                                        monthLocale[7] = "July";
                                        monthLocale[8] = "August";
                                        monthLocale[9] = "September";
                                        monthLocale[10] = "October";
                                        monthLocale[11] = "November";
                                        monthLocale[12] = "December";
                     var defaultdate = monthLocale[natDays[0][0]]+" "+ natDays[0][1] +","+ natDays[0][2];
                     $("#cal_-"+filename+"_-"+article).datepicker({
                        numberOfMonths: [1, 1],
                        showCurrentAtPos: 0,
                        beforeShowDay: function (date){
                            for (i = 0; i < natDays.length; i++) {
                                  if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]  && date.getFullYear() == natDays[i][2]) {
                                     
                                    return [true,"ui-state-active tooltip"];
                                  }
                                }
                                
                              
                              
                              return [false, ""];
                              
                        },
                        defaultDate: new Date (defaultdate),
                        onSelect: function(dateText, inst) { 
                        //alert(dateText);
                        }
                        
                    });
                   }
                   
         });
              
  }
  
 function sorteventsbycategory(catid){
    $(".eventstable tbody").removeClass("odd");
    if(catid ==""){
        $(".eventstable tbody").show();
    }else{
        $(".eventstable tbody").hide();
        $("."+catid).show();
        
    }
    $(".eventstable  tbody:nth-child:visible(odd)").addClass("odd");    
 }
 
 function loadmonth(month, containerid){
     $(".calendar_thismonth").datepicker( 'destroy' );
     $.ajax({url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=calendar&range=month&month="+month,
          success: function(content){
              $("#selectedMonthContainer").html(content);
                var d = new Date();
                var curr_year = d.getFullYear();
                var m = pad(month, 2)
              //$(".calendar_thismonth").datepicker('setDate' , m+'/01/'+curr_year);
              select_events_for_month(m+'/01/'+curr_year, containerid);
          }});
 }
 
 function select_events_for_month(month, containerid){
        $.ajax({
          url: "http://"+window.location.hostname+"/ajax.php",
          data: "action=getyearevents",
          dataType: "json",
          cache: false,
          success: function(calendarEvents){ 
                   //$("#calendartabs").tabs( 'add' , 'http://"+window.location.hostname+"/ajax.php?action=calendar&date='+dateText , dateText);
                   
                   $(".calendar_thismonth").datepicker({                        
                       numberOfMonths: [1, 1],
                       showCurrentAtPos: 0,
                       defaultDate: new Date(month),
                       changeMonth: true,
                       changeYear: true,
                       beforeShowDay: function (date){
                           
                            for (i = 0; i < calendarEvents.length; i++) {
                                  if (date.getMonth() == calendarEvents[i][0] - 1 
                                  && date.getDate() == calendarEvents[i][1]
                                  && date.getFullYear() == calendarEvents[i][2]) {
                                  //[disable/enable, class for styling appearance, tool tip]
                                  return [true,"ui-state-highlight tooltip","Click for more"]; 
                                  }
                               }
                               return [false, ""];//enable all other days
                        },
                        onSelect: function(dateText, inst) {
                            $("#"+containerid+" .calendar_loadday").html("");
                             $("#"+containerid+" .calendar_loadday").load('http://'+window.location.hostname+'/ajax.php?action=calendar&date='+dateText+'&range=singleday');
                            /* var index=$("#calendartabs").tabs('length');
                             $("#calendartabs").tabs( 'add' , 'http://'+window.location.hostname+'/ajax.php?action=calendar&date='+dateText , '<span id="'+index+'" class="removetab ui-icon ui-icon-circle-close" style="position:absolute; right:2px; margin: 0px 0px 0px 0px; cursor:pointer;"></span>'+dateText);
                             removetabs(index);*/
                        },
                        onChangeMonthYear: function(year, month, inst) { 
                            $("#"+containerid+" .calendar_loadday").load('http://'+window.location.hostname+'/ajax.php?action=calendar&month='+month+'&year='+year+'&range=nextmonth');
                        }
                    });
            }
        }); 
        zebratable();
    }
    
 function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}
  /* Pushup
 * Copyright (c) 2009 Nick Stakenburg (www.nickstakenburg.com)
 *
 * License: MIT-style license.
 * Website: http://www.pushuptheweb.com
 *
 */

var Pushup = {
  Version: '1.0.3',
  options: {
    appearDelay: .5,
    fadeDelay: 6,
    images: 'http://'+window.location.hostname+'/images/',
    message: 'Important browser update available',
    reminder: {
      hours: 6,
      message: 'Remind me again in #{hours}'
    },
    skip: true
  },
  updateLinks: {
    IE: 'http://www.microsoft.com/windows/downloads/ie/',
    Firefox: 'http://www.getfirefox.com',
    Safari: 'http://www.apple.com/safari/download/',
    Opera: 'http://www.opera.com/download/'
  },
  Browser: {
    IE: !!(window.attachEvent &&
      navigator.userAgent.indexOf('Opera') === -1),
    Firefox: navigator.userAgent.indexOf('Firefox') > -1,
    Safari: navigator.userAgent.indexOf('AppleWebKit/') > -1 &&
      /Apple/.test(navigator.vendor),
    Opera: navigator.userAgent.indexOf('Opera') > -1
  }
};

Pushup.conditions = {
  IE: (function(agent) {
    var version = /MSIE ([\d.]+)/.exec(agent);
    return version && parseFloat(version[1]) < 8;
  })(navigator.userAgent),
  Firefox: Pushup.Browser.Firefox &&
    parseFloat(navigator.userAgent.match(/Firefox[\/\s](\d+)/)[1]) < 3,
  Safari: Pushup.Browser.Safari &&
    parseFloat(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1]) < 500,
  Opera: Pushup.Browser.Opera && (!window.opera.version ||
    parseFloat(window.opera.version()) < 9.5)
};

(function() {
// find current browser and check if it needs an update
for (var browser in Pushup.Browser)
  if (Pushup.Browser[browser]) Pushup._browserUsed = browser;
Pushup._updateBrowser = Pushup.conditions[Pushup._browserUsed] &&
  Pushup._browserUsed;

// stop if no update is required and we want to skip build
if (!Pushup._updateBrowser && Pushup.options.skip) return;

function Extend(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
}

Extend(Pushup, {
  start: function() {
    // get the image directory
    if (/^(https?:\/\/|\/)/.test(this.options.images))
      this.images = this.options.images;
    else {
      var srcMatch = /pushup(?:-[\w\d.]+)?\.js(.*)/,
       scripts = document.getElementsByTagName('script');
      for (var i = 0, l = scripts.length; i < l; i++) {
        var s = scripts[i];
        if (s.src && s.src.match(srcMatch))
          this.images = s.src.replace(srcMatch, '') + this.options.images;
      }
    }
    if (Pushup._updateBrowser) this.show();
  },

  build: function() {
    this.pushup = document.createElement('div');
    Opacity.set(this.pushup, 0);
    this.pushup.id = 'pushup';

    this.messageLink = this.pushup.appendChild(document.createElement('a'));
    this.messageLink.className = 'pushup_messageLink';
    this.messageLink.target = '_blank';

    this.messageLink.appendChild(this.icon = document.createElement('div'));
    this.icon.className = 'pushup_icon';

    this.messageLink.appendChild(this.message = document.createElement('span'));
    this.message.className = 'pushup_message';
    this.message.innerHTML = this.options.message;

    // reminder message if cookies are enabled
    var hours = this.options.reminder.hours;
    if (hours && Pushup.cookiesEnabled) {
      this.pushup.appendChild(this.reminder = document.createElement('a'));
      this.reminder.href = '#';
      this.reminder.className = 'pushup_reminder';
      this.pushup.className = 'withReminder';
      var H = hours + ' hour' + (hours > 1 ? 's' : ''),
       message = this.options.reminder.message.replace('#{hours}', H);
      this.reminder.innerHTML = message;
    }

    // Older Opera doesn't handle float correctly
    if (Pushup.Browser.Opera &&
       (!window.opera.version || parseFloat(window.opera.version()) < 9.25)) {
      this.messageLink.style.cssFloat = 'none';
      this.reminder.style.cssFloat = 'none';
    }

    Pushup.setBrowser(Pushup._updateBrowser);
    document.body.appendChild(this.pushup);
    Pushup.addEvents();
  },

  addEvents: function() {
    if (this.reminder) {
      Event.add(this.reminder, 'click', function(event) {
        Event.stop(event);
        Pushup.setReminder(Pushup.options.reminder.hours);
        Pushup.fade();
      });
    }
    Event.add(this.pushup, 'mouseover', Pushup.clearFade);
    Event.add(this.pushup, 'mouseout', function() {
      Pushup.fade({ delay: Pushup.options.fadeDelay })
    });
  },

  setBrowser: function(browser) {
    browser = browser || 'IE';
    setPngBackground(this.icon, this.images + browser.toLowerCase() + '.png');
    this.messageLink.href = this.updateLinks[browser];
  },

  show: function() {
    // default to IE if no browser was detected
    var browser = typeof arguments[0] == 'string' ?
      arguments[0] : Pushup._browserUsed || 'IE',
     options = arguments[browser ? 1 : 0] || {};

    if (options.resetReminder) Pushup.resetReminder();

    // show if not blocked by cookie
    if (!options.ignoreReminder && Pushup.cookiesEnabled &&
      Cookie.get('_pushupBlocked')) return;

    if (!Pushup.pushup) Pushup.build();
    Opacity.set(Pushup.pushup, 0);
    Pushup.pushup.style.display = 'block';
    if (browser) Pushup.setBrowser(browser);
    this.appear({ fadeAfter: true, delay: Pushup.options.appearDelay });
  },

  appear: function(delay) {
    Pushup.clearFade();
    var options = arguments[0] || {};
    return window.setTimeout(function() {
      Appear(Pushup.pushup, { afterFinish: function() {
        if (options.fadeAfter)
          Pushup.fade({ delay: Pushup.options.fadeDelay });
      }});
    }, (options.delay || 0.01) * 1000);
  },

  clearFade: function() {
    if (Pushup._fadeTimer) {
      window.clearTimeout(Pushup._fadeTimer);
      Pushup._fadeTimer = null;
    }
  },

  fade: function() {
    var options = arguments[0] || {};
    Pushup._fadeTimer = window.setTimeout(function() {
      Fade(Pushup.pushup);
    }, (options.delay || 0.01) * 1000);
  },

  setReminder: function(hours) {
    Cookie.set('_pushupBlocked', 'blocked', { duration: 1 / 24 * hours })
  },

  resetReminder: function() { Cookie.remove('_pushupBlocked') }
});

// Opacity adapted from the Prototype JavaScript framework
// http://www.prototypejs.org
var Opacity = {
  set: function(element, value) {
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
  },

  get:  function(element) {
    var opacity = element.style.opacity;
    return opacity ? parseFloat(opacity) : 1.0;
  }
};

if (Pushup.Browser.IE) {
  Opacity.get = function(element) {
    var opacity = element.style.opacity;
    if (!opacity && element.currentStyle) opacity = element.currentStyle[opacity];

    if (opacity = (element.style.filter || '').match(/alpha\(opacity=(.*)\)/))
      if (opacity[1]) return parseFloat(opacity[1]) / 100;
    return 1.0;
  };

  Opacity.set = function(element, value) {
    function stripAlpha(filter) {
      return filter.replace(/alpha\([^\)]*\)/gi,'')
    }
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;
    var filter = element.style.filter,
     style = element.style;
    if (value == 1 || value === '') (filter = stripAlpha(filter)) ?
      style.filter = filter : style.filter = '';
    else style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
  };
}

function Appear(element) {
  var current = Opacity.get(element),
   options = arguments[1] || {};
  if (element.style.display != 'block')
    element.style.display = 'block';
  if (current < 1) {
    setTimeout(function() {
      Opacity.set(element, current += 0.05);
      Appear(element, options);
    }, 0.01);
  }
  else {
    if (Pushup.Browser.IE && element.style.filter)
      element.style.removeAttribute('filter');
    if (options.afterFinish) options.afterFinish.call();
  }
}

function Fade(element) {
  var current = Opacity.get(element),
   options = arguments[1] || {};
  if (current > 0) {
    setTimeout(function() {
      Opacity.set(element, current -= 0.05);
      Fade(element, options);
    }, 0.01);
  }
  else {
    element.style.display = 'none';
    if (options.afterFinish) options.afterFinish.call();
  }
}

function setPngBackground(element, url) {
  var options = Extend({
    align: 'top left',
    repeat: 'no-repeat',
    sizingMethod: 'crop',
    backgroundColor: ''
  }, arguments[2] || {});

  Extend(element.style, arguments.callee.IEBelow7 ? {
    filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' +
      url + '\'\', sizingMethod=\'' + options.sizingMethod + '\')'
  } : {
    background: options.backgroundColor + ' url(' + url + ') ' +
      options.align + ' ' + options.repeat
  });
}
setPngBackground.IEBelow7 = Pushup.Browser.IE &&
  parseFloat(/MSIE ([\d.]+)/.exec(navigator.userAgent)[1]) < 7;

// Based on the work of Peter-Paul Koch - http://www.quirksmode.org
var Cookie = {
  set: function(name, value) {
    var expires = '', options = arguments[2] || {};
    if (options.duration) {
      var date = new Date();
      date.setTime(date.getTime() + options.duration * 1000 * 60 * 60 * 24);
      value += '; expires=' + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
  },

  remove: function(name) { this.set(name, '', -1) },

  get: function(name) {
    var cookies = document.cookie.split(';'), nameEQ = name + "=";
    for (var i = 0, l = cookies.length; i < l; i++) {
      var c = cookies[i];
      while (c.charAt(0) == ' ')
        c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0)
        return c.substring(nameEQ.length, c.length);
    }
    return null;
  }
};

// check if cookies are enabled
Pushup.cookiesEnabled = (function(test) {
  if (Cookie.get(test)) return true;
  Cookie.set(test, 'test', { duration: 15 });
  return Cookie.get(test);
})('_pushupCookiesEnabled');

var Event = {
  add: function(obj, type, fn) {
    if (obj.attachEvent) {
      obj['e' + type + fn] = fn;
      obj[type + fn] = function(){ obj['e' + type +fn](window.event) };
      obj.attachEvent('on' + type, obj[type + fn]);
    }
    else obj.addEventListener(type, fn, false);
  },

  stop: function(event) {
    if (Pushup.Browser.IE) {
      event.cancelBubble = true;
      event.returnValue = false;
    }
    else {
      event.preventDefault();
      event.stopPropagation();
    }
  }
};

Event.add(window, 'load', function() { Pushup.start() });
})();