		var itemList = new Array();
		var numberOfItems = 20;
		var totalItems = 0;
		
		var searchObject;
		
		
		function mycarousel_initCallback(carousel) {
			$().keypress(
			function( e ) {
				// go down - space
				// check focus
				
				
				if( e.which == "46" || e.which == "32" ) {
					if( $('#info_box_tags_input input.tv-focused').length > 0) return;
					
					// select next one if space is pressed
		        	selectedIndex++;
		        	setThumbItemSelected(selectedIndex);
					
					/*
					var topString = $('#nav_thumb_list').css("top");
					var top = topString.substring( 0, topString.length-2 );
					var newTop = String(top - 96) + "px";
					alert( newTop );
					$('#nav_thumb_list').css("top", newTop );
					*/
					
					carousel.scroll(selectedIndex+1);
					
				}
				
			});
		
		};

		function mycarousel_itemLoadCallback(carousel, state)
		{
			
			globalCarousel = carousel;
		    //Check if the requested items already exist
		    if (carousel.has(carousel.first, carousel.last)) {
		
		        return;
		    }
			
			// to make it work in IE6 / IE7 (they do seem to properly evaluate the previous statement)
			//if( selectedIndex < $('#nav_thumb_list').children().length - 10 )
			//	return;
		
		    loadNewThumbs(carousel, numberOfItems);
		    
		        
		};
		
		function mycarousel_itemAddCallback(carousel, first, last, json)
		{
			
			// if json object is an array, we are dealing with solely an array of patterns
			if( json instanceof Array ) {
				
			  	// Set the size of the carousel
		    	carousel.size(carousel.size() + json.length);
				
				$.each( json, function(j,item) {
				
					itemList[totalItems] = item;
					
					totalItems++;
					
					var item = carousel.add(first + j, mycarousel_getItemHTML(item));
					
					item.click(function() {
						
						// scroll to top, or one below the top
						
						// set the background
						var itemIndex = $(this).attr('jcarouselindex');
						
						
						itemIndex = parseInt(itemIndex);
						setThumbItemSelected(itemIndex);
						
						carousel.scroll( itemIndex + 1 );
						
						// and the info box	        	
					});
				});
				
				setThumbItemSelected(selectedIndex);
				
				return;
			}
			
			// otherwise, we are dealing with the extended version of the response,
			// including the total number of items fitting the search request
			
			if( carousel.size >= json["total"] )
				return;
			
			// Set the size of the carousel
		    carousel.size(carousel.size() + json["patterns"].length);
			
		    $.each(json, function(i,item) {
				
				if( i == 'total' ) {
					$('#search_results').html( item );
				}
				else if( i == 'patterns') {
					
					$.each( item, function(j,item) {
				
						itemList[totalItems] = item;
						
						totalItems++;
						
						var item = carousel.add(first + j, mycarousel_getItemHTML(item));
						
						item.click(function() {
							
							// scroll to top, or one below the top
							
							// set the background
							var itemIndex = $(this).attr('jcarouselindex'); 
							
							itemIndex = parseInt(itemIndex);
							setThumbItemSelected(itemIndex);
							
							carousel.scroll( itemIndex + 1 );
							
							// and the info box	        	
						});
					});
					
					//$('#nav_thumb_list').css("top", "0");
				}
		    });
			
			setThumbItemSelected(selectedIndex);
			
			
		    
		};
		
		
			
		/**
		 * This is the callback function which receives notification
		 * when an item becomes the first one in the visible range.
		 */
		function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
		    //setThumbItemSelected(idx);
		}
		
		function mycarousel_itemLastInCallback(carousel, item, idx, state) {
	
		    if(selectedIndex >= totalItems-4 && !searchObject){ // load some new images
		    	loadNewThumbs(carousel, 1);
		    	//loadNewThumbs(carousel);
		    }
		}


		
		/**
		 * Item html creation helper.
		 */
		function mycarousel_getItemHTML(item)
		{
			var thumbWidth = 200;
			var thumbHeight = 75;
		    return '<a href="#"><img src="tiles/' + thumbWidth + 'x' + thumbHeight + '/' + item.name + '&s=1&r=2" width="' + thumbWidth + '" height="' + thumbHeight + '" alt="' + item.name + '" /></a>';
		}
		
		function loadNewThumbs( carousel, number ){
			
			if(searchObject){
				searchObject['of'] = totalItems;
				searchObject['num'] = numberOfItems; 
				//searchObject['num'] = number; 
				$.getJSON(
			        'do/search/',
			        searchObject,
			        function(json) {
			        	//itemList = json;
			            mycarousel_itemAddCallback(carousel, totalItems, totalItems + json.length, json);
			        });
			} else {
				// no search, go random
				$.getJSON(
			        'do/random/', {
						
						num: numberOfItems
					},
			        function(json) {
			        	//itemList = json;
			            mycarousel_itemAddCallback(carousel, totalItems, totalItems + json.length, json);
			        });
			}
		}
		
		var selectedItem = '';
		var selectedIndex = 0;
		
		function setThumbItemSelected( index ){
			
			selectedIndex = index;
			if(!itemList) return;
			selectedItem = itemList[index];
		    
		    if(!selectedItem) return;
        	var url = 'patterns/' + selectedItem.name;
        	
        	$(document.body).css('backgroundImage','url(' + url +')');
        	
        	// do the info box
        	
        	setInfoBox( selectedItem );
        	
		}
		
				
		function updateData( dataItem ){
			itemList[selectedIndex] = dataItem;
		}
		
		function doUpdate( o ){
			if(selectedItem){
					o.p = selectedItem.name;
					
					$.getJSON(
						'do/update/',
						o,
						function(json) { updateData(json);  setInfoBox( json ); });
				}
		}
		
		function setInfoBox( dataItem ){
			
			// update the row
			//itemList[selectedIndex] = dataItem;
			
			var pattern_url = 'http://repper.studioludens.com/view/' + dataItem.name + '.html';
			
			
			$('#info_box_likes .text-info').html('<span>' + dataItem.likes + "</span> likes");
			$('#info_box_dislikes .text-info').html('<span>' + dataItem.dislikes + "</span> dislikes");
			$('#info_box_views .text-info').html('<span>' + dataItem.views + "</span> views");
			$('#info_box_downloads .text-info').html('<span>' + dataItem.downloads + "</span> downloads");

			
			if(dataItem.tags.length > 0){
				$('#info_box_tags').html(''); // reset html
				$.each(dataItem.tags, function(){
										   $('#info_box_tags').append('<div class="tag">' + this + '</div>');
										   });
			} else {
				$('#info_box_tags').html('<div class="default">No tags yet</div>');
			}
			
			// download button
			$('#download_button').attr('href','/patterns/' + dataItem.name + "?d=1");
            
            // view button
            $('#view_button').attr('href','/view/' + dataItem.name + ".html");
			
			// set touchnote referral
			var tn_ref_url = 'http://repper.studioludens.com/tiles/touchnote/' + dataItem.name;
			$("#touchnote_referral").attr('href','http://www.touchnote.com/create-card-from-design/?refid=repper&imgsrc=' + tn_ref_url);
			
			// set share links
			
			// have to generate short url for twitter
			$.get(
				'/do/bitly/', { url : pattern_url }, function(short_url){
					 $("#twitter_share_link").attr('href', 'http://twitter.com/home?status=Found%20this%20awesome%20%23repper%20pattern:%20' + short_url + '%20via%20(@studioludens)');
				});
				
			$("#facebook_share_link").attr('href', 'http://www.facebook.com/sharer.php?u=' + pattern_url);
			$("#myspace_share_link").attr('href', 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + pattern_url);
			$("#digg_share_link").attr('href', 'http://digg.com/submit?phase=2&url=' + pattern_url);
			$("#su_share_link").attr('href', 'http://www.stumbleupon.com/submit?url=' + pattern_url);
			
		}

		
		
		
		$(document).ready(function() {
		    
			// prepare search object for search
			searchObject = new Object();
			
			var c1 = getUrlParameter('c1');
			if( c1 != "" ) {
				searchObject['c1'] = c1.toString();
				$('#color_picker_1 .selected-color').css('background', "#" + c1);
			}
			
            // the tag to search for
            // url decode this first!
			var t = $.URLDecode(getUrlParameter('t'));
            
			if( t != "" ) {
				searchObject['t'] = t.toString();
                
                
				$('#keyword_search_input').val(t);
			}
			
			var s = getUrlParameter('s');
			if( s != "" ) {
				searchObject['s'] = s.toString();
				$('#size_select').val(s);
			}
			
			var o = getUrlParameter('o');
			if( o != "" ) {
				searchObject['o'] = o.toString();
				$('#order_select').val(o);
			}
			
			
			var count = 0;
			for (k in searchObject) {
				if (searchObject.hasOwnProperty(k)) count++;
			}
			
			if( count < 1 )
				searchObject = null;
			else if( count > 0 && (count != 1 && searchObject['o'] ) ) {
				$("#order_select").children().filter( function(index) { return $(this).attr("value") == "random" } ).remove();				
			}
			
		    $('#nav_thumb_list').jcarousel({
		        vertical: true,
		        scroll: 3,
				initCallback:		mycarousel_initCallback,
		        itemLoadCallback: mycarousel_itemLoadCallback,
		        itemFirstInCallback:  mycarousel_itemFirstInCallback,
		        itemLastInCallback:   mycarousel_itemLastInCallback,


		        animation: 205
		    });
			
			if(count > 0) {
				$('#help_box').hide();
				$('#help_box_icon_button').animate( { width: "34", height: "35" }, 300);
			}
			
			$('#help_box_close_button').click( function(e) {
				$('#help_box').fadeOut("fast");
				$('#help_box_icon_button').animate( { width: "34", height: "35" }, 300);
			} );
			
			$('#help_box_icon_button').click( function(e) {
				$('#help_box').fadeIn("fast");
				$('#help_box_icon_button').animate( { width: "0", height: "0" }, 300);
			} );
			
			
			// like button click
			$('#like_button').click(function() {
				doUpdate({ addLike: '1'});
			});
			
			// dislike button click
			$('#dislike_button').click(function() {
				doUpdate({ addDislike: '1'});
			});
            
			
			$('#flag_button').click(function() {
				doUpdate({ addFlag: '1'});
			});
			
			
			/*
			 *   INFO_BOX INIT
			 *
			 */
			 
			 var info_box_open = true;
			 $('#box_info_button').click(function(e){
			 	
			 	if(info_box_open){
				 	$('#info_box .contents').fadeOut();
				 	$('#info_box').animate({width: 0 });
				 	info_box_open = false;
			 	} else {
			 		$('#info_box .contents').fadeIn();
				 	$('#info_box').animate({width: 220 });
				 	info_box_open = true;
			 	}
			 });
			 
			 $("#info_box a").tooltip({
			 	track: true,
			 	delay: 0,
			 	showURL: false,
			 	showBody: " - ",
			 	fade: 250,
			 	bottom: 0,
			 	left: 10
			 	});
			 
			 $(".combo-box").tooltip({
			 	track: true,
			 	delay: 0,
			 	showURL: false,
			 	showBody: " - ",
			 	fade: 250,
			 	bottom: 0,
			 	left: 10
			 	});
			 
			 $('#info_box_tags_input input').toggleVal();
			 
			 $('#info_box_tags_input input').keypress( function(e){
			 	if(e.which == 13 && selectedItem){
					doUpdate({ addTags: $('#info_box_tags_input input').val()});
					$('#info_box_tags_input input').val(''); 
				}
			  });
			 
			/* 
			$('.minimizable-panel').css("overflow", "hidden");
			$('.minimizable-panel').append("<img class='min-tab' src='images/min_tab.png' />");
			$('.min-tab').attr('closed', 0);
			$('.min-tab').click( function() {
				if( $(this).attr('closed') == 0 ) {
					$(this).attr('closed', 1);
					$(this).attr('src', 'images/max_tab.png');
					$(this).parent('.minimizable-panel').animate({ width: $(this).parent('.minimizable-panel').css('min-width'), height: $(this).parent('.minimizable-panel').css('min-height') }, 300 );
				}
				else {
					$(this).attr('closed', 0);
					$(this).attr('src', 'images/min_tab.png');
					$(this).parent('.minimizable-panel').animate({ width: $(this).parent('.minimizable-panel').css('max-width'), height: $(this).parent('.minimizable-panel').css('max-height') }, 300 );
				}
			});
			*/
			 
			 
		});