$(document).ready(function(){

	$("#b-login a").click(function(){
    $("#login").animate({opacity: "show"}, "slow");
	  return false;
	});
	
jQuery.fn.inputFieldText = function(string) {
  this.each(function() {
      $(this).addClass("fieldhint").val(string);
      $(this).focus(function(){
        if ($(this).val() == string){
          $(this).removeClass("fieldhint").val('');
        }
      });
      $(this).blur(function(){
        if ($(this).val() == '' ){
          $(this).addClass("fieldhint").val(string);
        }
      });  
  });
}

jQuery.fn.extend({
  scrollTo : function(speed, easing) {
    return this.each(function() {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset - 10}, speed, easing);
    });
  }
});
	
  $("#login input[name=logmail]").inputFieldText("E-post"); 
  $("#search input[name=q]").inputFieldText("Hva leter du etter?");
  
  $("form .hinted").focus(function () {
  	$(this).nextAll("em").animate({opacity: "show"}, "slow");
	})
	$("form .hinted").blur(function() {
	  $(this).nextAll("em").animate({opacity: "hide"}, "fast");
	});
	
  $("select[multiple]").asmSelect();
  if($(".asmListItem").length == 3) {
	  $(".asmSelect").attr("disabled", true);
	}
  
  $(".asmSelect").click(function() {
	  if($(".asmListItem").length == 3) {
	    $(this).attr("disabled", true);
	  }
	});
  
  $("#regcats").change(function() {
	  if($(".asmListItem").length < 3) {
      $(".asmSelect").removeAttr("disabled");
    }
	});
	
	$(".register").validate({
	  rules: {
	    regname: "required",
	    regblogname: "required",
	    regmail: {
	      required: true,
	      email: true
	    },
	    regpass: {
	      required: true,
	      minlength: 5
	    },
	    passrepeat: {
	      equalTo: "#regpass"
	    },
	    regurl: {
	      required: true,
	      url: true
	    },
	    regdesc: "required"
	  },
	  messages: {
	    regname: "Vennligst fyll inn et navn",
	    regblogname: "Vennligst fyll inn et navn",
	    regmail: {
	      required: "Vennligst fyll inn en e-mail",
	      email: "Sjekk at du har skrevet riktig"
	    },
	    regpass: {
	      required: "Du trenger et passord",
	      minlength: "Minst fem bokstaver"
	    },
	    passrepeat: {
	      equalTo: "Passordene stemmer ikke overens"
	    },
	    regurl: {
	      required: "Vennligst skriv inn adressa til bloggen din",
	      url: "Sjekk at du har skrevet adressa riktig"
	    },
	    regdesc: "Vennligst beskriv bloggen din"
	  }
	});
	
	$(".comment .editlink").click(function () {
    if ($(this).is(":contains('Rediger')")) {
      $(this).parent().next("p").replaceWith("<textarea>" + $(this).parent().next("p").text() + "</textarea>");
      $(this).text("Lagre");
    } else {
      $(this).after('<em id="ajaxloading">Lagrer...</em>');
      $(this).hide();
      var commentid = $(this).attr("href").split("=")[1];
      $.post("commentupdate.php", { id: commentid, text: $(this).parent().next("textarea").val() }, function(data){
        console.log("Result:" + data.result);
        console.log("Text:" + data.text);
        $("#ajaxloading").replaceWith("<em>Lagret</em>");
      }, "json" );
      $(this).parent().next("textarea").replaceWith('<p class="commenttext">' + $(this).parent().next("textarea").val() + "</p>");
    }
    return false;
  });
    
    $.fn.infinitescroll = function(options,callback){
      function debug(){
        if (opts.debug) { window.console && console.log.call(console,arguments)}
      }
      function areSelectorsValid(opts){
        for (var key in opts){
          if (key.indexOf && key.indexOf('Selector') && $(opts[key]).length === 0){
              debug('Your ' + key + ' found no elements.');    
              return false;
          } 
          return true;
        }
      }
      function determinePath(path){
        
        path.match(relurl) ? path.match(relurl)[2] : path; 
  
        // /page/2/
        if ( path.match(/^(.*?)\b2\b(.*?$)/) ){  
            path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1);
        } else 
          // any 2 at all.
          if (path.match(/^(.*?)2(.*?$)/)){
            // page=2
            if ( path.match(/^(.*?page=)2(\/.*|$)/) ){
              path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1);
              return path;
            }
            
            path = path.match(/^(.*?)2(.*?$)/).slice(1);
        } else {  
          props.isInvalidPage = true;  //prevent it from running on this page.
        }
        
        return path;
      }
      function getDocumentHeight(){
        return opts.localMode ? ($(props.container)[0].scrollHeight && $(props.container)[0].scrollHeight)  : $(document).height()
      }
      
      
          
      function isNearBottom(){
        var pixelsFromWindowBottomToBottom = 0 +
                  getDocumentHeight()  - (
                      opts.localMode ? $(props.container).scrollTop() : 
                      // have to do this bs because safari doesnt report a scrollTop on the html element
                      ($(props.container).scrollTop() || $(props.container.ownerDocument.body).scrollTop())
                      ) - $(opts.localMode ? props.container : window).height();
        
        debug('math:',pixelsFromWindowBottomToBottom, props.pixelsFromNavToBottom);
        
        // if distance remaining in the scroll (including buffer) is less than the orignal nav to bottom....
        return (pixelsFromWindowBottomToBottom  - opts.bufferPx < props.pixelsFromNavToBottom);    
      }    
      
      function showDoneMsg(){
        props.loadingMsg
          .find('img').hide()
          .parent()
            .find('div').html(opts.donetext).animate({opacity: 1},2000).fadeOut('normal');  
        opts.errorCallback();
      }
      
      function infscrSetup(){
      
          if (props.isDuringAjax || props.isInvalidPage || props.isDone) return; 
          
          if ( !isNearBottom(opts,props) ) return; 
          
          $(document).trigger('retrieve.infscr');
                  
                  
      }  // end of infscrSetup()
            
    
        
      function kickOffAjax(){
          props.isDuringAjax = true; 
          props.loadingMsg.appendTo( opts.contentSelector ).show();
          $( opts.navSelector ).hide(); 
          props.currPage++;
          // if we're dealing with a table we can't use DIVs
          box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>');  
          box
            .attr('id','infscr-page-'+props.currPage)
            .addClass('infscr-pages')
            .appendTo( opts.contentSelector )
            .load( path.join( props.currPage ) + ' ' + opts.itemSelector,null,loadCallback); 
          
      }
      
      function loadCallback(){
          // if we've hit the last page...
          if (props.isDone){ 
              showDoneMsg();
              return false;    
                
          } else {
            
              // if it didn't return anything
              if (box.children().length == 0){
                // fake an ajaxError so we can quit.
                $.event.trigger( "ajaxError", [{status:404}] ); 
              } 
              
              // fadeout currently makes the <em>'d text ugly in IE6
              props.loadingMsg.fadeOut(100, function() {$('#infscr-page-'+props.currPage).scrollTo(1000);});
              $( opts.navSelector ).show(); 
          
              // pass in the new DOM element as context for the callback
              callback.call( box[0] );
          
              props.isDuringAjax = false;
              
          }
      }
      
      var opts    = $.extend({}, $.infinitescroll.defaults, options),
          props   = $.infinitescroll, // shorthand
          box;
          
      callback    = callback || function(){};
      
      if (!areSelectorsValid(opts)){ return false;  }
      
       // we doing this on an overflow:auto div?
      props.container   =  opts.localMode ? this : document.documentElement;
                            
      // contentSelector we'll use for our .load()
      opts.contentSelector = opts.contentSelector || this; 
      
      
      // get the relative URL - everything past the domain name.
      var relurl        = /(.*?\/\/).*?(\/.*)/,
          path          = $(opts.nextSelector).attr('href');
      
      
      if (!path) { debug('Navigation selector not found'); return; }
      
      // set the path to be a relative URL from root.
      path          = determinePath(path);
      
  
      // reset scrollTop in case of page refresh:
      if (opts.localMode) $(props.container)[0].scrollTop = 0;
  
      // distance from nav links to bottom
      // computed as: height of the document + top offset of container - top offset of nav link
      props.pixelsFromNavToBottom =  getDocumentHeight()  +
                                       (props.container == document.documentElement ? 0 : $(props.container).offset().top )- 
                                       $(opts.navSelector).offset().top;
      
      // define loading msg
      props.loadingMsg = $('<div id="infscr-loading" style="text-align: center;"><img alt="Loading..." src="'+
                                    opts.loadingImg+'" /><div>'+opts.loadingText+'</div></div>');    
       // preload the image
      (new Image()).src    = opts.loadingImg;
                
  
    
      // set up our bindings
      $(document).ajaxError(function(e,xhr,opt){
        debug('Page not found. Self-destructing...');    
        
        // die if we're out of pages.
        if (xhr.status == 404){ 
          showDoneMsg();
          props.isDone = true; 
          $(opts.localMode ? this : window).unbind('scroll.infscr');
        } 
      });
       
      $(opts.localMode ? this : window)
        .bind('scroll.infscr', infscrSetup)
        .trigger('scroll.infscr'); // trigger the event, in case it's a short page
      
      $(document).bind('retrieve.infscr',kickOffAjax);
      
      return this;
    
    }  // end of $.fn.infinitescroll()
    
  
    
    // options and read-only properties object
    
    $.infinitescroll = {     
          defaults      : {
                            debug           : false,
                            preload         : false,
                            nextSelector    : "div.navigation a:first",
                            loadingImg      : "http://www.infinite-scroll.com/loading.gif",
                            loadingText     : "<em>Loading the next set of posts...</em>",
                            donetext        : "<em>Congratulations, you've reached the end of the internet.</em>",
                            navSelector     : "div.navigation",
                            contentSelector : null,           // not really a selector. :) it's whatever the method was called on..
                            extraScrollPx   : 150,
                            itemSelector    : "div.post",
                            animate         : false,
                            localMode      : false,
                            bufferPx        : 40,
                            errorCallback   : function(){}
                          }, 
          loadingImg    : undefined,
          loadingMsg    : undefined,
          container     : undefined,
          currPage      : 1,
          currDOMChunk  : null,  // defined in setup()'s load()
          isDuringAjax  : false,
          isInvalidPage : false,
          isDone        : false  // for when it goes all the way through the archive.
    };
    
      $('.infscroll').infinitescroll({
        navSelector  : "a#next:last",            
        nextSelector : "a#next:last",   
        itemSelector : ".infscroll div",
        animate      : true
      });
   
      // kill scroll binding
      $(window).unbind('.infscr');
      
      // hook up the manual click guy.
      $('a#next').click(function(){
        $(document).trigger('retrieve.infscr');
        return false;
      });
      
      // remove the paginator when we're done.
      $(document).ajaxError(function(e,xhr,opt){
        if (xhr.status == 404) { $('a#next').remove(); }
      });

});
