// Colors
var colors = new Array();
colors[0] = '#ef9f22';
colors[1] = '#7b99bf';
colors[2] = '#48b305';
colors[3] = '#e9a01e';
colors[4] = '#7f97c0';
colors[5] = '#59b7b7';
colors[6] = '#8bb97d';

// Shuffle array
function shuffleArray(myArray) {
  var i = myArray.length;
  if ( i === 0 ) return false;
  while ( --i ) {
    var j = Math.floor(Math.random() * (i + 1));
    var tempi = myArray[i];
    var tempj = myArray[j];
    myArray[i] = tempj;
    myArray[j] = tempi;
  }
}

$(document).ready(function(){
  
  // Search
  var resultData;
  var templateUrl = $('#templateUrl').val();
  var searchOn = false;
  $('#search').keyup(function(){
    searchOn = true;
		if(resultData == undefined){
		  $(this).parent().append('<img src="'+templateUrl+'/img/assets/ajax-loader.gif" class="loader" alt="Loading..." />');
			//resultData = "searching";
			$.get(templateUrl+"/assets/querys/searchQuery.php", function(data){
				resultData = $(data).find('#searchQuery').html();
				$('.loader').fadeOut('fast');
				$('#search-results').html(data);
				filterSearch();
			});
		}
		
		filterSearch();
		
	  var searchTerm = $(this).attr('value');
		if(searchTerm != ''){
			$('#search-results').fadeIn('fast');
			$('#adressbok').css('z-index','-10');			
			filterSearch();
		}else{
			$('#search-results').fadeOut('fast');
			$('#adressbok').css('z-index','1000');
		}
	});
  
  // Filter search
  function filterSearch(){
    $("#search-results li").each(function(){
      var filter = $('#search').val(), count = 0;
      if ( $(this).text().search(new RegExp(filter, "i")) < 0 ){
        $(this).css("display", 'none');
      }else{
        $(this).css("display", 'list-item');
        count++;
      }
    });

	// Maximum 5 of each
	$('#searchResultPosts li:visible').slice(5).css('display', 'none');
	$('#searchResultMembers li:visible').slice(5).css('display', 'none');
	$('.wp-tag-cloud li:visible').slice(5).css('display', 'none');
	
  }
  
  // Search input
  $('input[type="text"]:not(.permalink), textarea').focus(function() {
    if (this.value == this.defaultValue){ 
      this.value = '';
    }
  });
  
  $('input[type="text"]:not(.permalink), textarea').blur(function() {
    if (this.value == ''){
      this.value = (this.defaultValue ? this.defaultValue : '');
    }
  });
  
  // Close search
  $('body:not(#search-results)').click(function(){
    $('#search-results').fadeOut('fast');
  });
  
  // Open search after search
  $('input[type="text"]#search').focus(function() {
    if ( searchOn == true && this.value != '' ){
      $('#search-results').fadeIn('fast');
    }
  });
  
  // Random colors on search hover
  $('#searchResultPosts li, #searchResultMembers li, .wp-tag-cloud li').live('mouseover mouseout', function(event){
    if (event.type == 'mouseover'){
      shuffleArray(colors);
      $(this).css({
        'background': colors[0]
      });
    }else{
      $(this).css({
        'background': '#fff'
      });
    }
  });
  
  // Share dropdown
  $('.share a:first-child').toggle(function(){
    $(this).parent().parent().siblings('.shareDropDown').slideDown('fast');
    $(this).css({
      'background-position': '45px -8px'
    });
  },function(){
    $(this).parent().parent().siblings('.shareDropDown').slideUp('fast');
    $(this).css({
      'background-position': '45px 8px'
    });
  });
  
  // Share select
  $('input.permalink').click(function(){
    $(this).select();
  });
  
  $('input.copy').click(function(){
    $(this).siblings('input.permalink').select();
  });
  
  // Menu random color hover
  $('#infoWrapper ul li a').hover(function(){
    shuffleArray(colors);
    $(this).css({
      'color': colors[0]
    });
  },function(){
    $(this).css({
      'color': '#222'
    });
  });
  
  // Menu random color mousedown
  $('#infoWrapper ul li a').mousedown(function(){
    shuffleArray(colors);
    $(this).css({
      'color': colors[0]
    });
  });

  // Like button
  $('.like').click(function(){
	_this = $(this);
	_this.hide()
	var dataVar = $(this).attr('name');
	
  	if($(this).css('background-image') == 'url("'+templateUrl+'/img/icons/likeLiked.png")'){
  		$(this).css('background-image', $(this).data('bg'));
  		var oldText = $(this).text();
  		var newText = parseFloat(oldText) -1;
  		$(this).text(newText).css({'color':'#aaa'});
		
  		$.ajax({ 
  		   type: "POST", 
  		   url: templateUrl+"/assets/querys/likeQuery.php", 
  		   data: "postId="+dataVar+"&remove=true", 
  		   success: function(msg){
  		     _this.fadeIn('450')
  		   }
  		 });
		
  	}else {
  		
  		$(this).data('bg', $(this).css('background-image'));
  		$(this).css('background-image', 'url('+templateUrl+'/img/icons/likeLiked.png)');
		
  		$.ajax({ 
  		   type: "POST", 
  		   url: templateUrl+"/assets/querys/likeQuery.php", 
  		   data: "postId="+dataVar+"&remove=false", 
  		   success: function(msg){
  		     _this.fadeIn('550')
  		   } 
  		 });

  		var oldText = $(this).text();
  		var newText = parseFloat(oldText) + 1;
  		$(this).text(newText).css({'color':'#ff453c'});
  	}
  	return false;
  });
  /*
  // Like large (single)
  $('.likeLarge').toggle(function(){
  	orig_like_bg = $(this).css('background-image');
    $(this).css({
   	  'background-image': 'url("http://sofo-stockholm.se/wp-content/themes/sofo-main/img/backgrounds/likeLarge9.png")',
      'background-position': '0 -134px'
    });
  },function(){
    $(this).css({
   	  'background-image': orig_like_bg,
      'background-position': '0 0'
    });
  });
  */
  // Image gallery
  $('.imagePost').hover(function(){
    $('.postMeta', this).css({
      'display':'block'
    });
    $('.postThumb', this).css({
      'display':'none'
    });
  }, function(){
    $('.postMeta', this).css({
      'display':'none'
    });
    $('.postThumb', this).fadeIn('fast');
  });
  
  // Infinite scroll
  if ( $('#postNavigation').length == 0 ){
    $('#loadMorePosts').hide();
  }
  
  $('#postNavigation').hide();
  
  $('#loadMorePosts').click(function(){
    
    $('a span',this).each(function(){
      /*
      shuffleArray(colors);
      $(this).css({
        'color': colors[0]
      });
      */
    });
    //$(this).html('<img src="'+templateUrl+'/img/assets/loadMorePostsLoader.gif" alt="Laddar..." />');
    $(document).trigger('retrieve.infscr');
    return false;
  });
  
  // Load more posts hover
  $('#loadMorePosts').hover(function(){
    shuffleArray(colors);
    $('a span',this).css({
      'color': colors[0]
    });
  },function(){
    $('a span',this).css({
      'color': '#fff'
    });
  });
  
  // Share permalink through e-mail
  $('.send').live('click', function(){
  	fieldset=$(this).parent('.send-via-mail');
    $.ajax({
      type: 'POST',
      data: ({
        postTitle     : $(this).siblings('.postTitle').val(),
        permalink     : $(this).siblings('.permalink').val(),
        senderEmail   : $(this).siblings('.senderEmail').val(),
        receiverEmail : $(this).siblings('.receiverEmail').val(),
        message       : $(this).siblings('.message').val()
      }),
      url: templateUrl+'/assets/querys/emailPermalink.php',
      success: function(data) {
        fieldset.slideUp();
      }
    });
  });
  
  // CSS in JavaScript (god forbid)
  $('#storeDescription .text').css({
    'top'       : '50%',
    'marginTop' : -($('#storeDescription .text').height()/2)
  });
  
  // Google translate
  $('#translate').hover(function(){
    $(this).css({
      'background-position' : '0 -53px'
    });
    $(this).siblings('#translatePopup').fadeIn('fast');
  },function(){
    $(this).css({
      'background-position' : '0 0'
    });
    $(this).siblings('#translatePopup').fadeOut('fast');
  });
  
  $('#translate').click(function(){
    location.href = 'http://translate.google.com/translate?js=y&prev=_t&hl=sv&ie=UTF-8&layout=1&eotf=1&u=http%3A%2F%2Fsofo-stockholm.se&sl=sv&tl=en';
  });
  
  // Contact grid
  /*
  var blockWidth = 240;
  var blockHeight = 180;
  var columns = 4;
  var loopcounter = 0;
  
  function contactGrid(){
    loopcounter = 0;
    $('.storeCard.'+filterStore).each(function(){
      offsetX = (loopcounter % columns) * (blockWidth);
      offsetY = Math.floor(loopcounter/columns) * (blockHeight);
      
      $(this).css({
        'left' : offsetX+'px',
        'top'  : offsetY+'px'
      });
      
      loopcounter++;
    });
  }
  */
  
  // Hover contact grid
  $('.storeCard').hover(function(){
    $('.storeCard').css({
      'z-index':1
    });
    $(this).css({
      'z-index':2
    });
    
    $(this).animate({
      'height'      : '445px',
      'width'       : '330px',
      'marginLeft'  : '-40px'
    }, { duration: 200, queue: false });
  },function(){
    
    $(this).animate({
      'width'       : '199px',
      'height'      : '180px',
      'marginLeft'  : '0'
    }, { duration: 200, queue: false });
  });
  
  // Random contact grid outline
  $('.storeCard').each(function(){
    shuffleArray(colors);
    $(this).css({
      'border' : '1px solid'+colors[0]
    });
  });
  
  $('.storeCard em').each(function(){
    shuffleArray(colors);
    $(this).css({
      'color' : colors[0]
    });
  });
  
 
  // Filter stores
  var letterX = 0;
  var letter;
  var filterStore;
  var visibleContacts = 0;
  var contactRows = 0;
  
  /*$('#filterStores ul li:not(.dont)').hover(function(){
    $(this).addClass('active');
    letterX = Math.round($(this).position().left);
    letter = $(this).html();
    $('#filterOverlay').css({
      'left'    : letterX+'px',
      'display' : 'block'
    }).html(letter);
  },function(){
    $(this).removeClass('active');
  });
  
  $('#filterStores').mouseleave(function(){
    $('#filterOverlay').hide();
  });
*/
 /* $('#filterOverlay a, #filterStores ul li a').live('click', function(){
    visibleContacts = 0;
    filterStore = $(this).text().toLowerCase();
    
    $('.storeCard').hide();
    visibleContacts = $('.storeCard.'+filterStore).length;
    
    contactRows = Math.ceil(visibleContacts/columns);
    
    $('#contactWrapper').animate({
      'height'  : (contactRows*blockHeight)+'px'
    },function(){
      $('.storeCard.'+filterStore).fadeIn('fast');
    });
    //console.log(filterStore);
    
    contactGrid();
    
    return false;
  });
  */
  
  // Init
  //if( $('#filterStores').length > 0 ){
  //  $('#filterStores ul li a').eq( Math.floor( Math.random()* $('#filterStores ul li a').length ) ).trigger('click');
  //}
  
  
  // Logged in menu hover
  $('.logged-in #adminMenu ul li').hover(function(){
    $(this).css({
      'background'  : '#292929'
    });
    $('a', this).css({
      'color'       : '#ead915'
    });
  },function(){
    $(this).css({
      'background'  : '#ead915'
    });
    $('a', this).css({
      'color'       : '#292929'
    });
  });
  
});
