$(document).ready(function(){

	var jsonurl = 'http://search.twitter.com/search.json?q=';
	var query = 'http://search.twitter.com/search.json?q=';
	var users = $('#twittersave textarea').val().toString().split(/\r\n|\r|\n/);
	
	$.each(users,function(key,val){
		if(val.length > 0){
			query = query + val.replace('@','from:') + ' OR ';
		}
	});

	jsonurl = encodeURI(query.substr(0,query.length-4) + '&callback=?');
	
	$.getJSON(jsonurl, function(data){
		if(data.results.length){
			var max = 5;
			var counter = 1;
			var tweets = [];
			$.each(data.results,function(key,val){
				var user = this.from_user;
				var shortmsg = this.text.substr(0,60);
				var msg = this.text;
				var img = this.profile_image_url;
				var itemstring = '<div><img src="'+img+'" /><p><a href="http://twitter.com/'+user+'/" target="_blank" title="'+msg+'">'+shortmsg+'...</a><br />by '+user+'</p></div>';
				if(counter%max == 0){ itemstring = itemstring + '</li>'; }
				if((counter-1)%max == 0){ itemstring = '<li>' + itemstring; }
				tweets.push(itemstring);
				counter++;
			});
			$('<ul/>', {
				'class': 'tweetlist',
				html: tweets.join('')
			}).appendTo('#twitterwrapper').cycle({
				slideExpr: 'li',
				fx: 'scrollUp',
				height: 'auto',
				fit: true,
				timeout: 10000,
				pause: true
			}).after('<a href="http://twitter.com/UMIC_Ltd" target="_blank" class="twitterfollowlink">FOLLOW US ON TWITTER</a>');
		} else {
			$('<p/>',{
				html: 'Sorry, there was an error connecting to Twitter'
			}).appendTo('#twitterwrapper');
		}
	});
	
	
	
	$('#duocmsToolbar').load(function(){
		$('#duocmsToolbar').contents().ready(function(){
			var savebutton = $('#duocmsToolbar').contents().find('#textedit a').first();
			var sid = $('#duocmsStructureId').val();
			
			savebutton.mousedown(function(){
			
				var usersave = $('#twittersave textarea').val().toString().split(/\r\n|\r|\n/);
				var userlist = '';
				$.each(usersave,function(key,val){
					userlist = userlist + val + '|';
				});
				
				userlist = userlist.substr(0,userlist.length-1);
				
				//alert(userlist);
				
				// save order of boxes				
				$.ajax({
					type: "POST",
					url: '/duocms/twitter/save/'+userlist+'/',
					success: function(msg){
						//console.log('layout saved');
					}
				});
			});
		});
	});

	
	
	

});
