jQuery(document).ready(function($) {


	$('#tw-expander').click(expand);
	$('.tweethide').css('display', 'none');
	update_tweets();
	setInterval(update_tweets, 120000); //update tweets every 2 minutes
	setup_unlink();


	function update_tweets() {
	  $("#tw-content").empty()
	  $.getJSON('http://search.twitter.com/search.json?q=%23medieteknik&rpp=5&result_type=recent&callback=?',
	    	function(json, status) {
	      		$(json.results).each(function(i){
	      			//hitta urler
	      		var urlRegEx = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
            var msg = this.text.replace(urlRegEx, function(urlMatch) {
              return '<a href="' + urlMatch + '">' + urlMatch + '</a>';
            });
            
		        if (i % 2 == 0) {
		          var oddeven = 'odd'
		        } else {
		          var oddeven = 'even'
		        }
		        var tweet = '<div class="tweet ' + oddeven + '" >' +
		        	'<div class="tweet-body">' +
					'<img class="tweet-img" src="' + this.profile_image_url +'" />' +
					'<p class="tweet-from">'+this.from_user+': </p>'+
		        	'<div class="tweet-text">' + msg + ' </div>' +		
					'<div class="tweet-date"> ' + new Date(this.created_at).toLocaleString() + '</div>'+
					'</div></div>'; 
		        $(tweet).appendTo("#tw-content");
				if(i < 1) { // visa bara den första
					//$('.tweet').fadeIn('slow');
					$('.tweet').css('display', 'block');
				}
				
		      });
		
		      //set_container_minheight();
	    });
	}

	function set_container_minheight() {
	 // $('#tw-content').css('height', $('.tweet').height() + 'px');
	}


/*	function setup_slide() {

	} */
	
	function show_one(selector) {
	
		$(selector).each(function(index) { 
			if(index < 1) { // visa bara de tre första entries
				$(this).fadeIn('slow');
			} else {
				$(this).fadeOut();
			}
		});
	}


	function expand(){
	  if($('#tw-frame').css('height') != 'auto') {
	    	//time to expand
	    	//$('#tw-content').height('100%'); //make room to show tweets
	    	$('#tw-frame').height('auto');
			$('.tweet').css('margin','0 0 10px');
			$('.tweet').fadeIn('slow');
			$('.tweethide').fadeIn('slow'); //unhide tweet back form
			$('#tw-expander').html('Minimera'); //change text of button
		} else {
		  //make the box the height the myBar
			$('#tw-frame').stop().animate({height:'100%'},{queue:false,duration:400});
			$('.tweet').css('margin','0px');
			$('#tw-expander').html('Expandera');
	    	$('.tweethide').fadeOut(); //hide tweetback form
			show_one('.tweet');
		}
	}
	
	function setup_unlink() {
	  $('#twitterUnlink').click(function() {
      $.get('http://medieteknik.com/wp-content/plugins/medieteknik-myBar/twitter/twitter_unlink.php', function(data) {
        $('.tw-bottom').html('Ditt twitterkonto har avlänkats!');
      });
	  });
	}
	
//	$('#tweetbox').focus().animate({height:'25px'},{queue:false,duration:200});

	
});

