//namespace container
var blog = {};
//cufon classes
var NOKIALARGE = '.nokialarge, .sidebar h3, .#footer h3, .single h1 .entry-title, blockquote.pullquote, .footer-column li span.num';
var NOKIASTANDARD = '.nokiastandard, .post-excerpt-text p, .sociable_tagline, .rate-wrapper h4';
var NOKIALIGHT = '.nokialargelight';
var NOKIALARGE_HOVER = '.main-menu a ,#all-destinations-header ,.archive h2.entry-title a, .about h2.entry-title, .archive-menu h4 a';

//container for custom UI objects
blog.running = {}
blog.init = {};

/*
Before onload
  -Stuff that doesn't need to or shouldn't be run on document.ready
*/


/* END OF before onload*/

/* ONLOAD */

$(document).ready(function(){
  $('#noscript').hide();
  $('body').addClass('dynamic');
  $('.s').each(function(){blog.searchField($(this));});


  blog.footerHover();
  blog.prevnextNumbers();
  blog.running.gallery = new blog.Postgallery();
  blog.running.mostpopular = new blog.MostPopular();
//~ if(blog.init.archive) {
    blog.themesToggle();
//~ }
  if(blog.init.single) {
    blog.initCommentForm();
    blog.sociableLabels();
    blog.blockQuotes();
    blog.addSomeRaquos('.tag-cloud.destinations .tag-cloud-content a');
    //blog.insertClearButton();
  }

  if(blog.init.frontpage) {
    blog.featureTags();
    blog.frontpageHovers.init();
  }


  if(blog.init.feedback) {
    blog.setFeedbackDefaults();
  }
  //keep this last!!!
  blog.cufonInit();

});
/* END OF onload*/

/* FUNCTIONS */

//~ blog.initFeature1Hover = function () {
//~ $('.feature-1 .feature-text').hover(
	//~ function() {
		//~ $(this).addClass('hover');
	//~ }
	//~ ,
	//~ function() {
		//~ $(this).removeClass('hover');
	//~ }
	//~ );
//~ }


blog.sociableLabels = function() {

  $('.sociable li a').each(function(){
      $link = $(this);
      //take only the first word
      $title = $('<span class="sTitle">'+this.title.split(' ')[0]+'</span>');
      $link.append($title);


    });
  }

blog.footerHover = function() {
  $('#footer').hover(
    function(){
        $(this).find('.wrapper').addClass('hover');
        Cufon.replace('#footer h3, #footer .num',{fontFamily:'Nokia Large',color:'#333'})
    }
    ,

    function(){
        $(this).find('.wrapper').removeClass('hover');
        Cufon.replace('#footer h3, #footer .num',{fontFamily:'Nokia Large',color:'#999'})
    }
  );
}
blog.prevnextNumbers = function() {

  var buttons = $('#wp_page_numbers');

  if(buttons.length) {

  currentPage = location.href.match(/\/page\/(\d{1,9})\/$/);
  currentPage = currentPage != null ? parseInt(currentPage[1]) : 1;

  var prevBtn = buttons.find('.prev_page a');
  var nextBtn = buttons.find('.next_page a');
  var lastNum = parseInt(buttons.find('.next_page').prev().text());

  if(currentPage != 1)
  prevBtn.html('<span class="""><span class="green">&laquo;</span> Page '  + (currentPage-1) + '</span> ').show();


  if(currentPage < lastNum)
  nextBtn.html('<span class="">Page '  + (currentPage+1) +' <span class="green">&raquo;</span> </span>' ).show();

  }
}

blog.blockQuotes = function() {

  $('blockquote.blockquote').prepend('<span class="icon quote"></span>');
}

blog.addSomeRaquos = function(someSelectors) {


$(someSelectors).prepend('<span class="green">&raquo;</span> ');

}

//~ blog.insertClearButton = function() {
  //~ $('.feedback .submit').before('<input class="button" type="reset" value="Clear form" style="margin-right:10px;"/>');
//~ }

blog.cufonInit= function() {
  //Cufon.replace('.nokialarge', {fontFamily:'Nokia Large'});
  Cufon.replace(NOKIALARGE_HOVER, {fontFamily:'Nokia Large',hover:true});
  Cufon.replace(NOKIALARGE, {fontFamily:'Nokia Large'});
  Cufon.replace(NOKIASTANDARD, {fontFamily:'Nokia Standard'});
  Cufon.replace(NOKIALIGHT, {fontFamily:'Nokia Large Light'});
}

blog.setFeedbackDefaults = function () {


  $('.radio_type input:first, .radio_topic input:first').select();

  $('.radio:_type input, .radio_topic input').each(function(i){
    var oldLabel = $(this).next();
    var newLabel =  $('<label></label')
                      .text(oldLabel.text())
                      .addClass('wpcf7-list-item-label')
                      .attr('for','radio-'+i);
    oldLabel.remove();
    $(this).attr('id','radio-'+i).after(newLabel);

  });


}

blog.featureTags = function() {

    var $tags = $('#tags-places');
    if(!$tags.length) return false; //no tags? byebye

    var tabToggle = function() {

	    var $button = $(this);
	    var $target = $($button.attr('href'));
	    if($target.is(':visible') )return false;

	    $button.addClass('active').siblings('a').removeClass('active');
	    $tags.children('.tab-content').hide();
	    $target.show();
	    return false;

    }

    //$tags.find('.tab-content:not(:first)').hide();
    $('.tags-places-menu a').click(tabToggle)
			    .filter(':first')
			    .click();

}



blog.searchField = function($s) {

  if(!$s.length) return false;

  var defaultText = $s.siblings('label.defaultvalue').text();
  $s.focus(function(){
  this.value == defaultText ? this.value = '' :  $(this).select();
this.select();
  })
    .blur(function(){
      this.value = (this.value == ''? defaultText: this.value);
    });

   if($('body').hasClass('search-no-results')) {
    $('form#searchform-no-results').find('.s').focus();
   }
   return 1;
}


blog.MostPopular = function(viewtype) {


  this.selectors = {root: '.most-popular',navi:'.navi-container', allpages:'.all-pages', current:'.current-page'}
  this.root = null;
  this.naviCurrentpageHtml = null;
  this.naviAllpagesHtml = null;

  this.paging = {pagecount:0, current:1, perpage:0, imagecount:0};
  this.navihtml = '<div class="navi-container fRight"> \
  <span class="paging"><span class="current-page"></span> / \
  <span class="all-pages"></span></span> \
  <a href="#prev-popular" class="prev-popular">&lt;=</a> \
  <a href="#next-popular" class="next-popular">=&gt;</a> \
  </div> ';

  var init = function () {
    self.root = $(self.selectors.root);
    if(!self.root.length) {return false;} //do nothing if there's nothing to do...

   //put the navigation in place and bind the buttons
    self.root.find('h3').before(self.navihtml).end()
	     .find('.next-popular').click(self.nextpage).end()
	     .find('.prev-popular').click(self.prevpage);


    self.naviCurrentpageHtml = self.root.find('.current-page');
    self.naviAllpagesHtml = self.root.find('.all-pages');
    self.paging.pagecount = self.root.find('li').length;
    self.root.find('li:gt(0)').hide();
    self.root.find('li').click(self.bigLink)
                        .find('h2 a')
                        .prepend('<span class="relative"><span class="view-upleft"></span></span>');
    self.updatepagenums();

    return true
  }

 this.updatepagenums = function() {
	self.naviCurrentpageHtml.text( self.paging.current);
	self.naviAllpagesHtml.text( self.paging.pagecount);
	return true;
    }

  this.nextpage = function() {

    if(self.paging.current < self.paging.pagecount)
      {
        self.paging.current++;
        self.root.find('li:visible').hide().next().fadeIn('fast');

      }
    else
      {
        self.paging.current = 1;
        self.root.find('li:visible').hide().siblings(':first').fadeIn('fast');
      }

	  self.updatepagenums();



      return false;
  }

  this.prevpage = function() {

    if(self.paging.current > 1)
      {
        self.paging.current--;
        self.root.find('li:visible').hide().prev().fadeIn('fast');
      }
    else
      {
        self.paging.current =self.paging.pagecount;
        self.root.find('li:visible').hide().siblings(':last').fadeIn('fast');
      }

	  self.updatepagenums();


      return false;
  }

  this.bigLink = function() {
    top.location.href = $(this).find('h2 a').attr('href');

  }

  var self = this;
  init();

}

blog.themesToggle = function() {
  var button =$('.themes #view-all');
  if(!button.length) return false;
  var doToggle = function(){

    var container = $('.tag-cloud');
    container.find('span.header-state').toggle();
    var hideCloud = container.find('p:visible');
    var showCloud = container.find('p:hidden');
    var hideLabel = button.find('span.label:visible');
    var showLabel = button.find('span.label:hidden');
    hideCloud.hide();
    showCloud.fadeIn('normal');
    hideLabel.hide();
    showLabel.show();

    return false;
  }

  button.click(doToggle);

}


blog.initCommentForm = function() {

  var checkCommentForm = function() {
    var $form = $(this);
    $form.find('.error').removeClass('error');

    $form.find('input.required, textarea.required').each(function(){
		$errMessage = $(this).next().hide()
		if(!$(this).val())
			$(this).addClass('error')

		if(this.id == 'email' && !( /^(([a-zA-Z0-9_\.\-+])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+(( *, *)|( +)|$))+/.test(this.value) ))
			$(this).addClass('error')
    
		if($(this).hasClass('error'))
			$errMessage.fadeIn('fast')
    });

    var hasErrors = ($form.find('.error').length == 0 )

    return hasErrors;
    //return false;
  }

 $('#commentform').unbind('submit')
                  .submit(checkCommentForm).find('input[type="text"]')
                  .focus(function(){this.select()});;
}




blog.frontpageHovers = {

  dimmer:null,
  timer: null,
  current:null,
  //container: $('.mozaic-1'),
  init:function(){


//    blog.frontpageHovers.container = $('.mozaic-1');
      //feature click handler
    $('.feature-1 .feature-text, .small-feature').click(
      function(e){

        switch(e.target.nodeName) {

          case 'DIV':
            window.location = $(this).find('h2 a').attr('href');

          break;
          //mozaic-1
          case 'IMG':
            window.location = $(this).parent().find('h2 a').attr('href');
          break;
          default:

        }
      }
      
    );      
    
   $('.mozaic').click(
        function(e) {
          if (e.target.nodeName == 'DIV' ||  e.target.nodeName == 'IMG' )  {
                window.location = $(this).find('h2 a').attr('href');
          }
        }
      
      
    );

    //FEATURE HOVER & BIG MOZAIC HOVER

    //$('.mozaic-1, .feature-1 .feature-text,  .small-feature').hover(

    $('.mozaic , .feature-1 .feature-text,  .small-feature').hover(

      function(){
        $(this).find('h2')
               .css('background','url('+preloads.t80.src+')');
      }
      ,
      function(){
        $(this).find('h2')
               .css('background','url('+preloads.t60.src+')');
      }
    )
    
    

    //SMALL TILE HOVERS
/*
    $('.mozaic-small').hover (
    function() {
      if($(this).hasClass('hover') ) return false; //no repetition
      blog.frontpageHovers.dimmer =  $(this).find('.dimmer');
      blog.frontpageHovers.current = $(this);
      blog.frontpageHovers.timer = setTimeout('blog.frontpageHovers.show()',300);
    }
    ,
    function() {
      clearTimeout(blog.frontpageHovers.timer);
    }

    ).click(function(){
      top.location.href =   $(this).find('h2 a').attr('href');
    });
*/
  }


/*
  ,
  show: function() {

    blog.frontpageHovers.hide();
    blog.frontpageHovers.dimmer.parent().addClass('hover');
    blog.frontpageHovers.dimmer.stop(true,true).fadeIn(100);
    blog.frontpageHovers.dimmer.siblings('h2').fadeOut(100);
    blog.frontpageHovers.container
                        .html(blog.frontpageHovers.current.html())
                        .find('.dimmer').remove();
    ;

    Cufon.refresh('.mozaic-1 .large-header');

  }
  ,
  hide: function(){
    var active = $('.mozaic-wrapper .hover');
    active.removeClass('hover')
          .find('.dimmer').hide().end()
          .find('h2').show();

  }
*/

}



blog.Postgallery = function() {

    this.galleryHtml = null; //parent level reference to the gallery html object... all is inside this
    this.paging = {pagecount:0, current:1, perpage:8, imagecount:0};
    this.naviCurrentpageHtml = null;
    this.naviAllpagesHtml = null;
    this.thumbnails = null; //shorthand to all image thumbnails;


    var init = function() {
      //html parent for gallery

      self.galleryHtml= $('#gallery-container');
      //if gallery html is not in the page.. forget it, this script is going home
      if(!$('.ngg-galleryoverview:first').length){return false;}

      //move the gallery from post to sidebar and hide all but the first page
      self.galleryHtml.append($('.ngg-galleryoverview:first'))
      this.thumbnails = self.galleryHtml.find('.ngg-gallery-thumbnail-box');

      //calculate some values for paging
      self.paging.imagecount = this.thumbnails.length;
      self.paging.pagecount = Math.round(self.paging.imagecount / self.paging.perpage);
      self.naviCurrentpageHtml = self.galleryHtml.find('.gallery-current-page');
      self.naviAllpagesHtml = self.galleryHtml.find('.gallery-total-pages');
      self.nextHtml = self.galleryHtml.find('a.gallery-next');

      if(this.thumbnails.find('a[rel*=lightbox]').length){


	  this.thumbnails.find('a[rel*=lightbox]').lightBox();
      }
      //this.thumbnails.children('a').lightBox();

      //divide pictures into page sets
      for(i = 1; i<=self.paging.pagecount; i++) {
	  var thumbset = this.thumbnails;
	  var start = i*self.paging.perpage -self.paging.perpage;
	  var end = (i == self.paging.pagecount ? undefined : i*self.paging.perpage);
	  if(end){
	      thumbset.slice(start,end).wrapAll('<div class="gallery-page"></div>');
	  }
	  else {
	      thumbset.slice(start).wrapAll('<div class="gallery-page"></div>');
	  }
      }


      //show the gallery and first page, (all pages are hidden from styles.css)
      //bind paging buttons
      self.galleryHtml.show()
		      .find('.gallery-page:first').show().end()
		      .find('.ngg-gallery-thumbnail-box:even').addClass('even').end()
		      .find('a.gallery-prev').click(self.prevpage).end()
		      .find('a.gallery-next').click(self.nextpage);
      //populate paging indicators
      self.updatepagenums();
      return true;
    }



    this.updatepagenums = function() {
	self.naviCurrentpageHtml.text( self.paging.current);
	self.naviAllpagesHtml.text( self.paging.pagecount);
	return true;
    }

    this.nextpage = function() {
	if(self.paging.current < self.paging.pagecount) {
	    self.paging.current++;
	    self.updatepagenums();
	    self.galleryHtml.find('.gallery-page:visible').hide().next().fadeIn('fast');

	}
	return false;
    }

    this.prevpage = function() {

	if(self.paging.current > 1) {
	    self.paging.current--;
	    self.updatepagenums();
	    self.galleryHtml.find('.gallery-page:visible').hide().prev().fadeIn('fast');
	}
	return false;
    }


    var self = this;

    init();
}

