<?php
/*
Plugin Name: Fancy Gallery (radykal)
Plugin URI: http://codecanyon.net/item/fancy-gallery-wordpress-plugin/400535
Description: Create your own galleries with unlimited of albums. You can upload different types of media. Use the generator for external usage of a gallery.
Version: 1.2.1
Author: Rafael Dery
Author URI: http://codecanyon.net/user/radykal
*/


if (!defined('FG_PLUGIN_DIR'))
              define( 'FG_PLUGIN_DIR', dirname(__FILE__) );
if (!defined('FG_CONTENT_DIR'))
              define( 'FG_CONTENT_DIR', WP_CONTENT_DIR . "/fancygallery" );

if(!class_exists('FancyGallery')) {
	class FancyGallery {
		
		private $wpdb;
		private $version = '1.2.1';
		private $version_field_name = 'fancygallery_version';
		private $options_field_name = 'fg_gallery_options';
		private $gallery_table_name;
		private $album_table_name;
		private $images_table_name;
		private $default_options;
		
		const CAPABILITY = "manage_options";
		
	    public function __construct() {
			
			global $wpdb;
            
			//set table option names
			$this->wpdb = $wpdb;
			$this->gallery_table_name = $wpdb->prefix . "fg_gallery";
			$this->album_table_name = $wpdb->prefix . "fg_album"; 
			$this->images_table_name = $wpdb->prefix . "fg_media";
			
			$this->default_options = array('background_color' => '#F5F5F5',
			                               'title_color' => '#383634',
										   'thumbnail_width' => 140,
										   'thumbnail_height' => 79,
										   'thumbnail_opacity' => '0.6',
										   'thumbnails_per_page' => 6,
										   'thumbnail_zc' => 1,
										   'title_height' => 20,
										   'border_thickness' => 3,
										   'row_offset' => 15,
										   'column_offset' => 15,
										   'shadow_offset' => 0,
										   'shadow_image' => plugins_url('/images/fancygallery/shadow.png', __FILE__),
										   'text_fade_direction' => 'normal',
										   'dropdown_theme' => 'default',
										   'dropdown' => 1,
										   'divider' => 1,
										   'show_title' => 0,
										   'slide_title' => 1,
										   'prettyphoto_theme' => 'pp_default',
										   'prettyphoto_overlay' => 1,
										   'prettyphoto_image_resize' => 1,
										   'prettyphoto_deeplinking' => 0,
										   'prettyphoto_slideshow' => 0
									    );
			
			require_once(FG_PLUGIN_DIR . '/widgets.php');
			
			//activation and actions
            register_activation_hook(  __FILE__, array( &$this, 'activate_plugin' ) );
			//Uncomment this line to delete all database tables when deactivating the plugin
            register_deactivation_hook( __FILE__, array( &$this,'deactive_plugin' ) );
			
			//action hooks
			add_action( 'init', array( &$this,'init_plugin' ) );
			add_action( 'admin_init', array( &$this,'init_admin' ) );
			add_action( 'plugins_loaded', array( &$this,'check_version' ) );
			add_action( 'wp_print_styles', array( &$this,'add_styles' ) );
			add_action( 'wp_print_scripts',array( &$this,'add_scripts' ) );
			add_action( 'admin_menu', array( &$this,'add_menu_pages' ) );
			add_action( 'add_meta_boxes', array( &$this, 'add_custom_box' ) );
			add_action( 'widgets_init', create_function( '', 'return register_widget("FancyGalleryWidget");' ) );
					
			//filter hooks
            add_filter('widget_text', 'do_shortcode');
			
			//shortcodes
	        add_shortcode('fancygallery', array($this,'add_fancyGallery'));
		}
		
		public function init_plugin() {
									
			if( !is_admin() ) {
				wp_deregister_script( 'jquery' );
				wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', array(), '1.6.2');
				wp_enqueue_script( 'jquery' );
			}
			
			//register some scripts and sytles
			wp_register_script('uniform', plugins_url('/js/jquery.uniform.min.js', __FILE__));
			
			wp_register_style('uniform-default', plugins_url('/css/uniform.default.css', __FILE__));
			wp_register_style('uniform-aristo', plugins_url('/css/uniform.aristo.css', __FILE__));
			wp_register_style('uniform-agent', plugins_url('/css/uniform.agent.css', __FILE__));
			
		}
		
		public function init_admin() {
			
			// get value for safe mode
			if ( (gettype( ini_get('safe_mode') ) == 'string') ) {
				if ( ini_get('safe_mode') == 'off' ) define('SAFE_MODE', FALSE);
				else define( 'SAFE_MODE', ini_get('safe_mode') );
			} else
			define( 'SAFE_MODE', ini_get('safe_mode') );
			
			//action hooks for the admin
			add_action( 'wp_ajax_newgallery', array( &$this, 'new_gallery' ) );
			add_action( 'wp_ajax_deletegallery', array( &$this, 'delete_gallery' ) );
			add_action( 'wp_ajax_deletegalleries', array( &$this, 'delete_galleries' ) );
			add_action( 'wp_ajax_loadalbums', array( &$this, 'load_albums' ) );
			add_action( 'wp_ajax_newalbum', array( &$this, 'new_album' ) );
			add_action( 'wp_ajax_editalbum', array( &$this, 'edit_album' ) );
			add_action( 'wp_ajax_deletealbum', array( &$this, 'delete_album' ) );
			add_action( 'wp_ajax_deletealbums', array( &$this, 'delete_albums' ) );
			add_action( 'wp_ajax_updatealbums', array( &$this, 'update_albums' ) );
			add_action( 'wp_ajax_loadfiles', array( &$this, 'load_files' ) );
			add_action( 'wp_ajax_savefile', array( &$this, 'save_file' ) );
			add_action( 'wp_ajax_deletefiles', array( &$this, 'delete_files' ) );
			add_action( 'wp_ajax_updatefiles', array( &$this, 'update_files' ) );
			
			wp_register_script('ajax-utils', plugins_url('/admin/js/ajax-utils.js', __FILE__));
			
		}
		
		public function check_version() {
			
			if( get_option($this->version_field_name) != $this->version)
			    $this->upgrade();
		}
		
		public function activate_plugin() {
		  
		   if(version_compare(PHP_VERSION, '5.2.0', '<')) { 
			  deactivate_plugins(plugin_basename(__FILE__)); // Deactivate plugin
			  wp_die("Sorry, but you can't run this plugin, it requires PHP 5.2 or higher."); 
			  return; 
			}
			
			$this->install();
			
		}
		
		public function deactive_plugin() {
			
			//delete everything
			if( get_option($this->options_field_name) )
			    delete_option( $this->options_field_name );
			
			$this->wpdb->query("DROP TABLE " . $this->gallery_table_name . "");
			$this->wpdb->query("DROP TABLE " . $this->album_table_name . "");
			$this->wpdb->query("DROP TABLE " . $this->images_table_name . "");
			
			if(file_exists(FG_CONTENT_DIR))
			    $this->delete_directory(FG_CONTENT_DIR);
				
			delete_option($this->version_field_name);
			
		}
		
		public function add_custom_box() {
			
			//create a meta box for adding the shortocde to the editor
			wp_enqueue_script('fg-metabox', plugins_url('/admin/js/metabox.js', __FILE__));
			
			add_meta_box( 'fg-meta', 'Fancy Gallery', array( &$this, 'create_meta_box'), 'post', 'side' );
			add_meta_box( 'fg-meta', 'Fancy Gallery', array( &$this, 'create_meta_box'), 'page', 'side' );
			
		}
		
		public function create_meta_box() {
			
			//the meta box output
			echo "<p>Select a gallery:</p>";
			echo "<select id='fg-galleries'>";
			
			$galleries = $this->wpdb->get_results("SELECT * FROM " . $this->gallery_table_name . "");
			
			foreach($galleries as $gallery) {
				echo "<option value='" .  $gallery->slug . "'>" .  stripslashes($gallery->title) . "</option>";
			}
			
			echo "</select>";
			echo "<a href='#' id='fg-add-gallery' class='button-secondary' style='float: right;'>Add gallery</a>";
			echo "<div class='clear'></div>";
			
		}
		
		public function add_menu_pages() {
			
			//create own admin menu with subs
			add_menu_page( 'Fancy Gallery', 'Fancy Gallery',  FancyGallery::CAPABILITY, 'fancy-gallery', array($this, 'galleries_admin_page'), plugins_url('/admin/images/menu_icon.png', __FILE__) );
			$galleries = add_submenu_page( 'fancy-gallery', 'Manage galleries', 'Manage galleries',  FancyGallery::CAPABILITY, 'fancy-gallery', array($this, 'galleries_admin_page') );
			$albums = add_submenu_page( 'fancy-gallery', 'Manage albums', 'Manage albums', FancyGallery::CAPABILITY, 'fancy-gallery-albums', array($this, 'albums_admin_page') );
			$media = add_submenu_page( 'fancy-gallery', 'Upload media', 'Upload media',  FancyGallery::CAPABILITY, 'fancy-gallery-media', array($this, 'media_admin_page') );
			$options = add_submenu_page( 'fancy-gallery', 'Options', 'Options',  FancyGallery::CAPABILITY, 'fancy-gallery-options', array($this, 'options_admin_page') );
			$generator =  add_submenu_page('fancy-gallery', 'Generator', 'Generator',  FancyGallery::CAPABILITY, 'fancy-gallery-generator', array($this, 'generator_admin_page') );
			
			//include styles and  scripts for the admin
			add_action('admin_print_styles-' . $galleries, array( &$this,'galleries_styles'));
			add_action('admin_print_scripts-' . $galleries, array( &$this,'galleries_scripts'));
			add_action('admin_print_styles-' . $albums, array( &$this,'albums_styles'));
			add_action('admin_print_scripts-' . $albums, array( &$this,'albums_scripts'));
			add_action('admin_print_styles-' . $media, array( &$this,'media_styles'));
			add_action('admin_print_scripts-' . $media, array( &$this,'media_scripts'));
			add_action('admin_print_styles-' . $options, array( &$this,'options_styles'));
			add_action('admin_print_scripts-' . $options, array( &$this,'options_scripts'));
			add_action('admin_print_styles-' . $generator, array( &$this,'generator_styles'));
			add_action('admin_print_scripts-' . $generator, array( &$this,'generator_scripts'));
			
		}
		
		public function galleries_styles() {
			
			wp_enqueue_style('fg-admin', plugins_url('/admin/css/admin.css', __FILE__), array(), $this->version);
			
		}
		
		public function galleries_scripts() {
			
			wp_enqueue_script('fg-gallery', plugins_url('/admin/js/galleries.js', __FILE__), array('jquery', 'wp-ajax-response', 'ajax-utils'), $this->version);
			wp_localize_script('fg-gallery', 'options', array( 'Ajax_Url' => admin_url( 'admin-ajax.php') ));
			
		}
		
		public function albums_styles() {
			
			wp_enqueue_style('fg-admin', plugins_url('/admin/css/admin.css', __FILE__), array('uniform-aristo'), $this->version);
			
		}
		
		public function albums_scripts() {
			
			wp_enqueue_script('fg-albums', plugins_url('/admin/js/albums.js', __FILE__), array('jquery', 'jquery-ui-core', 'jquery-ui-sortable', 'wp-ajax-response', 'ajax-utils', 'uniform'), $this->version);
			wp_localize_script( 'fg-albums', 'options', array( 'Ajax_Url' => admin_url( 'admin-ajax.php') ) );
			
		}
		
		public function media_styles() {
			
			wp_enqueue_style('fg-admin', plugins_url('/admin/css/admin.css', __FILE__), array('thickbox', 'uniform-aristo'), $this->version);
				
		}
		
		public function media_scripts() {
						
			wp_enqueue_script('fg-media', plugins_url('/admin/js/media.js', __FILE__), array('jquery', 'jquery-ui-core', 'jquery-ui-sortable', 'wp-ajax-response', 'swfobject', 'ajax-utils', 'media-upload','thickbox', 'uniform'), $this->version);
			wp_localize_script('fg-media', 'options', array( 'Ajax_Url' => admin_url( 'admin-ajax.php'), 'adminUrl' => plugins_url("admin", __FILE__), 'contentDir' => FG_CONTENT_DIR, 'contentUrl' => content_url() ));
			
		}
		
		public function options_styles() {
			
			wp_enqueue_style('fg-colorpicker', plugins_url('/admin/css/colorpicker.css', __FILE__));
			wp_enqueue_style('fg-admin', plugins_url('/admin/css/admin.css', __FILE__), array('thickbox', 'uniform-aristo'), $this->version);
				
		}
		
		public function options_scripts() {
			
			wp_enqueue_script('fg-colorpicker', plugins_url('/admin/js/colorpicker.js', __FILE__));			
			wp_enqueue_script('fg-options', plugins_url('/admin/js/options.js', __FILE__), array('jquery', 'uniform', 'media-upload','thickbox'), $this->version);
						
		}
		
		public function generator_styles() {
			
			wp_enqueue_style('fg-colorpicker', plugins_url('/admin/css/colorpicker.css', __FILE__));
			wp_enqueue_style('fg-admin', plugins_url('/admin/css/admin.css', __FILE__), array('thickbox', 'uniform-aristo'), $this->version);
				
		}
		
		public function generator_scripts() {
			
			wp_enqueue_script('fg-colorpicker', plugins_url('/admin/js/colorpicker.js', __FILE__));			
			wp_enqueue_script('fg-options', plugins_url('/admin/js/options.js', __FILE__), array('jquery', 'uniform', 'media-upload','thickbox'), $this->version);
						
		}
		
		public function galleries_admin_page() {
			
			require_once(FG_PLUGIN_DIR . '/admin/galleries.php');
			
		}
		
		public function albums_admin_page() {
											
			require_once(FG_PLUGIN_DIR . '/admin/albums.php');
			
		}
		
		public function media_admin_page() {
			
			require_once(FG_PLUGIN_DIR . '/admin/media.php');
				
		}
		
		public function options_admin_page() {
			
			//get/update options
			if(isset($_POST['fg_opts_save'])){
								
				$options = array('background_color' => $_POST['background_color'],
				                 'title_color' => $_POST['title_color'],
				                 'thumbnail_width' => $_POST['thumbnail_width'], 
								 'thumbnail_height' => $_POST['thumbnail_height'], 
								 'thumbnail_opacity' => $_POST['thumbnail_opacity'], 
								 'thumbnails_per_page' => $_POST['thumbnails_per_page'],
								 'thumbnail_zc' => $_POST['thumbnail_zc'],
								 'title_height' => $_POST['title_height'], 
								 'border_thickness' => $_POST['border_thickness'],
								 'row_offset' => $_POST['row_offset'],
							     'column_offset' => $_POST['column_offset'],
								 'shadow_offset' => $_POST['shadow_offset'],
								 'shadow_image' => $_POST['shadow_image'],
								 'text_fade_direction' => $_POST['text_fade_direction'], 
								 'dropdown_theme' => $_POST['dropdown_theme'],
								 'dropdown' => $_POST['dropdown'],
								 'divider' => $_POST['divider'],
								 'show_title' => $_POST['show_title'],
								 'slide_title' => $_POST['slide_title'],
								 'prettyphoto_theme' => $_POST['prettyphoto_theme'], 
								 'prettyphoto_overlay' => $_POST['prettyphoto_overlay'], 
								 'prettyphoto_image_resize' => $_POST['prettyphoto_image_resize'],
								 'prettyphoto_deeplinking' => $_POST['prettyphoto_deeplinking'],
								 'prettyphoto_slideshow' => $_POST['prettyphoto_slideshow']);
				
				update_option($this->options_field_name, $options);
				
			}
			else
				$options = get_option($this->options_field_name);
			
			require_once(FG_PLUGIN_DIR . '/admin/options.php');	
				
		}
		
		public function generator_admin_page() {
			
			if(isset($_POST['fg_generate'])){
				require_once(FG_PLUGIN_DIR . '/admin/generate-code.php');
			}
			else {
				
				$options = $this->default_options;
				require_once(FG_PLUGIN_DIR . '/admin/generator.php');	
			}    	
				
		}
		
		public function add_fancyGallery($atts) {
			
			if(!is_singular())
			  return;
			
			$selectAlbum = '';
			if( isset( $_GET['album']) )
			    $selectAlbum = $_GET['album'];

			extract( shortcode_atts( array(
				'id' => ''
			), $atts ) );
			
			$options = get_option($this->options_field_name);
			
			//get albums of the gallery corresponding to the ID
			$albums = $this->wpdb->get_results("SELECT * FROM " . $this->album_table_name . " WHERE gallery='" . $id . "' ORDER BY sort ASC");

			//check if gallery exists and has albums
			if(sizeof($albums) == 0)
				return "<p class='fg-error'>Fancy Gallery Error:<br />No gallery with the ID '" . $id . "' was found or you have not created albums for it yet.</p>";
			
			//html output
			$output = '';
			$output .= '<div id="fancygallery-' . $id .'" class="fancygallery-panel">';
			
			
			foreach($albums as $album) {
				$output .= '<div title="' . stripslashes($album->title) . '">';
				
				$album_files = $this->wpdb->get_results("SELECT * FROM " . $this->images_table_name . " WHERE album='" . sanitize_file_name(sanitize_title($album->title)) . "' AND gallery='" . $id . "' ORDER BY sort ASC");
				foreach($album_files as $album_file) {
					$output .= '<a href="'. $album_file->file .'" ><img src="' . plugins_url('/admin/timthumb.php', __FILE__) . '?src='. $album_file->thumbnail . '&w='.$options['thumbnail_width'].'&h='.$options['thumbnail_height'].'&zc='.$options['thumbnail_zc'].'&q=100" title="'.stripslashes($album_file->title).'" /><span>'.strip_tags($album_file->description).'</span></a>';
				}
					
				$output .= "</div>";
			}
			$output .= "</div>";
			
			//js output
			
			
			$dropdown = $options['dropdown'] == null ? 0 : $options['dropdown'];
			$divider = $options['divider'] == null ? 0 : $options['divider'];
			$showTitle = $options['show_title'] == null ? 0 : $options['show_title'];
			$slideTitle = $options['slide_title'] == null ? 0 : $options['slide_title'];			
			$prettyphoto_image_resize = $options['prettyphoto_image_resize'] == null ? 0 : $options['prettyphoto_image_resize'];
			$prettyphoto_overlay_gallery = $options['prettyphoto_overlay'] == null ? 0 : $options['prettyphoto_overlay'];
			$prettyphoto_autoplay_slideshow = $options['prettyphoto_slideshow'] == null ? 0 : $options['prettyphoto_slideshow'];
			$prettyphoto_deeplinking = $options['prettyphoto_deeplinking'] == null ? 0 : $options['prettyphoto_deeplinking'];
			
			$output .= "<script type='text/javascript'>
			jQuery(document).ready(function(){
			  jQuery('#fancygallery-" . $id ."').fancygallery({
				  backgroundColor: '" . $options['background_color'] . "', titleColor: '" . $options['title_color'] . "', thumbWidth: " . $options['thumbnail_width'] . ", thumbHeight: " . $options['thumbnail_height'] . ",
				  thumbOpacity: " . $options['thumbnail_opacity'] . ", imagesPerPage: " . $options['thumbnails_per_page'] . ", titleHeight: " . $options['title_height'] . ", borderThickness: " . $options['border_thickness'] . ",
				  rowOffset: " . $options['row_offset'] . ", columnOffset: " . $options['column_offset'] . ", shadowOffset: " . $options['shadow_offset'] . ", textFadeDirection: '" . $options['text_fade_direction'] . "', 
				  shadowImage: '" . $options['shadow_image'] . "', selectAlbum: '" . $selectAlbum . "', dropdown: " . $dropdown . ", divider: " . $divider . ", showTitle: " .$showTitle .", slideTitle: " . $slideTitle . ",
				  boxOptions: {theme: '" . $options['prettyphoto_theme'] . "', allow_resize: " . $prettyphoto_image_resize . " , overlay_gallery: " . $prettyphoto_overlay_gallery . ", 
				               autoplay_slideshow: " . $prettyphoto_autoplay_slideshow . ", deeplinking: " . $prettyphoto_deeplinking . ", social_tools: '' }});
		    });
			</script>";
			
			return $output;
			
		}
		
		public function add_styles() {		
			if(!is_singular())
			  return;
			
			global $post;
			
			//search for the shortcode and if one is found, include the necessary styles
			if(strpos($post->post_content,'[fancygallery') !== false) {
				
				$options = get_option($this->options_field_name);
				
				wp_enqueue_style('prettyphoto', plugins_url('/css/prettyPhoto.css', __FILE__));
				wp_enqueue_style('radykal-fancy-gallery', plugins_url('/css/jquery.fancygallery.css', __FILE__), array('uniform-'. $options['dropdown_theme'] . ''), $this->version);
				
			}
		}
		
		//includes scripts for the shortcodes
		public function add_scripts() {	
			if(!is_singular())
			  return;
			
			global $post;
			
			//search for the shortcode and if one is found, include the necessary scripts		
			if(strpos($post->post_content,'[fancygallery') !== false) {

				wp_register_script('prettyphoto', plugins_url('/js/jquery.prettyPhoto.js', __FILE__));
				wp_enqueue_script('radykal-fancy-gallery', plugins_url('/js/jquery.fancygallery.min.js', __FILE__), array('jquery', 'prettyphoto', 'uniform'), $this->version);
																   
			}
		}
		
		public function new_gallery() {
			
			//Get post data
		    if ( !isset( $_POST['title'] ) ) 
			    exit;
				
			$title = trim($_POST['title']);
			$slug = sanitize_file_name(sanitize_title($title));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
				
			//check if main gallery folder exists
			if(!file_exists(FG_CONTENT_DIR)) {
				//try to create main gallery folder
				if( !wp_mkdir_p(FG_CONTENT_DIR) ) {
				     $errors->add( 'makeroot-error', ' '. WP_CONTENT_DIR .': Could not create the main gallery folder! Please check the permission. Set the CHMOD to 755 or 777.');
					 $this->ajax_error_handler($errors, $error_response);
					 exit;
				}
				
				//check if main gallery folder is writable
				if( !@is_writable(FG_CONTENT_DIR) ) {
					$errors->add( 'gallery-permission-error', ' <strong>' . FG_CONTENT_DIR . '</strong> '.' is not writable! Please check the permission. Set the CHMOD to 755 or 777.');
					$this->ajax_error_handler($errors, $error_response);
					exit;
				}
			}
			
			$gallery_directory = FG_CONTENT_DIR . '/' . $slug;
			if(file_exists($gallery_directory)) {	
				$errors->add( 'exist', 'A gallery with the same title already exists. Please choice another title!' );
				$this->ajax_error_handler($errors, $error_response);
				exit;
			}	
			else {
				if (wp_mkdir_p($gallery_directory)) {
					$this->wpdb->insert( $this->gallery_table_name, array( 'slug' => $slug , 'title' => $title ) );
					$success_response->add(array( 'what' => 'object', 'data' => 'Gallery successfully created!' ) );
					$success_response->send();
							
					exit;
				}
				else
				  $errors->add( 'new-gallery-error', 'An new gallery ('.$title.') directory could not be created. Please try again!!' );
				  $this->ajax_error_handler($errors, $error_response);
				  exit;
			}
			
		}
		
		public function delete_gallery() {
			
			//Get post data
		    if ( !isset( $_POST['title'] ) ) 
			    exit;
		    
			$title = trim($_POST['title']);
			$slug = sanitize_file_name(sanitize_title($title));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			try {
				$this->wpdb->query("DELETE FROM " . $this->gallery_table_name . " WHERE slug ='" . $slug . "' ");
				$this->wpdb->query("DELETE FROM " . $this->album_table_name . " WHERE gallery ='" . $slug . "' ");
		        $this->wpdb->query("DELETE FROM " . $this->images_table_name . " WHERE gallery ='" . $slug . "' ");
				$this->delete_directory(FG_CONTENT_DIR . '/' . $slug);
				
				$success_response->add( array( 'what' => 'object', 'data' => 'Gallery successfully deleted!' ) );
				$success_response->send();
				
				exit;
			}
			catch(Exception $e) {
				$errors->add( 'delete-gallery-error', 'Could not delete gallery!' );		
			}
			
			$this->ajax_error_handler($errors, $error_response);
			
		}
		
		public function delete_galleries() {
			
			$success_response = new WP_Ajax_Response();
			
			$this->wpdb->query("TRUNCATE TABLE " . $this->gallery_table_name . "");
			$this->wpdb->query("TRUNCATE TABLE " . $this->album_table_name . "");
			$this->wpdb->query("TRUNCATE TABLE " . $this->images_table_name . "");
			$this->delete_directory(FG_CONTENT_DIR);
			wp_mkdir_p(FG_CONTENT_DIR);
			
			$success_response->add( array( 'what' => 'object', 'data' => 'All galleries successfully deleted!' ) );
			$success_response->send();
			
			exit;
		}
		
		public function load_albums() {
			
			//Get post data
		    if ( !isset( $_POST['gallery'] ) ) 
			    exit;
		    
			$gallery = trim($_POST['gallery']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
					
			$albums = $this->wpdb->get_results("SELECT * FROM " . $this->album_table_name . " WHERE gallery='" . $slugGallery . "' ORDER BY sort ASC");
			
			$response = json_encode( $albums );
 
			// response output
			header( "Content-Type: application/json" );
			echo $response;
									
			exit;
		}
		
		public function new_album() {
			
			//Get post data
		    if ( !isset($_POST['title']) || !isset($_POST['gallery']) || !isset($_POST['sortId']) ) 
			    exit;
		    
			$gallery = trim($_POST['gallery']);
			$title = trim($_POST['title']);
			$sortId = trim($_POST['sortId']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($title));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			$album_directory = FG_CONTENT_DIR . '/' . $slugGallery . '/'. $slugAlbum;
			if(file_exists($album_directory)) {	
				$errors->add( 'exist', 'An album with the same title already exists. Please choice another title!' );
			}	
			else {
				if (wp_mkdir_p($album_directory)) {
					$this->wpdb->insert( $this->album_table_name, array( 'gallery' => $slugGallery, 'slug' => $slugAlbum, 'title' => $title, 'sort' => $sortId ) );
					$success_response->add( array( 'what' => 'object', 'data' => 'Album successfully created!' ) );
					$success_response->send();
							
					exit;
				}
				else
				  $errors->add( 'new-album-error', 'An new album directory could not be created. Please try again!!' );
			}
			
			$this->ajax_error_handler($errors, $error_response);
		}
		
		public function edit_album() {
			
			//Get post data
		    if ( !isset($_POST['oldTitle']) || !isset($_POST['newTitle']) || !isset($_POST['gallery']) ) 
			    exit;
			
			$gallery = trim($_POST['gallery']);
		    $oldTitle = trim($_POST['oldTitle']);		 
		    $newTitle = trim($_POST['newTitle']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugOldTitle = sanitize_file_name(sanitize_title($oldTitle));
			$slugNewTitle = sanitize_file_name(sanitize_title($newTitle));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			$album_directory_old = FG_CONTENT_DIR . '/' . $slugGallery . '/'. $slugOldTitle;
			if(file_exists($album_directory_old)) {
				$this->wpdb->update($this->album_table_name, array('slug' => $slugNewTitle, 'title' => $newTitle ), array('slug' => $slugOldTitle, 'gallery' => $slugGallery ) );
				$this->wpdb->update($this->images_table_name, array('album' => $slugNewTitle ), array('album' => $slugOldTitle, 'gallery' => $slugGallery  ) );
				$this->wpdb->query("UPDATE ". $this->images_table_name ." SET file = REPLACE(file, '" . $slugOldTitle . "', '". $slugNewTitle ."') WHERE gallery='".$slugGallery."' ");
				$this->wpdb->query("UPDATE ". $this->images_table_name ." SET thumbnail = REPLACE(thumbnail, '" . $slugOldTitle . "', '". $slugNewTitle ."') WHERE gallery='".$slugGallery."' ");
				rename($album_directory_old, dirname($album_directory_old) . '/' . $slugNewTitle);
				
				$success_response->add( array( 'what' => 'object', 'data' => 'Album title successfully changed!' ) );
				$success_response->send();
				
				exit;	
			}
			else {
				$errors->add( 'edit-album-error', 'Could not rename album directory!' );
			}
			
			$this->ajax_error_handler($errors, $error_response);
		}
		
		public function delete_album() {
			
			//Get post data
		    if ( !isset($_POST['title']) || !isset($_POST['gallery']) ) 
			    exit;
		    
			$gallery = trim($_POST['gallery']);
			$title = trim($_POST['title']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($title));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			try {
				$this->wpdb->query("DELETE FROM " . $this->album_table_name . " WHERE title ='" . $title . "' AND gallery='" . $slugGallery . "' ");
			    $this->wpdb->query("DELETE FROM " . $this->images_table_name . " WHERE album ='" . $slugAlbum . "' AND gallery='" . $slugGallery . "' ");
			    $this->delete_directory(FG_CONTENT_DIR . '/' . $slugGallery . '/' . $slugAlbum);
				
				$success_response->add( array( 'what' => 'object', 'data' => 'Album successfully deleted!' ) );
				$success_response->send();
				
				exit;
			}
			catch(Exception $e) {
				$errors->add( 'delete-album-error', 'Could not delete album directory!' );		
			}
			
			$this->ajax_error_handler($errors, $error_response);   
		}
		
		public function delete_albums() {
			
			//Get post data
		    if ( !isset( $_POST['gallery'] ) ) 
			    exit;
		    
			$gallery = trim($_POST['gallery']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			try {
				$this->wpdb->query("DELETE FROM " . $this->album_table_name . " WHERE gallery ='" . $slugGallery . "' ");
				$this->wpdb->query("DELETE FROM " . $this->images_table_name . " WHERE gallery ='" . $slugGallery . "' ");
				$this->delete_directory(FG_CONTENT_DIR . '/' . $slugGallery);
				wp_mkdir_p(FG_CONTENT_DIR . '/' . $slugGallery);
				
				$success_response->add( array( 'what' => 'object', 'data' => 'All albums successfully deleted!' ) );
				$success_response->send();
				
				exit;
			}
			catch(Exception $e) {
				$errors->add( 'delete-albums-error', 'Could not delete albums!' );
			}
			
			$this->ajax_error_handler($errors, $error_response);
		}
		
		public function update_albums() {
			
			//Get post data
		    if ( !isset($_POST['albums']) || !isset($_POST['gallery']) ) 
			    exit;
				
			$gallery = trim($_POST['gallery']);
			$albums = $_POST['albums'];
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			
			$error_response = $success_response = new WP_Ajax_Response();
			$errors = new WP_Error();
			
			try {
				$this->wpdb->query("DELETE FROM " . $this->album_table_name . " WHERE gallery='". $slugGallery ."' ");
				
				for($i = 0; $i < sizeof($albums); $i++) {
				  if(isset($albums[$i])) {	
					  $this->wpdb->insert( $this->album_table_name, array( 'gallery' => $slugGallery, 'slug' => sanitize_file_name(sanitize_title($albums[$i]['value'])), 'title' => $albums[$i]['value'], 'sort' => $i) );
				  }
				}
				$success_response->add( array( 'what' => 'object', 'data' => 'Album successfully updated!' ) );
				$success_response->send();
				
				exit;
			}
			catch(Exception $e) {
				$errors->add( 'update-album-error', 'Album could not be updated. Please try again!' );
			}
			$this->ajax_error_handler($errors, $error_response);
				
		}
		
		public function load_files() {
			
			//Get post data
		    if ( !isset($_POST['album']) || !isset($_POST['gallery']) ) 
			    exit;
		    
			$gallery = trim($_POST['gallery']);
			$album = trim($_POST['album']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($album));
					
			$results = $this->wpdb->get_results("SELECT * FROM " . $this->images_table_name . " WHERE album='" . $slugAlbum . "' AND gallery='" . $slugGallery . "' ORDER BY sort DESC");
			
			$response = json_encode( $results );
 
			// response output
			header( "Content-Type: application/json" );
			echo $response;
			
			exit;						
		}
		
		public function save_file() {
			
			//Get post data
		    if ( !isset($_POST['album']) || !isset($_POST['gallery']) || !isset($_POST['file']) || !isset($_POST['thumbnail']) || !isset($_POST['sortId']) ) 
			    exit;
			
			$gallery = trim($_POST['gallery']);
		    $album = trim($_POST['album']);
			$file = trim($_POST['file']);
			$thumbnail = trim($_POST['thumbnail']);
			$sortId = trim($_POST['sortId']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($album));
						
			$this->wpdb->insert( $this->images_table_name, array( 'gallery' => $slugGallery, 'album' => $slugAlbum, 'file' => $file, 'thumbnail' => $thumbnail, 'title' => '', 'description' => '', 'sort' => $sortId ) );
		}
		
		public function delete_files() {
			
			//Get post data
		    if ( !isset($_POST['files']) || !isset($_POST['gallery']) || !isset($_POST['album']) ) 
			    exit;
			
			$gallery = trim($_POST['gallery']);
			$album = trim($_POST['album']);
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($album));
		    $files = $_POST['files'];		     
			 
		    foreach($files as $file) {
			   $file_url = $file['value'];
			   $this->wpdb->query("DELETE FROM " . $this->images_table_name . " WHERE file='". trim($file_url) ."' ");

			   $file_path = FG_CONTENT_DIR . '/' . $slugGallery . '/' . $slugAlbum . '/' . basename(trim($file_url));
			   if(file_exists($file_path))
				   @unlink($file_path);
		    }
		}
		
		public function update_files() {
			
			//Get post data
		    if ( !isset($_POST['files']) || !isset($_POST['thumbnails']) || !isset($_POST['gallery']) || !isset($_POST['album']) ) 
			    exit;
			
			$gallery = trim($_POST['gallery']);	
			$album = trim($_POST['album']);
			$files = $_POST['files'];
			$thumbnails = $_POST['thumbnails'];
		    $descriptions = $_POST['descriptions'];
			$titles = $_POST['titles'];
			$slugGallery = sanitize_file_name(sanitize_title($gallery));
			$slugAlbum = sanitize_file_name(sanitize_title($album));
			
			$this->wpdb->query("DELETE FROM " . $this->images_table_name . " WHERE album='". $slugAlbum ."' AND gallery='" . $slugGallery . "' ");	
			 
			for($i = 0; $i < sizeof($files); $i++) {
				if(isset($files[$i])) {
					$this->wpdb->insert( $this->images_table_name, array( 'gallery' => $slugGallery, 'album' => $slugAlbum, 'file' => trim($files[$i]['value']), 'thumbnail' => trim($thumbnails[$i]['value']), 'title' => $titles[$i]['value'], 'description' => $descriptions[$i]['value'], 'sort' => $i ) );
				}
			}
			
		}
		
		private function install() {
			
			require_once(FG_PLUGIN_DIR . '/admin/functions.php');
			
			//create gallery options in db
			if( !get_option($this->options_field_name) ) {
			    add_option($this->options_field_name, $this->default_options);
			}	
			
			//create tables in the db
			$gallery_sql = "id INT NOT NULL AUTO_INCREMENT,
			              slug TEXT COLLATE utf8_general_ci NOT NULL,  
			              title TEXT COLLATE utf8_general_ci NOT NULL,
						  UNIQUE KEY (id)";
			
			$album_sql = "id INT NOT NULL AUTO_INCREMENT,
			              gallery TEXT COLLATE utf8_general_ci NOT NULL,
						  slug TEXT COLLATE utf8_general_ci NOT NULL,
			              title TEXT COLLATE utf8_general_ci NOT NULL,
						  sort INT COLLATE utf8_general_ci NOT NULL,
						  UNIQUE KEY (id)";
						  
			$images_sql = "id INT NOT NULL AUTO_INCREMENT,
			              gallery TEXT COLLATE utf8_general_ci NOT NULL,
			              album TEXT COLLATE utf8_general_ci NOT NULL,
						  file VARCHAR(255) COLLATE utf8_general_ci NOT NULL,
						  thumbnail VARCHAR(255) COLLATE utf8_general_ci NOT NULL,
						  title TEXT COLLATE utf8_general_ci NULL,
						  description TEXT COLLATE utf8_general_ci NULL,
						  sort INT COLLATE utf8_general_ci NOT NULL,
						  UNIQUE KEY (id)";
			
			createDbTable($this->gallery_table_name, $gallery_sql);
			createDbTable($this->album_table_name, $album_sql);
			createDbTable($this->images_table_name, $images_sql);
			
			add_option($this->version_field_name, $this->version);
			
			$cache_dir = FG_PLUGIN_DIR . '/admin/cache/';
			$temp_dir = FG_PLUGIN_DIR . '/admin/temp/';
			
			//create cache for timthumb and set chmod to 755
			if(!file_exists($cache_dir)) {
				wp_mkdir_p($cache_dir);
			}
			if(!file_exists($temp_dir)) {
				wp_mkdir_p($temp_dir);
			}
			chmod($cache_dir, 0777);
			chmod($temp_dir, 0777);
			
	   }
	   
	   private function upgrade() {
		          
		   //update version in db
		   update_option($this->version_field_name, $this->version);
		   update_option($this->options_field_name, $this->default_options);
		      
	   }
		       
	   //deletes a directory and is content 
	   private function delete_directory($dir) {
			$iterator = new RecursiveDirectoryIterator($dir);
			foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
			if ($file->isDir()) {
				@rmdir($file->getPathname());
			 } 
			 else {
			    @unlink($file->getPathname());
			 }
		   }
		   @rmdir($dir);
	   }
	   
	   //returns an error to the ajax handler
	   private function ajax_error_handler($errors, $error_response) {
		   if ( count ( $errors->get_error_codes() ) > 0 ) {
				$error_response->add( array( 'what' => 'errors', 'id' => $errors ) );
				$error_response->send();
				
				exit;
			}
	   }
	}
}

//init Fancy Gallery
if(class_exists('FancyGallery')) {
	$fg = new FancyGallery();
}

?>