// -------------- Saved gallery Accordian  --------------------------------

$(document).ready(function () {   
           
    $('#accordion li').click(function () {   
  
        /* FIRST SECTION */  
  
        //slideup or hide all the Submenu   
        $('#accordion li').children('ul').slideUp('fast');     
               
        //remove all the "Over" class, so that the arrow reset to default   
        $('#accordion li > a').each(function () {   
            if ($(this).attr('rel')!='') {   
                $(this).removeClass($(this).attr('rel') + ' Over');     
            }   
        });   
               
        /* SECOND SECTION */       
               
        //show the selected submenu   
        $(this).children('ul').slideDown('fast');   
               
        //add "Over" class, so that the arrow pointing down   
        $(this).children('a').addClass($(this).children('li a').attr('rel') + 'Over');             
  
        return false;   
    });   
       
}); 

$(function() {
		var dates = $('#from, #to').datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1,
			dateFormat: 'yy-mm-dd',
			onSelect: function(selectedDate) {
				var option = this.id == "from" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
			}
		});
	});

$(function() {
		$("#accordion").accordion({ autoHeight: false });
	});
 
// --------  End saved gallery accordian ------------
	

//  ---------- Main Drag and Drop area ------------------------
$(function() {
	// define the areas that are both dragable and droppable
	var $gallery = $('.gallery'), $default_gallery = $('#default_gallery'),$trash = $('#trash'),$big_trash = $('#big_trash');

	// 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'
	});
	
	// let the active lightbox elements be draggable for the trash can
	$('li',$default_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: 'active-li-state-dragable',
		appendTo: '.drag_drop',
		helper: 'clone',
		cursor: 'move'
	});

	// let the active gallery be droppable, accepting the search result items
	$default_gallery.droppable({
		tolerance: 'touch',
		accept: '.gallery > li',
		activeClass: 'ui-state-highlight',
		appendTo: '.drag_drop',
		revert: 'valid',
		drop: function(ev, ui) {
			addImage(ui.draggable);
		}
	});

	// let the trash be droppable as well, accepting items from the active lightbox
	$trash.droppable({
		tolerance: 'touch',
		accept: '#default_gallery li',
		activeClass: 'custom-state-active',
		revert: 'valid',
		drop: function(ev, ui) {
			removeImage(ui.draggable);
		}
	});
	
	// let the big trash be droppable, accepting items on the gallery detail page
	$big_trash.droppable({
		tolerance: 'touch',
		accept: '#gallery li',
		activeClass: 'custom-state-active',
		revert: 'valid',
		drop: function(ev, ui) {
			removeImage(ui.draggable);
		}
	});

	// Add an image to the lightbox
	function addImage($item) {
		$item.fadeOut(function() {

			//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");
				
				// Post data to create a new lightbox in the database and return the lightbox id
				var $url = "/lightbox/add_lightbox/"+ $item.attr("name").substring(3);
				
				$.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='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");
				
				resize_image($item);
				
				
				// 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");			
				
				
				//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)
				{
					//Danny - Feb 4th - changed image name as was not appearing on the list ov active images
					//var $url = "/lightbox/add_image/" + $item.attr("name");
					var $url = "/lightbox/add_image/" + $item.attr("name").substring(3);
					//alert( $item.attr("name").substring(3));
					//alert ($item).html;
                                        //alert($(this).serialize());
                                        //$.dump($item);

					$.post($url, { lightbox_id: $active_lightbox_id });					
					$item.find('a.view_details').remove();
					$item.find('a.add_to_gallery').remove();
					$item.appendTo($list).show('slow', function(){$(this).css('border', 'solid .1em #ccc'); });
                                        
				}
			}			
		});
		
		

	}

// when you click on the "add" button under the image in the search results call the main add)image function
	$('a.add_to_gallery').click(function() {
		
		var $item = $(this).offsetParent();	
		
		addImage($item);
		return false;
	});

	
	//resize images when they are added to a lightbox
	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;
		
		//alert($this_width); 100
		//alert($this_height); 60
		
		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 || $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));
		}

	}
	$('.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();      
		$('#mask').fadeTo("fast",0.8);    
		
		//Get the window height and width  
		var winH = $(window).height();  
		var winW = $(window).width();  
		
		var modalH = $('.window').height()/2;
		var modalW = $('.window').width()/2;
		//Danny - 19th April 2011 - change to fix location where image box shows on screen
		//using - document.documentElement.scrollTop + document.body.scrollTop - to get around a bug in Chrome
		//adding 40px padding from top
		var modal_top = document.documentElement.scrollTop + document.body.scrollTop + 40;//Math.round((winH/2)-modalH)-10;
		var modal_left = Math.round((winW/2)-modalW)-20;
		
		//alert(oEvent.screenY);
		//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/-loader.gif' /> </div>";
		$('.window').html($loading_html);
		
		var $url = "/gallery/image_detail/"+id;
		$.post($url, { lightbox_name: "Untitled Gallery" }, function(data){	
			$('.window').html(data);
			$('.window').show(); 
			$('#add_image_from_detail').click(function() {
				var $id = $('#add_image_from_detail').attr('rel');
				//$id = "#"+$id;
				//Danny - 19th April 2011 - Caption reworded as requested by Tourism
				$('#add_image_from_detail').html("Image 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  
		 
		
		
	});  
	
	//if close button is clicked  
	 
	
	//if mask is clicked  
	$('#mask').click(function () {  
		$(this).hide();  
		$('.window').hide();  
	}); 	
	
	
	
	$('.view_submission').click(function(e) {  
		//Cancel the link behavior  
		e.preventDefault(); 
		
		//Get the A tag  
		//alert($(this).html());
		var id = $(this).attr('rel').substring(4);  
		
		//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();      
		$('#mask').fadeTo("fast",0.8);    
		
		//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)-10;
		var modal_left = Math.round((winW/2)-modalW)-20;
		
		//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/-loader.gif' /> </div>";
		$('.window').html($loading_html);
		
		var $url = "/dua/submission_detail/"+id;
		$.post($url, { lightbox_name: "Untitled Gallery" }, function(data){	
			$('.window').html(data);
			$('.window').show(); 
						
			$('.close').click(function (e) {  
				//Cancel the link behavior  
				e.preventDefault();  
				$('#mask, .window').hide();  
			}); 
		});
		
		//transition effect  
		 
		
		
	});  
	
	
	
	
// image remove from lightbox
	function removeImage($item) {		
   		var retVal = confirm("You are about to delete this image - continue ?");
   		if( retVal == true ){
      		$item.fadeOut(function() {		
      	var $gallery = jQuery.url.segment(3);	
      	//alert($gallery);
				var $url = "http://www.tourismirelandimagery.com/lightbox/remove_image/" + ($item.attr("name") + "/" + $gallery);
				var my_item = $item;
				//console.debug($default_gallery);
				//alert($default_gallery);
				//alert(my_item);
				
				$.post($url);
				//$.post($url, { lightbox_name: $default_gallery });
				$item.remove();
				//alert("deleted");
		    });
	  		return true;
    	}else{
      	alert("image not deleted");
	  		return false;
    	}
	}


	$(".date_picker_save").click(function() {

		var $from=$("#from").val();
		var $to=$("#to").val();
		var $lightbox = $("#date_picker_id").attr("name");
		var $url = "/lightbox/save_date/";
		
		alert ('Dates have been saved : from: '+$from+' to:'+$to);
		
		$.post($url, { from: $from, to: $to, lightbox_id: $lightbox });		
	});

	$('.edit').click(function($this) {
		if ($(this).attr('class') == "saved_gallery edit active"){
			var $button_id=$(this).attr('id');
			
			var $header= "#"+$button_id.substring(7);		
			
			var $edit_id = "#edit_" + $button_id.substring(14);
			
			var $gallery_name = $($edit_id).val();
			
			var $header_id = $button_id.substring(14);
			
			//alert("header:" + $header_id + " | button_id:" + $button_id + " | gallery name: " + $gallery_name + " | edit id: " + $edit_id);
			$($header).html($gallery_name);			
			//$($header).html("<input id='edit_"+ $edit_id+ "' name=\"edit_title\" type=\"text\" value=\""+ $gallery_name +"\"/>");
			
			var $url = "/lightbox/edit_title";
			$.post($url, { header_id: $header_id, lightbox_name: $gallery_name });
			$(this).attr('class','saved_gallery edit')
			
			$(this).html('edit');
			
		}
		
		else{
			var $button_id=$(this).attr('id');
			
			var $header= "#"+$button_id.substring(7);		
			
			var $gallery_name = $($header).html();
			
			var $edit_id = $button_id.substring(14);
				
			//alert("header:" + $header + " | button_id:" + $button_id + " | gallery name: " + $gallery_name + " | edit id: " + $edit_id);
						
			$($header).html("<input class='edit_gallery_title' id='edit_"+ $edit_id+ "' name=\"edit_title\" type=\"text\" value=\""+ $gallery_name +"\"/>");
			
			$(this).attr('class','saved_gallery edit active')
			
			$(this).html('save');			
		}					
	});
	
});


	// -------------------   Function to add an image from the image detail page   --------------------------
function add_image_from_detail($image_id){
		var $url = "/lightbox/add_image_from_detail/" + $image_id;
		$.post($url, {}, function(data){									
					 $('#add_image_from_detail').html("Added To Gallery");
					 $('#add_image_from_detail').removeAttr('onClick');
					 								 
					 },"text");
}



// --------------------   Function to empty an active lightbox   -----------------------------
function empty_gallery($lightbox_id){
		var $url = "/lightbox/empty_gallery";
		$.post($url, { lightbox_id: $lightbox_id });
		//alert($lightbox_id);
		document.getElementById("active_lightbox").innerHTML='';
		
}

// --------------------   Delete the active lightbox   -----------------------------
function clear_all_active($lightbox_id,$gallery_list){
		// Alert to confirm the user wants to delete this gallery
		var answer = confirm ("Do you really want to delete this gallery?")
		if (answer){
			var $url = "/lightbox/delete_gallery";
			//var $lightbox_id = document.getElementById("active_lightbox").getAttribute("name");
			$.post($url, { lightbox_id: $lightbox_id });
			
			//If its the gallery detail page
			if($gallery_list=='yes'){
				var $ul = document.getElementById('gallery_list');
				var $list_item = document.getElementById($lightbox_id);
				$ul.removeChild($list_item);
			}
			
			// if its the search results page
			if($gallery_list=='no'){
				var $h3 = "#h3_"+$lightbox_id;
				var $div = "#div_"+$lightbox_id;
				$($h3).remove();
				$($div).remove();
			}
			else{
				document.getElementById("default_gallery").innerHTML='';
				document.getElementById("gallery_actions").innerHTML='';
			}
		}
		else{}
	
		
}

// --------------------   Create new gallery in the active gallery area   -----------------------------	
function create_new_gallery($header_id){
		$('#default_gallery').empty();	
		$('#gallery_actions').empty();	
		document.getElementById("active_header").innerHTML ="Untitled Gallery <span class=\"active_gallery\" onClick=\"edit_title('active_header')\">edit</span>";
		//document.getElementById("default_gallery").innerHTML += "<ul id='active_lightbox' name =\"\" class=\"gallery ui-helper-reset\"/>";	
				// Post data to create a new lightbox in the database and return the lightbox id
		var $url = "/lightbox/add_lightbox";
		$.post($url, { lightbox_name: "Untitled Gallery" }, function(data){									
			 document.getElementById("default_gallery").innerHTML += "<ul id='active_lightbox' name =\""+ data +"\" class=\"gallery ui-helper-reset\"/>";	
			 var lightbox_id = data.substring(9);
					 	//alert (lightbox_id);
					 	var $create = "<div onclick=\"create_new_gallery()\" title=\'Create New Gallery\' id='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 +"' title='View This Gallery'><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()\"/></div>";
						var $trash = "<div id='trash' class='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>";

						
						$('#gallery_actions').append($create);
						$('#gallery_actions').append($empty);			
						$('#gallery_actions').append($view);
						$('#gallery_actions').append($download);	
						$('#gallery_actions').append($trash);				 
			 //document.getElementById("active_lightbox").setAttribute("name",data);										 
		},"text");
}

// --------------------   Edit the title of the Active lightbox   -----------------------------	
function edit_title(){
		$contents = document.getElementById("active_header").innerHTML;
		
		//use the angle bracket as a delimiter to extract the current name
		$contents_array = $contents.split("<");
		document.getElementById("active_header").innerHTML = "<input id=\"edit_active_header\" name=\"edit_title\" type=\"text\" value=\""+ $contents_array[0] +"\"/>";
		
		document.getElementById("active_header").innerHTML += "<span onclick=\"save_title()\" style=\"float: right; padding-right: 1em;\">save</span>";
		document.getElementById("edit_active_header").focus();
}

// --------------------   save the title of the Active lightbox   -----------------------------	
function save_title($header_id){
		var $form_id = "#edit_active_header";
		var $form_value = $($form_id).val();
		
		document.getElementById("active_header").innerHTML = $form_value;
		document.getElementById("active_header").innerHTML += "<span onclick=\"edit_title()\" style=\"float: right; padding-right: 1em;\">edit</span>";
		var $url = "/lightbox/edit_title";
		var $active_lightbox_id = document.getElementById("active_lightbox").getAttribute("name");
		$.post($url, { lightbox_id: $active_lightbox_id, lightbox_name: $form_value });
}

/*	$('span.edit').click(function() {
		var $header_id = $(this).attr( "title" );	
		var $_header = "#"+$header_id;
		
		contents = $($_header_id).html();
		$button_id = "#button_"+$header_id;
 
		$($_header_id).html("<input id=\"edit"+ $header_id+"\" name=\"edit_title\" type=\"text\" value=\""+ $contents +"\"/>");
		$($button_id).html("save");
		$($button_id).attr( "onclick", "save_saved_title('"+ $header_id+"')" );
		alert($($button_id).attr( "onclick"));
		
		$(this).removeClass('edit').addClass('save');
		
		$("#edit"+ $header_id).focus();

		return false;
	});
*/	
	
	
	// --------------------   edit the title of a saved lightbox   -----------------------------	
function edit_saved_title($header_id){
		//$contents = document.getElementById($header_id).innerHTML;
		
		//alert("THIS IS EDIT");
		
		$contents = $("#"+$header_id).html();
		
		$button_id = "#button_"+$header_id;
		$_header_id = "#"+$header_id;	
		
		var $edit_id= "edit"+ $header_id;
		
		$($_header_id).html("<input id='"+ $edit_id+ "' name=\"edit_title\" type=\"text\" value=\""+ $contents +"\"/>");
		
		
		$($button_id).html("save");

		$($button_id).removeAttr("onClick");

		
		$($button_id).attr( "onClick", "save_saved_title('"+ $header_id+"')" );

		$("#edit"+ $header_id).focus();
}


// --------------------   save the title of a saved lightbox   -----------------------------
function save_saved_title($header_id){

		var $form_id = "#edit"+$header_id;
		
		var $form_value = $($form_id).val();
		
		//alert($form_value);
		//alert ($header_id + " : " + $form_id);
		
		$button_id = "#button_"+$header_id;
		$_header_id = "#"+$header_id;
		
		$($_header_id).html($form_value);
		//alert($button_id + $($button_id).html());
		$($button_id).html("edit");
		$($button_id).attr( "onclick", "edit_saved_title('"+ $header_id +"')" );
		alert ($($button_id).attr( "onclick"));
		
		
		var $url = "/lightbox/edit_title";
		$.post($url, { header_id: $header_id, lightbox_name: $form_value });
		
}
