<?php
/**
 * Plugin Name: Portfolio Manager
 * Plugin URI: http://OTWthemes.com 
 * Description: Portfolio Manager for WordPress adds tons of portfolio functionality in terms of layout variation, styling options, content re-arrangement, etc. to your WordPress based website. Upload portfolio items in a custom post type. Create as many portfolio lists as you like. This plugin comes with over 20 templates to choose from. Select list content, modify layout and style your list to get the content and the look you want. Use the list’s shortcode or a widget to place your lists anywhere in your site – WYSIWYG editor of your page/post, any sidebar, template files.
 * Author: OTWthemes
 * Version: 3.7
 * Author URI: https://codecanyon.net/user/otwthemes/portfolio?ref=OTWthemes
 */
/**
 * Global Constants that are need for this plugin
 */
	// Directory Separator
	if( !defined( 'DS' ) ){
		define( 'DS', '/' );
	}
	
	if( !defined( 'OTW_PLUGIN_PORTFOLIO_MANAGER' ) ){
		define( 'OTW_PLUGIN_PORTFOLIO_MANAGER', 1 );
	}
	
  // Plugin Folder Name
  if( function_exists( 'plugin_basename' ) ){
	define( 'OTW_PM_PATH', preg_replace( "/\/otw\_portfolio\_manager\.php$/", '', plugin_basename( __FILE__ ) ) );
  }else{
	define( 'OTW_PM_PATH', 'otw-portfolio-manager' );
  }
  // Full map 
  define( 'OTW_PM_SERVER_PATH', dirname(__FILE__) );
  // Namespace for translation
  define( 'OTW_PM_TRANSLATION', 'otw-portfolio-manager' );
  
  $otw_pm_plugin_url = plugin_dir_url( __FILE__);
  $otw_pm_js_version = '2.2';
  $otw_pm_css_version = '1.9';

  $otw_pm_plugin_id = '40880db0bbb7600807e740a1c0d9f44f';
  
  load_plugin_textdomain( 'otw-portfolio-manager' ,false,dirname(plugin_basename(__FILE__)) . '/languages/');
	
	$upload_dir = wp_upload_dir();
	
	if( isset( $upload_dir['basedir'] ) ){
		define( 'SKIN_PM_URL', set_url_scheme( $upload_dir['baseurl'] ).DS.'otwpm'.DS.'skins'.DS );
		define( 'SKIN_PM_PATH', $upload_dir['basedir'].DS.'otwpm'.DS.'skins'.DS );
		define( 'UPLOAD_PM_PATH', $upload_dir['basedir'].DS );
	}else{
		define( 'SKIN_PM_URL',  plugins_url(). DS . 'wp-content' . DS . 'uploads'. DS .'otwpm'. DS .'skins' . DS );
		define( 'SKIN_PM_PATH', $_SERVER['DOCUMENT_ROOT'] . DS . 'wp-content'. DS .'uploads' . DS .'otwpm'. DS . 'skins' .DS );
		define( 'UPLOAD_PM_PATH', $_SERVER['DOCUMENT_ROOT'] . DS . 'wp-content'. DS .'uploads' . DS );
	}
	
	//components
	$otw_pm_grid_manager_component = false;
	$otw_pm_grid_manager_object = false;
	$otw_pm_page_grid_manager_component = false;
	$otw_pm_page_grid_manager_object = false;
	$otw_pm_shortcode_component = false;
	$otw_pm_page_shortcode_component = false;
	$otw_pm_shortcode_object = false;
	$otw_pm_page_shortcode_object = false;
	$otw_pm_form_component = false;
	$otw_pm_validator_component = false;
	$otw_pm_image_component = false;
	$otw_pm_factory_component = false;
	$otw_pm_factory_object = false;
	$otw_pm_image_object = false;
	$otw_pm_image_profile = false;
	$otw_pm_validator_component = false;
	$otw_pm_validator_object = false;
	
	//load core component functions
	@include_once( 'include/otw_components/otw_functions/otw_functions.php' );
	
	if( !function_exists( 'otw_register_component' ) ){
		wp_die( 'Please include otw components' );
	}
	
	otw_set_up_memory_limit( '256M' );
	
	//register grid manager component
	otw_register_component( 'otw_portfolio_template_grid_manager', dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_grid_manager/', $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_grid_manager/' );
	
	//register grid manager component
	otw_register_component( 'otw_grid_manager', dirname( __FILE__ ).'/include/otw_components/otw_grid_manager/', $otw_pm_plugin_url.'include/otw_components/otw_grid_manager/' );
	
	//register factory component
	otw_register_component( 'otw_factory', dirname( __FILE__ ).'/include/otw_components/otw_factory/', $otw_pm_plugin_url.'include/otw_components/otw_factory/' );
	
	//register image component
	otw_register_component( 'otw_image', dirname( __FILE__ ).'/include/otw_components/otw_image/', '/include/otw_components/otw_image/' );
	
	//register form component
	otw_register_component( 'otw_form', dirname( __FILE__ ).'/include/otw_components/otw_form/', $otw_pm_plugin_url.'include/otw_components/otw_form/' );
	
	//register validator component
	otw_register_component( 'otw_validator', dirname( __FILE__ ).'/include/otw_components/otw_validator/', $otw_pm_plugin_url.'include/otw_components/otw_validator/' );
	
	//register shortcode component
	otw_register_component( 'otw_portfolio_template_shortcode', dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	
	//register shortcode component
	otw_register_component( 'otw_shortcode', dirname( __FILE__ ).'/include/otw_components/otw_shortcode/', $otw_pm_plugin_url.'include/otw_components/otw_shortcode/' );



if( !class_exists('OTWPortfolioManager') ) {

class OTWPortfolioManager {

  // Query Class Instance
  public $otwPMQuery = null;
  
  // CSS Class Instance
  public $otwCSS = null;

  // Tempalte Dispatcher
  public $otwDispatcher = null;

  public $fontsArray = null;

  // Validation errors array
  public $errors = null;

  // Form data on error
  public $errorData = null;

  public $portfolio_post_type = 'otw_pm_portfolio';
  
  public $portfolio_category = 'otw_pm_portfolio_category';
  
  public $portfolio_tag = 'otw_pm_portfolio_tag';
  
  public $menu_parent = 'edit.php?post_type=otw_pm_portfolio';
  
  public $otw_pm_plugin_options = array();
  
  public $portfolio_meta_details = array();
  /**
   * Initialize plugin
   */
  public function __construct() {
    
	$this->portfolio_meta_details = array(
		'1' => esc_html__( 'Skills Needed', 'otw-portfolio-manager' ),
		'2' => esc_html__( 'Date', 'otw-portfolio-manager' ),
		'3' => esc_html__( 'Project URL', 'otw-portfolio-manager' ),
		'4' => esc_html__( 'Copyright', 'otw-portfolio-manager' ),
		'5' => esc_html__( 'Client', 'otw-portfolio-manager' ),
		'6' => esc_html__( 'Client URL', 'otw-portfolio-manager' )
	);
    // Create an instance of the OTWPMQuery Class
    $this->otwPMQuery = new OTWPMQuery();
    
    $this->otwPMQuery->portfolio_category  = $this->portfolio_category;
    $this->otwPMQuery->portfolio_tag  = $this->portfolio_tag;
    $this->otwPMQuery->portfolio_post_type  = $this->portfolio_post_type;

    $this->otwCSS = new OTWPMCss();

    $this->otwDispatcher = new OTWPMDispatcher();
    $this->otwDispatcher->portfolio_category  = $this->portfolio_category;
    $this->otwDispatcher->portfolio_tag  = $this->portfolio_tag;
    $this->otwDispatcher->portfolio_post_type  = $this->portfolio_post_type;
    $this->otwDispatcher->portfolio_templates = array(
		'single-portfolio-media-left' => esc_html__( 'Media Left (default)', 'otw-portfolio-manager' ),
		'single-portfolio-media-right' => esc_html__( 'Media Right', 'otw-portfolio-manager' ),
		'single-portfolio-media-top' => esc_html__( 'Media Top', 'otw-portfolio-manager' ),
		'single-portfolio-with-accordion' => esc_html__( 'With Accordion', 'otw-portfolio-manager' ),
		'single-portfolio-with-tabs' => esc_html__( 'With Tabs', 'otw-portfolio-manager' ),
		'-' => '-'
	);
	$otw_custom_templates = $this->get_custom_templates();
	
	foreach( $otw_custom_templates as $custom_template ){
		$this->otwDispatcher->portfolio_templates['otw_custom_template_'.$custom_template['id'] ] = $custom_template['title'];
	}
    
    $this->otw_pm_plugin_options = get_option( 'otw_pm_plugin_options' );
    $this->otwDispatcher->otw_pm_plugin_options = $this->otw_pm_plugin_options;

    require_once( 'include' . DS . 'fonts.php' );
    $this->fontsArray = json_decode($allFonts);

    // Add Admin Menu only if role is Admin
    if( is_admin() ) {
      

      // Add Admin Assets
      add_action( 'admin_init', array($this, 'register_resources') );
      // Add Admin menu
      add_action( 'admin_menu', array($this, 'register_menu') );
      // Add Meta Box 
      add_action( 'add_meta_boxes', array($this, 'pm_meta_boxes'), 10, 2 );
      // Save Meta Box Data
      add_action( 'save_post', array($this, 'pm_save_meta_box') );
      
      add_action( 'wp_ajax_otw_pm_select2_options', array($this, 'get_select2_options') );
      
	//filter for factory messages
	add_filter( 'otwfcr_notice', array( $this, 'factory_message' ) );

    }
    
    add_action('init', array($this, 'load_resources') );
    
    register_activation_hook( __FILE__, array( $this, 'flush_rewrites' ) );
    
    // Load Short Code
    add_shortcode( 'otw-pm-list', array($this, 'pm_list_shortcode') );

    // Include Widgets Functionality
    add_action( 'widgets_init', array($this, 'pm_register_widgets') );

    /**
     * Init Front End template functions
     */

    // Enque template JS and CSS files
    add_action( 'wp_enqueue_scripts', array($this, 'register_fe_resources') );

    // Ajax FE Actions - Load More Pagination
    add_action( 'wp_ajax_get_pm_posts', array($this, 'otw_pm_get_posts') );
    add_action( 'wp_ajax_nopriv_get_pm_posts', array($this, 'otw_pm_get_posts') );
    
    // Ajax FE Social Share
    add_action( 'wp_ajax_pm_social_share', array($this, 'otw_pm_social_share') );
    add_action( 'wp_ajax_nopriv_pm_social_share', array($this, 'otw_pm_social_share') );
    
    //Ajax actions fro videos
    add_action( 'wp_ajax_otw_pm_get_video', array($this, 'otw_pm_get_video') );
    add_action( 'wp_ajax_nopriv_otw_pm_get_video', array($this, 'otw_pm_get_video') );
    

	add_action( 'template_redirect', array( $this, 'otw_pm_portfolio_template' ) );
	
	add_filter( 'get_post_metadata', array( $this, 'otw_pm_portfolio_thumbnail_metadata' ), 99, 5 );
	add_filter( 'post_thumbnail_html', array( $this, 'otw_pm_portfolio_thumbnail' ), 99, 5 );
	
	if( is_admin() ){
		add_filter('manage_'.$this->portfolio_post_type.'_posts_columns', array( $this, 'portfolio_table_head' ) );
	}
}
  /**
   * Add Menu To WP Backend
   * This menu will be available only for Admin users
   */
public function register_menu(){
	
	global $otw_pm_factory_object, $otw_pm_plugin_id;
	
	if( $otw_pm_factory_object->is_plugin_active( $otw_pm_plugin_id ) ){
		
		add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager | Details', 'otw-portfolio-manager'), esc_html__('Portfolio Items Details', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-details', array( $this , 'pm_details' ) );
		add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager Lists', 'otw-portfolio-manager'), esc_html__('Portfolio Lists', 'otw-portfolio-manager'), 'manage_options', 'otw-pm', array( $this , 'pm_list' ) );
		$hook_suffix_0 = add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager | Add List', 'otw-portfolio-manager'), esc_html__('Add New List', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-add', array( $this , 'pm_add' ) );
		$hook_suffix_1 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Duplicate List', 'otw-portfolio-manager'), esc_html__('Duplicated List', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-copy', array( $this , 'pm_copy' ) );
		add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager | Options', 'otw-portfolio-manager'), esc_html__('Options', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-settings', array( $this , 'pm_settings' ) );
		$hook_suffix_8 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Options | Import from OTW Portfolio Light', 'otw-portfolio-manager'), esc_html__('Import from OTW Portfolio Light', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-import-from-light', array( $this , 'pm_import_from_light' ) );
		$hook_suffix_2 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Details | Add', 'otw-portfolio-manager'), esc_html__('Add Detail', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-details-add', array( $this , 'pm_details_edit' ) );
		$hook_suffix_3 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Details | Edit', 'otw-portfolio-manager'), esc_html__('Edit Detail', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-details-edit', array( $this , 'pm_details_edit' ) );
		$hook_suffix_4 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Details | Action', 'otw-portfolio-manager'), esc_html__('Action', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-details-action', array( $this , 'pm_details_action' ) );
		
		add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager | Single Posts Templates', 'otw-portfolio-manager'), esc_html__('Single Posts Templates', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-custom-templates', array( $this , 'pm_custom_templates' ) );
		$hook_suffix_5 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Single Posts Templates | Add', 'otw-portfolio-manager'), esc_html__('Add Single Posts Templates', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-custom-templates-add', array( $this , 'pm_custom_templates_edit' ) );
		$hook_suffix_6 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Single Posts Templates | Edit', 'otw-portfolio-manager'), esc_html__('Edit Single Posts Templates', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-custom-templates-edit', array( $this , 'pm_custom_templates_edit' ) );
		$hook_suffix_7 = add_submenu_page( __FILE__, esc_html__('Portfolio Manager | Single Posts Templates | Action', 'otw-portfolio-manager'), esc_html__('Action Single Posts Templates', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-custom-templates-action', array( $this , 'pm_custom_templates_action' ) );
		
		add_submenu_page( $this->menu_parent, esc_html__('Portfolio Manager | Export/Import (Backup)', 'otw-portfolio-manager'), esc_html__('Export/Import (Backup)', 'otw-portfolio-manager'), 'manage_options', 'otw-pm-backup', array( $this , 'pm_backup' ) );
		
		add_action( 'load-' . $hook_suffix_0 , array( $this, 'open_pm_menu' ) );
		add_action( 'load-' . $hook_suffix_1 , array( $this, 'open_pm_menu' ) );
		add_action( 'load-' . $hook_suffix_2 , array( $this, 'open_pm_menu' )  );
		add_action( 'load-' . $hook_suffix_3 , array( $this, 'open_pm_menu' )  );
		add_action( 'load-' . $hook_suffix_4 , array( $this, 'open_pm_menu' )  );
		add_action( 'load-' . $hook_suffix_5 , array( $this, 'open_pm_menu' )  );
		add_action( 'load-' . $hook_suffix_6 , array( $this, 'open_pm_menu' )  );
		add_action( 'load-' . $hook_suffix_7 , array( $this, 'open_pm_menu' )  );
	}else{
		remove_submenu_page( $this->menu_parent, 'post-new.php?post_type='.$this->portfolio_post_type );
		remove_submenu_page( $this->menu_parent, 'edit.php?post_type='.$this->portfolio_post_type );
		remove_submenu_page( $this->menu_parent, 'edit-tags.php?taxonomy='.$this->portfolio_category.'&amp;post_type='.$this->portfolio_post_type );
		remove_submenu_page( $this->menu_parent, 'edit-tags.php?taxonomy='.$this->portfolio_tag.'&amp;post_type='.$this->portfolio_post_type );
	}
}

public function open_pm_menu(){
	
	global $menu, $submenu;
	
	foreach( $menu as $key => $item ){
		
		if( $item[2] == $this->menu_parent ){
			$menu[ $key ][4] = $menu[ $key ][4].' wp-has-submenu wp-has-current-submenu wp-menu-open menu-top otw-pm-menu-open current';
			
			if( function_exists( 'get_current_screen' ) ){
			
				$screen = get_current_screen();
				
				if( preg_match( "/otw\-pm\-add$/", $screen->base ) && isset( $submenu[ $this->menu_parent ] ) && otw_get('action',false) && ( otw_get('action','') == 'edit' ) ){
					foreach( $submenu[ $this->menu_parent ] as $s_key => $s_data ){
						
						if( $s_data[2] == 'otw-pm' ){
							$submenu[ $this->menu_parent ][ $s_key ][4] = 'current';
						}
					}
				}
			}
		}
	}
}

/**
* Modify portfolio listing table header
*/
public function portfolio_table_head( $columns ){
	
	$old_columns = $columns;
	
	$columns = array();
	
	foreach( $old_columns as $c_key => $c_value ){
		
		$columns[ $c_key ] = $c_value;
		
		if( $c_key == 'title' ){
			$columns['author'] = esc_html__( 'Author', 'otw-portfolio-manager' );
		}
	}
	
	return $columns;
}

/**
  * Add components
  */
public function load_resources(){
	
	global $otw_pm_image_component, $otw_pm_factory_component, $otw_pm_factory_object, $otw_pm_image_profile, $otw_pm_image_object, $otw_pm_grid_manager_component, $otw_pm_grid_manager_object, $otw_pm_page_grid_manager_component, $otw_pm_page_grid_manager_object, $otw_pm_plugin_url, $otw_pm_js_version, $otw_pm_css_version, $otw_pm_shortcode_component, $otw_pm_page_shortcode_component, $otw_pm_page_shortcode_object, $otw_pm_shortcode_object, $otw_pm_plugin_id;
	
	$this->register_portfolio_custom_types();
	
	//otw portfolio grid manager component
	$otw_pm_grid_manager_component = otw_load_component( 'otw_portfolio_template_grid_manager' );
	$otw_pm_grid_manager_object = otw_get_component( $otw_pm_grid_manager_component );
	$otw_pm_grid_manager_object->js_version = $otw_pm_js_version;
	$otw_pm_grid_manager_object->css_version = $otw_pm_css_version;
	$otw_pm_grid_manager_object->text_info = esc_html__( 'Add some rows and columns in the rows. Then you will be able to add your portfolio elements and sidebars in the columns. Once you build your layout you can save it so you can use it for another page.', 'otw-portfolio-manager' );
	
	include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_grid_manager_object.labels.php' );
	$otw_pm_grid_manager_object->init();
	
	
	if( !isset( $this->otw_pm_plugin_options['otw_pm_grid_pages'] ) || ( $this->otw_pm_plugin_options['otw_pm_grid_pages'] != 'no' ) )
	{
		//otw portfolio grid manager component
		$otw_pm_page_grid_manager_component = otw_load_component( 'otw_grid_manager' );
		$otw_pm_page_grid_manager_object = otw_get_component( $otw_pm_page_grid_manager_component );
		$otw_pm_page_grid_manager_object->js_version = $otw_pm_js_version;
		$otw_pm_page_grid_manager_object->css_version = $otw_pm_css_version;
		$otw_pm_page_grid_manager_object->text_info = esc_html__( 'Add some rows and columns in the rows. Then you will be able to add your portfolio elements and sidebars in the columns. Once you build your layout you can save it so you can use it for another page.', 'otw-portfolio-manager' );
		$otw_pm_page_grid_manager_object->active_for_pages = true;
		$otw_pm_page_grid_manager_object->active_for['page'] = true;
		$otw_pm_page_grid_manager_object->active_for['post'] = false;
		$otw_pm_page_grid_manager_object->active_for['cpt'] = false;
		
		include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_page_grid_manager_object.labels.php' );
		
		$otw_pm_page_grid_manager_object->init();
	}
	
	//validator component
	$otw_pm_validator_component = otw_load_component('otw_validator');
	$otw_pm_validator_object = otw_get_component($otw_pm_validator_component);
	$otw_pm_validator_object->init();
	
	//portfolio manager shortcode component
	$otw_pm_shortcode_component = otw_load_component( 'otw_portfolio_template_shortcode' );
	$otw_pm_shortcode_object = otw_get_component( $otw_pm_shortcode_component );
	$otw_pm_shortcode_object->js_version = $otw_pm_js_version;
	$otw_pm_shortcode_object->css_version = $otw_pm_css_version;
	
	$otw_pm_shortcode_object->add_default_external_lib( 'css', 'style', get_stylesheet_directory_uri().'/style.css', 'live_preview', 10 );
	
	$otw_pm_shortcode_object->shortcodes['portfolio_item_title'] = array( 'title' => esc_html__('Portfolio Title', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 100,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_media'] = array( 'title' => esc_html__('Portfolio Media', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 101,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_description'] = array( 'title' => esc_html__('Portfolio Description', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 102,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_details'] = array( 'title' => esc_html__('Portfolio Details', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 103,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_tabs'] = array( 'title' => esc_html__('Portfolio Tabs', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 104,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_social_icons'] = array( 'title' => esc_html__('Portfolio Social Icons', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 105,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_prev_next_navigation'] = array( 'title' => esc_html__('Portfolio Prev/Next Nav', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 106,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['portfolio_item_related_projects'] = array( 'title' => esc_html__('Portfolio Related Projects', 'otw-portfolio-manager'), 'options' => false, 'enabled' => true,'children' => false,'order' => 107,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	$otw_pm_shortcode_object->shortcodes['contactuspage'] = array('title' => esc_html__('Get a Quote', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'parent' => false, 'order' => 133, 'path' => dirname(__FILE__) . '/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_portfolio_template_shortcode/');
	$otw_pm_shortcode_object->shortcodes['divider'] = array('title' => esc_html__('Divider', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'parent' => false, 'order' => 130, 'path' => dirname(__FILE__) . '/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_portfolio_template_shortcode/');
	$otw_pm_shortcode_object->shortcodes['sidebars'] = array( 'title' => esc_html__('Sidebars', 'otw-portfolio-manager' ),'enabled' => true,'children' => false,'order' => 132,'parent' => false, 'path' => dirname( __FILE__ ).'/include/otw_components/otw_portfolio_template_shortcode/', 'url' => $otw_pm_plugin_url.'include/otw_components/otw_portfolio_template_shortcode/' );
	
	include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_shortcode_object.labels.php' );
	$otw_pm_shortcode_object->init();
	
	if( !isset( $this->otw_pm_plugin_options['otw_pm_grid_pages'] ) || ( $this->otw_pm_plugin_options['otw_pm_grid_pages'] != 'no' ) )
	{
		//shortcode component
		
		$otw_pm_page_shortcode_component = otw_load_component( 'otw_shortcode' );
		$otw_pm_page_shortcode_object = otw_get_component( $otw_pm_page_shortcode_component );
		$otw_pm_page_shortcode_object->js_version = $otw_pm_js_version;
		$otw_pm_page_shortcode_object->css_version = $otw_pm_css_version;
		
		$otw_pm_page_shortcode_object->add_default_external_lib( 'css', 'style', get_stylesheet_directory_uri().'/style.css', 'live_preview', 10 );
		$otw_pm_page_shortcode_object->shortcodes['divider'] = array('title' => esc_html__('Divider', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'parent' => false, 'order' => 17, 'path' => dirname(__FILE__) . '/include/otw_components/otw_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_shortcode/');
		$otw_pm_page_shortcode_object->shortcodes['sidebars'] = array('title' => esc_html__('Sidebars', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'order' => 132, 'parent' => false, 'path' => dirname(__FILE__) . '/include/otw_components/otw_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_shortcode/');
		$otw_pm_page_shortcode_object->shortcodes['welcome_text'] = array('title' => esc_html__('Welcome text', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'parent' => false, 'order' => 133, 'path' => dirname(__FILE__) . '/include/otw_components/otw_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_shortcode/');
		
		if( class_exists( 'OTWPMQuery' ) ){
			$otw_pm_page_shortcode_object->shortcodes['portfolio_manager'] = array('title' => esc_html__('Portfolio Manager', 'otw-portfolio-manager' ), 'enabled' => true, 'children' => false, 'order' => 134, 'parent' => false, 'path' => dirname(__FILE__) . '/include/otw_components/otw_shortcode/', 'url' => $otw_pm_plugin_url . 'include/otw_components/otw_shortcode/');
		}
		$otw_pm_page_shortcode_object->editor_button_active_for['post'] = false;
		$otw_pm_page_shortcode_object->editor_button_active_for['page'] = true;
		
		include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_page_shortcode_object.labels.php' );
		$otw_pm_page_shortcode_object->init();
		
	}
	
	//form component
	$otw_pm_form_component = otw_load_component( 'otw_form' );
	$otw_pm_form_object = otw_get_component( $otw_pm_form_component );
	$otw_pm_form_object->js_version = $otw_pm_js_version;
	$otw_pm_form_object->css_version = $otw_pm_css_version;
	
	global $wp_filesystem;
	
	if( otw_init_filesystem() ){
	
		if( $wp_filesystem->is_file( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_form_object.labels.php' ) ){
		
			include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_form_object.labels.php' );
		}
	}
	$otw_pm_form_object->init();
	
	$otw_pm_factory_component = otw_load_component( 'otw_factory' );
	$otw_pm_factory_object = otw_get_component( $otw_pm_factory_component );
	$otw_pm_factory_object->add_plugin( $otw_pm_plugin_id, __FILE__, array( 'menu_parent' => $this->menu_parent, 'lc_name' => esc_html__( 'License Manager', OTW_PM_TRANSLATION ), 'menu_key' => 'otw-pm' ) );
	
	include_once( plugin_dir_path( __FILE__ ).'include/otw_labels/otw_pm_factory_object.labels.php' );
	$otw_pm_factory_object->init();
	
	$otw_pm_image_component = otw_load_component( 'otw_image' );
	
	$otw_pm_image_object = otw_get_component( $otw_pm_image_component );
	
	$otw_pm_image_object->init();
	
	$img_location = wp_upload_dir();
	
	$otw_pm_image_profile = $otw_pm_image_object->add_profile( $img_location['basedir'].'/', $img_location['baseurl'].'/', 'otwpm' );
	
	$this->otw_rewrite_rules();
	
	// Save and redirect are done before any headers are loaded
	
	if( $otw_pm_factory_object->is_plugin_active( $otw_pm_plugin_id ) ){
		$this->saveAction();
		$this->process_actions();
	}
}

private function process_actions(){
	
	global $otw_pm_validate_messages, $wpdb, $otw_pm_factory_object, $otw_pm_plugin_id;
	
	if( !$otw_pm_factory_object->is_plugin_active( $otw_pm_plugin_id ) ){
		
		$otw_pm_validate_messages[] = esc_html__( 'The plugin is not activated.', 'otw-portfolio-manager' );
		return;
	}
	
	if( otw_post( 'otw_pm_action', false ) ){
		
		switch( otw_post( 'otw_pm_action', '' ) ){
			
			case 'otw_pm_import_backup':
					set_time_limit( 0 );
					$otw_pm_validate_messages = array();
					$valid_page = true;
					global $wp_filesystem;
					
					$wp_upload_dir = wp_upload_dir();
					
					if( !isset( $_FILES['otw_pm_import_pm_file'] ) || !isset( $_FILES['otw_pm_import_pm_file']['size'] ) || !$_FILES['otw_pm_import_pm_file']['size'] ){
					
						$otw_pm_validate_messages[] = esc_html__( 'No file selected', 'otw-portfolio-manager' );
						$valid_page = false;
					}
					elseif( !isset( $_FILES['otw_pm_import_pm_file']['tmp_name'] ) ){
					
						$otw_pm_validate_messages[] = esc_html__( 'File can not be uploaded', 'otw-portfolio-manager' );
						$valid_page = false;
						
					}elseif( !isset( $wp_upload_dir['path'] ) || !otw_init_filesystem() || !$wp_filesystem->is_writable( $wp_upload_dir['path'] ) ){
						
						$otw_pm_validate_messages[] = esc_html__( 'Can not write to upload directory', 'otw-portfolio-manager' );
						$valid_page = false;
					}else{
					
						$backup_data = false;
						
						if( otw_init_filesystem() ){
							$backup_data = unserialize( $wp_filesystem->get_contents( $_FILES['otw_pm_import_pm_file']['tmp_name'] ) );
						}
						
						if( !is_array( $backup_data ) || !isset( $backup_data['backup_type'] ) || empty( $backup_data['site_url'] ) || ( $backup_data['backup_type'] != 'otw_pm_backup' ) ){
						
							$otw_pm_validate_messages[] = esc_html__( 'Invalid backup file', 'otw-portfolio-manager' );
							$valid_page = false;
						}
					}
					
					if( !$valid_page ){
						
						if( ini_get( 'upload_max_filesize' ) && ini_get( 'post_max_size' ) ){
							$files_size_warning = '';
							$files_size_warning .= esc_html__( 'Please make sure that the backup file has smaller size than the limits set by your server configuration.', 'otw-portfolio-manager' );
							$files_size_warning .= '<br />';
							$files_size_warning .= esc_html__( 'Max Upload File Size', 'otw-portfolio-manager' ).': '.ini_get( 'upload_max_filesize' ).'<br />';
							$files_size_warning .= esc_html__( 'Max Post Size', 'otw-portfolio-manager' ).': '.ini_get( 'post_max_size' );
							$otw_pm_validate_messages[] = $files_size_warning;
						}
					}
					
					if( $valid_page ){
						
						//import images if any
						$import_mapping = $this->get_import_mapping();
						
						//import images
						if( isset( $backup_data['media_data'] ) && is_array( $backup_data['media_data'] ) && count( $backup_data['media_data'] ) ){
							
							foreach( $backup_data['media_data'] as $image_name => $image_data ){
								
								if( !isset( $import_mapping['media_data'][ $image_name ] ) ){
									
									if( preg_match( "/\/([^\/]*)$/", $image_name, $image_matches ) ){
										
										$file_name = $image_matches[1];
										
										$local_file_name = $wp_upload_dir['path'].'/'.$file_name;
										
										global $wp_filesystem;
										
										if( otw_init_filesystem() ){
											
											if( dirname( $local_file_name ) == $wp_upload_dir['path'] ){
											
												$wp_filesystem->put_contents( $local_file_name, base64_decode( $image_data ) );
												
												if( $wp_filesystem->is_file( $local_file_name ) ){
													
													$import_mapping['media_data'][ $image_name ] = array();
													$import_mapping['media_data'][ $image_name ]['file_name'] = $file_name;
													$import_mapping['media_data'][ $image_name ]['subdir'] = $wp_upload_dir['subdir'];
													$import_mapping['media_data'][ $image_name ]['file_path'] = $local_file_name;
													$import_mapping['media_data'][ $image_name ]['url'] = $wp_upload_dir['url'];
												}
											}
										}
									}
								}
							}
							//save the option with image mapping
							$import_mapping = $this->save_import_mapping( $import_mapping );
						}
						
						//import categories
						if( isset( $backup_data['otw_pm_export_pm_categories'] ) && is_array( $backup_data['otw_pm_export_pm_categories'] ) && count( $backup_data['otw_pm_export_pm_categories'] ) ){
							
							$import_mapping = $this->import_pm_backup_terms( $this->portfolio_category, $backup_data['otw_pm_export_pm_categories'], $import_mapping, 0 );
							$import_mapping = $this->save_import_mapping( $import_mapping );
							
						}
						if( isset( $backup_data['otw_pm_export_pm_tags'] ) && is_array( $backup_data['otw_pm_export_pm_tags'] ) && count( $backup_data['otw_pm_export_pm_tags'] ) ){
							
							$import_mapping = $this->import_pm_backup_terms( $this->portfolio_tag, $backup_data['otw_pm_export_pm_tags'], $import_mapping, 0 );
							$import_mapping = $this->save_import_mapping( $import_mapping );
						}
						
						if( isset( $backup_data['otw_pm_export_pm_details'] ) && is_array( $backup_data['otw_pm_export_pm_details'] ) && count( $backup_data['otw_pm_export_pm_details'] ) ){
							
							$import_mapping = $this->get_import_mapping();
							
							foreach( $backup_data['otw_pm_export_pm_details'] as $import_detail ){
								
								$exists_details = $this->get_details();
								$exists_details_assoc = array();
								
								if( is_array( $exists_details ) && count( $exists_details ) ){
									
									foreach( $exists_details as $e_detail ){
										$exists_details_assoc[ $e_detail['title'] ] = $e_detail['id'];
									}
								}
							
								$exists = false;
								if( isset( $import_mapping['pm_details'][ $import_detail['id'] ] ) ){
									
									if( isset( $exists_details[ $import_mapping['pm_details'][ $import_detail['id'] ] ] ) ){
										$exists = $import_mapping['pm_details'][ $import_detail['id'] ];
									}
								}
								
								if( !$exists ){
									
									if( isset( $exists_details_assoc[ $import_detail['title'] ] ) ){
										
										//make sure it does not point to something else.
										if( !in_array( $exists_details_assoc[ $import_detail['title'] ], $import_mapping['pm_details'] ) ){
											$exists = $exists_details_assoc[ $import_detail['title'] ];
										}
									}
								}
								
								if( $exists ){
									$exists_details[ $exists ]['order'] = $import_detail['order'];
									
									$import_mapping['pm_details'][ $import_detail['id'] ] = $exists;
								}else{
									$otw_detail_id = $this->get_next_detail_id();
									
									$exists_details[ $otw_detail_id ] = $import_detail;
									$exists_details[ $otw_detail_id ]['id'] = $otw_detail_id;
									
									$import_mapping['pm_details'][ $import_detail['id'] ] = $otw_detail_id;
									
								}
								update_option( 'otw_pm_portfolio_details', $exists_details );
								$import_mapping = $this->save_import_mapping( $import_mapping );
							}
						}
						
						//import custom templates
						if( isset( $backup_data['otw_pm_export_pm_custom_templates'] ) && is_array( $backup_data['otw_pm_export_pm_custom_templates'] ) && count( $backup_data['otw_pm_export_pm_custom_templates']  ) ){
							
							$import_mapping = $this->get_import_mapping();
							
							foreach( $backup_data['otw_pm_export_pm_custom_templates'] as $import_template ){
							
								$exists_templates = $this->get_custom_templates();
								
								$exists_templates_assoc = array();
								
								if( is_array( $exists_templates ) && count( $exists_templates ) ){
									
									foreach( $exists_templates as $e_template ){
										$exists_templates_assoc[ $e_template['title'] ] = $e_template['id'];
									}
								}
								
								$exists = false;
								if( isset( $import_mapping['pm_custom_templates'][ $import_template['id'] ] ) ){
									
									if( isset( $exists_templates[ $import_mapping['pm_custom_templates'][ $import_template['id'] ] ] ) ){
										$exists = $import_mapping['pm_custom_templates'][ $import_template['id'] ];
									}
								}
								
								if( !$exists ){
									
									if( isset( $exists_templates_assoc[ $import_template['title'] ] ) ){
										
										//make sure it does not point to something else.
										if( !in_array( $exists_templates_assoc[ $import_template['title'] ], $import_mapping['pm_custom_templates'] ) ){
											$exists = $exists_templates_assoc[ $import_template['title'] ];
										}
									}
								}
								
								if( $exists ){
									$exists_templates[ $exists ]['title'] = $import_template['title'];
									$exists_templates[ $exists ]['grid_content'] = $import_template['grid_content'];
									
									$import_mapping['pm_custom_templates'][ $import_template['id'] ] = $exists;
									
								}else{
									$otw_template_id = $this->get_next_custom_template_id();
									
									$exists_templates[ $otw_template_id ] = $import_template;
									$exists_templates[ $otw_template_id ]['id'] = $otw_template_id;
									
									//fix the grid connent
									if( !empty( $exists_templates[ $otw_template_id ]['grid_content'] ) ){
										
										$grid_content = $exists_templates[ $otw_template_id ]['grid_content'];
										
										foreach( $import_mapping['media_data'] as $orig_key => $local_data ){
											$grid_content = $this->otw_backup_replace( $orig_key, $local_data['url'].'/'.$local_data['file_name'], $grid_content );
										}
										$grid_content = $this->otw_backup_replace( $backup_data['site_url'], get_site_url(), $grid_content  );
										
										$exists_templates[ $otw_template_id ]['grid_content'] = $grid_content;
										
									}
									
									$import_mapping['pm_custom_templates'][ $import_template['id'] ] = $otw_template_id;
								}
								
								update_option( 'otw_pm_custom_templates', $exists_templates );
								$import_mapping = $this->save_import_mapping( $import_mapping );
							}
						}
						
						//import settings
						if( isset( $backup_data['otw_pm_export_pm_settings'] ) && is_array( $backup_data['otw_pm_export_pm_settings'] ) && count( $backup_data['otw_pm_export_pm_settings'] ) ){
						
							update_option( 'otw_pm_plugin_options', $backup_data['otw_pm_export_pm_settings'] );
							
							if( !empty( $backup_data['otw_pm_export_pm_custom_css'] ) ){
								
								$cssPath = SKIN_PM_PATH . DS . 'custom.css';
								
								global $wp_filesystem;
								
								if( otw_init_filesystem() ){
									
									$writableCssError = $wp_filesystem->is_writable( SKIN_PM_PATH );
									
									if( $writableCssError ){
										$wp_filesystem->put_contents( $cssPath, $backup_data['otw_pm_export_pm_custom_css'] );
									}
								}
							}
						}
						
						//import posts
						if( isset( $backup_data['otw_pm_export_pm_posts'] ) && is_array( $backup_data['otw_pm_export_pm_posts'] ) && count( $backup_data['otw_pm_export_pm_posts'] ) ){
							
							$import_mapping = $this->get_import_mapping();
							
							foreach( $backup_data['otw_pm_export_pm_posts'] as $import_post ){
								
								$replaced_post = $import_post;
								
								if( isset( $import_mapping['media_data'] ) && is_array( $import_mapping['media_data'] ) && count( $import_mapping['media_data'] ) ){
									
									foreach( $import_mapping['media_data'] as $import_key => $local_data ){
										$replaced_post = $this->otw_backup_replace( $import_key, $local_data['url'].'/'.$local_data['file_name'], $replaced_post );
									}
								}
								$replaced_post = $this->otw_backup_replace( $backup_data['site_url'], get_site_url(), $replaced_post );
								
								$exists = false;
								if( isset( $import_mapping['pm_posts'][ $replaced_post['ID'] ] ) ){
									
									$exists_args = array(
										'p' => $import_mapping['pm_posts'][ $replaced_post['ID'] ],
										'post_type' => $this->portfolio_post_type
									);
									
									$existsPosts = new WP_Query( $exists_args );
									
									if( isset( $existsPosts->posts ) && ( count( $existsPosts->posts ) == 1 ) ){
										foreach( $existsPosts->posts as $exists_post ){
											$exists = $exists_post->ID;
											break;
										}
									}
								}
								
								if( !$exists ){
									
									//check for the slug
									$exists_args = array(
										'post_type' => $this->portfolio_post_type,
										'name' => $replaced_post['post_name']
									);
									
									$existsPosts = new WP_Query( $exists_args );
									
									if( isset( $existsPosts->posts ) && ( count( $existsPosts->posts ) == 1 ) ){
										foreach( $existsPosts->posts as $exists_post ){
											$exists = $exists_post->ID;
											break;
										}
									}
								}
								
								$new_post_args = array();
								
								if( $exists ){
									$new_post_args['ID'] = $exists;
									$new_post_args['post_content'] = $replaced_post['post_content'];
									$new_post_args['post_title'] = $replaced_post['post_title'];
									$new_post_args['post_name'] = $replaced_post['post_name'];
									$new_post_args['post_excerpt'] = $replaced_post['post_excerpt'];
									$new_post_args['post_status'] = $replaced_post['post_status'];
									$new_post_args['post_date'] = $replaced_post['post_date'];
									$new_post_args['post_date_gmt'] = $replaced_post['post_date_gmt'];
									$new_post_args['post_modified'] = $replaced_post['post_modified'];
									$new_post_args['post_modified_gmt'] = $replaced_post['post_modified_gmt'];
									$new_post_args['post_type'] = $this->portfolio_post_type;
								}else{
									
									$new_post_args['post_content'] = $replaced_post['post_content'];
									$new_post_args['post_title'] = $replaced_post['post_title'];
									$new_post_args['post_name'] = $replaced_post['post_name'];
									$new_post_args['post_excerpt'] = $replaced_post['post_excerpt'];
									$new_post_args['post_status'] = $replaced_post['post_status'];
									$new_post_args['post_author'] = $replaced_post['post_author'];
									$new_post_args['post_date'] = $replaced_post['post_date'];
									$new_post_args['post_date_gmt'] = $replaced_post['post_date_gmt'];
									$new_post_args['post_modified'] = $replaced_post['post_modified'];
									$new_post_args['post_modified_gmt'] = $replaced_post['post_modified_gmt'];
									$new_post_args['post_type'] = $this->portfolio_post_type;
								}
								
								$new_post_id = wp_insert_post( $new_post_args );
								
								if( $new_post_id ){
									$import_mapping['pm_posts'][ $replaced_post['ID'] ] = $new_post_id;
								}
								
								$import_mapping = $this->save_import_mapping( $import_mapping );
								
								if( $new_post_id ){
									
									//update post meta
									if( isset( $replaced_post['otw_export_meta'] ) && is_array( $replaced_post['otw_export_meta'] ) && count( $replaced_post['otw_export_meta'] ) ){
										
										foreach( $replaced_post['otw_export_meta'] as $meta_key => $meta_data ){
											
											if( is_string( $meta_data ) ){
												
												if( $meta_key == 'otw_grid_manager_content' ){
													$meta_object = json_decode( $meta_data );
													$meta_object = $this->otw_backup_replace( $backup_data['site_url'], get_site_url(), $meta_object, $import_mapping );
													
													$meta_data = json_encode( $meta_object );
													
												}
												$meta_data = addslashes( $meta_data );
												
											}
											add_post_meta( $new_post_id, $meta_key, $meta_data, true );
											update_post_meta( $new_post_id, $meta_key, $meta_data );
										}
									}
									
									//update category post relation
									if( isset( $replaced_post['otw_export_post_categories'] ) && is_array( $replaced_post['otw_export_post_categories'] ) && count( $replaced_post['otw_export_post_categories'] ) ){
										
										$terms_to_add = array();
										
										foreach( $replaced_post['otw_export_post_categories'] as $post_term ){
											
											//check if we have this term in the mapping
											if( isset( $import_mapping[ $this->portfolio_category ][ $post_term['term_id'] ] ) ){
												
												$terms_to_add[] = $import_mapping[ $this->portfolio_category ][ $post_term['term_id'] ];
											}
										}
										wp_set_post_terms( $new_post_id, $terms_to_add, $this->portfolio_category, false );
									}
									
									//update tags post relation
									if( isset( $replaced_post['otw_export_post_tags'] ) && is_array( $replaced_post['otw_export_post_tags'] ) && count( $replaced_post['otw_export_post_tags'] ) ){
										
										$terms_to_add = array();
										
										foreach( $replaced_post['otw_export_post_tags'] as $post_term ){
											
											//check if we have this term in the mapping
											if( isset( $import_mapping[ $this->portfolio_tag ][ $post_term['term_id'] ] ) ){
												
												$terms_to_add[] = $import_mapping[ $this->portfolio_tag ][ $post_term['term_id'] ];
											}
										}
										wp_set_post_terms( $new_post_id, $terms_to_add, $this->portfolio_tag, false );
									}
								}
							}
							
						}
						
						//import lists
						if( isset( $backup_data['otw_pm_export_pm_lists'] ) && is_array( $backup_data['otw_pm_export_pm_lists'] ) && count( $backup_data['otw_pm_export_pm_lists'] ) ){
							$import_mapping = $this->get_import_mapping();
							
							if( isset( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] ) && count( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] ) ){
								
								$current_lists = get_option( 'otw_pm_lists' );
								
								if( !is_array( $current_lists ) ){
								
									$current_lists = array();
									$current_lists['next_id'] = 1;
									$current_lists['otw-pm-list'] = array();
								}
								
								$import_ids = array();
								
								foreach( $current_lists['otw-pm-list'] as $check_list ){
									
									if( isset( $check_list['import_id'] ) ){
										$import_ids[ $check_list['import_id'] ] = $check_list['id'];
									}
								}
								
								if( isset( $current_lists['next_id'] ) ){
									$next_id = $current_lists['next_id'];
								}else{
									$next_id = 1;
								}
								
								foreach( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] as $list_key => $import_list ){
								
									if( preg_match( "/^otw\-pm\-list\-\d+$/", $list_key ) ){
										
										$exists = false;
										if( isset( $import_mapping['pm_lists'][ $import_list['id'] ] ) ){
											
											$exists = $import_mapping['pm_lists'][ $import_list['id'] ];
										}
										
										if( !$exists && count( $import_ids ) && isset( $import_ids[ $import_list['id'] ] ) ){
											
											$exists = $import_ids[ $import_list['id'] ];
										}
										
										$custom_css = '';
										
										$new_list = array();
										
										foreach( $import_list as $key => $list_data ){
										
											switch( $key ){
												
												case 'id':
														$new_list[ $key ] = 0;
													break;
												case 'user_id':
														$new_list[ $key ] = get_current_user_id();
													break;
												case 'categories':
												case 'exclude_categories':
														
														$new_value = '';
														if( !empty( $list_data ) ){
															$terms = explode( ',', $list_data );
															
															$new_terms_array = array();
															foreach( $terms as $term_id ){
																
																if( isset( $import_mapping[ $this->portfolio_category ][ $term_id ] ) ){
																	$new_terms_array[ $import_mapping[ $this->portfolio_category ][ $term_id ] ] = $import_mapping[ $this->portfolio_category ][ $term_id ];
																}
															}
															if( count( $new_terms_array ) ){
																
																$new_value = implode( ',', $new_terms_array );
															}
														}
														$new_list[ $key ] = $new_value;
													break;
												case 'tags':
												case 'exclude_tags':
														$new_value = '';
														if( !empty( $list_data ) ){
															$terms = explode( ',', $list_data );
															
															$new_terms_array = array();
															foreach( $terms as $term_id ){
																
																if( isset( $import_mapping[ $this->portfolio_tag ][ $term_id ] ) ){
																	$new_terms_array[ $import_mapping[ $this->portfolio_tag ][ $term_id ] ] = $import_mapping[ $this->portfolio_tag ][ $term_id ];
																}
															}
															if( count( $new_terms_array ) ){
																
																$new_value = implode( ',', $new_terms_array );
															}
														}
														$new_list[ $key ] = $new_value;
													break;
												case 'users':
												case 'exclude_users':
												case 'view_all_page':
														$new_list[ $key ] = '';//users may be different so better not replicated them
													break;
												case 'meta-items':
														$new_value = '';
														
														if( !empty( $list_data ) ){
															$items = explode( ',', $list_data );
															
															$new_items_array = array();
															foreach( $items as $item_id ){
																
																if( preg_match( "/^otw_portfolio_detail_([0-9]+)$/", $item_id, $item_match ) ){
																	
																	if( isset( $import_mapping['pm_details'][ $item_match[1] ] ) ){
																		
																		$new_items_array[ 'otw_portfolio_detail_'.$import_mapping['pm_details'][ $item_match[1] ] ] = 'otw_portfolio_detail_'.$import_mapping['pm_details'][ $item_match[1] ];
																	}
																}else{
																	$new_items_array[ $item_id ] = $item_id;
																}
															}
															if( count( $new_items_array ) ){
																
																$new_value = implode( ',', $new_items_array );
															}
														}
														$new_list[ $key ] = $new_value;
													break;
												case '_custom_css':
														
														$custom_css = $list_data;
													break;
												default:
														$new_list[ $key ] = $list_data;
													break;
											}
										}
										
										
										
										$new_list['import_id'] = $import_list['id'];
										
										if( $exists ){
											$new_list['id'] = $exists;
										}else{
											$new_list['id'] = $next_id;
											$next_id++;
										}
										$current_lists['next_id'] = $next_id;
										$current_lists['otw-pm-list'][ 'otw-pm-list-'.$new_list['id'] ] = $new_list;
										$import_mapping['pm_lists'][ $import_list['id'] ] = $new_list['id'];
										
										if( !empty( $custom_css ) ){
											
											$source_customCssFile = SKIN_PM_PATH . DS .'otw-pm-list-'.$new_list['id'].'-custom.css';
											
											global $wp_filesystem;
											
											if( otw_init_filesystem() ){
											
												if( $wp_filesystem->is_writable( SKIN_PM_PATH ) ){
													
													$custom_css = str_replace( 'otw-pm-list-'.$import_list['id'], 'otw-pm-list-'.$new_list['id'], $custom_css );
													
													$wp_filesystem->put_contents( $source_customCssFile, $custom_css );
												}
											}
										}
									}
								}
								
								$import_mapping = $this->save_import_mapping( $import_mapping );
								update_option( 'otw_pm_lists', $current_lists );
							}
						}
						
						//import pages
						if( isset( $backup_data['otw_pm_export_pages'] ) && is_array( $backup_data['otw_pm_export_pages'] ) && count( $backup_data['otw_pm_export_pages'] ) ){
							
							$import_mapping = $this->get_import_mapping();
							
							foreach( $backup_data['otw_pm_export_pages'] as $import_post ){
								
								$replaced_post = $import_post;
								
								if( isset( $import_mapping['media_data'] ) && is_array( $import_mapping['media_data'] ) && count( $import_mapping['media_data'] ) ){
									
									foreach( $import_mapping['media_data'] as $import_key => $local_data ){
										$replaced_post = $this->otw_backup_replace( $import_key, $local_data['url'].'/'.$local_data['file_name'], $replaced_post );
									}
								}
								$replaced_post = $this->otw_backup_replace( $backup_data['site_url'], get_site_url(), $replaced_post );
								
								$exists = false;
								if( isset( $import_mapping['pages'][ $replaced_post['ID'] ] ) ){
									
									$exists_args = array(
										'p' => $import_mapping['pages'][ $replaced_post['ID'] ],
										'post_type' => 'page'
									);
									
									$existsPosts = new WP_Query( $exists_args );
									
									if( isset( $existsPosts->posts ) && ( count( $existsPosts->posts ) == 1 ) ){
										foreach( $existsPosts->posts as $exists_post ){
											$exists = $exists_post->ID;
											break;
										}
									}
								}
								
								if( !$exists ){
									
									//check for the slug
									$exists_args = array(
										'post_type' => 'page',
										'name' => $replaced_post['post_name']
									);
									
									$existsPosts = new WP_Query( $exists_args );
									
									if( isset( $existsPosts->posts ) && ( count( $existsPosts->posts ) == 1 ) ){
										foreach( $existsPosts->posts as $exists_post ){
											$exists = $exists_post->ID;
											break;
										}
									}
								}
								
								$new_post_args = array();
								
								if( $exists ){
									$new_post_args['ID'] = $exists;
									$new_post_args['post_content'] = $replaced_post['post_content'];
									$new_post_args['post_title'] = $replaced_post['post_title'];
									$new_post_args['post_name'] = $replaced_post['post_name'];
									$new_post_args['post_excerpt'] = $replaced_post['post_excerpt'];
									$new_post_args['post_status'] = $replaced_post['post_status'];
									$new_post_args['post_date'] = $replaced_post['post_date'];
									$new_post_args['post_date_gmt'] = $replaced_post['post_date_gmt'];
									$new_post_args['post_modified'] = $replaced_post['post_modified'];
									$new_post_args['post_modified_gmt'] = $replaced_post['post_modified_gmt'];
									$new_post_args['post_type'] = 'page';
								}else{
									
									$new_post_args['post_content'] = $replaced_post['post_content'];
									$new_post_args['post_title'] = $replaced_post['post_title'];
									$new_post_args['post_name'] = $replaced_post['post_name'];
									$new_post_args['post_excerpt'] = $replaced_post['post_excerpt'];
									$new_post_args['post_status'] = $replaced_post['post_status'];
									$new_post_args['post_author'] = $replaced_post['post_author'];
									$new_post_args['post_date'] = $replaced_post['post_date'];
									$new_post_args['post_date_gmt'] = $replaced_post['post_date_gmt'];
									$new_post_args['post_modified'] = $replaced_post['post_modified'];
									$new_post_args['post_modified_gmt'] = $replaced_post['post_modified_gmt'];
									$new_post_args['post_type'] = 'page';
								}
								
								$new_post_id = wp_insert_post( $new_post_args );
								
								if( $new_post_id ){
									$import_mapping['pages'][ $replaced_post['ID'] ] = $new_post_id;
								}
								
								$import_mapping = $this->save_import_mapping( $import_mapping );
								
								if( $new_post_id ){
									
									//update post meta
									if( isset( $replaced_post['otw_export_meta'] ) && is_array( $replaced_post['otw_export_meta'] ) && count( $replaced_post['otw_export_meta'] ) ){
										
										foreach( $replaced_post['otw_export_meta'] as $meta_key => $meta_data ){
											
											if( is_string( $meta_data ) ){
												
												if( $meta_key == 'otw_grid_manager_content' ){
													$meta_object = json_decode( $meta_data );
													$meta_object = $this->otw_backup_replace( $backup_data['site_url'], get_site_url(), $meta_object, $import_mapping );
													
													$meta_data = json_encode( $meta_object );
												}
												$meta_data = addslashes( $meta_data );
												
											}
											add_post_meta( $new_post_id, $meta_key, $meta_data, true );
											update_post_meta( $new_post_id, $meta_key, $meta_data );
										}
									}
								}
							}
							
						}
						
						
						wp_redirect( 'admin.php?page=otw-pm-backup&imported=1' );
					}
				break;
			case 'otw_pm_export_backup':
					$otw_pm_validate_messages = array();
					
					$has_options = false;
					
					$backup_data = array();
					$backup_data['backup_type'] = 'otw_pm_backup';
					$backup_data['site_url'] = get_site_url();
					$backup_data['media_data'] = array();
					
					if( otw_post( 'otw_pm_export_pm_posts', false ) && ( otw_post( 'otw_pm_export_pm_posts', '' ) == 'yes' ) ){
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_posts'] = array();
						
						//get posts
						$args = array(
							'post_type' => $this->portfolio_post_type,
							'posts_per_page' => -1,
							'orderby' => 'ID',
							'order' => 'ASC'
						);
						$posts = new WP_Query( $args );
						
						$wp_upload_dir = wp_upload_dir();
						$wp_upload_base_path = str_replace( '/', '\/', $wp_upload_dir['baseurl'] );
						
						if( isset( $posts->posts ) && count( $posts->posts ) ){
							
							foreach( $posts->posts as $e_post ){
								
								$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ] = array();
								
								foreach( $e_post as $prop_key => $prop_var ){
									$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ][ $prop_key ] = $prop_var;
								}
								
								$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_meta'] = array();
								$meta_data = get_post_meta( $e_post->ID );
								
								foreach( $meta_data as $meta_key => $meta_array ){
									
									$meta_clear = get_post_meta( $e_post->ID, $meta_key ,true );
									$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_meta'][ $meta_key ] = $meta_clear;
									
									if( preg_match_all( "/".$wp_upload_base_path."[^\.]*\.([a-zA-Z]{2,4})/", $meta_array[0], $media_matches ) ){
									
										foreach( $media_matches[0] as $match_key => $file_name ){
											
											if( !isset( $backup_data['media_data'][ $file_name ] ) ){
												
												global $wp_filesystem;
												
												if( otw_init_filesystem() ){
													
													$file_content = $wp_filesystem->get_contents( $file_name );
													
													if( !empty( $file_content ) ){
														$backup_data['media_data'][ $file_name ] = base64_encode( $file_content );
													}
												}
											}
											
										}
									}
								}
								//get post - category relations
								$wp_terms = wp_get_post_terms( $e_post->ID, $this->portfolio_category );
								
								if( count( $wp_terms ) ){
									
									$new_term_id = 0;
									
									foreach( $wp_terms as $term ){
										
										if( !isset( $backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_categories'] ) ){
											$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_categories'] = array();
										}
										
										$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_categories'][ $new_term_id ] = array();
										
										foreach( $term as $term_key => $term_data ){
											$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_categories'][ $new_term_id ][ $term_key ] = $term_data;
										}
										
										$new_term_id++;
									}
								}
								
								$wp_terms = wp_get_post_terms( $e_post->ID, $this->portfolio_tag );
								
								if( count( $wp_terms ) ){
									
									$new_term_id = 0;
									
									foreach( $wp_terms as $term ){
										
										if( !isset( $backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_tags'] ) ){
											$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_tags'] = array();
										}
										
										$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_tags'][ $new_term_id ] = array();
										
										foreach( $term as $term_key => $term_data ){
											$backup_data['otw_pm_export_pm_posts'][ $e_post->ID ]['otw_export_post_tags'][ $new_term_id ][ $term_key ] = $term_data;
										}
										
										$new_term_id++;
									}
								}
							}
						}
					}
					
					if( otw_post( 'otw_pm_export_pm_categories', false ) && ( otw_post( 'otw_pm_export_pm_categories', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_categories'] = array();
						
						$wp_terms = get_terms( $this->portfolio_category, array( 'number' => '', 'hide_empty' => false  ) );
						
						if( count( $wp_terms ) ){
							
							$new_term_id = 0;
							
							foreach( $wp_terms as $term ){
								
								$backup_data['otw_pm_export_pm_categories'][ $new_term_id ] = array();
								
								foreach( $term as $term_key => $term_data ){
									$backup_data['otw_pm_export_pm_categories'][ $new_term_id ][ $term_key ] = $term_data;
								}
								
								$new_term_id++;
							}
						}
					}
					
					if( otw_post( 'otw_pm_export_pm_tags', false ) && ( otw_post( 'otw_pm_export_pm_tags', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_tags'] = array();
						
						$wp_terms = get_terms( $this->portfolio_tag, array( 'number' => '', 'hide_empty' => false  ) );
						
						if( count( $wp_terms ) ){
							
							$new_term_id = 0;
							
							foreach( $wp_terms as $term ){
								
								$backup_data['otw_pm_export_pm_tags'][ $new_term_id ] = array();
								
								foreach( $term as $term_key => $term_data ){
									$backup_data['otw_pm_export_pm_tags'][ $new_term_id ][ $term_key ] = $term_data;
								}
								
								$new_term_id++;
							}
						}
					}
					
					if( otw_post( 'otw_pm_export_pm_details', false ) && ( otw_post( 'otw_pm_export_pm_details', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_details'] = $this->get_details();
					}
					
					if( otw_post( 'otw_pm_export_pm_settings', false ) && ( otw_post( 'otw_pm_export_pm_settings', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_settings'] = get_option( 'otw_pm_plugin_options' );
						$backup_data['otw_pm_export_pm_custom_css'] = '';
						
						$cssPath = SKIN_PM_PATH . DS . 'custom.css';
						
						global $wp_filesystem;
						
						if( otw_init_filesystem() ){
							
							if( $wp_filesystem->is_file( $cssPath ) && $wp_filesystem->exists( $cssPath ) ){
								
								$css_content = $wp_filesystem->get_contents( $cssPath );
								$backup_data['otw_pm_export_pm_custom_css'] = $css_content;
							}
						}
					}
					
					if( otw_post( 'otw_pm_export_pm_custom_templates', false ) && ( otw_post( 'otw_pm_export_pm_custom_templates', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_custom_templates'] = $this->get_custom_templates();
						
					}
					
					if( otw_post( 'otw_pm_export_pm_lists', false ) && ( otw_post( 'otw_pm_export_pm_lists', '' ) == 'yes' ) ){
						
						$has_options = true;
						
						$backup_data['otw_pm_export_pm_lists'] = get_option( 'otw_pm_lists' );
						
						if( isset( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] ) && count( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] ) ){
							
							foreach( $backup_data['otw_pm_export_pm_lists']['otw-pm-list'] as $export_list_key => $export_list_data ){
							
								if( is_array( $export_list_data ) && isset( $export_list_data['id'] ) ){
									
									$source_customCssFile = SKIN_PM_PATH . DS .'otw-pm-list-'.$export_list_data['id'].'-custom.css';
									
									global $wp_filesystem;
									
									if( otw_init_filesystem() ){
										
										if( $wp_filesystem->exists( $source_customCssFile ) ){
										
											$css_file_content = $wp_filesystem->get_contents( $source_customCssFile );
											
											$backup_data['otw_pm_export_pm_lists']['otw-pm-list'][ $export_list_key ]['_custom_css'] = $css_file_content;
										}
									}
								}
							}
						}
					}
					
					//export pages
					if( otw_post( 'otw_pm_export_pages', false ) && in_array( otw_post( 'otw_pm_export_pages', '' ), array( 'yes', 'yes_opm' ) ) ){
						$has_options = true;
						
						$backup_data['otw_pm_export_pages'] = array();
						
						//get posts
						$args = array(
							'post_type' => 'page',
							'posts_per_page' => -1,
							'orderby' => 'ID',
							'order' => 'ASC'
						);
						$pages = new WP_Query( $args );
						
						$wp_upload_dir = wp_upload_dir();
						$wp_upload_base_path = str_replace( '/', '\/', $wp_upload_dir['baseurl'] );
						
						if( isset( $pages->posts ) && count( $pages->posts ) ){
							
							foreach( $pages->posts as $e_post ){
								
								$meta_data = get_post_meta( $e_post->ID );
								
								//filter out non pm pages
								if( otw_post( 'otw_pm_export_pages', '' ) == 'yes_opm' ){
									
									$is_pm_page = false;
									
									//check the content for pm shortcode
									if( preg_match( "/\[otw\-pm\-list id\=/", $e_post->post_content ) ){
										$is_pm_page = true;
									}
									elseif( preg_match( "/\[otw\_shortcode\_portfolio\_manager portfoliolist_id\=/", $e_post->post_content ) ){
										$is_pm_page = true;
									}
									
									if( !$is_pm_page && isset( $meta_data['otw_grid_manager_content'] ) )
									{
										$meta_clear = get_post_meta( $e_post->ID, 'otw_grid_manager_content' ,true );
										
										if( preg_match( "/\[otw\-pm\-list id\=/", $meta_clear ) ){
											$is_pm_page = true;
										}elseif( preg_match( "/\[otw\_shortcode\_portfolio\_manager portfoliolist_id\=/", $meta_clear ) ){
											$is_pm_page = true;
										}
									}
									
									if( !$is_pm_page ){
										continue;
									}
								}
								
								$backup_data['otw_pm_export_pages'][ $e_post->ID ] = array();
								
								foreach( $e_post as $prop_key => $prop_var ){
									$backup_data['otw_pm_export_pages'][ $e_post->ID ][ $prop_key ] = $prop_var;
								}
								
								$backup_data['otw_pm_export_pages'][ $e_post->ID ]['otw_export_meta'] = array();
								
								foreach( $meta_data as $meta_key => $meta_array ){
									
									$meta_clear = get_post_meta( $e_post->ID, $meta_key ,true );
									
									$backup_data['otw_pm_export_pages'][ $e_post->ID ]['otw_export_meta'][ $meta_key ] = $meta_clear;
									
									if( preg_match_all( "/".$wp_upload_base_path."[^\.]*\.([a-zA-Z]{2,4})/", $meta_array[0], $media_matches ) ){
									
										foreach( $media_matches[0] as $match_key => $file_name ){
											
											if( !isset( $backup_data['media_data'][ $file_name ] ) ){
												
												global $wp_filesystem;
												
												if( otw_init_filesystem() ){
													
													$file_content = $wp_filesystem->get_contents( $file_name );
													
													if( !empty( $file_content ) ){
														$backup_data['media_data'][ $file_name ] = base64_encode( $file_content );
													}
												}
											}
											
										}
									}
								}
							}
						}
					}
					
					if( !$has_options ){
						$otw_pm_validate_messages[] = esc_html__( 'No options selected', 'otw-portfolio-manager' );
					}else{
						$backup_data_ser = serialize( $backup_data );
						
						$size = strlen( $backup_data_ser );
						header('Content-Description: File Transfer');
						header('Content-Type: application/octet-stream');
						header('Content-Disposition: attachment; filename="otw_portfolio_manager_backup_'.date( 'YmdHi' ).'.ser"');
						header('Content-Transfer-Encoding: binary');
						header('Expires: 0');
						header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
						header('Pragma: public');
						header('Content-Length: ' . $size);
						echo $backup_data_ser;
						die;
					}
				break;
			case 'import_from_light':
					
					if( otw_post( 'cancel', false ) ){
						
						wp_redirect( 'admin.php?page=otw-pm-settings' );
						
					}elseif( otw_post( 'submit', false ) ){
						
						//first import categories
						$light_categories = get_terms( 'otw-portfolio-category', array( 'number' => '', 'hide_empty' => false  )  );
						$exists_categories = get_terms( $this->portfolio_category, array( 'number' => '', 'hide_empty' => false  ) );
						
						$exists_categories_assoc = array();
						
						if( is_array( $exists_categories ) && count( $exists_categories ) ){
							
							foreach( $exists_categories as $exists_cat ){
								$exists_categories_assoc[ $exists_cat->name ] = $exists_cat;
							}
						}
						
						$cat_to_cat = array();
						
						$cat_to_cat = $this->import_light_categories( $light_categories, $exists_categories_assoc, $cat_to_cat, 0 );
						
						
						$args = array(
							'post_type' => 'otw-portfolio',
							'posts_per_page' => '-1'
						);
						$light_items = new WP_Query( $args );
						
						if( isset( $light_items->posts ) && count( $light_items->posts ) ){
							
							foreach( $light_items->posts as $light_post ){
								
								//first check if we already imported this post by id in meta data
								$new_post_args = array();
								
								$exists_args = array(
									'post_type' => $this->portfolio_post_type,
									'meta_query' => array(
										array(
											'key' => 'otw_pm_light_id',
											'value' => $light_post->ID
										)
									)
								);
								$existsPosts = new WP_Query( $exists_args );
								
								if( isset( $existsPosts->posts ) && ( count( $existsPosts->posts ) == 1 ) ){
									foreach( $existsPosts->posts as $exists_post ){
										$new_post_args['ID'] = $exists_post->ID;
										break;
									}
								}
								
								$new_post_args['post_content'] = $light_post->post_content;
								$new_post_args['post_title'] = $light_post->post_title;
								$new_post_args['post_name'] = $light_post->post_name;
								$new_post_args['post_excerpt'] = $light_post->post_excerpt;
								$new_post_args['post_status'] = $light_post->post_status;
								$new_post_args['post_author'] = $light_post->post_author;
								$new_post_args['post_date'] = $light_post->post_date;
								$new_post_args['post_date_gmt'] = $light_post->post_date_gmt;
								$new_post_args['post_modified'] = $light_post->post_modified;
								$new_post_args['post_modified_gmt'] = $light_post->post_modified_gmt;
								$new_post_args['post_type'] = $this->portfolio_post_type;
								
								$new_post_id = wp_insert_post( $new_post_args );
								
								if( $new_post_id ){ //insert meta for reference
									add_post_meta( $new_post_id, 'otw_pm_light_id', $light_post->ID, true );
									
									$light_meta_data = get_post_meta( $light_post->ID );
									
									if( isset( $light_meta_data['custom_otw-portfolio-repeatable-image'] ) ){
									
										$custom_repeatable = unserialize( $light_meta_data['custom_otw-portfolio-repeatable-image'][0] );
										
										$otw_new_meta_data = array(
											'media_type'      => '',
											'youtube_url'     => '',
											'vimeo_url'       => '',
											'soundcloud_url'  => '',
											'img_url'         => '',
											'slider_url'      => ''
										);
										
										if( is_array( $custom_repeatable ) && $crSize = count( $custom_repeatable ) ){
										
											$image_string = '';
											foreach ( $custom_repeatable as $custom_image ){
												
												$image_url = wp_get_attachment_image_src($custom_image, 'otw-porfolio-large');
												$image_string .= $image_url[0].',';
											}
											$image_string = substr( $image_string, 0, -1 );
											
											if( $crSize == 1 ){
												$otw_new_meta_data['media_type'] = 'img';
												$otw_new_meta_data['img_url'] = $image_string;
												
											}else{
												$otw_new_meta_data['media_type'] = 'slider';
												$otw_new_meta_data['slider_url'] = $image_string;
											}
											
											add_post_meta( $new_post_id, 'otw_pm_meta_data', $otw_new_meta_data, true);
											// If POST is in the DB update it
											update_post_meta( $new_post_id, 'otw_pm_meta_data', $otw_new_meta_data);
										}else{
											delete_post_meta( $new_post_id, 'otw_pm_meta_data'  );
										}
										
										
									}else{
										delete_post_meta( $new_post_id, 'otw_pm_meta_data'  );
									}
									
									//save details
									$portfolio_meta_details = $this->get_details();
									
									$key_name = '';
									foreach( $portfolio_meta_details as $detail_id => $detail_data ){
									
										if( $detail_data['id'] == '6' ){
											$key_name = 'otw_pm_portfolio_detail_'.$detail_id;
										}
									}
									
									if( $key_name ){
										
										if( isset( $light_meta_data['custom_otw-portfolio-url'] ) && !empty( $light_meta_data['custom_otw-portfolio-url'][0] ) ){
											add_post_meta( $new_post_id, $key_name, $light_meta_data['custom_otw-portfolio-url'][0], true);
											update_post_meta( $new_post_id, $key_name, $light_meta_data['custom_otw-portfolio-url'][0] );
										}else{
											delete_post_meta( $new_post_id, $key_name );
										}
									}
									
									//save categories
									$new_categories = wp_get_post_terms( $new_post_id, $this->portfolio_category );
									$light_categories = wp_get_post_terms( $light_post->ID, 'otw-portfolio-category' );
									
									$cats_to_add = array();
									
									if( is_array( $light_categories ) && count( $light_categories ) ){
									
										foreach( $light_categories as $light_cat ){
										
											if( isset( $cat_to_cat[ $light_cat->term_id ] ) ){
												$cats_to_add[] = $cat_to_cat[ $light_cat->term_id ];
											}
										}
									}
									
									
									wp_set_post_terms( $new_post_id, $cats_to_add, $this->portfolio_category, false );
								}
							}
						}
						wp_redirect( 'admin.php?page=otw-pm-settings&message=3' );
					}
				break;
			case 'manage_otw_pm_custom_templates':
					
					$otw_pm_validate_messages = array();
					$valid_page = true;
					
					if( $valid_page ){
						$otw_custom_templates = $this->get_custom_templates();
						
						if( otw_get( 'custom_template', false ) && isset( $otw_custom_templates[ otw_get( 'custom_template', '' ) ] ) ){
							$otw_custom_template_id = otw_get( 'custom_template', '' );
							$db_custom_template = $otw_custom_templates[ otw_get( 'custom_template', '' ) ];
						}else{
							$db_custom_template = array();
							$otw_custom_template_id = false;
						}
						
						$db_custom_template['title'] = (string) otw_stripslashes( otw_post( 'pm_custom_template_title', '' ) );
						$db_custom_template['grid_content'] = otw_post( array( '_otw_portfolio_template_grid_manager_content', 'code' ), '' );
						
						if( otw_post( 'pm_custom_template_maxwidth', false ) )
						{
							$db_custom_template['maxwidth'] = (string) otw_stripslashes( otw_post( 'pm_custom_template_maxwidth', '' ) );
						}
						
						if( $otw_custom_template_id === false ){
							
							$otw_custom_template_id = $this->get_next_custom_template_id();
							$db_custom_template['id'] = $otw_custom_template_id;
						}
						
						$otw_custom_templates[ $otw_custom_template_id ] = $db_custom_template;
						
						if( !update_option( 'otw_pm_custom_templates', $otw_custom_templates ) && $wpdb->last_error ){
							$valid_page = false;
							$otw_pm_validate_messages[] = esc_html__( 'DB Error: ', 'otw-portfolio-manager' ).$wpdb->last_error.'. Tring to save '.strlen( maybe_serialize( $otw_custom_templates ) ).' bytes.';
						}else{
							wp_redirect( 'admin.php?page=otw-pm-custom-templates-edit&custom_template='.$otw_custom_template_id.'&message=1' );
						}
					}
				break;
			case 'copy_otw_pm_custom_template':
					
					if( otw_post( 'cancel', false ) ){
						wp_redirect( 'admin.php?page=otw-pm-custom-templates' );
					}else{
						$otw_custom_templates = $this->get_custom_templates();
						
						if( otw_get( 'custom_template', false ) && isset( $otw_custom_templates[ otw_get( 'custom_template', '' ) ] ) ){
							
							$otw_custom_template_id = otw_get( 'custom_template', '' );
							
							$new_otw_custom_template_id = $this->get_next_custom_template_id();
							
							$template = $otw_custom_templates[ otw_get( 'custom_template', '' ) ];
							$template['id'] = $new_otw_custom_template_id;
							$template['title'] = esc_html__( 'Copy of '.$template['title'], 'otw-portfolio-manager' );
							
							$otw_custom_templates[ $template['id'] ] = $template;
							
							update_option( 'otw_pm_custom_templates', $otw_custom_templates );
							wp_redirect( 'admin.php?page=otw-pm-custom-templates&message=5' );
						}
					}
				break;
			case 'delete_otw_pm_custom_template':
					
					if( otw_post( 'cancel', false ) ){
						wp_redirect( 'admin.php?page=otw-pm-custom-templates' );
					}else{
						
						$otw_custom_templates = $this->get_custom_templates();
						
						if( otw_get( 'custom_template', false ) && isset( $otw_custom_templates[ otw_get( 'custom_template', '' ) ] ) ){
							
							$otw_custom_template_id = otw_get( 'custom_template', '' );
							
							$new_custom_templates = array();
							
							//remove the detail from otw_details
							foreach( $otw_custom_templates as $custom_template_key => $custom_template ){
								
								if( $custom_template_key != $otw_custom_template_id ){
									
									$new_custom_templates[ $custom_template_key ] = $custom_template;
								}
							}
							
							update_option( 'otw_pm_custom_templates', $new_custom_templates );
							wp_redirect( 'admin.php?page=otw-pm-custom-templates&message=2' );
						}
					}
				break;
			case 'delete_otw_pm_detail':
					
					if( otw_post( 'cancel', false ) ){
						wp_redirect( 'admin.php?page=otw-pm-details' );
					}else{
						
						$otw_details = get_option( 'otw_pm_portfolio_details' );
						
						if( otw_get( 'detail', false ) && isset( $otw_details[ otw_get( 'detail', '' ) ] ) ){
							
							$otw_detail_id = otw_get( 'detail', '' );
							
							$new_details = array();
							
							//remove the detail from otw_details
							foreach( $otw_details as $detail_key => $detail ){
								
								if( $detail_key != $otw_detail_id ){
									
									$new_details[ $detail_key ] = $detail;
								}
							}
							
							update_option( 'otw_pm_portfolio_details', $new_details );
							wp_redirect( 'admin.php?page=otw-pm-details&message=2' );
						}
					}
				break;
			case 'manage_otw_pm_detail':
					
					$otw_pm_validate_messages = array();
					$valid_page = true;
					
					if( !otw_post( 'pm_detail_title', false ) || !strlen( trim( otw_post( 'pm_detail_title', '' ) ) ) ){
						$valid_page = false;
						$otw_pm_validate_messages[] = esc_html__( 'Please type valid detail title', 'otw-portfolio-manager' );
					}
					
					if( !otw_post( 'pm_detail_order', false ) || !strlen( trim( otw_post( 'pm_detail_order', '' ) ) ) ){
						$valid_page = false;
						$otw_pm_validate_messages[] = esc_html__( 'Please type valid order', 'otw-portfolio-manager' );
					}elseif( otw_post( 'pm_detail_order', false ) && strlen( trim( otw_post( 'pm_detail_order', '' ) ) ) && !preg_match( "/^\d+$/", otw_post( 'pm_detail_order', '' ) ) ){
						$valid_page = false;
						$otw_pm_validate_messages[] = esc_html__( 'Please type valid number for order', 'otw-portfolio-manager' );
					}
					
					if( $valid_page ){
						
						$otw_details = get_option( 'otw_pm_portfolio_details' );
						
						if( !is_array( $otw_details ) ){
							$otw_details = array();
						}
						
						if( otw_get( 'detail', false ) && isset( $otw_details[ otw_get( 'detail', '' ) ] ) ){
							$otw_detail_id = otw_get( 'detail', '' );
							$db_detail = $otw_details[ otw_get( 'detail', '' ) ];
						}else{
							$db_detail = array();
							$otw_detail_id = false;
						}
						
						$db_detail['title'] = (string) otw_stripslashes( otw_post( 'pm_detail_title', '' ) );
						$db_detail['order'] = (string) otw_post( 'pm_detail_order', '' );
						
						if( $otw_detail_id === false ){
							
							$otw_detail_id = $this->get_next_detail_id();
							$db_detail['id'] = $otw_detail_id;
						}
						
						$otw_details[ $otw_detail_id ] = $db_detail;
						
						if( !update_option( 'otw_pm_portfolio_details', $otw_details ) && $wpdb->last_error ){
							$valid_page = false;
							$otw_pm_validate_messages[] = esc_html__( 'DB Error: ', 'otw-portfolio-manager' ).$wpdb->last_error.'. Tring to save '.strlen( maybe_serialize( $otw_details ) ).' bytes.';
						}else{
							wp_redirect( 'admin.php?page=otw-pm-details&message=1' );
						}
					}
				break;
		}
	}
}
/**
 * Import mapping
 */
private function save_import_mapping( $mapping ){
	
	wp_cache_delete( 'otw_pm_import_export_mapping', 'options' );
	
	update_option( 'otw_pm_import_export_mapping', $mapping, false );
	
	wp_cache_delete( 'otw_pm_import_export_mapping', 'options' );
	
	return $this->get_import_mapping();
}
/**
 * Import mapping
 */
private function get_import_mapping(){
	
	wp_cache_delete( 'otw_pm_import_export_mapping', 'options' );
	
	$import_mapping = get_option( 'otw_pm_import_export_mapping' );
	
	wp_cache_delete( 'otw_pm_import_export_mapping', 'options' );
	
	$exists = true;
	if( !is_array( $import_mapping ) ){
		$import_mapping = array();
		$exists = false;
	}
	if( !isset( $import_mapping['media_data'] ) ){
		$import_mapping['media_data'] = array();
	}
	if( !isset( $import_mapping[ $this->portfolio_category ] ) ){
		$import_mapping[ $this->portfolio_category ] = array();
	}
	if( !isset( $import_mapping[ $this->portfolio_tag ] ) ){
		$import_mapping[ $this->portfolio_tag ] = array();
	}
	if( !isset( $import_mapping['pm_details'] ) ){
		$import_mapping['pm_details'] = array();
	}
	if( !isset( $import_mapping['pm_custom_templates'] ) ){
		$import_mapping['pm_custom_templates'] = array();
	}
	if( !isset( $import_mapping['pm_posts'] ) ){
		$import_mapping['pm_posts'] = array();
	}
	if( !isset( $import_mapping['pm_lists'] ) ){
		$import_mapping['pm_lists'] = array();
	}
	if( !isset( $import_mapping['pages'] ) ){
		$import_mapping['pages'] = array();
	}
	
	if( !$exists ){
		add_option( 'otw_pm_import_export_mapping', $import_mapping, null, false );
	}
	
	return $import_mapping;
}
/**
 * Import backup terms
 */
private function import_pm_backup_terms( $term_type, $import_terms, $import_mapping, $parent = 0 ){
	
	if( is_array( $import_terms ) && count( $import_terms ) ){
		
		foreach( $import_terms as $import_term ){
			
			if( $import_term['parent'] == $parent ){
				
				$exists = false;
				
				//check if exists in the mapping
				if( isset( $import_mapping[ $term_type ][ $import_term['term_id'] ] ) ){
					
					$exists_term = get_term( $import_mapping[ $term_type ][ $import_term['term_id'] ], $term_type );
					
					if( $exists_term ){
						$exists = $exists_term->term_id;
					}
				}
				
				if( !$exists ){ //check if it exists by slug
					
					$exists_term = get_term_by('slug', $import_term['slug'], $term_type );
					
					if( $exists_term ){
						$exists = $exists_term->term_id;
					}
				}
				
				
				if( $exists ){
					
					if( $parent ){
						
						$exists_parent = 0;
						if( isset( $import_mapping[ $term_type ][ $import_term['parent'] ] ) ){
							$exists_parent = $import_mapping[ $term_type ][ $import_term['parent'] ];
							
							wp_update_term( $exists, $term_type, array( 'parent' => $exists_parent ) );
						}
					}
					
					$import_mapping[ $term_type ][ $import_term['term_id'] ] = $exists;
				
				}else{
					
					$args = array();
					$args['slug'] = $import_term['slug'];
					$args['description'] = $import_term['description'];
					
					if( $import_term['parent'] && isset( $import_mapping[ $term_type ][ $import_term['parent'] ] ) ){
						
						$args['parent'] = $import_mapping[ $term_type ][ $import_term['parent'] ];
						
					}else{
						$args['parent'] = 0;
					}
					
					$result = wp_insert_term( $import_term['name'], $term_type, $args );
					
					if( isset( $result['term_id'] ) && intval( $result['term_id'] ) ){
						$import_mapping[ $term_type ][ $import_term['term_id'] ] = $result['term_id'];
					}
				}
				
				$import_mapping = $this->import_pm_backup_terms( $term_type, $import_terms, $import_mapping, $import_term['term_id'] );
			}
		}
	}
	return $import_mapping;
}
/**
 * Import light categories
 */
private function import_light_categories( $light_categories, $exists_categories_assoc, $cat_to_cat, $parent = 0 ){
	if( is_array( $light_categories ) && count( $light_categories ) ){
		
		foreach( $light_categories as $light_cat ){
			
			if( $light_cat->parent == $parent ){
				
				if( isset( $exists_categories_assoc[ $light_cat->name ] ) ){
					
					if( $parent )
					{
						$exists_parent = 0;
						if( isset( $cat_to_cat[ $light_cat->parent ] ) ){
							$exists_parent = $cat_to_cat[ $light_cat->parent ];
						}
						
						if( $exists_parent != $exists_categories_assoc[ $light_cat->name ]->parent ){
							wp_update_term( $exists_categories_assoc[ $light_cat->name ]->term_id, $this->portfolio_category, array( 'parent' => $exists_parent ) );
						}
					}
				
					$cat_to_cat[ $light_cat->term_id ] = $exists_categories_assoc[ $light_cat->name ]->term_id;
				}else{
					//import the missing category
					$args = array();
					$args['slug'] = $light_cat->slug;
					$args['description'] = $light_cat->description;
					
					if( $light_cat->parent && isset( $cat_to_cat[ $light_cat->parent ] ) ){
						
						$args['parent'] = $cat_to_cat[ $light_cat->parent ];
						
					}else{
						
						$args['parent'] = 0;
						
					}
					
					$result = wp_insert_term( $light_cat->name, $this->portfolio_category, $args );
					
					if( isset( $result['term_id'] ) && intval( $result['term_id'] ) ){
						$cat_to_cat[ $light_cat->term_id ] = $result['term_id'];
					}
				}
				
				$cat_to_cat = $this->import_light_categories( $light_categories, $exists_categories_assoc, $cat_to_cat, $light_cat->term_id  );
			}
		}
	}
	return $cat_to_cat;
}

/**
 * Get next detail id
 */
private function get_next_detail_id(){
	
	$next_id = 1;
	$existing_details = get_option( 'otw_pm_portfolio_details' );
	
	if( is_array( $existing_details ) && count( $existing_details ) ){
	
		foreach( $existing_details as $key => $s_data ){
			
			if( preg_match( "/^([0-9]+)$/", $key, $matches ) ){
				
				if( $matches[1] > $next_id ){
					$next_id = $matches[1];
				}
			}
		}
	}else{
		$next_id = 0;
	}
	return $next_id + 1;
}

/**
 * Get next custom template id
 */
private function get_next_custom_template_id(){
	
	$next_id = 1;
	$existing_custom_templates = $this->get_custom_templates();
	
	if( is_array( $existing_custom_templates ) && count( $existing_custom_templates ) ){
	
		foreach( $existing_custom_templates as $key => $s_data ){
			
			if( preg_match( "/^([0-9]+)$/", $key, $matches ) ){
				
				if( $matches[1] > $next_id ){
					$next_id = $matches[1];
				}
			}
		}
	}else{
		$next_id = 0;
	}
	return $next_id + 1;
}

/**
 * Activation hook
 */
public function flush_rewrites(){
	
	$this->register_portfolio_custom_types();
	flush_rewrite_rules();
}

/**
 * Register custom post type and taxonomies
 */
public function register_portfolio_custom_types(){
	
	if( !taxonomy_exists( $this->portfolio_category ) ){
		
		$labels = array(
			'name' => _x( 'Portfolio Categories', '','otw-portfolio-manager' ),
			'singular_name' => _x( 'Portfolio Category', '', 'otw-portfolio-manager' ),
			'search_items' =>  esc_html__( 'Search Portfolio Category', 'otw-portfolio-manager' ),
			'all_items' => esc_html__( 'All Portfolio Category', 'otw-portfolio-manager' ),
			'parent_item' => esc_html__( 'Parent Portfolio Category', 'otw-portfolio-manager' ),
			'parent_item_colon' => esc_html__( 'Parent Portfolio Category:', 'otw-portfolio-manager' ),
			'edit_item' => esc_html__( 'Edit Portfolio Category', 'otw-portfolio-manager' ),
			'update_item' => esc_html__( 'Update Portfolio Category', 'otw-portfolio-manager' ),
			'add_new_item' => esc_html__( 'Add New Portfolio Category', 'otw-portfolio-manager' ),
			'new_item_name' => esc_html__( 'New Portfolio Category Name', 'otw-portfolio-manager' ),
			'menu_name' => esc_html__( 'Portfolio Categories', 'otw-portfolio-manager' ),
			'separate_items_with_commas' => esc_html__( 'Separate categories with commas', 'otw-portfolio-manager' ),
			'add_or_remove_items' => esc_html__( 'Add or remove categories', 'otw-portfolio-manager' ),
			'choose_from_most_used' => esc_html__( 'Choose from the most used categories', 'otw-portfolio-manager' ),
			'popular_items' => esc_html__( 'Popular Categories', 'otw-portfolio-manager' )
		);
		
		$args = array(
			'hierarchical' => true,
			'labels' => $labels,
			'poblic' => true,
			'publicly_queryable' => true,
			'show_ui' => true,
			'exclude_from_search' => false,
			'query_var' => true,
			'has_archive'       =>  true,
			'rewrite' => 1,
			'show_admin_column' => true
		);
		
		$otw_pm_plugin_options = get_option( 'otw_pm_plugin_options' );
		
		if( isset( $otw_pm_plugin_options['otw_pm_portfolio_category_slug'] ) && strlen( trim( $otw_pm_plugin_options['otw_pm_portfolio_category_slug'] ) ) ){
			$args['rewrite'] = array( 'slug' => $otw_pm_plugin_options['otw_pm_portfolio_category_slug'], 'with_front' => true );
		}
		register_taxonomy( $this->portfolio_category , array( $this->portfolio_post_type ), $args );
	}
	
	if( !taxonomy_exists( $this->portfolio_tag ) ){
		
		$labels = array(
			'name' => _x( 'Portfolio Tags', '','otw-portfolio-manager' ),
			'singular_name' => _x( 'Portfolio Tag', '', 'otw-portfolio-manager' ),
			'search_items' =>  esc_html__( 'Search Portfolio Tag', 'otw-portfolio-manager' ),
			'all_items' => esc_html__( 'All Portfolio Tag', 'otw-portfolio-manager' ),
			'parent_item' => esc_html__( 'Parent Portfolio Tag', 'otw-portfolio-manager' ),
			'parent_item_colon' => esc_html__( 'Parent Portfolio Tag:', 'otw-portfolio-manager' ),
			'edit_item' => esc_html__( 'Edit Portfolio Tag', 'otw-portfolio-manager' ),
			'update_item' => esc_html__( 'Update Portfolio Tag', 'otw-portfolio-manager' ),
			'add_new_item' => esc_html__( 'Add New Portfolio Tag', 'otw-portfolio-manager' ),
			'new_item_name' => esc_html__( 'New Portfolio Tag Name', 'otw-portfolio-manager' ),
			'menu_name' => esc_html__( 'Portfolio Tags', 'otw-portfolio-manager' ),
			'separate_items_with_commas' => esc_html__( 'Separate tags with commas', 'otw-portfolio-manager' ),
			'add_or_remove_items' => esc_html__( 'Add or remove tags', 'otw-portfolio-manager' ),
			'choose_from_most_used' => esc_html__( 'Choose from the most used tags', 'otw-portfolio-manager' ),
			'popular_items' => esc_html__( 'Popular Tags', 'otw-portfolio-manager' )
		);
		
		$args = array(
			'hierarchical' => false,
			'labels' => $labels,
			'poblic' => true,
			'publicly_queryable' => true,
			'show_ui' => true,
			'exclude_from_search' => false,
			'query_var' => true,
			'has_archive'       =>  true,
			'rewrite' => 1,
			'show_admin_column' => true
		);
		
		$otw_pm_plugin_options = get_option( 'otw_pm_plugin_options' );
		
		if( isset( $otw_pm_plugin_options['otw_pm_portfolio_tag_slug'] ) && strlen( trim( $otw_pm_plugin_options['otw_pm_portfolio_tag_slug'] ) ) ){
			$args['rewrite'] = array( 'slug' => $otw_pm_plugin_options['otw_pm_portfolio_tag_slug'] );
		}
		
		register_taxonomy( $this->portfolio_tag , array( $this->portfolio_post_type ), $args );
	}
	
	if( !post_type_exists( $this->portfolio_post_type ) ){
		
		$labels = array(
			'name' => _x( 'Portfolio Items', 'post type general name', 'otw-portfolio-manager' ),
			'singular_name' => _x( 'PM Portfolio Item', 'post type singular name', 'otw-portfolio-manager' ),
			'add_new' => _x( 'Add New Item', 'slide', 'otw-portfolio-manager' ),
			'add_new_item' => esc_html__( 'Add New Item', 'otw-portfolio-manager' ),
			'edit_item' => esc_html__( 'Edit Portfolio Item', 'otw-portfolio-manager' ),
			'new_item' => esc_html__( 'New Portfolio Item', 'otw-portfolio-manager' ),
			'view_item' => esc_html__( 'View Portfolio Item', 'otw-portfolio-manager' ),
			'search_items' => esc_html__( 'Search Portfolio Items', 'otw-portfolio-manager' ),
			'menu_name' => esc_html__( 'Portfolio Manager', 'otw-portfolio-manager' ),
			'all_items' => esc_html__( 'Portfolio Items', 'otw-portfolio-manager' ),
			'not_found' =>  esc_html__( 'No portfolio items found', 'otw-portfolio-manager' ),
			'not_found_in_trash' => esc_html__( 'No portfolio items found in Trash', 'otw-portfolio-manager' ),
			'parent_item_colon' => ''
		);
		
		$args = array(
			'labels' => $labels,
			'public' => true,
			'publicly_queryable' => true,
			'show_ui' => true,
			'query_var' => true,
			'rewrite' => true,
			'capability_type' => 'post',
			'hierarchical' => false,
			'menu_icon' => plugins_url() . DS . OTW_PM_PATH . DS .'assets'. DS .'img'. DS .'menu_icon.png',
			'menu_position' => null, 
			'has_archive' => true, 
			'taxonomies' => array( $this->portfolio_category, $this->portfolio_tag ), 
			'supports' => array( 'title','editor','excerpt' )
		);
		
		$otw_pm_plugin_options = get_option( 'otw_pm_plugin_options' );
		
		if( isset( $otw_pm_plugin_options['otw_pm_portfolio_slug'] ) && strlen( trim( $otw_pm_plugin_options['otw_pm_portfolio_slug'] ) ) ){
			
			$args['rewrite'] = array( 'slug' => $otw_pm_plugin_options['otw_pm_portfolio_slug'] );
		}
		
		register_post_type( $this->portfolio_post_type, $args );
	}
	
	$details = get_option( 'otw_pm_portfolio_details' );
	
	if( !is_array( $details ) ){
		
		$details = array();
		
		$order = 0;
		foreach( $this->portfolio_meta_details as $id => $title ){
			
			$details[ $id ] = array( 'id' => $id, 'title' => $title, 'order' => $order );
			$order++;
		}
		update_option( 'otw_pm_portfolio_details', $details );
	}
}
  /**
   * Add Styles and Scripts needed by the Admin interface
   */
  public function register_resources () {
	
	global $otw_pm_grid_manager_component, $otw_pm_grid_manager_object, $otw_pm_plugin_url, $otw_pm_js_version, $otw_pm_css_version, $otw_pm_shortcode_component, $otw_pm_shortcode_object;
	
	if( !function_exists( 'wp_enqueue_media' ) ) {
		wp_enqueue_media(); //WP 3.5 media uploader
	}
	
	//check the skin folder
	$upload_dir = wp_upload_dir();
	
	global $wp_filesystem;
		
	if( otw_init_filesystem() ){
		
		if( isset( $upload_dir['basedir'] ) && $wp_filesystem->is_writable( $upload_dir['basedir'] ) && !$wp_filesystem->is_dir( SKIN_PM_PATH ) ){
			
			if( !$wp_filesystem->is_dir( $upload_dir['basedir'].DS.'otwpm' ) ){
				$wp_filesystem->mkdir( $upload_dir['basedir'].DS.'otwpm' );
			}
			if( $wp_filesystem->is_dir( $upload_dir['basedir'].DS.'otwpm' ) && !$wp_filesystem->is_dir( SKIN_PM_PATH ) ){
				$wp_filesystem->mkdir( SKIN_PM_PATH );
			}
		}
	}
	
	add_action('admin_print_styles', array( $this, 'enqueue_admin_styles' ) );
	add_action('admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );

  }
	public function enqueue_admin_styles( $requested_page ){
		
		if( function_exists( 'get_current_screen' ) ){
			
			$screen = get_current_screen();
			
			if( isset( $screen->id ) && strlen( $screen->id ) ){
				$requested_page = $screen->id;
			}
		}
		
		if( preg_match( "/otw\-pm\-add$/", $requested_page ) || preg_match( "/otw\-pm$/", $requested_page ) || preg_match( "/otw\-pm\-settings$/", $requested_page ) || preg_match( "/otw\-pm\-backup$/", $requested_page ) || ( $this->portfolio_post_type == $requested_page ) ){
			wp_register_style( 'otw-pm-admin-color-picker', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'css'.DS.'colorpicker.css' );
			wp_register_style( 'otw-pm-admin-pm-default', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'css'.DS.'otw-portfolio-list-default.css' );
			wp_register_style( 'otw-pm-admin-pm-select2', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'css'.DS.'select2.min.css' );
			wp_enqueue_style( 'otw-pm-admin-color-picker' );
			wp_enqueue_style( 'otw-pm-admin-pm-default' );
			wp_enqueue_style( 'otw-pm-admin-pm-select2' );
		}elseif( preg_match( "/otw\-pm\-custom\-templates\-(add|edit)$/", $requested_page ) ){
			wp_register_style( 'otw-pm-admin-pm-default', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'css'.DS.'otw-portfolio-list-default.css' );
			wp_enqueue_style( 'otw-pm-admin-pm-default' );
			if (function_exists('wp_enqueue_media')){
				wp_enqueue_media();
			}else{
				wp_enqueue_style('thickbox');
				wp_enqueue_script('media-upload');
				wp_enqueue_script('thickbox');
			}
		}
	}
	
	public function enqueue_admin_scripts( $requested_page ){
		
		global $otw_pm_plugin_url, $otw_pm_js_version, $otw_pm_grid_manager_object, $otw_pm_shortcode_object;
		
		if( function_exists( 'get_current_screen' ) ){
			
			$screen = get_current_screen();
			
			if( isset( $screen->id ) && strlen( $screen->id ) ){
				$requested_page = $screen->id;
			}
		}
		
		if( preg_match( "/otw\-pm\-add$/", $requested_page ) || preg_match( "/otw\-pm$/", $requested_page ) || preg_match( "/otw\-pm\-settings$/", $requested_page ) || ( $this->portfolio_post_type == $requested_page ) ){
			
			// Get ALL categories to be used in SELECT 2
			$categoriesData     = array();
			$catCount = 0;
			
			// Get ALL tags to be used in SELECT 2
			$tagsData           = array();
			$tagCount           = 0;
			
			// Get ALL users Authors
			$usersData          = array();
			$userCount          = 0;
			
			$pagesData          = array();
			$pageCount          = 0;
			
			$messages = array(
				'delete_confirm'  => esc_html__('Are you sure you want to delete ', 'otw-portfolio-manager'),
				'modal_title'     => esc_html__('Select Images', 'otw-portfolio-manager'),
				'modal_btn'       => esc_html__('Add Image', 'otw-portfolio-manager')
			);
			
			wp_register_script( 'otw-pm-admin-colorpicker', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'js'.DS.'plugins'.DS.'colorpicker.js', array('jquery') );
			wp_register_script( 'otw-pm-admin-select2', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'js'.DS.'plugins'.DS.'select2.full.min.js', array('jquery') );
			wp_register_script( 'otw-pm-admin-variables', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'js'.DS.'otw-admin-pm-variables.js' );
			wp_register_script( 'otw-pm-admin-functions', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'js'.DS.'otw-admin-pm-functions.js' );
			wp_register_script( 'otw-pm-admin-fonts', plugins_url() . DS . OTW_PM_PATH . DS . 'assets'.DS.'js'.DS.'fonts.js' );
			
			// Custom Scripts + Plugins
			wp_enqueue_script( 'otw-pm-admin-colorpicker' );
			wp_enqueue_script( 'otw-pm-admin-select2' );
			wp_enqueue_script( 'otw-pm-admin-otwpmpreview' );
			wp_enqueue_script( 'otw-pm-admin-fonts');
			wp_enqueue_script( 'otw-pm-admin-functions');
			wp_enqueue_script( 'otw-pm-admin-variables');
			
			// Core Scripts
			wp_enqueue_script( 'jquery' );
			wp_enqueue_script( 'jquery-ui-core' );
			wp_enqueue_script( 'jquery-ui-draggable' );
			wp_enqueue_script( 'jquery-ui-droppable' );
			wp_enqueue_script( 'jquery-ui-accordion' );
			wp_enqueue_script( 'jquery-ui-tabs' );
			wp_enqueue_script( 'jquery-ui-sortable' );
			
			wp_add_inline_script( 'otw-pm-admin-functions', 'var categories = "'.addslashes( json_encode( $categoriesData ) ).'";', 'before' );
			wp_add_inline_script( 'otw-pm-admin-functions', 'var tags = "'.addslashes( json_encode( $tagsData ) ).'";', 'before' );
			wp_add_inline_script( 'otw-pm-admin-functions', 'var users = "'.addslashes( json_encode( $usersData ) ).'";', 'before' );
			wp_add_inline_script( 'otw-pm-admin-functions', 'var pages = "'.addslashes( json_encode( $pagesData ) ).'";', 'before' );
			wp_add_inline_script( 'otw-pm-admin-functions', 'var messages = "'.addslashes( json_encode( $messages ) ).'";', 'before' ) ;
			wp_add_inline_script( 'otw-pm-admin-functions', 'var frontendURL = "'.plugins_url() . DS . OTW_PM_PATH . DS . 'frontend/";', 'before' );
			
		}
		
		if( preg_match( "/otw\-pm\-custom\-templates\-(add|edit)$/", $requested_page ) ){
			$otw_pm_grid_manager_object->include_admin_scripts();
			$otw_pm_shortcode_object->include_admin_scripts();
			wp_enqueue_style('thickbox');
			wp_enqueue_script('thickbox');
		}
	}

  /**
   * Add Meta Boxes 
   */
public function pm_meta_boxes(){
	// Add Support for POSTS
	add_meta_box(
		'otw-pm-meta-box',
		esc_html__('OTW Portfolio Manager Media Item', 'otw-portfolio-manager'),
		array($this, 'otw_portfolio_manager_media_meta_box'),
		$this->portfolio_post_type,
		'normal',
		'default'
	);
	
	add_meta_box(
		'otw-pm-details-meta-box',
		esc_html__('OTW Portfolio Details', 'otw-portfolio-manager'),
		array($this, 'otw_portfolio_manager_details_meta_box'),
		$this->portfolio_post_type,
		'normal',
		'default'
	);
	
	add_meta_box(
		'otw-pm-tabs-meta-box',
		esc_html__('OTW Portfolio Tabs', 'otw-portfolio-manager'),
		array($this, 'otw_portfolio_manager_tabs_meta_box'),
		$this->portfolio_post_type,
		'normal',
		'default'
	);
	
	add_meta_box(
		'otw-pm-options-meta-box',
		esc_html__('OTW Portfolio item single', 'otw-portfolio-manager'),
		array($this, 'otw_portfolio_manager_options_meta_box'),
		$this->portfolio_post_type,
		'normal',
		'default'
	);
}

/**
  * Add Custom HTML Meta Box on portfolio items
  */
public function otw_portfolio_manager_media_meta_box( $post ){
	$otw_pm_meta_data = get_post_meta( $post->ID, 'otw_pm_meta_data', true );
	require_once( 'views'. DS .'otw_portfolio_manager_meta_box.php' );
}
/**
  * Add Custom HTML Meta Box on portfolio items
  */
public function otw_portfolio_manager_details_meta_box( $post ){
	
	$portfolio_meta_details = $this->get_details();
	
	require_once( 'views'. DS .'otw_portfolio_manager_details_meta_box.php' );
}
/**
  * Add Custom HTML Meta Box on portfolio items
  */
public function otw_portfolio_manager_tabs_meta_box( $post ){
	
	$otw_pm_tabs_meta_data = get_post_meta( $post->ID, 'otw_pm_tabs_meta_data', true );
	
	$total_tabs = 0;
	
	if( is_array( $otw_pm_tabs_meta_data ) ){
	
		ksort( $otw_pm_tabs_meta_data );
		
		foreach( $otw_pm_tabs_meta_data as $key => $value ){
		
			if( otw_post( 'otw_pm_tab_title', false ) && otw_post( array( 'otw_pm_tab_title', $key ), false ) ){
				$otw_pm_tabs_meta_data[ $key ]['title'] = otw_post( array( 'otw_pm_tab_title', $key ), array() );
			}
			if( otw_post( 'otw_pm_tab_content', false ) && otw_post( array( 'otw_pm_tab_content', $key ), false ) ){
				$otw_pm_tabs_meta_data[ $key ]['content'] = otw_post( array( 'otw_pm_tab_content', $key ), array() );
			}
		}
		
		$total_tabs = count( $otw_pm_tabs_meta_data );
	}
	
	require_once( 'views'. DS .'otw_portfolio_manager_tabs_meta_box.php' );
}

/**
  * Add Custom HTML Meta Box on portfolio items
  */
public function otw_portfolio_manager_options_meta_box( $post ){
	
	$otw_pm_options_meta_data = get_post_meta( $post->ID, 'otw_pm_options_meta_data', true );
	
	if( !is_array( $otw_pm_options_meta_data ) || !isset( $otw_pm_options_meta_data ) ){
		$otw_pm_options_meta_data = array();
		$otw_pm_options_meta_data['otw_pm_options_type'] = 'default';
		$otw_pm_options_meta_data['options'] = array();
	}
	
	$otw_pm_templates = array( 'default' => esc_html__( 'Default Theme\'s Post Template', 'otw-portfolio-manager' ) ) + $this->otwDispatcher->portfolio_templates;
	
	$otw_pm_options_meta_data['options'] = $this->init_portfolio_item_values( $otw_pm_options_meta_data['options'] );
	
	$otw_pm_social_icons = array(
		'' => esc_html__( 'None (default)', 'otw-portfolio-manager' ),
		'share_icons' => esc_html__( 'Share Icons', 'otw-portfolio-manager' ),
		'share_btn_small' => esc_html__( 'Share Buttons Small', 'otw-portfolio-manager' ),
		'share_btn_large' => esc_html__( 'Share Buttons Large', 'otw-portfolio-manager' ),
		'like_buttons' => esc_html__( 'Like Buttons', 'otw-portfolio-manager' )
	);
	
	$otw_pm_prev_next_nav_options = array(
		'' => esc_html__( 'No (default)', 'otw-portfolio-manager' ),
		'yes' => esc_html__( 'Yes', 'otw-portfolio-manager' )
	);
	
	$otw_pm_item_title_options = array(
		'yes' => esc_html__( 'Yes (default)', 'otw-portfolio-manager' ),
		'no' => esc_html__( 'No', 'otw-portfolio-manager' )
	);
	
	$otw_pm_related_posts_options = array(
		'' => esc_html__( 'No (default)', 'otw-portfolio-manager' ),
		'yes' => esc_html__( 'Yes', 'otw-portfolio-manager' )
	);
	
	$otw_pm_item_media_format_options = array(
		'' => esc_html__('Keep original file format (default)', 'otw-portfolio-manager' ),
		'jpg' => 'jpg',
		'png' => 'png',
		'gif' => 'gif'
	);
	
	$otw_pm_related_posts_criteria_options = array(
		$this->portfolio_category => esc_html__( 'Category (default)', 'otw-portfolio-manager' ),
		$this->portfolio_tag => esc_html__( 'Tag', 'otw-portfolio-manager' )
	);
	
	$otw_details = $this->get_details();
	
	if( is_array( $otw_details ) && count( $otw_details ) ){
		
		foreach( $otw_details as $otw_detail ){
			$otw_pm_related_posts_criteria_options[ 'otw_pm_portfolio_detail_'.$otw_detail['id'] ] = $otw_detail['title'];
		}
	}
	
	$otw_pm_media_lightbox_options = array(
		'yes' => esc_html__( 'Yes (default)', 'otw-portfolio-manager' ),
		'no' => esc_html__( 'No', 'otw-portfolio-manager' )
	);
	
	require_once( 'views'. DS .'otw_portfolio_manager_options_meta_box.php' );
}

private function init_portfolio_item_values( $otw_pm_plugin_options ){
	
	if( !isset( $otw_pm_plugin_options['otw_pm_template'] ) ){
		
		$otw_pm_plugin_options['otw_pm_template'] = 'single-portfolio-media-left';
	}
	
	if( !isset( $otw_pm_plugin_options['otw_pm_portfolio_slug'] ) ){
		$otw_pm_plugin_options['otw_pm_portfolio_slug'] = $this->portfolio_post_type;
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_portfolio_category_slug'] ) ){
		$otw_pm_plugin_options['otw_pm_portfolio_category_slug'] = $this->portfolio_category;
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_portfolio_tag_slug'] ) ){
		$otw_pm_plugin_options['otw_pm_portfolio_tag_slug'] = $this->portfolio_tag;
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_description_title_text'] ) ){
		$otw_pm_plugin_options['otw_pm_description_title_text'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_details_title_text'] ) ){
		$otw_pm_plugin_options['otw_pm_details_title_text'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_social_title_text'] ) ){
		$otw_pm_plugin_options['otw_pm_social_title_text'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_moreinfo_title_text'] ) ){
		$otw_pm_plugin_options['otw_pm_moreinfo_title_text'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_title_text'] ) ){
		$otw_pm_plugin_options['otw_pm_related_title_text'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_posts_criteria'] ) ){
		$otw_pm_plugin_options['otw_pm_related_posts_criteria'] = $this->portfolio_category;
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_archive_media_width'] ) ){
		$otw_pm_plugin_options['otw_pm_archive_media_width'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_archive_media_height'] ) ){
		$otw_pm_plugin_options['otw_pm_archive_media_height'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_archive_media_format'] ) ){
		$otw_pm_plugin_options['otw_pm_archive_media_format'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_width'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_width'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_height'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_height'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_format'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_format'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_title_attr'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_title_attr'] = 'no';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_alt_attr'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_alt_attr'] = 'no';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_media_format'] ) ){
		$otw_pm_plugin_options['otw_pm_related_media_format'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_lightbox_width'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_lightbox_width'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_lightbox_height'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_lightbox_height'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_media_lightbox_format'] ) ){
		$otw_pm_plugin_options['otw_pm_item_media_lightbox_format'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_item_title'] ) ){
		$otw_pm_plugin_options['otw_pm_item_title'] = 'yes';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_media_width'] ) ){
		$otw_pm_plugin_options['otw_pm_related_media_width'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_media_lightbox'] ) ){
		$otw_pm_plugin_options['otw_pm_media_lightbox'] = 'yes';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_media_height'] ) ){
		$otw_pm_plugin_options['otw_pm_related_media_height'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_related_posts_number'] ) ){
		$otw_pm_plugin_options['otw_pm_related_posts_number'] = '';
	}
	if( !isset( $otw_pm_plugin_options['otw_pm_grid_pages'] ) ){
		$otw_pm_plugin_options['otw_pm_grid_pages'] = 'yes';
	}
	return $otw_pm_plugin_options;
}

/**
 * Get details and prepare the result
 */

public function get_details(){

	$otw_details = get_option( 'otw_pm_portfolio_details' );
	
	if( is_array( $otw_details ) && count( $otw_details ) ){
		
		uasort( $otw_details, array( $this, 'sort_details' ) );
		
	}else{
		$otw_details = array();
	}
	
	foreach ( $otw_details as $key => $otw_detail ){
		$otw_details[$key]['title'] = esc_html__( $otw_detail['title'], 'otw-portfolio-manager' );
	}
	
	return $otw_details;
}

/**
 * Get custom templates
 */
public function get_custom_templates(){

	$otw_custom_templates = get_option( 'otw_pm_custom_templates' );
	
	if( !is_array( $otw_custom_templates ) || !count( $otw_custom_templates ) ){
		
		$otw_custom_templates = array();
		
	}
	return $otw_custom_templates;
}

/**
 * Sort details
 */
public function sort_details( $a, $b ){
	
	if( $a['order'] > $b['order'] ){
		return 1;
	}elseif( $a['order'] < $b['order'] ){
		return -1;
	}elseif( $a['id'] > $b['id'] ){
		return 1;
	}elseif( $a['id'] < $b['id'] ){
		return -1;
	}
	return 0;
	
}

  /**
   * Save Meta Box Data
   * @param $post_id - int - Current POST ID beeing edited
   */
function pm_save_meta_box( $post_id ){
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
		return;
	}
	
	if( !empty( $_POST ) && !empty( otw_post( 'otw-pm-list-media_type', '' )) ){
		$otw_meta_data = array(
			'media_type'      => otw_post( 'otw-pm-list-media_type', '' ),
			'youtube_url'     => otw_post( 'otw-pm-list-youtube_url', '' ),
			'vimeo_url'       => otw_post( 'otw-pm-list-vimeo_url', '' ),
			'soundcloud_url'  => otw_post( 'otw-pm-list-soundcloud_url', '' ),
			'img_url'         => otw_post( 'otw-pm-list-img_url', '' ),
			'slider_url'      => otw_post( 'otw-pm-list-slider_url', '' )
		);
		
		/**
		 * Add Custom POST Meta Data
		 * If POST is found in the DB it will just be ignored and return FALSE
		*/
		add_post_meta($post_id, 'otw_pm_meta_data', $otw_meta_data, true);
		
		// If POST is in the DB update it
		update_post_meta($post_id, 'otw_pm_meta_data', $otw_meta_data);
	}elseif( !empty( $_POST ) &&  otw_post( 'otw-pm-list-media_type', false )  ){
		delete_post_meta($post_id, 'otw_pm_meta_data');
	}
	
	if( !empty( $_POST ) && !empty( otw_post( 'otw_pm_meta_details', '' )) ){
	
		$otw_details_meta = array();
		
		$portfolio_meta_details = $this->get_details();
		
		foreach( $portfolio_meta_details as $detail_id => $detail_data ){
			
			$key_name = 'otw_pm_portfolio_detail_'.$detail_id;
			
			if( otw_post( $key_name, false ) && strlen( trim( otw_post( $key_name, '' ) ) ) ){
				
				add_post_meta($post_id, $key_name, otw_post( $key_name, '' ), true);
				update_post_meta($post_id, $key_name, otw_post( $key_name, '' ) );
			}else{
				delete_post_meta($post_id, $key_name );
			}
		}
	}
	
	if( !empty( $_POST ) && !empty( otw_post( 'otw_pm_meta_tabs', '' )) ){
		
		$otw_tabs_meta = array();
		
		if( otw_post( 'otw_pm_tab_title', false ) ){
			
			foreach( otw_post( 'otw_pm_tab_title', '' ) as $new_id => $new_title ){
			
				if( strlen( trim( $new_title ) ) || strlen( trim( otw_post( array( 'otw_pm_tab_content', $new_id ), array() ) ) ) ){
				
					$otw_tabs_meta[] = array( 
						'title' => $new_title,
						'content' => otw_post( array( 'otw_pm_tab_content', $new_id ), array() )
					);
				}
			}
		}
		
		add_post_meta($post_id, 'otw_pm_tabs_meta_data', $otw_tabs_meta, true);
		
		update_post_meta($post_id, 'otw_pm_tabs_meta_data', $otw_tabs_meta );
	}
	
	if( !empty( $_POST ) && !empty( otw_post( 'otw_pm_meta_options', '' )) ){
		
		$otw_options_meta = array();
		
		$otw_options_meta['otw_pm_options_type'] = @otw_post( 'otw_pm_options_type', '' );
		$otw_options_meta['options'] = array();
		
		$portfolio_settings = array( 'otw_pm_template', 'otw_pm_item_title', 'otw_pm_social_icons', 'otw_pm_prev_next_nav', 'otw_pm_related_posts', 'otw_pm_related_posts_number', 'otw_pm_description_title_text', 'otw_pm_details_title_text', 'otw_pm_moreinfo_title_text', 'otw_pm_related_title_text', 'otw_pm_item_media_width', 'otw_pm_item_media_height', 'otw_pm_item_media_format', 'otw_pm_related_media_width', 'otw_pm_related_media_height', 'otw_pm_related_media_format', 'otw_pm_media_lightbox', 'otw_pm_item_media_lightbox_width', 'otw_pm_item_media_lightbox_height', 'otw_pm_item_media_lightbox_format','otw_pm_social_title_text', 'otw_pm_related_posts_criteria', 'otw_pm_item_media_title_attr', 'otw_pm_item_media_alt_attr' );
		
		foreach( $portfolio_settings as $setting_key )
		{
			$otw_pm_plugin_options[ $setting_key ] = '';
			
			if( otw_post( $setting_key, false ) ){
				$otw_options_meta['options'][ $setting_key ] = otw_stripslashes( otw_post( $setting_key, '' ) );
			}
		}
		
		add_post_meta($post_id, 'otw_pm_options_meta_data', $otw_options_meta, true);
		
		update_post_meta($post_id, 'otw_pm_options_meta_data', $otw_options_meta );
	}
}

  /**
   * OTW Portfolio Manager List Page
   */
  public function pm_list () {
    $action = $_GET;

    // Check if writing permissions
    $writableCssError = $this->check_writing( SKIN_PM_PATH );
    $writableError    = $this->check_writing( UPLOAD_PM_PATH );

    $otw_pm_lists = get_option( 'otw_pm_lists' );

    if( !empty( $action['action'] ) && $action['action'] === 'delete' ) {
      $list_id = otw_get( 'otw-pm-list-id', '' );
      $item = 'otw-pm-list-'.$list_id;
      
      unset( $otw_pm_lists['otw-pm-list'][ $item ] );

      update_option( 'otw_pm_lists', $otw_pm_lists );

    }
    require_once('views' . DS . 'otw_portfolio_manager_list.php');
  }

  /**
   * OTW Portfolio Manager Copy List
   */
  public function pm_copy () {
  
	include( 'include' . DS . 'content.php' );
	
	if( !empty(otw_get( 'otw-pm-list-id', '' )) ){
		$listID = (int) otw_get( 'otw-pm-list-id', '' );
		
		$content = $this->otwPMQuery->getItemById( $listID );
		
		$content['new_list_name'] = esc_html__('Copy of', 'otw-portfolio-manager').' '.$content['list_name'];
		
		require_once('views' . DS . 'otw_portfolio_manager_copy_list.php');
	}
  }

  /**
   * OTW Portfolio Manager Add / Edit Page
   */
  public function pm_add () {

    // Default Values 
    // $content and $widgets
    include( 'include' . DS . 'content.php' );
    
	$default_content = $content;
	
    // Edit field - used to determin if we are on an edit or add action
    $edit = false;

    // Reload $_POST data on error
    if( !empty( $this->errors ) ) {
      $content = $this->errorData;
    }

    // Edit - Load Values for current list
    if( !empty(otw_get( 'otw-pm-list-id', '' )) ) {
      
      $listID = (int) otw_get( 'otw-pm-list-id', '' );
      $nextID = $listID;
      $edit = true;
      $content = $this->otwPMQuery->getItemById( $listID );
      
		foreach( $default_content as $content_key => $content_value ){
			
			if( !array_key_exists( $content_key, $content ) ){
				$content[ $content_key ] = $content_value;
			}
		}
    }

    // Make manipulations to the $content in order to be used in the UI
    if( !empty( $content ) ) {
      // Replace escaping \ in order to display in textarea
      $content['custom_css'] = str_replace('\\', '', $content['custom_css']);

      // Select All functionality, remove all items from the list if Select All is used
      // We use this approach in order not to show any items in the text field if select all is used
      if( !empty( $content['all_categories'] ) ) { $content['categories'] = ''; }
      if( !empty( $content['all_tags'] ) ) { $content['tags'] = ''; }
      if( !empty( $content['all_users'] ) ) { $content['users'] = ''; }

      if( !array_key_exists('select_categories' , $content ) ) { $content['select_categories'] = ''; }
      if( !array_key_exists('select_tags' , $content ) ) { $content['select_tags'] = ''; }
      if( !array_key_exists('select_users' , $content ) ) { $content['select_users'] = ''; }
    }

    require_once('views' . DS . 'otw_portfolio_manager_add_list.php');
  }

  /**
   * saveAction - Validate form and save + redirect
   * @return void
   */
  public function saveAction() {
  
	global $otw_pm_factory_object, $otw_pm_plugin_id;
	
	if( !$otw_pm_factory_object->is_plugin_active( $otw_pm_plugin_id ) ){
		
		return;
	}
  
    if( !empty( $_POST ) &&  otw_post( 'submit-otw-pm-copy', false )  ){
    
	$this->errors = null;
	
	// Get Current Items in the DB
	$otw_pm_list = $this->otwPMQuery->getLists();
	
	if( empty( otw_post( 'id', '' ) ) || !isset( $otw_pm_list['otw-pm-list'] ) || !isset( $otw_pm_list['otw-pm-list']['otw-pm-list-'.otw_post( 'id', '' ) ] )){
		$this->errors['source_list_name'] = esc_html__('Source Portfolio List Not found', 'otw-portfolio-manager');
	}
	
	if( empty( otw_post( 'list_name', '' ) ) ){
		$this->errors['list_name'] = esc_html__('New Portfolio List Name is Required', 'otw-portfolio-manager');
	}
	
	// Errors have been detected persist data
	if( !empty( $this->errors ) ){
		$this->errorData = $_POST;
		return null;
	}
	
	if( isset( $otw_pm_list['otw-pm-list']['next_id'] ) ){
		
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ] = $otw_pm_list['otw-pm-list']['otw-pm-list-'.otw_post( 'id', '' ) ];
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ]['id'] = $otw_pm_list['otw-pm-list']['next_id'];
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ]['list_name'] = otw_post( 'list_name', '' );
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ]['edit'] = false;
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ]['date_created'] = date('Y/m/d');
		$otw_pm_list['otw-pm-list'][ 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'] ]['user_id'] = get_current_user_id();
		
		$source_customCssFile = SKIN_PM_PATH . DS .'otw-pm-list-'.otw_post( 'id', '' ).'-custom.css';
		$customCssFile = SKIN_PM_PATH . DS .'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'].'-custom.css';
		
		global $wp_filesystem;
		
		if( otw_init_filesystem() ){
			
			if( $wp_filesystem->exists( $source_customCssFile ) ){
				
				$css_file_content = $wp_filesystem->get_contents( $source_customCssFile );
				
				$css_file_content = str_replace( 'otw-pm-list-'.otw_post( 'id', '' ), 'otw-pm-list-'.$otw_pm_list['otw-pm-list']['next_id'], $css_file_content );
				
				$wp_filesystem->put_contents( $customCssFile, $css_file_content );
			}
		}
		$otw_pm_list['otw-pm-list']['next_id']++;
		update_option( 'otw_pm_lists', $otw_pm_list );
		
		$this->redirect('admin.php?page=otw-pm&success=true');
		exit;
	}
    
    }else if( !empty( $_POST ) &&  otw_post( 'submit-otw-pm', false )  ){
      
      $this->errors = null;

      // Check if Portfolio List Name is present
      if( empty( otw_post( 'list_name', '' ) ) ) {
        $this->errors['list_name'] = esc_html__('Portfolio List Name is Required', 'otw-portfolio-manager');
      }

      // Check if Protfolio List Template is present
      if( empty( otw_post( 'template', '' ) ) || otw_post( 'template', '' ) === 0 ) {
        $this->errors['template'] = esc_html__('Please select a Portfolio List Template', 'otw-portfolio-manager');
      }

      //Check Selection of content: Category OR Tag OR Author
      if( 
          ( empty( otw_post( 'categories', '' ) ) && empty( otw_post( 'tags', '' ) ) && empty( otw_post( 'users', '' ) ) ) &&
          ( empty( otw_post( 'all_categories', '' ) ) && empty( otw_post( 'all_tags', '' ) ) && empty( otw_post( 'all_users', '' ) ) )
        ) {
        $this->errors['content'] = esc_html__('Please select a Category or Tag or Author.', 'otw-portfolio-manager');
      }

      // Add dates created / modified to current post
      if( empty( otw_post( 'date_created', '' ) ) && empty( $this->errors ) ) {
    	otw_spost( 'date_created', date('Y/m/d') );
    	otw_spost( 'date_modified', date('Y/m/d') );
      }

      // Update modified if post is edited
      if( !empty( otw_post( 'id', '' ) ) ) {
        // Inject Date Modified into $_POST
        otw_spost( 'date_modified', date('Y/m/d') );
      }

      /** 
       * If select All functionality is used, adjust the POST
       */
      if( !empty( otw_post( 'all_categories', '' ) ) ) {
        otw_spost( 'categories', otw_post( 'all_categories', '' ) );
      }
      if( !empty( otw_post( 'all_tags', '' ) ) ) {
        otw_spost( 'tags', otw_post( 'all_tags', '' ) );
      }
      if( !empty( otw_post( 'all_users', '' ) ) ) {
        otw_spost( 'users', otw_post( 'all_users', '' ) );
      }

      // Errors have been detected persist data
      if( !empty( $this->errors ) ) {
        $this->errorData = $_POST;
        return null;
      }

      // This is a new list get the ID
      if( empty( otw_post( 'edit', '' ) ) &&  empty( $this->errors ) ) {
        $otw_pm_lists = $this->otwPMQuery->getLists();

        // This is the first list generated
        if( empty( $otw_pm_lists ) ) {
          otw_spost( 'id', 1 );
        } else {
          otw_spost( 'id', $otw_pm_lists['otw-pm-list']['next_id'] );
        }
      }

      // Assign $_POST to variable in order to fill form on error / edit
      $content = $_POST;
      

      /**
      * Create Custom CSS file for inline styles such as: Title, Meta Items, Excpert, View project
      */
      $customCssFile = SKIN_PM_PATH . DS .'otw-pm-list-'.otw_post( 'id', '' ).'-custom.css';

      // Make sure all the older CSS rules are deleted in order for a fresh save
	global $wp_filesystem;
	
	if( otw_init_filesystem() ){
		if( $wp_filesystem->exists( $customCssFile ) ) {
			$wp_filesystem->put_contents( $customCssFile, '');
		}
	}

      // Write Custom CSS
      $this->otwCSS->writeCSS( str_replace('\\', '', otw_post( 'custom_css', '' )),  $customCssFile );

      $metaStyles = array(
        'font'        => (!empty(otw_post( 'meta_font', '' )))? $this->fontsArray[ otw_post( 'meta_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'meta-color', '' )))? otw_post( 'meta-color', '' ) : '',
        'size'        => (!empty(otw_post( 'meta-font-size', '' )))? otw_post( 'meta-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'meta-font-style', '' )))? otw_post( 'meta-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-meta-wrapper'
      );

      $this->otwCSS->buildCSS( $metaStyles, $customCssFile );

      $metaLinkStyles = array(
        'font'        => (!empty(otw_post( 'meta_font', '' )))? $this->fontsArray[ otw_post( 'meta_font', '' ) ]->text : '',
        'size'        => (!empty(otw_post( 'meta-font-size', '' )))? otw_post( 'meta-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'meta-font-style', '' )))? otw_post( 'meta-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-meta-wrapper a'
      );

      $this->otwCSS->buildCSS( $metaLinkStyles, $customCssFile );

      $metaLabelStyles = array(
        'font'        => (!empty(otw_post( 'meta_font', '' )))? $this->fontsArray[ otw_post( 'meta_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'meta-color', '' )))? otw_post( 'meta-color', '' ) : '',
        'size'        => (!empty(otw_post( 'meta-font-size', '' )))? otw_post( 'meta-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'meta-font-style', '' )))? otw_post( 'meta-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-meta-wrapper .head'
      );

      $this->otwCSS->buildCSS( $metaLabelStyles, $customCssFile );

      $titleNoLinkStyles = array(
        'font'        => (!empty(otw_post( 'title_font', '' )))? $this->fontsArray[ otw_post( 'title_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'title-color', '' )))? otw_post( 'title-color', '' ) : '',
        'size'        => (!empty(otw_post( 'title-font-size', '' )))? otw_post( 'title-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'title-font-style', '' )))? otw_post( 'title-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-title'
      );

      $this->otwCSS->buildCSS( $titleNoLinkStyles, $customCssFile );

      $titleWidgetStyles = array(
        'font'        => (!empty(otw_post( 'title_font', '' )))? $this->fontsArray[ otw_post( 'title_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'title-color', '' )))? otw_post( 'title-color', '' ) : '',
        'size'        => (!empty(otw_post( 'title-font-size', '' )))? otw_post( 'title-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'title-font-style', '' )))? otw_post( 'title-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw-widget-title'
      );

      $this->otwCSS->buildCSS( $titleWidgetStyles, $customCssFile );

      $titleWLinkStyles = array(
        'font'        => (!empty(otw_post( 'title_font', '' )))? $this->fontsArray[ otw_post( 'title_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'title-color', '' )))? otw_post( 'title-color', '' ) : '',
        'size'        => (!empty(otw_post( 'title-font-size', '' )))? otw_post( 'title-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'title-font-style', '' )))? otw_post( 'title-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-title a'
      );

      $this->otwCSS->buildCSS( $titleWLinkStyles, $customCssFile );

      $excpertStyles = array(
        'font'        => (!empty(otw_post( 'excpert_font', '' )))? $this->fontsArray[ otw_post( 'excpert_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'excpert-color', '' )))? otw_post( 'excpert-color', '' ) : '',
        'size'        => (!empty(otw_post( 'excpert-font-size', '' )))? otw_post( 'excpert-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'excpert-font-style', '' )))? otw_post( 'excpert-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-content p'
      );

      $this->otwCSS->buildCSS( $excpertStyles, $customCssFile );

      $excpertWidgetStyles = array(
        'font'        => (!empty(otw_post( 'excpert_font', '' )))? $this->fontsArray[ otw_post( 'excpert_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'excpert-color', '' )))? otw_post( 'excpert-color', '' ) : '',
        'size'        => (!empty(otw_post( 'excpert-font-size', '' )))? otw_post( 'excpert-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'excpert-font-style', '' )))? otw_post( 'excpert-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw-widget-content'
      );

      $this->otwCSS->buildCSS( $excpertWidgetStyles, $customCssFile );

      $linkStyles = array(
        'font'        => (!empty(otw_post( 'read-more_font', '' )))? $this->fontsArray[ otw_post( 'read-more_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'read-more-color', '' )))? otw_post( 'read-more-color', '' ) : '',
        'size'        => (!empty(otw_post( 'read-more-font-size', '' )))? otw_post( 'read-more-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'read-more-font-style', '' )))? otw_post( 'read-more-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-continue-reading'
      );

      $this->otwCSS->buildCSS( $linkStyles, $customCssFile );

      $titleSliderStyles = array(
        'font'        => (!empty(otw_post( 'title_font', '' )))? $this->fontsArray[ otw_post( 'title_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'title-color', '' )))? otw_post( 'title-color', '' ) : '',
        'size'        => (!empty(otw_post( 'title-font-size', '' )))? otw_post( 'title-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'title-font-style', '' )))? otw_post( 'title-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-caption-title a'
      );

      $this->otwCSS->buildCSS( $titleSliderStyles, $customCssFile );

      $excpertSliderStyles = array(
        'font'        => (!empty(otw_post( 'excpert_font', '' )))? $this->fontsArray[ otw_post( 'excpert_font', '' ) ]->text : '',
        'color'       => (!empty(otw_post( 'excpert-color', '' )))? otw_post( 'excpert-color', '' ) : '',
        'size'        => (!empty(otw_post( 'excpert-font-size', '' )))? otw_post( 'excpert-font-size', '' ) : '',
        'font-style'  => (!empty(otw_post( 'excpert-font-style', '' )))? otw_post( 'excpert-font-style', '' ) : '',
        'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-caption-excpert'
      );

      $this->otwCSS->buildCSS( $excpertSliderStyles, $customCssFile );
      
      $borderStyles = array(
    	    'border-style' => (!empty(otw_post( 'border-style', '' )))? otw_post( 'border-style', '' ) : '',
    	    'border-size' => (!empty(otw_post( 'border-size', '' )))? otw_post( 'border-size', '' ) : '',
    	    'border-color' => (!empty(otw_post( 'border-color', '' )))? otw_post( 'border-color', '' ) : '',
    	    'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .with-border'
      );
      
      $this->otwCSS->buildCSS( $borderStyles, $customCssFile );
      
	if( !empty( otw_post( 'background-color', '' ) ) ){
		global $otw_pm_image_object;
		
		$bgcolors = $otw_pm_image_object->html2rgb( preg_replace( "/^\#/", '', otw_post( 'background-color', '' ) ) );
		
		if( is_array( $bgcolors ) && count( $bgcolors ) == 3 ){
			
			$opacity = '';
			
			if( otw_post( 'background-color-opacity', false ) && strlen( trim( otw_post( 'background-color-opacity', '' ) ) ) ){
				$opacity = otw_post( 'background-color-opacity', '' );
			}
			
			if( $opacity != '' ){
				$backgroundStyles = array(
					'background-color' => 'rgba('.$bgcolors[0].','.$bgcolors[1].', '.$bgcolors[2].', '.$opacity.')',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .with-bg'
				);
			}else{
				$backgroundStyles = array(
					'background-color' => 'rgb('.$bgcolors[0].','.$bgcolors[1].', '.$bgcolors[2].')',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .with-bg'
				);
			}
			
			$this->otwCSS->buildCSS( $backgroundStyles, $customCssFile );
		}
	}
	
	if( !empty( otw_post( 'hover-color', '' ) ) ){
		global $otw_pm_image_object;
		
		$hover_colors = $otw_pm_image_object->html2rgb( preg_replace( "/^\#/", '', otw_post( 'hover-color', '' ) ) );
		
		if( is_array( $hover_colors ) && count( $hover_colors ) == 3 ){
		
			if( isset( $content['image_hover'] ) && in_array( $content['image_hover'], array( 'otw_portfolio_manager-hover-effect-18', 'otw_portfolio_manager-hover-effect-19' ) ) ){
				$hover18Styles = array(
					'background-color' => 'rgba('.$hover_colors[0].','.$hover_colors[1].', '.$hover_colors[2].', 0.5)',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-hover-effect-18 .otw_portfolio_manager-portfolio-overlay .otw_portfolio_manager-portfolio-title-with-meta'
				);
				$this->otwCSS->buildCSS( $hover18Styles, $customCssFile );
				
				$hover19Styles = array(
					'background-color' => 'rgba('.$hover_colors[0].','.$hover_colors[1].', '.$hover_colors[2].', 0.5)',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-hover-effect-19 .otw_portfolio_manager-portfolio-overlay .otw_portfolio_manager-portfolio-title-with-meta'
				);
				$this->otwCSS->buildCSS( $hover19Styles, $customCssFile );
			}else{
				$hoverStyles = array(
					'background-color' => 'rgba('.$hover_colors[0].','.$hover_colors[1].', '.$hover_colors[2].', 0.5)',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-portfolio-overlay:hover'
				);
				$this->otwCSS->buildCSS( $hoverStyles, $customCssFile );
				
				$hover5Styles = array(
					'box-shadow' => '0 0 0 5px '.otw_post( 'hover-color', '' ).' inset',
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-hover-effect-5 .otw_portfolio_manager-portfolio-media.otw_portfolio_manager-format-image:hover .otw-hover-effect'
				);
				$this->otwCSS->buildCSS( $hover5Styles, $customCssFile );
				
				$hover12Styles = array(
					'box-shadow' => '0 0 7px '.otw_post( 'hover-color', '' ),
					'container'   => '#otw-pm-list-'.otw_post( 'id', '' ).' .otw_portfolio_manager-hover-effect-12 .otw_portfolio_manager-portfolio-media.otw_portfolio_manager-format-image:hover .otw-hover-effect'
				);
				$this->otwCSS->buildCSS( $hover12Styles, $customCssFile );
			}
			
		}
    		
      }
          
      
      
      // Get Current Items in the DB
      $otw_pm_list = $this->otwPMQuery->getLists();

      // Create new entry 
      $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ] = $_POST;
      
	//reformat select2 values
	$select2_vars = array( 'categories', 'tags', 'users', 'exclude_categories', 'exclude_tags', 'exclude_users' );
	
	foreach( $select2_vars as $select2_name ){
	
		if( isset( $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] ) && is_array( $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] ) ){
			
			if( count( $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] ) ){
				$otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] = implode( ',', $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] );
			}else{
				$otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] = '';
			}
		}else{
			$otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $select2_name ] = '';
		}
	}
	
	$default_empty_fields = array( 'show-social-icons-facebook', 'show-social-icons-twitter', 'show-social-icons-googleplus', 'show-social-icons-linkedin', 'show-social-icons-pinterest' );
	
	foreach( $default_empty_fields as $f_key ){
		
		if( !array_key_exists( $f_key, $otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ] ) ){
			$otw_pm_list_data['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ][ $f_key ] = 0;
		}
	}


      // We setup the next_id value. This will apply to the first save only
      if( empty($otw_pm_list['otw-pm-list']['next_id']) && empty( otw_post( 'edit', '' ) ) ) {
        // We assume this is the first save with ID is 1, next ID has to be 2. Count starts from 1 because of short-code
        $otw_pm_list_data['otw-pm-list']['next_id'] = 2;      
      } elseif ( empty( otw_post( 'edit', '' ) ) ) {
        $otw_pm_list['otw-pm-list']['next_id'] = $otw_pm_list['otw-pm-list']['next_id'] + 1;
        $otw_pm_list_data['otw-pm-list']['next_id'] =  $otw_pm_list['otw-pm-list']['next_id'];
      }

      // Merge the 2 arrays
      if ( $otw_pm_list === false || empty( $otw_pm_list ) ) {
        $listData = $otw_pm_list_data;
      } elseif ( !empty($otw_pm_list) ) {
        // Do not remove the 'otw-pm-list' from they array_merge. There is a strange behavior related to this
        $listData['otw-pm-list'] = array_merge( $otw_pm_list['otw-pm-list'], $otw_pm_list_data['otw-pm-list'] );
      }

      // Update
      if( empty($this->errors) ) {
        
        // Get $widget from included file
        include( 'include' . DS . 'content.php' );

        if( in_array( otw_post( 'template', '' ), $widgets) ) {
          // It's a widget
          $listData['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ]['widget'] = 1;
        } else {
          // It's NOT a Widget
          $listData['otw-pm-list'][ 'otw-pm-list-' . otw_post( 'id', '' ) ]['widget'] = 0;
        }

        update_option( 'otw_pm_lists', $listData );
        
        $this->redirect('admin.php?page=otw-pm-add&action=edit&otw-pm-list-id='.otw_post( 'id', '' ).'&success=true');
        exit;
        
      } // End update

    } // End if (!empty($_POST))
  }

	/*
	* Single portfolio template
	*/
	public function otw_pm_portfolio_template(){
		
		
		global $post, $otw_pm_grid_manager_object;
		
		if( is_single() && !is_archive() && isset( $post->post_type ) && ( $post->post_type == $this->portfolio_post_type ) ){	
			
			$this->otwDispatcher->otw_custom_templates = $this->get_custom_templates();
			
			$this->otwDispatcher->grid_manager_component_object = $otw_pm_grid_manager_object;
			
			$this->otwDispatcher->buildPortfolioTemplate( $post, $this->get_details() );
		}
	}
	
	function otw_pm_portfolio_thumbnail_metadata( $value, $post_id, $meta_key, $single ){
		
		if( ( get_post_type( $post_id ) == $this->portfolio_post_type ) && ( $meta_key == '_thumbnail_id' ) ){
			
			if( is_archive() ){
				
				$otw_portfolio_meta_data = get_post_meta( $post_id, 'otw_pm_meta_data', true );
				
				if( is_array( $otw_portfolio_meta_data ) && count( $otw_portfolio_meta_data ) ){
					return 1;
				}
			}
		}
		return $value;
	}
	
	function otw_pm_portfolio_thumbnail( $html, $post_id, $post_thumbnail_id, $size, $attr ){
		
		if( get_post_type( $post_id ) == $this->portfolio_post_type ){
			
			$html = $this->otwDispatcher->getArchiveMedia( $post_id );
			
		}
		return $html;
	}
	public function pm_details_action(){
	
		$page_title = '';
		
		$otw_action = '';
		$details = get_option( 'otw_pm_portfolio_details' );
		$confirm_text = '';
		$otw_detail_values = array();
		$otw_detail_values['title'] = esc_html__( 'N/A', 'otw-portfolio-manager' );
		
		if( otw_get('action',false) ){
			
			switch( otw_get('action','') ){
			
				case 'delete':
						$otw_action = 'delete_otw_pm_detail';
						$page_title = esc_html__( 'Delete detail', 'otw-portfolio-manager' );
						$confirm_text = esc_html__( 'Please confirm to delete the detail', 'otw-portfolio-manager' );
						
						if( otw_get( 'detail', false ) && preg_match( "/^\d+$/", otw_get( 'detail', '' ) ) && intval( otw_get( 'detail', '' ) ) && array_key_exists( otw_get( 'detail', '' ), $details ) ){
							$otw_detail_values['title'] = $details[ otw_get( 'detail', '' ) ]['title'];
						}
					break;
				default:
					    $page_title = esc_html__( 'Invalid action', 'otw-portfolio-manager' );
					break;
			}
		}else{
			$page_title = esc_html__( 'Invalid action', 'otw-portfolio-manager' );
		}
		
		require_once('views' . DS . 'otw_portfolio_manager_details_action.php');
	}
	
	public function pm_details(){
		
		$details = $this->get_details();
		
		require_once('views' . DS . 'otw_portfolio_manager_details.php');
	}
	
	public function pm_details_edit(){
		
		$page_title = 'Add Detail';
		
		$details = get_option( 'otw_pm_portfolio_details' );
		
		$otw_pm_detail_values = array();
		$otw_pm_detail_values['title'] = '';
		$otw_pm_detail_values['order'] = '';
		
		if( otw_get( 'detail', false ) && preg_match( "/^\d+$/", otw_get( 'detail', '' ) ) && intval( otw_get( 'detail', '' ) ) && array_key_exists( otw_get( 'detail', '' ), $details ) ){
			
			$page_title = 'Edit Detail';
			
			$otw_pm_detail_values['title'] = $details[ otw_get( 'detail', '' ) ]['title'];
			$otw_pm_detail_values['order'] = $details[ otw_get( 'detail', '' ) ]['order'];
		}else{
		
			$max_order = 0;
			foreach( $details as $detail ){
				if( $detail['order'] >= $max_order ){
					$max_order = $detail['order'] + 1;
				}
			}
			$otw_pm_detail_values['order'] = $max_order;
		}
		
		if( otw_post( 'otw_pm_action', false ) && ( otw_post( 'otw_pm_action', '' ) == 'manage_otw_pm_detail' ) ){
		
			$otw_pm_detail_values['title'] = otw_stripslashes( otw_post( 'pm_detail_title', '' ) );
			$otw_pm_detail_values['order'] = otw_stripslashes( otw_post( 'pm_detail_order', '' ) );
		}
		
		require_once('views' . DS . 'otw_portfolio_manager_details_manage.php');
	}
	
	public function pm_custom_templates(){
		
		$otw_custom_templates = $this->get_custom_templates();
		
		require_once('views' . DS . 'otw_portfolio_manager_custom_templates.php');
	}
	
	public function pm_import_from_light(){
		
		//get all posts that we have registered from the light plugin
		$args = array(
			'post_type' => 'otw-portfolio',
			'posts_per_page' => '-1'
		);
		$light_items = new WP_Query( $args );
		
		require_once('views' . DS . 'otw_portfolio_manager_import_from_light.php');
	}
	
	public function pm_custom_templates_edit(){
		
		global $otw_pm_grid_manager_object;
		
		$page_title = 'Add Single Posts Template';
		
		$custom_templates = $this->get_custom_templates();
		
		$otw_pm_custom_template_values = array();
		$otw_pm_custom_template_values['title'] = '';
		$otw_pm_custom_template_values['maxwidth'] = '';
		$otw_pm_custom_template_values['grid_content'] = '';
		
		
		if( otw_get( 'custom_template', false ) && preg_match( "/^\d+$/", otw_get( 'custom_template', '' ) ) && intval( otw_get( 'custom_template', '' ) ) && array_key_exists( otw_get( 'custom_template', '' ), $custom_templates ) ){
			
			$page_title = 'Edit Single Posts Template';
			
			$otw_pm_custom_template_values['title'] = $custom_templates[ otw_get( 'custom_template', '' ) ]['title'];
			$otw_pm_custom_template_values['grid_content'] = otw_stripslashes( $custom_templates[ otw_get( 'custom_template', '' ) ]['grid_content'] );
			
			if( isset( $custom_templates[ otw_get( 'custom_template', '' ) ]['maxwidth'] ) )
			{
				$otw_pm_custom_template_values['maxwidth'] = $custom_templates[ otw_get( 'custom_template', '' ) ]['maxwidth'];
			}
		}
		
		if( otw_post( 'otw_pm_action', false ) && ( otw_post( 'otw_pm_action', '' ) == 'manage_otw_pm_custom_templates' ) ){
		
			$otw_pm_custom_template_values['title'] = otw_stripslashes( otw_post( 'pm_custom_template_title', '' ) );
			$otw_pm_custom_template_values['grid_content'] = otw_post( array( '_otw_portfolio_template_grid_manager_content', 'code' ), '' );
			
			if( otw_post( 'pm_custom_template_maxwidth', false ) )
			{
				$otw_pm_custom_template_values['maxwidth'] = otw_stripslashes( otw_post( 'pm_custom_template_maxwidth', '' ) );
			}
		}
		
		
		require_once('views' . DS . 'otw_portfolio_manager_custom_templates_manage.php');
		
	}
	
	public function pm_backup(){
		
		global $otw_pm_validate_messages;
		
		global $wp_filesystem;
		
		if( otw_init_filesystem() ){
			
			$writableCssError = $wp_filesystem->is_writable( SKIN_PM_PATH );
			
			if( !$writableCssError ){
				$otw_pm_validate_messages[] = 'Please make sure you have write permitions to '.SKIN_PM_PATH;
			}
		}else{
			$otw_pm_validate_messages[] = 'Please make sure you have write permitions to '.SKIN_PM_PATH;
		}
		
		$otw_backup_values = array();
		$otw_backup_values['otw_pm_export_pm_posts'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_categories'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_tags'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_details'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_lists'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_settings'] = 'yes';
		$otw_backup_values['otw_pm_export_pm_custom_templates'] = 'yes';
		$otw_backup_values['otw_pm_export_pages'] = 'no';
		
		foreach( $otw_backup_values as $key => $value ){
			if( otw_post( $key, false ) ){
				$otw_backup_values[ $key ] = otw_post( $key, '' );
			}
		}
		
		$files_size_warning = '';
		if( ini_get( 'upload_max_filesize' ) && ini_get( 'post_max_size' ) ){
			$files_size_warning .= esc_html__( 'Please make sure that the backup file has smaller size than the limits set by your server configuration.', 'otw-portfolio-manager' );
			$files_size_warning .= '<br />';
			$files_size_warning .= esc_html__( 'Max Upload File Size', 'otw-portfolio-manager' ).': '.ini_get( 'upload_max_filesize' ).'<br />';
			$files_size_warning .= esc_html__( 'Max Post Size', 'otw-portfolio-manager' ).': '.ini_get( 'post_max_size' );
		}
		
		require_once('views' . DS . 'otw_portfolio_manager_backup.php');
	}
	
	public function pm_custom_templates_action(){
	
		$page_title = '';
		
		$otw_action = '';
		$custom_templates = $this->get_custom_templates();
		
		$confirm_text = '';
		$otw_custom_template_values = array();
		$otw_custom_template_values['title'] = esc_html__( 'N/A', 'otw-portfolio-manager' );
		
		if( otw_get('action',false) ){
			
			switch( otw_get('action','') ){
			
				case 'delete':
						$otw_action = 'delete_otw_pm_custom_template';
						$page_title = esc_html__( 'Delete custom template', 'otw-portfolio-manager' );
						$confirm_text = esc_html__( 'Please confirm to delete the custom template', 'otw-portfolio-manager' );
						
						if( otw_get( 'custom_template', false ) && preg_match( "/^\d+$/", otw_get( 'custom_template', '' ) ) && intval( otw_get( 'custom_template', '' ) ) && array_key_exists( otw_get( 'custom_template', '' ), $custom_templates ) ){
							$otw_custom_template_values['title'] = $custom_templates[ otw_get( 'custom_template', '' ) ]['title'];
						}
					break;
				case 'copy':
						$otw_action = 'copy_otw_pm_custom_template';
						$page_title = esc_html__( 'Duplicate custom template', 'otw-portfolio-manager' );
						$confirm_text = esc_html__( 'Please confirm to duplicate the custom template', 'otw-portfolio-manager' );
						
						if( otw_get( 'custom_template', false ) && preg_match( "/^\d+$/", otw_get( 'custom_template', '' ) ) && intval( otw_get( 'custom_template', '' ) ) && array_key_exists( otw_get( 'custom_template', '' ), $custom_templates ) ){
							$otw_custom_template_values['title'] = $custom_templates[ otw_get( 'custom_template', '' ) ]['title'];
						}
					break;
				default:
					    $page_title = esc_html__( 'Invalid action', 'otw-portfolio-manager' );
					break;
			}
		}else{
			$page_title = esc_html__( 'Invalid action', 'otw-portfolio-manager' );
		}
		
		require_once('views' . DS . 'otw_portfolio_manager_custom_templates_action.php');
	}
  /**
   * OTW Portfolio Manager Settings Page
   */
  public function pm_settings () {
  
    global $otw_pm_plugin_id;
    
    $customCss = '';
    $cssPath = SKIN_PM_PATH . DS . 'custom.css';

    // Check if writing permissions
    $writableCssError = $this->check_writing( SKIN_PM_PATH );
    
    // Open File for edit
    if( empty( $_POST ) && !$writableCssError  ) {
	
	global $wp_filesystem;
		
	if( otw_init_filesystem() ){
		
		if( $wp_filesystem->exists( $cssPath ) ){
			$customCss = $wp_filesystem->get_contents( $cssPath );
		}else{
			$customCss = '';
		}
	}
        
    }

    // Save File on disk and redirect.
	if( !empty( $_POST ) && otw_post( 'otw_pm_save_settings', false ) && ( otw_post( 'otw_pm_save_settings', '' ) == 1 ) )
	{
		$otw_pm_plugin_options = get_option( 'otw_pm_plugin_options' );
		
		$portfolio_settings = array( 'otw_pm_template', 'otw_pm_social_icons', 'otw_pm_prev_next_nav', 'otw_pm_related_posts', 'otw_pm_portfolio_slug', 'otw_pm_portfolio_category_slug', 'otw_pm_portfolio_tag_slug', 'otw_pm_description_title_text', 'otw_pm_details_title_text', 'otw_pm_related_title_text', 'otw_pm_archive_media_width', 'otw_pm_archive_media_height', 'otw_pm_archive_media_format','otw_pm_item_media_width', 'otw_pm_item_media_height', 'otw_pm_item_media_format', 'otw_pm_related_media_width', 'otw_pm_related_media_height', 'otw_pm_related_media_format' ,'otw_pm_related_posts_number', 'otw_pm_item_title', 'otw_pm_moreinfo_title_text', 'otw_pm_media_lightbox', 'otw_pm_item_media_lightbox_width', 'otw_pm_item_media_lightbox_height', 'otw_pm_item_media_lightbox_format', 'otw_pm_social_title_text', 'otw_pm_related_posts_criteria', 'otw_pm_grid_pages', 'otw_pm_item_media_title_attr', 'otw_pm_item_media_alt_attr' );
		
		foreach( $portfolio_settings as $setting_key )
		{
			$otw_pm_plugin_options[ $setting_key ] = '';
			
			if( otw_post( $setting_key, false ) ){
				
				$otw_pm_plugin_options[ $setting_key ] = otw_stripslashes( otw_post( $setting_key, '' ) );
				
			}
		}
		
		update_option( 'otw_pm_plugin_options', $otw_pm_plugin_options );
		
		if( otw_post( 'otw_pm_promotions', false ) && !empty( otw_post( 'otw_pm_promotions', '' ) ) ){
			
			global $otw_pm_factory_object;
			
			update_option( $otw_pm_plugin_id.'_dnms', otw_post( 'otw_pm_promotions', '' ) );
			
			if( is_object( $otw_pm_factory_object ) ){
				$otw_pm_factory_object->retrive_plungins_data( true );
			}
		}
		
		$customCSS = str_replace('\\', '', otw_post( 'otw_css', '' ));
		
		global $wp_filesystem;
		
		if( otw_init_filesystem() ){
			$wp_filesystem->put_contents( $cssPath, $customCSS );
		}
		echo "<script>window.location = 'admin.php?page=otw-pm-settings&success_css=true';</script>";
		die;
	}
	
	$import_from_light = post_type_exists( 'otw-portfolio' );
	
	require_once('views' . DS . 'otw_portfolio_manager_settings.php');
  }

  /**
   * Check Writing Permissions
   */
  public function check_writing( $path ) {
    
	global $wp_filesystem;
	
	$writableCssError = false;
	
	if( otw_init_filesystem() ){
		
		if( !$wp_filesystem->is_writable( $path ) ) {
			$writableCssError = true;
		}
	}

	return $writableCssError;
  }


  /*****
    Front End Related Actions
   ****/

  /**
   * Load Lists on the Front End using short code
   * @param $attr - array
   */
  public function pm_list_shortcode( $attr ) {

	global $otw_pm_factory_object, $otw_pm_plugin_id;
	
	if( !$otw_pm_factory_object->is_plugin_active( $otw_pm_plugin_id ) ){
		
		return;
	} 
	
    $listID = $attr['id'];

    // Get Current Items in the DB
    $otw_pm_options = $this->otwPMQuery->getItemById( $listID );

    if( !empty( $otw_pm_options ) ) {

	global $wp_filesystem;
		
	if( otw_init_filesystem() ){
		// Enqueue Custom Styles CSS
		if( $wp_filesystem->exists(SKIN_PM_PATH . DS . 'otw-pm-list-'.$listID.'-custom.css') ) {
			wp_register_style( 'otw-pm-custom-css-'.$listID, SKIN_PM_URL .'otw-pm-list-'.$listID.'-custom.css' );
			wp_enqueue_style( 'otw-pm-custom-css-'.$listID );
		}
	}

      $customFonts = array(
        'title'         => !empty( $otw_pm_options['title_font'] )?$otw_pm_options['title_font']:'',
        'meta'          => !empty( $otw_pm_options['meta_font'])?$otw_pm_options['meta_font']:'',
        'excpert'       => !empty( $otw_pm_options['excpert_font'])?$otw_pm_options['meta_font']:'',
        'continue_read' => !empty( $otw_pm_options['read-more_font'])?$otw_pm_options['meta_font']:''
      );

      $googleFonts = $this->otwCSS->getGoogleFonts( $customFonts, $this->fontsArray  );
      
      if( !empty( $googleFonts ) ) {
        $httpFonts = (!empty($_SERVER['HTTPS'])) ? "https" : "http";
        $url = $httpFonts.'://fonts.googleapis.com/css?family='.$googleFonts.'&variant=italic:bold';
        wp_enqueue_style('otw-pm-googlefonts',$url, null, null);
      }
      
      // Load $templateOptions - array
      include('include' . DS . 'content.php');

      $currentPage = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

      $otw_posts_result = $this->otwPMQuery->getPosts( $otw_pm_options, $currentPage );

      return $this->otwDispatcher->generateTemplate( $otw_pm_options, $otw_posts_result, $templateOptions );

    } else {
      $errorMsg = '<p>';
      $errorMsg .= esc_html__('Woops, we have encountered an error. The List you are trying to use can not be found: ', 'otw-portfolio-manager');
      $errorMsg .= 'otw-pm-list-'.$attr['id'].'<br/>';
      $errorMsg .= '</p>';

      return $errorMsg;
    }
  }

  /**
   * Load Widget Class
   * Init Widget Class
   */
  public function pm_register_widgets () {
	
	register_widget( 'OTWPM_Widget' );
  }

  /**
   * Load Resources for FE - CSS and JS
   */
  public function register_fe_resources () {
    $uniqueHash = wp_create_nonce("otw_pm_social_share"); 
    $socialShareLink = admin_url( 'admin-ajax.php?action=pm_social_share&nonce='. $uniqueHash );

    wp_register_script( 
      'otw-pm-fancybox', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'jquery.fancybox.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-flexslider', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'jquery.flexslider.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-infinitescroll', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'jquery.infinitescroll.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-imagesloaded', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'imagesloaded.pkgd.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-isotope', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'isotope.pkgd.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-pixastic', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'pixastic.custom.min.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-fitvid',
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'jquery.fitvids.js', 
      array( 'jquery' )
    );
    wp_register_script( 
      'otw-pm-main-script', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'js'. DS .'script.js', 
      array( 'jquery', 'jquery-ui-accordion', 'jquery-ui-tabs' ), '', true
    );

    // Custom Scripts + Plugins
    wp_enqueue_script( 'otw-pm-fancybox' );
    wp_enqueue_script( 'otw-pm-flexslider' );
    wp_enqueue_script( 'otw-pm-infinitescroll' );
    wp_enqueue_script( 'otw-pm-imagesloaded' );
    wp_enqueue_script( 'otw-pm-isotope' );
    wp_enqueue_script( 'otw-pm-pixastic' );
    wp_enqueue_script( 'otw-pm-fitvid' );
    wp_enqueue_script( 'otw-pm-main-script' );

	$otw_js_labels = array( 'otw_pm_loading_text' =>__( 'Loading items...', 'otw-portfolio-manager' ),
			    'otw_pm_no_more_posts_text' => esc_html__( 'No More Items Found', 'otw-portfolio-manager' )
			);
	wp_add_inline_script( 'otw-pm-main-script', 'var otw_pm_js_labels = '.json_encode( $otw_js_labels ).';', 'before' );
	wp_add_inline_script( 'otw-pm-main-script', 'var socialShareURL = "'.$socialShareLink.'";', 'before' ); 
    
    wp_register_style( 
      'otw-pm-default', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'css'. DS .'default.css' 
    );

    wp_register_style( 
      'otw-pm-font-awesome', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'css'. DS .'font-awesome.min.css' 
    );
    wp_register_style( 
      'otw-pm-pm', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'css'. DS .'otw-portfolio-manager.css' 
    );

    wp_register_style( 
      'otw-pm-grid', 
      plugins_url() . DS . OTW_PM_PATH . DS .'frontend'. DS .'css'. DS .'otw-grid.css' 
    );
	
	global $wp_filesystem;
		
	if( otw_init_filesystem() ){
		if( $wp_filesystem->is_file( SKIN_PM_PATH . DS . 'custom.css' ) ){
			wp_register_style( 'otw-pm-custom', SKIN_PM_URL .'custom.css'  );
		}
	}
	
	wp_enqueue_style( 'otw-pm-grid' );
	wp_enqueue_style( 'otw-pm-pm' );
	wp_enqueue_style( 'otw-pm-font-awesome' );
	wp_enqueue_style( 'otw-pm-default' );
	
		
	if( otw_init_filesystem() ){
		if( $wp_filesystem->is_file( SKIN_PM_PATH . DS . 'custom.css' ) ){
			wp_enqueue_style( 'otw-pm-custom' );
		}
	}

  }


	function otw_rewrite_rules(){
		
		$last_update = get_option( 'otw_pm_rewrite_rules' );
		
		if( !$last_update || ( $last_update < strtotime( 'now -24 hours' ) ) ){
			flush_rewrite_rules();
			$last_update = time();
			update_option( 'otw_pm_rewrite_rules', $last_update );
		}
	}

  public function otw_pm_get_posts () {
    // Load $templateOptions - array
    include('include' . DS . 'content.php');

    $otw_pm_options = $this->otwPMQuery->getItemById( otw_get( 'post_id', '' ) );
    $otw_pm_results = $this->otwPMQuery->getPosts( $otw_pm_options, otw_get( 'page', '' ) );
    $paginationPageNo = (int) otw_get( 'page', '' ) + 1;

    if( !empty($otw_pm_results->posts) ) {
      echo $this->otwDispatcher->generateTemplate( $otw_pm_options, $otw_pm_results, $templateOptions, true, $paginationPageNo );
    } else {
      echo ' ';  
    }
    exit;
  }

	public function otw_pm_get_video(){
	
		$post_id = 0;
		
		if( otw_get( 'post_id', false ) && intval( otw_get( 'post_id', '' ) ) ){
			$post_id = otw_get( 'post_id', '' );
			$list_id = 0;
			
			$view_type = '';
			
			if( otw_get( 'vr', false ) && (  otw_get( 'vr', '' ) == 'item_media' ) ){
				$view_type =  otw_get( 'vr', '' );
			}
			elseif( otw_get( 'vr', false ) && (  otw_get( 'vr', '' ) == 'list_media' ) ){
			
				if( otw_get( 'list_id', false ) && intval( otw_get( 'list_id', '' ) ) ){
					$list_id = otw_get( 'list_id', '' );
					$view_type =  otw_get( 'vr', '' );
				}
			}
			
			if( $post_id ){
				$post = get_post( $post_id );
				
				if( isset( $post->ID ) && ( $post->post_type == $this->portfolio_post_type ) ){
					
					$postMetaData = get_post_meta( $post->ID, 'otw_pm_meta_data', true );
					
					if( $view_type == 'item_media' ){
						
						$this->otwDispatcher->otwImageCrop = new OTWPMImageCrop();
						
						$videoWidth = '1024';
						$videoHeight = '640';
						
						$item_options = get_post_meta( $post->ID, 'otw_pm_options_meta_data', true );
						
						if( isset( $item_options['otw_pm_options_type'] ) && ( $item_options['otw_pm_options_type'] == 'custom' ) ){
							
							if( isset( $item_options['options'] ) ){
							
								if( isset( $item_options['options']['otw_pm_item_media_lightbox_width'] ) && strlen( $item_options['options']['otw_pm_item_media_lightbox_width'] ) ){
									$videoWidth = $item_options['options']['otw_pm_item_media_lightbox_width'];
								}
								
								if( isset( $item_options['options']['otw_pm_item_media_lightbox_height'] ) && strlen( $item_options['options']['otw_pm_item_media_lightbox_height'] ) ){
									$videoHeight = $item_options['options']['otw_pm_item_media_lightbox_height'];
								}
							}
						}else{
							if( isset( $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_width'] ) && strlen( $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_width'] ) ){
								$videoWidth = $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_width'];
							}
							
							if( isset( $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_height'] ) && strlen( $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_height'] ) ){
								$videoHeight = $this->otw_pm_plugin_options['otw_pm_item_media_lightbox_height'];
							}
						}
					}elseif( $view_type == 'list_media' ){
						
						$this->otwDispatcher->otwImageCrop = new OTWPMImageCrop();
						
						$videoWidth = '1024';
						$videoHeight = '640';
						
						$listOptions = $this->otwPMQuery->getItemById( $list_id );
						
						if( isset( $listOptions['lightbox_thumb_width'] ) && strlen( $listOptions['lightbox_thumb_width'] ) ){
							$videoWidth = $listOptions['lightbox_thumb_width'];
						}
						if( isset( $listOptions['lightbox_thumb_height'] ) && strlen( $listOptions['lightbox_thumb_height'] ) ){
							$videoHeight = $listOptions['lightbox_thumb_height'];
						}
						
					}
					
					if( isset( $postMetaData['media_type'] ) ){
					
						switch( $postMetaData['media_type'] ){
						
							case 'youtube':
									if( !empty( $postMetaData['youtube_url'] ) ){
										
										if( in_array( $view_type, array( 'item_media', 'list_media' ) ) ){
											echo $this->otwDispatcher->otwImageCrop->embed_resize( $this->otwDispatcher->oembed_get($postMetaData['youtube_url'], array('width' => $videoWidth)), $videoWidth, $videoHeight, 'center_center' );
										}else{
											echo $this->otwDispatcher->oembed_get( $postMetaData['youtube_url'] );
										}
										die;
									}
								break;
							case 'vimeo':
									if( !empty( $postMetaData['vimeo_url'] ) ){
										
										if( in_array( $view_type, array( 'item_media', 'list_media' ) ) ){
											echo $this->otwDispatcher->otwImageCrop->embed_resize( $this->otwDispatcher->oembed_get($postMetaData['vimeo_url'], array('width' => $videoWidth)), $videoWidth, $videoHeight, 'center_center' );
										}else{
											echo $this->otwDispatcher->oembed_get( $postMetaData['vimeo_url'] );
										}
										die;
									}
								break;
							case 'soundcloud':
									if( !empty( $postMetaData['soundcloud_url'] ) ){
										
										if( in_array( $view_type, array( 'item_media', 'list_media' ) ) ){
											echo $this->otwDispatcher->otwImageCrop->embed_resize( $this->otwDispatcher->oembed_get($postMetaData['soundcloud_url'], array('width' => $videoWidth)), $videoWidth, $videoHeight, 'center_center' );
										}else{
											echo $this->otwDispatcher->oembed_get( $postMetaData['soundcloud_url'] );
										}
										die;
									}
								break;
						}
					}
				}
			}
		}
		_e( 'Video not found', 'otw-portfolio-manager' );
		die;
	}

  public function otw_pm_social_share () {
    include( 'social-shares.php' );
    
    if( otw_post( 'url', false )  && otw_post( 'url', '' ) != '' && filter_var(otw_post( 'url', '' ), FILTER_VALIDATE_URL)){
      $url = otw_post( 'url', '' );
      $otw_social_shares = new otw_social_shares($url);
      
      echo $otw_social_shares->otw_get_shares();
    } else {
      echo json_encode(array('info' => 'error', 'msg' => 'URL is not valid!'));
    }
    exit;
  }
  
	public function redirect( $location ){
		
		header("Location: $location" );
		
		return true;
	}
	
	public function get_select2_options(){
	
		$options = array();
		$options['results'] = array();
		
		$options_type = '';
		$options_limit = 100;
		
		if( otw_post( 'otw_options_type', false ) ){
			$options_type = otw_post( 'otw_options_type', '' );
		}
		
		if( otw_post( 'otw_options_limit', false ) ){
			$options_limit = otw_post( 'otw_options_limit', '' );
		}
		
		switch( $options_type ){
			
			case 'otw_pm_category':
					$args = array();
					$args['hide_empty']      = 0;
					$args['number']          = $options_limit;
					
					if( otw_post( 'otw_options_ids', false ) && strlen( otw_post( 'otw_options_ids', '' ) ) ){
						
						$args['include'] = array();
						$include_items = explode( ',', otw_post( 'otw_options_ids', '' ) );
						
						foreach( $include_items as $i_item ){
							
							if( intval( $i_item ) ){
								$args['include'][] = $i_item;
							}
						}
					}
					
					if( otw_post( 'otw_options_search', false ) && strlen( otw_post( 'otw_options_search', '' ) ) ){
						$args['search'] = urldecode( otw_post( 'otw_options_search', '' ) );
					}
					
					$all_items = get_terms( $this->portfolio_category, $args );
					
					if( is_array( $all_items ) && count( $all_items ) ){
						foreach( $all_items as $item ){
							$o_key = count( $options['results'] );
							$options['results'][ $o_key ] = array();
							$options['results'][ $o_key ]['id'] = $item->term_id;
							$options['results'][ $o_key ]['text'] = $item->name;
						}
					}
				break;
			case 'otw_pm_tag':
					$args = array();
					$args['hide_empty']      = 0;
					$args['number']          = $options_limit;
					
					if( otw_post( 'otw_options_ids', false ) && strlen( otw_post( 'otw_options_ids', '' ) ) ){
						
						$args['include'] = array();
						$include_items = explode( ',', otw_post( 'otw_options_ids', '' ) );
						
						foreach( $include_items as $i_item ){
							
							if( intval( $i_item ) ){
								$args['include'][] = $i_item;
							}
						}
					}
					
					if( otw_post( 'otw_options_search', false ) && strlen( otw_post( 'otw_options_search', '' ) ) ){
						$args['search'] = urldecode( otw_post( 'otw_options_search', '' ) );
					}
					
					$all_items = get_terms( $this->portfolio_tag, $args );
					
					if( is_array( $all_items ) && count( $all_items ) ){
						foreach( $all_items as $item ){
							$o_key = count( $options['results'] );
							$options['results'][ $o_key ] = array();
							$options['results'][ $o_key ]['id'] = $item->term_id;
							$options['results'][ $o_key ]['text'] = $item->name;
						}
					}
				break;
			case 'user':
					$args = array();
					
					if( otw_post( 'otw_options_ids', false ) && strlen( otw_post( 'otw_options_ids', '' ) ) ){
						
						$args['include'] = array();
						$include_items = explode( ',', otw_post( 'otw_options_ids', '' ) );
						
						foreach( $include_items as $i_item ){
							
							if( intval( $i_item ) ){
								$args['include'][] = $i_item;
							}
						}
					}
					
					if( otw_post( 'otw_options_search', false ) && strlen( otw_post( 'otw_options_search', '' ) ) ){
						$args['search'] = '*'.urldecode( otw_post( 'otw_options_search', '' ) ).'*';
					}
					
					$all_items = get_users( $args );
					
					if( is_array( $all_items ) && count( $all_items ) ){
						foreach( $all_items as $item ){
							$o_key = count( $options['results'] );
							$options['results'][ $o_key ] = array();
							$options['results'][ $o_key ]['id'] = $item->ID;
							$options['results'][ $o_key ]['text'] = $item->user_login;
						}
					}
				break;
			case 'page':
					$args = array();
					$args['post_type'] = 'page';
					$args['number']          = $options_limit;
					
					if( otw_post( 'otw_options_ids', false ) && strlen( otw_post( 'otw_options_ids', '' ) ) ){
						
						$args['post__in'] = array();
						$include_items = explode( ',', otw_post( 'otw_options_ids', '' ) );
						
						foreach( $include_items as $i_item ){
							
							if( intval( $i_item ) ){
								$args['post__in'][] = $i_item;
							}
						}
					}
					
					if( otw_post( 'otw_options_search', false ) && strlen( otw_post( 'otw_options_search', '' ) ) ){
						$args['s'] = urldecode( otw_post( 'otw_options_search', '' ) );
					}
					
					$query = new WP_Query( $args );
					$all_items = $query->posts;
					
					if( is_array( $all_items ) && count( $all_items ) ){
						foreach( $all_items as $item ){
							$o_key = count( $options['results'] );
							$options['results'][ $o_key ] = array();
							$options['results'][ $o_key ]['id'] = $item->ID;
							$options['results'][ $o_key ]['text'] = $item->post_title;
						}
					}
				break;
		}
		
		echo json_encode( $options );
		die;
	}
	
	function factory_message( $params ){
		
		global $otw_pm_plugin_id;
		
		if( isset( $params['plugin'] ) && $otw_pm_plugin_id == $params['plugin'] ){
			
			//filter out some messages if need it
		}
		if( isset( $params['message'] ) )
		{
			return $params['message'];
		}
		return $params;
	}
	
	private function otw_backup_mapping_replace( $object_key, $string, $import_mapping ){
	
		if( $import_mapping && is_array( $import_mapping ) ){
		
			//check for portfoli list
			if( preg_match_all( "/otw_shortcode_portfolio_manager portfoliolist_id=\"(\d+)\"/", $string, $matches ) ){
				
				foreach( $matches[0] as $s_key => $string_match ){
					
					$backup_id = $matches[1][ $s_key ];
					if( isset( $import_mapping['pm_lists'] ) && isset( $import_mapping['pm_lists'][ $backup_id ] ) ){
						
						$string = str_replace( $string_match, 'otw_shortcode_portfolio_manager portfoliolist_id="'.esc_attr( $import_mapping['pm_lists'][ $backup_id ] ).'"', $string );
					}
				}
				
			}elseif( ( $object_key == 'portfoliolist_id' ) && preg_match( "/^(\d+)$/", $string, $matches ) ){
				
				$backup_id = $matches[1];
				
				if( isset( $import_mapping['pm_lists'] ) && isset( $import_mapping['pm_lists'][ $backup_id ] ) ){
					$string = str_replace( $backup_id, $import_mapping['pm_lists'][ $backup_id ], $string );
				}
			}
		}
		return $string;
	}
	
	private function otw_backup_replace( $search_string, $replace_string, $object, $import_mapping = false ){
	
		if( ( is_array( $object ) && count( $object ) ) ){
		
			foreach( $object as $object_key => $object_value ){
			
				if( is_string( $object_value ) ){
					$object[ $object_key ] = str_replace( $search_string, $replace_string, $object_value );
					$object[ $object_key ] = $this->otw_backup_mapping_replace( $object_key, $object[ $object_key ], $import_mapping );
				}else{
					$object[ $object_key ] = $this->otw_backup_replace( $search_string, $replace_string, $object_value, $import_mapping );
				}
			}
			
		}elseif( is_object( $object ) ){
			
			foreach( $object as $object_key => $object_value ){
				if( is_string( $object_value ) ){
					$object->{$object_key} = str_replace( $search_string, $replace_string, $object_value );
					$object->{$object_key} = $this->otw_backup_mapping_replace( $object_key, $object->{$object_key}, $import_mapping );
				}else{
					$object->{$object_key} = $this->otw_backup_replace( $search_string, $replace_string, $object_value, $import_mapping );
				}
			}
		}
		
		
		return $object;
	}

} // End OTWPortfolioManager Class

} // End IF Class Exists

// DB Query
require_once( 'classes' . DS . 'otw_pm_query.php' );

// Template Dispatcher
require_once( 'classes' . DS . 'otw_pm_dispatcher.php' );

// Custom CSS
require_once( 'classes' . DS . 'otw_pm_css.php' );

// Add Image Crop Functionality
require_once( 'classes' . DS . 'otw_pm_image_crop.php' );

// Register Widgets
require_once( 'classes' . DS . 'otw_portfolio_manager_widgets.php' );

// Register VC add on
require_once( 'classes' . DS . 'otw_portfolio_manager_vc_addon.php' );

$otwPortfolioMangerPlugin = new OTWPortfolioManager();
