// Custom scrolling script with ajax page loading
$(document).ready(function() {   
	$('.page_number').click(function() {
		var $this = $(this);
		var $new_page = $(this).attr('id');							
		//alert($page_number);
		var $loading_html = "<div align='center' style='margin-top:7em;'><img src='/graphics/ajax-loader.gif' /> </div>";
		$('#search_results').html($loading_html);
		
		var $result_start = ($new_page.substring(5)*15)-15;
		var $result_amount = 15; //$page_number.substring(5)*15;
		
		var $keywords = $('#search_string').html();
		
		var $search_log_id = $('#search_string').attr('class');
		
		var $current_page = "#page_"+$('#current_page').html();
		
		var $search_url = "/search/ajax/"+$result_start+"/"+$result_amount;
		//alert("from: " + $result_from +" to : " + $result_to);
		
		$.post($search_url, { keywords: $keywords, start:$result_start, search_log_id:$search_log_id }, function(data) {
			$('#search_results').html(data);
						
			pagination($new_page.substring(5));
		});
		var eventCategory = "search";
		var eventLabel = "search?keywords="+$keywords+"&page="+$result_start;
		pageTracker._trackEvent(eventCategory, 'click', eventLabel);
	});	
	
	$('.prevPage').click(function() {
		var $new_page = $('#current_page').html();
		$new_page=$new_page-1;
		//alert($new_page);

		
		var $loading_html = "<div align='center' style='margin-top:7em;'><img src='/graphics/ajax-loader.gif' /> </div>";
		$('#search_results').html($loading_html);
		
		var $result_start = ($new_page*15)-15;
		var $result_amount = 15; //$page_number.substring(5)*15;
		
		var $keywords = $('#search_string').html();
		
		var $search_log_id = $('#search_string').attr('class');
		
		var $new_page_id = "#page_"+$new_page;
		
		var $search_url = "/search/ajax/"+$result_start+"/"+$result_amount;
		//alert("from: " + $result_from +" to : " + $result_to);
		
		$.post($search_url, { keywords: $keywords, start:$result_start, search_log_id:$search_log_id }, function(data) {
  			$('#search_results').html(data);
			
			pagination($new_page);
			
		});	
		var eventCategory = "search";
		var eventLabel = "search?keywords="+$keywords+"&page="+$result_start;
		pageTracker._trackEvent(eventCategory, 'click', eventLabel);
	});	
	
	$('.nextPage').click(function() {
		
		var $new_page = $('#current_page').html();
		$new_page++;
		
		var $loading_html = "<div align='center' style='margin-top:7em;'><img src='/graphics/ajax-loader.gif' /> </div>";
		$('#search_results').html($loading_html);
		
		var $result_start = ($new_page*15)-15;
		var $result_amount = 15; //$page_number.substring(5)*15;
		
		var $keywords = $('#search_string').html();
		
		var $search_log_id = $('#search_string').attr('class');
		
		var $new_page_id = "#page_"+$new_page;
		
		var $search_url = "/search/ajax/"+$result_start+"/"+$result_amount;
		//alert("from: " + $result_from +" to : " + $result_to);
		
		$.post($search_url, { keywords: $keywords, start:$result_start, search_log_id:$search_log_id }, function(data) {
  			$('#search_results').html(data);
			pagination($new_page);
		});	
		var eventCategory = "search";
		var eventLabel = "search?keywords="+$keywords+"&page="+$result_start;
		pageTracker._trackEvent(eventCategory, 'click', eventLabel);
		
	});	
	
	function pagination($this){
				$('.view_details').click(function(e) {  
				//Cancel the link behavior  
				e.preventDefault(); 
				
				//Get the A tag  
				//alert($(this).html());
				var id = $(this).attr('rel').substring(3);  
				
				//Get the screen height and width  
				var maskHeight = $(document).height();  
				var maskWidth = $(window).width();  
				$('.window').css('width', "71em");
				//Set height and width to mask to fill up the whole screen  
				$('#mask').css({'width':maskWidth,'height':maskHeight});  
				
				//transition effect       
				$('#mask').show('fast');      
				$('#mask').fadeTo("fast",0.7);    
				
				//Get the window height and width  
				var winH = $(window).height();  
				var winW = $(window).width();  
				
				var modalH = $('.window').height()/2;
				var modalW = $('.window').width()/2;
				
				var modal_top = Math.round((winH/2)-modalH);
				var modal_left = (Math.round((winW/2)-modalW))-30;
				
				//alert (modal_top +":"+modal_left);
				//Set the popup window to center  
				$('.window').css('top', modal_top );  
				$('.window').css('left', modal_left); 
				
				var $loading_html = "<div align='center' style='margin-top:7em;'><img src='/graphics/ajax-loader.gif' /> </div>";
				$('.window').html($loading_html);
				
				var $url = "/gallery/image_detail/"+id;
				$.post($url, { lightbox_name: "Untitled Gallery" }, function(data){	
					$('.window').html(data);
					$('#add_image_from_detail').click(function() {
						var $id = $('#add_image_from_detail').attr('rel');
						//$id = "#"+$id;
						$('#add_image_from_detail').html("Added To Gallery");
						var $img = $('[name='+$id+']');;
						
						// $item = $($item).offsetParent();
						addImage($img);
						return false;
					});
					
					$('.close').click(function (e) {  
						//Cancel the link behavior  
						e.preventDefault();  
						$('#mask, .window').hide();  
					}); 
				});
				
				//transition effect  
				$('.window').fadeIn(2000);  
				
				
			});  
		$(function() {
				// define the areas that are both dragable and droppable
					var $gallery = $('.gallery'), $default_gallery = $('#default_gallery');
		
					// let the images be draggable from the search results
					$('li',$gallery).draggable({
						cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
						revert: 'invalid', // when not dropped, the item will revert back to its initial position
						activeClass: 'li-state-dragable',
						appendTo: 'body',
						helper: 'clone',
						cursor: 'move'
					});
					$default_gallery.droppable({
						tolerance: 'touch',
						accept: '.gallery > li',
						activeClass: 'ui-state-highlight',
						appendTo: '.drag_drop',
						revert: 'valid',
						drop: function(ev, ui) {
							addImage(ui.draggable);
						}
					});
				});
				
				function resize_image($this){
					var $this_height = $this.find('img').attr('height');
					var $this_width = $this.find('img').attr('width');
					var $max_height = 60;
					var $max_width = 40;
					
					if ($this_width == $this_height){
						var $x = $this_height / $max_width;
						$new_height = $this_height / $x;
						$new_width = $this_width / $x;
						$this.find('img').attr('height',$new_height);
						$this.find('img').attr('width',$new_width);
						//alert("new height: "+Math.round($new_height)+" | new width: "+Math.round($new_width));
							  
					}
					//landscape
					if ($this_width > $this_height){
						var $x = $this_width / $max_width;
						$new_height = $this_height / $x;
						$new_width = $this_width / $x;
						var $padding = ($max_height - $new_height) / 2;
						//alert ($padding);
						$this.find('img').attr('height',$new_height);
						$this.find('img').attr('width',$new_width);
						//$this.find('img').css("padding-top",$padding);
						//$this.find('img').css("padding-bottom",$padding);
						//alert("new height: "+Math.round($new_height)+" | new width: "+Math.round($new_width));
					}
					//portrait
					if ($this_width < $this_height){
						var $x = $this_height / $max_height;
						$new_height = $this_height / $x;
						$new_width = $this_width / $x;
						if($new_width > "40"){
							var $x = $new_width / 40;
							$new_height = $new_height / $x;
							$new_width = $new_width / $x;
						}
							
						$this.find('img').attr('height',$new_height);
						$this.find('img').attr('width',$new_width);
						//alert("new height: "+Math.round($new_height)+" | new width: "+Math.round($new_width));
					}
						
				}
				$('a.add_to_gallery').click(function() {
			
					var $item = $(this).offsetParent();	
					
					addImage($item);
					return false;
				});
				function addImage($item) {
					$item.fadeOut(function() {
					var $default_gallery = $('#default_gallery');
						//check if the active gallery is empty. ie it is new gallery
						if($('#default_gallery').html()==''){		
							// print the UL to the default gallery
							$('#default_gallery').html("<ul id='active_lightbox' name =\"\" class=\"gallery ui-helper-reset\"/>");	
							
							//var $active_lightbox_id = document.getElementById("active_lightbox").getAttribute("name");
							//resize the thumbnail
							resize_image($item);
							// Post data to create a new lightbox in the database and return the lightbox id
							//var $url = "/lightbox/add_lightbox/"+ $item.attr("name");
							var $url = "/lightbox/add_lightbox/"+ $item.attr("name").substring(3);
							//resize_image($item);
							$.post($url, { lightbox_id: $active_lightbox_id }, function(data){									
									$("#active_lightbox").attr( "name", data ); 																	//setAttribute("name",data);
									
									// parse the lightbox it. It is returned as "lightbox_1"					 	
									var lightbox_id = data.substring(9);
			
									
									//declare all the actions to go in the active lightbox
									var $new =  '<div id="new_gallery" onclick=\"create_new_gallery()\" title=\'Create New Gallery\'><span class=\'hidden\'>New Gallery</span></div>';
									var $empty =  '<div id="empty_gallery" onclick="empty_gallery(\'' +data+'\')" title="Empty This Gallery"><span class="hidden">Empty Gallery</span></div>';
									var $view = "<div id='view_gallery' title='View This Gallery'><a href='/account/reports/gallery_detail/"+ lightbox_id +"'><span class='hidden'>View Gallery</span></a></div>";
									var $download = "<div id='download_gallery' title='Download This Gallery'><a href='/gallery/download_gallery/"+ lightbox_id +"'><span class='hidden'>Download Gallery</span></a></div>";	
									var $trash = "<div id='trash' class='gallery ui-helper-reset ui-helper-clearfix ui-droppable' title='Delete This Gallery' onclick=\"clear_all_active('lightbox_"+ lightbox_id +"')\"/><span class='hidden'>Delete Gallery</span></div>";
									// append the options to the gallery options div
									$('#gallery_actions').append($new);
									$('#gallery_actions').append($empty);			
									$('#gallery_actions').append($view);
									$('#gallery_actions').append($download);
									$('#gallery_actions').append($trash);		 
									
									//declare the edit button to add to the header once you activate the lightbox_id
									var $edit = "<span class=\"active_gallery\" onClick=\"edit_title()\">edit</span>";
									$('#active_header').append($edit);	
									
							},"text");
							
							// get the ul element for the default gallery, remove the actions from the item being dragged and append the item to the active gallery
							var $list = $('ul',$default_gallery);
							$item.find('a.view_details').remove();
							$item.find('a.add_to_gallery').remove();
							$item.appendTo($list).fadeIn();
						}
						
						// if a lightbox already exists
						else{
							var $list = $('ul',$default_gallery);
							// count instances of image in lightbox
							var $search_result = document.getElementById("default_gallery").innerHTML.search($item.attr("name"));
							
							// get the "lightbox_id" for the active gallery
							var $active_lightbox_id = document.getElementById("active_lightbox").getAttribute("name");			
							resize_image($item);
							//document.getElementById("default_gallery").innerHTML += $active_lightbox_id;
							//resize_image($item);
							// if count of images is 0 or -1 then add the image to the lightbox. This is to check if the image is already in this gallery
							if ($search_result < 1)
							{
								//var $url = "/lightbox/add_image/" + $item.attr("name");
								var $url = "/lightbox/add_image/" + $item.attr("name").substring(3);
								$.post($url, { lightbox_id: $active_lightbox_id });
								$item.find('a.view_details').remove();
								$item.find('a.add_to_gallery').remove();
								$item.appendTo($list).fadeIn();
							}
						}			
					});
				}
				// tooltip logged in version
	$('.image_thumb img').each(function(){
		$(this).qtip({
			content: { url: '/search/tooltip_detail/'+($(this).attr('id'))},
			hide: {
				fixed:true,
				delay: 300
			},
			position: {
				corner: {
					target: 'topRight',
					tooltip: 'topLeft'
				},
				adjust: {
					screen: true,
				  x: 15, y: 0
				}
			},
			style: {
				border: {	width: 3,	radius: 8, color: '#CCC'},
				width: 450
			}
		})
	});


	// tooltip logged out version (yes it makes a difference 

	$('.image_thumb_public img').each(function(){
		$(this).qtip({
			content: { url: '/public/tooltip_detail/'+($(this).attr('id'))},


			hide: {
				fixed:true,
				delay: 300
			},

			position: {
				corner: {
					target: 'topRight',
					tooltip: 'topLeft'
				},
				adjust: {
					screen: true,
					x: 15, y: 0
				}
			},

			style: {
				border: {
					width: 3,
					radius: 8,
					color: '#CCC'
				},
				width: 450
			}

		})
	});
	
	$(function() {
			
			var $this_id = "#page_"+$this;
			if($('#total_pages').html() < 10) {
				//alert("less than 10");
				$('.current').attr('class', 'page_number');
				$($this_id).attr('class', 'current');
				$('#current_page').html($this);
			}
			else{
				if ($this < 7 && $('#current_page').html() >= 7 ){
					var $count = 1;
					for(var $i=1; $i<=10; $i++){
						$('[rel='+$count+']').attr('id','page_'+$i);
						if( $i == $this){
							$('[rel='+$count+']').attr('class','current');
						}
						else{
							$('[rel='+$count+']').attr('class','page_number');
						}
						$('[rel='+$count+']').html($i);
						$count++;
					}					
					$('#current_page').html($this);
				}
				else if($this < 7) {
					//alert("less than 7");
					$('.current').attr('class', 'page_number');
					$($this_id).attr('class', 'current');;
					$('#current_page').html($this);
				}
				else{
					//alert("greater than or equal to");
					//alert($('#current_page').html());
					var $page_num_html = '';
					var $count = 2;
					var $page_start_num = $this-5;
					var $page_end_num = $this;
					$page_end_num++;
					$page_end_num++;
					$page_end_num++;
					if ($page_start_num > ($('#total_pages').html()-8)){
						$page_start_num = $('#total_pages').html()-8;
						$page_end_num = $('#total_pages').html();
					}
																  
						
					var $page_end_num = $this;
					$page_end_num++;
					$page_end_num++;
					$page_end_num++;
					$('[rel=1]').attr('id','page_1');
					$('[rel=1]').attr('class','page_number');
					$('[rel=1]').html('First');
					for(var $i=$page_start_num; $i<=$page_end_num; $i++){
						$('[rel='+$count+']').attr('id','page_'+$i);
						if( $i == $this){
							$('[rel='+$count+']').attr('class','current');
						}
						else{
							$('[rel='+$count+']').attr('class','page_number');
						}
						$('[rel='+$count+']').html($i);
						$count++;
					}					
					$('#current_page').html($this);
				}
			}
			//alert($this);			
			if($this != $('#total_pages').html()){
				$('.nextPage').removeClass('disabled');
			}

			if($this == $('#total_pages').html()){
				$('.nextPage').addClass('disabled');
			}
			
			if($this != 1){
				$('.prevPage').removeClass('disabled');
			}
			
			if($this == 1){
				$('.prevPage').addClass('disabled');
			}
			
			
		
		});			
	}
		
	
	
});
