<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

//
// Class SwiftySiteDesignerCustomizer
//

global $swifty_build_use;
$swifty_build_use = 'build';

require_once plugin_dir_path( __FILE__ ) . '../lib/swifty_plugin/php/autoload.php';
require_once 'class-walker-ssd-page.php';
require_once 'class-ssd-theme-update-check.php';

if( is_null( LibSwiftyPlugin::get_instance() ) ) {
    new LibSwiftyPlugin();
}

class SwiftySiteDesignerMain {

    protected $swifty_admin_page = 'swifty_theme_designer_admin';
    protected $theme_version = '3.0.1';
    protected $swifty_queue_lazy_js = array();
    protected $swifty_queue_lazy_css = array();
    protected $swifty_register_lazy_css = array();
    protected $use_admin_theme_menu = false;

    protected $is_contentview = false;
    protected $contentview_handle_area = '';
    protected $contentview_data = null; // array([area]=>[content])

    public function __construct() {
        $this->init();
    }

    public function init()
    {
        do_action( 'swifty_check_theme_inited' );

        add_filter( 'swifty_postid_from_area', array( &$this, 'swifty_postid_from_area' ), 10, 3 );
        add_filter( 'swifty_new_area_template_name', array( &$this, 'swifty_new_area_template_name' ), 10, 2 );
        add_filter( 'swifty_get_area_template_names', array( &$this, 'swifty_get_area_template_names' ) );
        add_filter( 'swifty_get_area_template', array( &$this, 'swifty_get_area_template' ), 10, 3 );
        add_action( 'swifty_set_area_template', array( &$this, 'swifty_set_area_template' ), 10, 2 );
        add_filter( 'swifty_is_theme_area_page', array( &$this, 'swifty_is_theme_area_page' ), 10, 2 );
        add_filter( 'swifty_lazy_load_js', array( &$this, 'hook_swifty_lazy_load_js' ), 10, 5 );
        add_filter( 'swifty_lazy_register_css', array( &$this, 'hook_swifty_lazy_register_css' ), 10, 5 );
        add_filter( 'swifty_lazy_load_css', array( &$this, 'hook_swifty_lazy_load_css' ), 10, 5 );
        add_filter( 'swifty_active_plugins', array( &$this, 'hook_swifty_active_plugins' ) );
        add_filter( 'swifty_active_plugin_versions', array( $this, 'hook_swifty_active_plugin_versions' ) );
        add_filter( 'swifty_get_css_location', array( &$this, 'hook_swifty_get_css_location' ), 10, 1 );

        add_filter( 'swifty_get_ssd_show_wizard', array( &$this, 'hook_swifty_get_ssd_show_wizard' ), 10, 1 );
        add_action( 'swifty_set_ssd_show_wizard', array( &$this, 'hook_swifty_set_ssd_show_wizard' ), 10, 1 );

        // widget support
        add_action( 'widgets_init', array( &$this, 'hook_widgets_init' ) );

        add_action( 'load-themes.php', array( $this, 'swifty_customize_redirect' ) );
        add_action( 'admin_menu', array( $this, 'admin_menu' ), 1/*000*/ );
        add_filter( 'admin_add_swifty_menu', array( &$this, 'hook_admin_add_swifty_menu' ), 999, 4 );
        add_filter( 'admin_add_swifty_admin', array( &$this, 'hook_admin_add_swifty_admin' ), 999, 8 );
        add_action( 'admin_init', array( $this, 'hook_admin_init' ) );
//        add_action( 'init', array( $this, 'hook_init') );
        //add_action( 'customize_controls_init', array( $this, 'hook_customize_controls_init_check_scc' ) );
        add_filter( 'post_row_actions', array( $this, 'hook_post_row_actions' ) );

        if( is_admin() ) {
            // Add plugin check for required plugins
            //add_action( 'stgmpa_register', array( &$this, 'hook_stgmpa_register' ) );
        }
        add_filter( 'customize_previewable_devices', array( $this, 'hook_customize_previewable_devices' ) );

        // Woocommerce integration
        remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
        remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );
        remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );

        add_action( 'woocommerce_before_main_content', array( &$this, 'ssd_theme_wrapper_start' ), 10 );
        add_action( 'woocommerce_after_main_content', array( &$this, 'ssd_theme_wrapper_end' ), 10 );
        add_action( 'after_setup_theme', array( &$this, 'woocommerce_support' ) );

        add_action( 'wp_ajax_ssd_dynamic_css', array( &$this, 'hook_ssd_dynamic_css' ) );
        add_action( 'wp_ajax_nopriv_ssd_dynamic_css', array( &$this, 'hook_ssd_dynamic_css' ) );

        LibSwiftyPluginView::get_instance()->init_script_hooks();

        $this->is_contentview = LibSwiftyPluginView::is_swifty_contentview();

        if( $this->is_contentview ) {
            // replace content by demo content
            add_filter( 'the_content', array( &$this, 'hook_the_content_contentview' ), 1 );
            // do not use autop
            remove_filter( 'the_content', 'wpautop' );

            // make sure the blog posts are not shown on the demo page
            add_filter( 'pre_option_show_on_front',
                function() {
                    return 'page';
                }
            );

            add_filter( 'pre_option_page_on_front', array( $this, 'hook_pre_option_page_on_front' ) );
        }
    }

    function hook_pre_option_page_on_front() {
        $page_ids = $this->get_all_published_page_ids();
        if( count( $page_ids ) ) {
            return $page_ids[0];
        }
        return false;
    }

    function get_all_published_page_ids() {
        global $wpdb;

        $page_ids = wp_cache_get('get_all_published_page_ids', 'posts');
        if ( ! is_array( $page_ids ) ) {
            $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE (post_type = 'page') AND (post_status = 'publish')");
            wp_cache_add('get_all_published_page_ids', $page_ids, 'posts');
        }

        return $page_ids;
    }

    public function swifty_postid_from_area($id, $areaName, $areaTemplate = null) {
        if( $areaName === 'main' ) {
            return $id;
        } else {
            $area_id = $this->get_postid_from_area( $areaName, $areaTemplate );
            if($area_id) {
                return $area_id;
            } else {
                return $id;
            }
        }
    }

    // return the post id of the given area, defaults to the original post id

    function get_postid_from_area( $areaName, $areaTemplate = null ) {
        $my_postid = 0;

        if( $areaTemplate == '' ) {
            $areaTemplate = null;
        }

        $posts = $this->get_postid_from_area_helper( $areaName, $areaTemplate );

        if( ! $posts ) {
            // Add the area post (custom page type) if it does not yet exist
            wp_insert_post( array(
                'post_type' => 'swifty_area',
                'post_title' => 'swifty_area_' . $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' ),
                'post_name' => 'swifty_area_' . $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' ), // slug
                'post_content' => '', //'AREA ' . $area_typ,
                'post_status' => 'publish'
            ) );

            $posts = $this->get_postid_from_area_helper( $areaName, $areaTemplate );
        }

        if( $posts ) {
            foreach( $posts as $post ) {
                $my_postid = $post->ID;
            }
        }

        return $my_postid;
    }

    function get_postid_from_area_helper( $areaName, $areaTemplate = null ) {
        return get_posts( array(
            'name' => 'swifty_area_' . $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' ),
            'posts_per_page' => 1,
            'post_type' => 'swifty_area',
            'post_status' => 'publish'
        ) );
    }

    /**
     * get unique new area template name (will be an number)
     *
     * @param $area_template
     * @param $areaName
     * @return int
     */
    public function swifty_new_area_template_name( $area_template, $areaName ) {
        // existing areas
        $areas = get_posts( array(
            'post_type' => 'swifty_area',
            'post_status' => 'publish',
            'numberposts' => -1
        ) );

        $area_unique_id = 1;
        $areaName = 'swifty_area_' . $areaName . '_';
        $found = true;
        while( $found ) {
            $found = false;
            $area_unique_id += 1;

            foreach( $areas as $key => $area ) {
                if( $area->post_name === ( $areaName . $area_unique_id ) ) {
                    $found = true;
                    break;
                }
            }
        }
        return $area_unique_id;
    }

    public function swifty_get_area_template_names( $areas ) {
        if( ! $areas ) {
            $areas = array();
        }

        // existing areas
        $area_posts = get_posts( array(
            'post_type' => 'swifty_area',
            'post_status' => 'publish',
            'numberposts' => -1
        ) );

        foreach( $area_posts as $key => $area ) {

            $new_area = null;
            foreach( array( 'page', 'main', 'topbar', 'header', 'navbar', 'sidebar', 'extrasidebar', 'footer', 'bottombar' ) as $areaName ) {
                $swiftyAreaName = 'swifty_area_' . $areaName;
                if( $area->post_name === $swiftyAreaName ) {
                    $new_area = array(
                        'name' => '',
                        'title' => __( 'default', 'swifty-site-designer' ),
                        'id' => $area->ID
                    );
                } else if ( strpos( $area->post_name, $swiftyAreaName . '_' ) === 0 ) {
                    $name = substr( $area->post_name, strlen( $swiftyAreaName ) + 1 );
                    $new_area = array(
                        'name' => $name,
                        'title' => $name,
                        'id' => $area->ID
                    );
                }

                if( $new_area ) {
                    $areas[$areaName][] = $new_area;
                    break;
                }
            }
        }
        return $areas;
    }

    /**
     * action: "swifty_set_area_template"
     *
     * @param $post_id
     * @param $area_info: array of areas with template name to use (# or empty string are the default areas)
     *
     * Example:
     * do_action( 'swifty_set_area_template', pageId, array( 'footer' => '1' ) );
     */
    public function swifty_set_area_template( $post_id, $area_info ) {
        if( $post_id && is_array( $area_info ) ) {
            foreach( $area_info as $areaName => $areaTemplate ) {
                if( $areaName && ( $areaName !== 'main' ) ) {
                    if( $areaTemplate && ( $areaTemplate !== '' ) && ( $areaTemplate !== '#' ) && is_string( $areaTemplate ) ) {
                        update_post_meta( $post_id, 'spm_' . $areaName . '_template', $areaTemplate );
                    } else {
                        delete_post_meta( $post_id, 'spm_' . $areaName . '_template' );
                    }
                }
            }
        }
    }

    /**
     * Filter: "swifty_get_area_template" - look for area template with content
     * if there is a existing area template with this content then return its name, otherwise create a new area template
     * and return the new name.
     *
     * @param $areaTemplate, call with '' to use this filter
     * @param $areaName
     * @param $areaContent
     */
    public function swifty_get_area_template( $areaTemplate, $areaName, $areaContent ) {

        // make sure this is only done once when multiple filters are handling this
        if( $areaTemplate === '' ) {
            // existing areas
            $area_posts = get_posts( array(
                'post_type' => 'swifty_area',
                'post_status' => 'publish',
                'numberposts' => -1
            ) );

            $areaTemplate = null;
            foreach( $area_posts as $key => $area ) {
                $swiftyAreaName = 'swifty_area_' . $areaName;
                if( ( $area->post_name === $swiftyAreaName ) && ( $area->post_content === $areaContent ) ) {
                    $areaTemplate = '';
                } else if( ( strpos( $area->post_name, $swiftyAreaName . '_' ) === 0 ) && ( $area->post_content === $areaContent ) ) {
                    $areaTemplate = substr( $area->post_name, strlen( $swiftyAreaName ) + 1 );
                }
                if( $areaTemplate !== null ) {
                    break;
                }
            }

            // not found, add one and return it
            if( $areaTemplate === null ) {
                $areaTemplate = $this->swifty_new_area_template_name( $areaTemplate, $areaName );

                wp_insert_post( array(
                    'post_type' => 'swifty_area',
                    'post_title' => 'swifty_area_' . $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' ),
                    'post_name' => 'swifty_area_' . $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' ), // slug
                    'post_content' => $areaContent,
                    'post_status' => 'publish'
                ) );
            }
        }
        return $areaTemplate;
    }

    /**
     * initialize the swifty_area custom_post_type
     */
    function register_post_types() {
        $showInMenu = 'swifty_admin';
        if( $this->use_admin_theme_menu ) {
            $showInMenu = 'themes.php';
        }

        call_user_func( 'register_post_type',
            'swifty_area',
            array(
                'labels' => array(
                    'name' => __( 'Swifty areas', 'swifty-site-designer' ),
                    'singular_name' => __( 'Swifty area', 'swifty-site-designer' ),
                    'edit' => __( 'Edit', 'swifty-site-designer' ),
                    'edit_item' => __( 'Edit Swifty area', 'swifty-site-designer' ),
                    'search_items' => __( 'Search Swifty areas', 'swifty-site-designer' ),
                    'not_found' => __( 'No Swifty area found', 'swifty-site-designer' ),
                    'not_found_in_trash' => __( 'No Swifty area found in trash', 'swifty-site-designer' )
                ),

                'public' => true,
                'menu_position' => 85,
                'supports' => array( 'title', 'editor', 'revisions' ),
                'taxonomies' => array( '' ),

                'exclude_from_search' => true,  // you should exclude it from search results
                'show_in_menu' => $showInMenu,
                'show_in_nav_menus' => false,  // you shouldn't be able to add it to menus
                'has_archive' => false,  // it shouldn't have archive page
                'rewrite' => false,  // it shouldn't have rewrite rules

                'capability_type' => 'post',
                'capabilities' => array(
                    'create_posts' => false, // Removes support for the "Add New" function ( use 'do_not_allow' instead of false for multisite set ups )
                    'delete_posts' => false  // no delete to trash
                ),
                'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts

                'hierarchical' => false,
            )
        );
    }

    /**
     * This action is called in the begin of customize.php just before most is initialized, we will not
     * continue without scc
     */
    function hook_customize_controls_init_check_scc() {

        if( ! LibSwiftyPluginView::is_swifty_plugin_active( 'swifty-content-' . 'creator' ) ) {

            $show_install_link = '<a href="' .
                add_query_arg(
                    'page',
                    Swifty_TGM_Plugin_Activation::get_instance()->menu,
                    Swifty_TGM_Plugin_Activation::get_instance()->menu_url ) .
                '">' . translate_nooped_plural( Swifty_TGM_Plugin_Activation::get_instance()->strings[ 'install_link' ], 1 ) . '</a>';

            wp_die(
                '<h1>Swifty Site Designer</h1>' .
                '<p>' . __( 'Swifty Content Creator is required for customizer.', 'swifty-site-designer' ) . '</p>' .
                ( $show_install_link ? '<p>' . $show_install_link . '</p>' : '' ),
                '',
                array( 'back_link' => true )
            );
        }
    }

    /**
     * remove actions from the posts screen when showing swifty_area custom_post_type
     *
     * @param $actions
     * @return mixed
     */
    function hook_post_row_actions( $actions ) {
        global $current_screen;
        if( $current_screen->post_type != 'swifty_area' ) {
            return $actions;
        }
        unset( $actions[ 'view' ] );
        unset( $actions[ 'trash' ] );
        unset( $actions[ 'inline hide-if-no-js' ] );

        return $actions;
    }

    /**
     * Register the required plugins for this plugin.
     *
     * This function is hooked into stgmpa_init, which is fired within the
     * Swifty_TGM_Plugin_Activation class constructor.
     */
    function hook_stgmpa_register()
    {
        $plugins = array(
            array(
                'name' => 'Swifty Content Creator',
                'slug' => 'swifty-site-designer',
                'version' => '1.4.6',
                'required' => false,
            ),
        );
        $config = array(
            'default_path' => '',                      // Default absolute path to pre-packaged plugins.
            'menu'         => 'swifty_required_plugins', // Menu slug.
            'menu_url'     => network_admin_url( 'admin.php' ),
            'has_notices'  => true,                    // Show admin notices or not.
            'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
            'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
            'is_automatic' => false,                   // Automatically activate plugins after installation or not.
            'message'      => '',                      // Message to output right before the plugins table.
            'skip_notices_on_pages' => array( 'swifty_page_swifty_content_creator_admin' )
        );

        stgmpa( $plugins, $config );
    }

    /**
     * Disable device preview buttons
     *
     * @param $devices
     * @return array
     */
    function hook_customize_previewable_devices( $devices ) {
        return array();
    }

    public function hook_swifty_lazy_load_js( $handle, $src, $deps, $ver, $in_footer ) {
        if( ! in_array( $src, $this->swifty_queue_lazy_js, true ) ) {
            $this->swifty_queue_lazy_js[] = array( 'handle' => $handle, 'src' => $src, 'deps' => $deps );
        }
    }

    public function hook_swifty_lazy_register_css( $handle, $src, $deps, $ver, $media ) {
        
        if( ! array_key_exists( $handle, $this->swifty_register_lazy_css ) ) {
            $this->swifty_register_lazy_css[ $handle ] = $src;
        }
    }

    public function hook_swifty_lazy_load_css( $handle, $src, $deps, $ver, $media ) {
        if( ! $src ) {
            if( array_key_exists( $handle, $this->swifty_register_lazy_css ) ) {
                $src = $this->swifty_register_lazy_css[ $handle ];
            }
        }
        if( $src ) {
            if( ! in_array( $src, $this->swifty_queue_lazy_css, true ) ) {
                $this->swifty_queue_lazy_css[] = $src;
            }
        }
    }

    /**
     * Called via Swifty filter 'swifty_active_plugins'
     *
     * Add the plugin name to the array
     */
    public function hook_swifty_active_plugins( $plugins )
    {
        $plugins[] = 'swifty-site-designer';
        return $plugins;
    }

    /**
     * Called via Swifty filter 'swifty_active_plugin_versions'
     *
     * Add the plugin name as key to the array with plugin version
     */
    public function hook_swifty_active_plugin_versions( $plugins )
    {
        $plugins['swifty-site-designer'] = array( 'version' => $this->theme_version );
        return $plugins;
    }

    /**
     * Filter 'swifty_get_css_location' gets the 'swifty_css_location' setting.
     *
     * @param $default
     * @return mixed|void
     */
    public function hook_swifty_get_css_location( $default ) {
        $value = get_option( 'swifty_css_location' );
        return $value ? $value : $default;
    }

    /**
     * Filter 'swifty_get_ssd_show_wizard' gets the 'ssd_show_wizard' setting.
     *
     * @param $default
     * @return mixed|void
     */
    public function hook_swifty_get_ssd_show_wizard( $default ) {
        return get_option( 'ssd_show_wizard', $default );
    }

    /**
     * Filter 'swifty_set_ssd_show_wizard' sets the 'ssd_show_wizard' setting.
     *
     * @param $default
     * @return mixed|void
     */
    public function hook_swifty_set_ssd_show_wizard( $value ) {
        update_option( 'ssd_show_wizard', $value );
    }


    // get the post id of the area, what when area does not exist?

    public function swifty_is_theme_area_page( $default, $page_guid ) {
        return $default || strpos( $page_guid, 'swifty_area_');
    }

    /**
     * Look for pages with children, a copy of the parent page is inserted at the top of the $pages array when
     * 'spm_show_as_first' value is not 'hide', the 'spm_alt_menu_text' value is used for this page title when set
     *
     * @param $pages
     * @return array
     */
    public function hook_get_pages_for_show_other_page_posts( $pages ) {
        $parentids = array();
        foreach( $pages as $page ) {
            if( $page->post_parent && ! in_array( $page->post_parent, $parentids ) ) {
                $parentids[] = $page->post_parent;
            }
        }

        $new_pages = array();
        foreach( $pages as $page ) {
            $new_pages[] = $page;
            if( in_array( $page->ID, $parentids ) ) {
                $spm_show_as_first = get_post_meta( $page->ID, 'spm_show_as_first', true );

                if( $spm_show_as_first !== 'hide' ) {
                    $page = WP_Post::get_instance( $page->ID );
                    $page->post_parent = $page->ID;
                    $spm_alt_menu_text = get_post_meta( $page->ID, 'spm_alt_menu_text', true );
                    if( $spm_alt_menu_text ) {
                        $page->post_title = $spm_alt_menu_text;
                    }
                    array_unshift( $new_pages, $page );
                }
            }
        }
        return $new_pages;
    }


    public function hook_the_content_contentview( $content ) {

        if( !$this->contentview_data ) {

            $this->contentview_data = array();

            $file_name = apply_filters( 'swifty_get_contentview', 'demo' );
            $file_name = get_template_directory() . '/ssd/content/' . $file_name . '.html';

            $contentview = swifty_read_text( $file_name );

            $img_demo_url = get_stylesheet_directory_uri() . '/ssd/img/';
            $contentview = str_replace( '[DEMO_IMG_URL]', $img_demo_url, $contentview );
            $img_demo_url = addslashes( $img_demo_url );
            $contentview = str_replace( '[DEMO_IMG_URL_ESC]', $img_demo_url, $contentview );

            $matches = preg_split( '/<!-- AREA\.(\S*) -->/', $contentview, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE );
            $i = 0;
            while( $i < count( $matches ) ) {
                // the main content is empty string in $this->contentview_handle_area
                if( $matches[ $i ] === 'MAIN' ) {
                    $areaName = '';
                } else {
                    $areaName = strtolower( $matches[ $i ] );
                }
                $i++;
                if( $i < count( $matches ) ) {
                    $this->contentview_data[ $areaName ] = trim( $matches[ $i ] );
                    $i++;
                }
            }
        }

        if( isset( $this->contentview_data[ $this->contentview_handle_area ] ) ) {
            return $this->contentview_data[ $this->contentview_handle_area ];
        } else {
            return '';
        }
    }

    function show_other_page_posts( $areaName ) {
        global $ssd_settings;

    //  $post2 = get_page_by_path($path);
    //  $content2 = apply_filters('the_content', $post2->post_content);
    //  echo $content2;

        if( $this->is_contentview ) {
            $areaTemplate = 'content';
        } else {
            // get area template for this area, get parameter overrules the spm area setting
            $area = null;
            if( isset( $_GET[ 'swcreator_edit' ] ) ) {
                $area = $_GET[ 'swcreator_edit' ];
            } else if( isset( $_GET[ 'swcreator_iframe' ] ) ) {
                $area = $_GET[ 'swcreator_iframe' ];
            }
            if( $area ) {
                // make sure the input is not tampered with
                $area = preg_replace( '/[^0-9a-zA-Z_]/', '', $area );
                if( $area == '' ) {
                    $area = null;
                }
            }

            $areaTemplate = null;
            if( isset( $_GET[ 'swcreator_area_template' ] ) && $area && ( $area === $areaName ) ) {
                $areaTemplate = $_GET[ 'swcreator_area_template' ];
                if( $areaTemplate ) {
                    // make sure the input is not tampered with
                    $areaTemplate = preg_replace( '/[^0-9a-zA-Z_#@]/', '', $areaTemplate );
                    if( ( $areaTemplate == '' ) || ( $areaTemplate == '#' ) ) {
                        $areaTemplate = null;
                    }
                }
            } else {
                $areaTemplate = get_post_meta( get_the_ID(), 'spm_' . $areaName . '_template', true );
            }
        }
        
        $areaWidgetName = $areaName . ( $areaTemplate ? '_' . $areaTemplate : '' );

        // dorh Now always show ALL areas; needed in customzier (when you change layouts, page is not refreshed, but different areas might be on or off)
//        if( $ssd_settings && $ssd_settings[ 'areas' ] && $ssd_settings[ 'areas' ][ $areaName ] && $ssd_settings[ 'areas' ][ $areaName ][ 'on' ] === 1 ) {
        if( $ssd_settings && $ssd_settings[ 'areas' ] && $ssd_settings[ 'areas' ][ $areaName ] ) {
            if( ! strpos( get_permalink(), '/swifty_areas/' ) ) {
                $direction_class = 'swifty_horizontal_area';

                if( $this->is_contentview ) {
                    $my_postid = -1;
                } else {
                    $my_postid = $this->get_postid_from_area( $areaName, $areaTemplate );
                }

                if( $areaName === 'sidebar' || $areaName === 'extrasidebar' ) {
                    $direction_class = 'swifty_vertical_area';
                }

                echo '<div class="swifty_area_' . $areaName . ' swifty_areatemplate_' . $areaTemplate . ' swifty_area swifty_area_included ' . $direction_class;
                if( $this->is_contentview ) {
                    $show = '';
                } else {
                    $show = get_post_meta( get_the_ID(), 'spm_' . $areaName . '_visibility', true );
                }
//                if( $show === 'default' || $show === 'show' || $show === 'hide' ) {
                    echo ' swifty_area_page_overrule_' . $show;
//                }
                echo '"';

                if( $show === 'show' ) {
                    echo ' style="min-height: 20px;"';
                }

//                if( $ssd_settings[ 'areas' ][ $areaName ][ 'on' ] !== 1 ) {
//                    echo ' style="display: none;"';
//                }
                echo '>';

                echo '<div class="swifty_area_inner_' . $areaName . ' swifty_area_inner">';

                if( isset( $ssd_settings[ 'items' ] ) ) {
                    foreach( $ssd_settings[ 'items' ] as $key => $item ) {
                        if( $item[ 'area' ] === $areaName ) {
                            if( $key === 'mainmenu' ) {
                                // Add the main menu
                                $ssd_details = get_theme_mod( 'ssd_details' );
                                $menu_type = isset( $ssd_details ) && is_array( $ssd_details ) && array_key_exists( 'mainmenu', $ssd_details ) && array_key_exists( 'set_menu_type', $ssd_details[ 'mainmenu' ] ) ? $ssd_details[ 'mainmenu' ][ 'set_menu_type' ] : 'swifty';
                                $open_sub = isset( $ssd_details ) && is_array( $ssd_details ) && array_key_exists( 'mainmenu', $ssd_details ) && array_key_exists( 'open_sub', $ssd_details[ 'mainmenu' ] ) ? $ssd_details[ 'mainmenu' ][ 'open_sub' ] : '';
                                $menu_add_class = $open_sub === 'hover' ? ' swifty_menu_allow_hover ' : '';
                                $show_arrows = isset( $ssd_details ) && is_array( $ssd_details ) && array_key_exists( 'mainmenu', $ssd_details ) && array_key_exists( 'show_arrows', $ssd_details[ 'mainmenu' ] ) ? $ssd_details[ 'mainmenu' ][ 'show_arrows' ] : '';
                                $menu_add_class .= $show_arrows === 'off' ? '' : ' swifty_menu_show_arrows ';
                                ?>
                                <nav id="site-navigation"
                                     class="main-navigation swifty_main_menu <?php echo $menu_add_class; ?> swifty_ssd_item_<?php echo $key; ?>"
                                     role="navigation">
                                    <div class="menu-toggle" aria-controls="menu" aria-expanded="false">
                                        <div class="menu-toggle_inner"></div>
                                    </div>
                                    <?php

                                    if( $this->is_contentview ) {
                                        $this->contentview_handle_area = 'menu';
                                        echo $this->hook_the_content_contentview( '' );
                                        $this->contentview_handle_area = '';
                                    } else {

                                        if( $menu_type === 'wp' ) {
                                            $menu_id = isset( $ssd_details ) && is_array( $ssd_details ) && array_key_exists( 'mainmenu', $ssd_details ) && array_key_exists( 'wp_menu', $ssd_details[ 'mainmenu' ] ) ? $ssd_details[ 'mainmenu' ][ 'wp_menu' ] : '';

                                            if( $menu_id ) {
                                                wp_nav_menu( array(
                                                    'menu' => $menu_id,
                                                    'menu_class' => 'nav-menu',
                                                    'container_class' => 'swifty_item_mainmenu',
                                                ) );
                                            }
                                        } else {
                                            $exclude = '';
                                            $pages = get_pages( array(
                                                'meta_key' => 'spm_show_in_menu',
                                                'meta_value' => 'hide',
                                                'parent' => -1,
                                                'hierarchical' => 0
                                            ) );
                                            foreach( $pages as $page ) {
                                                $exclude .= $exclude === '' ? '' : ',';
                                                $exclude .= $page->ID;
                                            }

                                            // duplicate parent pages when needed
                                            add_filter( 'get_pages', array( $this, 'hook_get_pages_for_show_other_page_posts' ) );

                                            wp_page_menu( array(
                                                'menu_class' => 'swifty_item_mainmenu',
                                                'walker' => new Walker_SSD_Page, // use our own walker class
                                                'exclude' => $exclude,
                                                'exclude_tree' => $exclude
                                            ) );

                                            remove_filter( 'get_pages', array( $this, 'hook_get_pages_for_show_other_page_posts' ) );
                                        }
                                    }

                                    ?>
                                </nav><!-- #site-navigation -->
                                <?php
                            }
                            if( $key === 'logo' ) {
                                // Add the logo
                                $url = '';

                                // Get the WP theme logo
                                $custom_logo_id = get_theme_mod( 'custom_logo' );

                                if( $custom_logo_id ) {
                                    $url = wp_get_attachment_url( $custom_logo_id );
                                    if( strpos( $url, '?swifty=1' ) === false ) {
                                        $url .= '?swifty=1';
                                    }
                                }

                                if( $url === '' ) {
                                    // No WP theme logo found. Use the old Swifty theme logo.
                                    $ssd_details = get_theme_mod( 'ssd_details' );
                                    if( is_array( $ssd_details ) ) {
                                        $url = isset( $ssd_details ) && array_key_exists( 'logo', $ssd_details ) && array_key_exists( 'fg_img', $ssd_details[ 'logo' ] ) ? $ssd_details[ 'logo' ][ 'fg_img' ] : '';
                                    }
                                }

                                $query_images_args = array(
                                    'name' => 'logo',
                                    'post_type' => 'attachment',
                                    'post_mime_type' =>'image',
                                    'post_status' => 'inherit',
                                    'posts_per_page' => -1,
                                );

                                if( $url === '' ) {
                                    $query_images = new WP_Query( $query_images_args );
                                    foreach( $query_images->posts as $image ) {
                                        $url = wp_get_attachment_url( $image->ID );
                                    }
                                }

                                if( $url !== '' ) {
                                    echo '<div class="swifty_ssd_item_' . $key . '">';

                                    if( LibSwiftyPluginView::is_swifty_plugin_active( 'swifty-content-' . 'creator' ) ) {
                                        echo do_shortcode( '[swifty_image url="' . $url . '" viewer="nothing" swc_swifty_on="1" swc_margin_top="0" swc_margin_bottom="0" swc_margin_left="0" swc_margin_right="0" swc_padding_top="0" swc_padding_bottom="0" swc_padding_left="0" swc_padding_right="0" swc_position="left" swc_width="100"]' );
                                    } else {
                                        global $swifty_lib_dir;

                                        if( isset( $swifty_lib_dir ) ) {
                                            require_once $swifty_lib_dir . '/php/lib/swifty-image-functions.php';

                                            echo SwiftyImageFunctions::get_img_tag( $url );
                                        } else {
                                            echo '<img src="' . $url . '">';
                                        }
                                    }

                                    echo '</div>';
                                }
                            }

                            if( $key === 'title' ) {
                                // Add the site title
                                $title = get_bloginfo( 'name' );

                                echo '<div class="swifty_ssd_item_' . $key . '">';
                                echo $title;
                                echo '</div>';
                            }

                            if( $key === 'slogan' ) {
                                // Add the site slogan
                                $slogan = get_bloginfo( 'description' );

                                echo '<div class="swifty_ssd_item_' . $key . '">';
                                echo $slogan;
                                echo '</div>';
                            }
                        }
                    }
                }

                if( $this->is_contentview ) {
                    $this->contentview_handle_area = $areaName;
                    $content = apply_filters( 'the_content', '' );
                    $this->contentview_handle_area = '';
                } else {
                    $content_post = get_post( $my_postid );
                    $content = $content_post->post_content;

                    global $post;
                    $post_ori = $post;
                    $post = $content_post;
                    $content = apply_filters( 'the_content', $content );
                    $post = $post_ori;
                }
                $content = str_replace( ']]>', ']]&gt;', $content );
                $extra_classes = '';
                $clean = preg_replace( '/(?:\s|&nbsp;)+/', '', $content, -1 );
                $clean = str_replace( 'swc_p_0', '', $clean );
                $clean = str_replace( '<divclass=""></div>', '', $clean );
                if( $clean === '' ) {
                    $extra_classes = 'swifty_area_empty';
                }

                echo '<div class="swifty_area_inner_content_' . $areaName . ' swifty_area_inner_content ' . $extra_classes . '">';

                echo $content;

                dynamic_sidebar( $areaWidgetName );

                echo '</div>';
                echo '</div>';
                echo '</div>';

                if( $this->is_contentview ) {
                    $style_json = '{}';
                } else {
                    $style_json = apply_filters( 'swifty_get_area_template_style', '', $areaName, $areaTemplate );
                }
                echo '<script>';
                echo 'if( typeof swifty_ssd_page_styles === "undefined" ) { swifty_ssd_page_styles = {}; }; ';
                // dorh Remove everything except used_fonts when NOT in edit mode!
                echo 'swifty_ssd_page_styles.' . $areaName . '_' . $areaTemplate . ' = ' . $style_json . ';';
                echo '</script>';

                $style_obj = json_decode( $style_json, true );
                if( array_key_exists( 'custom_css', $style_obj ) ) {
                    echo '<style id="swifty_scc_area_' . $areaName . '_' . $areaTemplate . '_css">';
                    echo $style_obj[ 'custom_css' ];
                    echo '</style>';
                }

                if( array_key_exists( 'area_data', $style_obj ) ) {
                    $area_data = $style_obj[ 'area_data' ];
                    if( isset($area_data[ 'bg_type' ] ) && ( $area_data[ 'bg_type' ] === 'image' ) ) {
                        ?>
                        <script>
                            try {
                                var swifty_timer_<?php echo $areaName ?> = window.setInterval(function(){
                                    if(swifty_setBgImg != undefined) {
                                        window.clearInterval(swifty_timer_<?php echo $areaName ?>);
                                        swifty_setBgImg(
                                            "<?php echo $areaName ?>",
                                            "<?php echo isset( $area_data[ 'bg_img' ] ) ? $area_data[ 'bg_img' ] : '' ?>",
                                            "<?php echo isset( $area_data[ 'bg_type' ] ) ? $area_data[ 'bg_type' ] : '' ?>",
                                            "<?php echo isset( $area_data[ 'def_bg_type' ] ) ? $area_data[ 'def_bg_type' ] : '' ?>",
                                            "<?php echo isset( $area_data[ 'def_bg_img' ] ) ? $area_data[ 'def_bg_img' ] : '' ?>",
                                            "<?php echo isset( $area_data[ 'bg_pattern' ] ) ? $area_data[ 'bg_pattern' ] : '' ?>",
                                            "<?php echo isset( $area_data[ 'bg_color' ] ) ? $area_data[ 'bg_color' ] : '#c4c4c4' ?>",
                                            "<?php echo isset( $area_data[ 'bg_colr2' ] ) ? $area_data[ 'bg_colr2' ] : '#898989' ?>",
                                            "<?php echo isset( $area_data[ 'boxed' ] ) && $area_data[ 'boxed' ] == 1 ? 'boxed' : 'wide' ?>",
                                            "<?php echo isset( $area_data[ 'set_bg_im_ssry' ] ) && $area_data[ 'set_bg_im_ssry' ] === 'custom' ? ( $area_data[ 'bg_im_ssry' ] != '' ? $area_data[ 'bg_im_ssry' ] : '50' ) : '' ?>"
                                        );
                                    }
                                }, 100);
                            } catch( e ) {}
                        </script>
                        <?php
                    }
                }


//                echo apply_filters('the_content', get_post_field('post_content', $my_postid));
            }
//        }
        }
    }

    /** 
     * Create a widget sidebar for each area variant
     */
    function hook_widgets_init() {
        
        $areas = $this->swifty_get_area_template_names( null );
        
        foreach( $areas as $areaName => $area ) {
            if( in_array( $areaName, array( 'main', 'page' ) ) ) {
                continue;
            }
            foreach( $area as $variant ) {

                $areaWidgetName = $areaName . ( $variant[ 'name' ] ? '_' . $variant[ 'name' ] : '' );

                register_sidebar( array(
                    'name' => $areaWidgetName,
                    'id' => $areaWidgetName,
                    'before_widget' => '<div id="%1$s" class="widget %2$s">',
                    'after_widget' => '</div>',
                    'before_title' => '<h5 class="widgettitle">',
                    'after_title' => '</h5>',
                ) );
            }
        }
    }

    // redirect to homepage when themes.php is loaded in swifty mode (when close button is pressed very quickly after load)
    function swifty_customize_redirect()
    {
        if( strstr( wp_get_referer(), '/wp-admin/customize.php' ) ) {
            if( LibSwiftyPluginView::is_ss_mode() ) {
                $url = get_home_url();
                wp_safe_redirect( $url );
                exit();
            }
        }
    }

    /**
     * add the ssd options and settings and bind them to the correct setting section
     */
    function hook_admin_init() {

        LibSwiftyPlugin::get_instance()->admin_add_swifty_admin();

        // setting group name, name of option
        register_setting( 'ssd_plugin_options', 'swifty_css_location' );
        register_setting( 'ssd_plugin_options', 'auto_page_titles' );
        register_setting( 'ssd_plugin_options', 'ssd_show_wizard' );

        add_settings_section(
            'ssd_plugin_options_main_id',
            '',
            array( $this, 'ssd_plugin_options_main_text_callback' ),
            'ssd_plugin_options_page'
        );

        add_settings_field(
            'ssd_plugin_options_swifty_css_location',
            __( 'Place css', 'swifty-site-designer' ),
            array( $this, 'plugin_setting_swifty_css_location' ),
            'ssd_plugin_options_page',
            'ssd_plugin_options_main_id'
        );

        add_settings_field(
            'ssd_plugin_options_auto_page_titles',
            __( 'Automatic page titles', 'swifty-site-designer' ),
            array( $this, 'plugin_setting_auto_page_titles' ),
            'ssd_plugin_options_page',
            'ssd_plugin_options_main_id'
        );

        add_settings_field(
            'ssd_plugin_options_ssd_show_wizard',
            __( 'Show start wizard', 'swifty-site-designer' ),
            array( $this, 'plugin_setting_ssd_show_wizard' ),
            'ssd_plugin_options_page',
            'ssd_plugin_options_main_id'
        );
    }

    function ssd_plugin_options_main_text_callback()
    {
    }

    function plugin_setting_swifty_css_location() {
        $swifty_css_location = $this->hook_swifty_get_css_location( 'inline' );

        echo '<input ' .
            'type="radio" ' .
            'id="ssd_plugin_options_swifty_css_location" ' .
            'name="swifty_css_location" ' .
            'value="inline" ' .
            ( ( $swifty_css_location === 'inline' ) ? 'checked="checked" ' : '' ) .
            '/>' . __( 'Inline.', 'swifty-site-designer' ) . '<br>';
        echo '<input ' .
            'type="radio" ' .
            'id="ssd_plugin_options_swifty_css_location" ' .
            'name="swifty_css_location" ' .
            'value="external" ' .
            ( ( $swifty_css_location === 'external' ) ? 'checked="checked" ' : '' ) .
            '/>' . __( 'External.', 'swifty-site-designer' ) . '<br>';

        echo '<label for="ssd_plugin_options_swifty_css_location">' .
            __( 'Placing the css inline will gives pages a much higher score in Google Page Speed Insights, but will cause those pages to load just a little bit slower. We strongly advise to place the css inline.', 'swifty-site-designer' ) .
            '</label>';
    }

    /**
     * Implement field for automatic page titles
     */
    function plugin_setting_auto_page_titles() {
        $auto_page_titles = get_option( 'auto_page_titles', 'hide' );

        foreach( array( 'show', 'hide' ) as $value ) {
            echo '<input '
                . 'type="radio" '
                . 'name="auto_page_titles" '
                . 'value="' . $value . '" '
                . ( ( $auto_page_titles === $value ) ? 'checked="checked" ' : '' )
                . '/>' . __( ucfirst( $value ) . ' automatic page titles', 'swifty-site-designer' ) . '<br>';
        }

        echo __( 'Show page titles as automatic headlines above the content of each page.', 'swifty-site-designer' ) . '<br>';
    }

    function plugin_setting_ssd_show_wizard() {
        $show_wizard = apply_filters( 'swifty_get_ssd_show_wizard', 'show' );

        echo '<input ' .
            'type="checkbox" ' .
            'id="ssd_plugin_options_ssd_show_wizard" ' .
            'name="ssd_show_wizard" ' .
            'value="show" ' .
            checked( 'show', $show_wizard, false ) .
            '/>';

        echo '<label for="ssd_plugin_options_ssd_show_wizard">' .
            __( 'Show the wizard steps when customizing the theme/design.', 'swifty-site-designer' ) .
            '</label>';
    }

    /**
     * Called via WP Action 'admin_menu' if can_edit_pages
     *
     * Add submenu to admin left menu
     */
    public function admin_menu()
    {
        add_filter( 'swifty_admin_page_links_' . $this->swifty_admin_page, array( $this, 'hook_swifty_admin_page_links' ) );

        LibSwiftyPlugin::get_instance()->admin_add_swifty_menu( $this->get_admin_page_title(), __( 'Design', 'swifty-site-designer' ), $this->swifty_admin_page, array( &$this, 'admin_ssd_menu_page' ), true );

        if ( Swifty_TGM_Plugin_Activation::get_instance()->is_admin_menu_needed() ) {
            LibSwiftyPlugin::get_instance()->admin_add_swifty_menu( __( 'Required plugins', 'swifty-site-designer' ), __( 'Required plugins', 'swifty-site-designer' ), 'swifty_required_plugins', array(Swifty_TGM_Plugin_Activation::get_instance(), 'install_plugins_page'), false);
        }

        $this->register_post_types();
    }

    function hook_admin_add_swifty_menu( $page, $name, $key, $func )
    {
        if( ! $page ) {
            $page = add_theme_page( $name, $name, 'manage_options', $key, $func );
        }
        return $page;
    }

    function hook_admin_add_swifty_admin( $done, $v1, $v2, $v3, $v4, $v5, $v6, $v7 )
    {
        if( ! $done ) {
            $this->use_admin_theme_menu = true;
        }
        return true;
    }

    public function get_admin_page_title()
    {
        $swifty_SS2_hosting_name = apply_filters( 'swifty_SS2_hosting_name', false );
        if( $swifty_SS2_hosting_name ) {
            $admin_page_title = __( 'SwiftySite Design', 'swifty-site-designer' );
        } else {
            $admin_page_title = 'Swifty Site Designer';
        }
        return $admin_page_title;
    }

    /**
     * Called via admin_menu hook
     *
     * Add links to admin menu
     */
    public function hook_swifty_admin_page_links( $settings_links )
    {
        $settings_links['general'] = array( 'title' => __( 'General', 'swifty-site-designer' ), 'method' => array( &$this, 'ssd_tab_options_content' ) );

        return $settings_links;
    }

    public function hook_ssd_dynamic_css()
    {
        header( "Content-type: text/css; charset: UTF-8" );

        echo get_theme_mod( 'ssd_css', '' );

        die();
    }

    // Our plugin admin menu page
    function admin_ssd_menu_page()
    {
        LibSwiftyPlugin::get_instance()->admin_options_menu_page( $this->swifty_admin_page );
    }

    function ssd_tab_options_content()
    {
        settings_fields( 'ssd_plugin_options' );
        do_settings_sections( 'ssd_plugin_options_page' );
        submit_button();

        echo '<p>' . 'Swifty Site Designer ' . $this->theme_version . '</p>';
    }

    function show_below_page() {
        global $ssd_settings;
        $bust_add = '?swcv=ssd_' . '3.0.1';

?>
<script>
    ssd_add_loadJs( '<?php echo get_template_directory_uri(); ?>/js/navigation.js<?php echo $bust_add; ?>' );
    ssd_add_loadJs( '<?php echo get_template_directory_uri(); ?>/js/skip-link-focus-fix.js<?php echo $bust_add; ?>' );
<?php

        foreach( $this->swifty_queue_lazy_js as $src ) {
            if( is_string( $src ) ) {
                echo 'ssd_add_loadJs( "' . $src . '" );';
            } else {
                echo 'ssd_add_loadJs( ' . json_encode( $src ) . ' );';
            }
        }
        foreach( $this->swifty_queue_lazy_css as $src ) {
            echo 'ssd_add_loadCss( "' . $src . $bust_add . '" );';
        }

?>
</script>
<?php

        // Add some SSD settings to the global ssd_data variable so Javascript can access them.

        if( $ssd_settings && is_array( $ssd_settings ) ) {
            echo "<script>";
            echo "var swifty_ssd_data = { ";

            echo "colors: [";
            if( $ssd_settings[ 'colors' ] && is_array( $ssd_settings[ 'colors' ] ) ) {
                foreach( $ssd_settings[ 'colors' ] as $i => $color ) {
                    if( $i > 0 ) {
                        echo ',';
                    }
                    echo '"' . $color . '"';
                }
            }
            echo "]";

            echo ", fonts: [";
            if( $ssd_settings[ 'fonts' ] && is_array( $ssd_settings[ 'fonts' ] ) ) {
                foreach( $ssd_settings[ 'fonts' ] as $i => $font ) {
                    if( $i > 0 ) {
                        echo ',';
                    }
                    echo '"' . $font . '"';
                }
            }
            echo "]";

            echo " };";
            echo "</script>";
        }

        // Code for optimally loading fonts

        if( $ssd_settings && $ssd_settings[ 'fonts' ] ) {
            // First load fonts directby by skipping the Google fonts css, so PageSpeed will not give a penalty.
            // We can update the font css files by visiting http://fonts.googleapis.com/css?family=Roboto in FIREFOX.
            echo "<style>";
            foreach( $ssd_settings[ 'fonts' ] as $i => $font ) {
                $font_file = dirname(__FILE__) . '/../cfg/' . $font . '.css';
                if( file_exists( $font_file ) ) {
                    $font_css = swifty_read_text( $font_file );
                    echo $font_css;
                }
            }
            echo "</style>";

            // Then, as a fallback:
            // Load Google fonts via Google's webfont script so we don't get a penalty in Google PageSpreed Insights
            // Not adding http: but leaving // will cause the font to be loaded via http or https depending on the current page
            echo "<script>ssd_add_loadJs('//ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js');";
            foreach( $ssd_settings[ 'fonts' ] as $i => $font ) {
                echo 'ssd_add_loadFont("' . $font . '");';
            }
            echo '</script>';
        }

// Code for lazy adding background images in the correct size
?>
<script>
var swifty_setBgImg = function( area, bg_img, bg_type, def_bg_type, def_bg_img, bg_pattern, bg_color, bg_colr2, boxed, bg_im_ssry ) {
    var elements = document.getElementsByClassName( 'swifty_area_' + area );
    var elements2 = document.getElementsByClassName( 'swifty_area_' + area );
    if( area === 'page' ) {
        if( boxed === 'boxed' ) {
            elements = document.getElementsByClassName( 'swifty_area_frame' );
            elements2 = document.getElementsByClassName( 'swifty_area_hub' );
        } else {
            elements = document.getElementsByClassName( 'swifty_area_hub' );
            elements2 = document.getElementsByClassName( 'swifty_area_frame' );
        }
    }
    var bgImg;
    if( elements.length > 0 ) {
        if( bg_type === 'image' || ( bg_type === 'default' && def_bg_type === 'image' ) ) {
            bgImg = bg_img;
            if( bg_type === 'default' ) {
                bgImg = def_bg_img;
            }
            if( bgImg !== '' ) {
                bgImg = bgImg.replace( 'http:', window.location.protocol ).replace( 'https:', window.location.protocol );
                var hAdd = '';
                if( bg_im_ssry !== '' && parseInt( bg_im_ssry, 10 ) >= 0 ) {
                    var bgImSsry = parseInt( bg_im_ssry, 10 );
                    if( bgImg.indexOf( '&ssry=' ) > 0 ) {
                        bgImg = bgImg.replace( /&ssry=[-+]?(\d*[.])?\d+/i, '&ssry=' + bg_im_ssry );
                    } else {
                        bgImg += '&ssry=' + bg_im_ssry;
                    }
                    if( bgImg.indexOf( '&ssrh=' ) > 0 ) {
                        bgImg = bgImg.replace( /&ssrh=[-+]?(\d*[.])?\d+/i, '&ssrh=0.01' );
                    } else {
                        bgImg += '&ssrh=0.01';
                    }
                    hAdd = '.' + bgImSsry;
                }
                var w = elements[ 0 ].clientWidth;
                var h = elements[ 0 ].clientHeight;
                var url = 'url("' + bgImg + '&ssw=' + w + '&ssh=' + h + hAdd;
                if( typeof window.devicePixelRatio !== 'undefined' && window.devicePixelRatio > 0 ) {
                    url += '&sspr=' + window.devicePixelRatio;
                }
                url += '")';
                elements[ 0 ].style.backgroundImage = url;
                var ssrx = url.indexOf( 'ssrx=' ) > 0 ? parseInt( url.substr( url.indexOf( 'ssrx=' ) + 5 ) ) : 0;
                var ssrw = url.indexOf( 'ssrw=' ) > 0 ? parseInt( url.substr( url.indexOf( 'ssrw=' ) + 5 ) ) : 0;
                var posx = parseInt( ssrx ) > 0 && parseInt( ssrw ) > 0 ? parseInt( ssrx ) + parseInt( ssrw ) / 2 : 50;
                elements[ 0 ].style.backgroundPosition = posx + '% center';
            } else {
                elements[ 0 ].style.backgroundImage = 'none';
                elements[ 0 ].style.backgroundPosition = 'initial';
            }
        } else if( bg_type === 'pattern' ) {
            bgImg = bg_pattern;
            if( bgImg !== '' ) {
                if( bgImg.indexOf( '&ssd_tp=stripe' ) > 0 || bgImg.indexOf( '&ssd_tp=shape' ) > 0 ) {
                    var c1 = bg_color;
                    if( c1.substr( 0, 1 ) === '#' ) {
                        c1 = c1.substr( 1 );
                    }
                    var c2 = bg_colr2;
                    if( c2.substr( 0, 1 ) === '#' ) {
                        c2 = c2.substr( 1 );
                    }
                    bgImg += '&ssc1=' + c1 + '&ssc2=' + c2;
                }
                bgImg = bgImg.replace( 'http:', window.location.protocol ).replace( 'https:', window.location.protocol );
                var url = 'url("' + bgImg + '")';
                elements[ 0 ].style.backgroundImage = url;
            }
        } else {
            elements[ 0 ].style.backgroundImage = 'none';
            if( elements2.length > 0 ) {
                elements2[ 0 ].style.backgroundImage = 'none';
            }
        }
    }
}
</script>
<?php

        if( $ssd_settings && $ssd_settings[ 'settings' ] && $ssd_settings[ 'settings' ][ 'items' ] ) {
            foreach( $ssd_settings[ 'settings' ][ 'items' ] as $area_name => $area ) {
?>
<script>
    swifty_setBgImg(
        "<?php echo $area_name ?>",
        "<?php echo isset( $area[ 'bg_img' ] ) ? $area[ 'bg_img' ] : '' ?>",
        "<?php echo isset( $area[ 'bg_type' ] ) ? $area[ 'bg_type' ] : '' ?>",
        "<?php echo isset( $area[ 'def_bg_type' ] ) ? $area[ 'def_bg_type' ] : '' ?>",
        "<?php echo isset( $area[ 'def_bg_img' ] ) ? $area[ 'def_bg_img' ] : '' ?>",
        "<?php echo isset( $area[ 'bg_pattern' ] ) ? $area[ 'bg_pattern' ] : '' ?>",
        "<?php echo isset( $area[ 'bg_color' ] ) ? $area[ 'bg_color' ] : '#c4c4c4' ?>",
        "<?php echo isset( $area[ 'bg_colr2' ] ) ? $area[ 'bg_colr2' ] : '#898989' ?>",
        "<?php echo isset( $ssd_settings[ 'boxed' ] ) && $ssd_settings[ 'boxed' ] == 1 ? 'boxed' : 'wide' ?>",
        "<?php echo isset( $area[ 'set_bg_im_ssry' ] ) && $area[ 'set_bg_im_ssry' ] === 'custom' ? ( $area[ 'bg_im_ssry' ] != '' ? $area[ 'bg_im_ssry' ] : '50' ) : '' ?>"
    );
</script>
<?php
            }
        }
    }

    function get_string_between($string, $start, $end) {
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
    }

    function ssd_theme_wrapper_start() {
        echo '<section id="main">';
    }

    function ssd_theme_wrapper_end() {
        echo '</section>';
    }

    function woocommerce_support() {
        add_theme_support( 'woocommerce' );
        add_theme_support( 'custom-logo', array(
            'height'      => 512,
            'width'       => 512,
            'flex-height' => true,
            'flex-width'  => true,
        ) );
    }
}

////////////////////////////////////////

function swifty_get_tmpl_type_list() {
    global $tm_start;

//    $filter = json_decode( $_POST[ 'filter' ] );

    $dir = dirname( __FILE__ ) . '/../tmpl/' . $_POST[ 'tp' ] . 's';
    $files = scandir( $dir, 0 );
//    $files = glob( $dir . '/*.less' );
    $data = array();
    foreach( $files as $file ) {
        if( $file !== '.' && $file !== '..' && substr( $file, 0, 1 ) !== '_' && substr( $file, -5 ) === '.less' ) {
            $s = str_replace( '.less', '', $file );
            $dat = array(
                '_id' => $s,
                'name' => str_replace( '_', ' ', $s )
            );

            if( $_POST[ 'tp' ] === 'color' ) {
                $dat[ 'colors' ] = array();
                $dat[ 'colors2' ] = array();

                WP_Filesystem();
                global $wp_filesystem;

                $lines = $wp_filesystem->get_contents_array( $dir . '/' . $file );
                foreach( $lines as $line ) {
                    list( $linePart1, $linePart2 ) = array_pad( explode( ':', $line, 2 ), 2, '' );
                    list( $linePart2a, $linePart2b ) = array_pad( explode( ';', $linePart2, 2 ), 2, '' );
                    $linePart2a = trim( $linePart2a );
                    if( $linePart1 === '@swifty_color_3' || $linePart1 === '@swifty_color_4' || $linePart1 === '@swifty_color_5' ) {
                        $dat[ 'colors' ][] = $linePart2a;
                    } else if( strpos( $linePart1, '@swifty_color_' ) === 0 ) {
                        $dat[ 'colors2' ][] = $linePart2a;
                    }
                }
            }

            $data[] = $dat;
        }
    }

    echo json_encode( array(
            'result' => $data,
            /*, 'filter' => $filter*/
            'tm_elapsed_secs' => microtime( true ) - $tm_start
        ) );
    die();
}

add_action( 'wp_ajax_swifty_tmpl_type_list', 'swifty_get_tmpl_type_list' );

////////////////////////////////////////

function swifty_get_less_files() {
    global $tm_start;

    $ret = "";

    $types = array( 'start', 'layout', 'style', 'color'/*, 'imageset', 'pagetype'*/, 'end' );
    foreach( $types as $type ) {
        $tp = '';
        if( array_key_exists( 'types', $_POST ) && array_key_exists( $type, $_POST[ 'types' ] ) ) {
            $tp = $_POST[ 'types' ][ $type ];
        }
        $fn = dirname( __FILE__ ) . '/../tmpl/' . $type . 's/' . $tp . '.less';
        if( $type === 'start' || $type === 'end' ) {
            $fn = dirname( __FILE__ ) . '/../tmpl/_base/base_' . $type . '.less';
        }

        $ret .= "// INCLUDED FILE: " . $fn . "\r\n";

        if( file_exists( $fn ) ) {

            WP_Filesystem();
            global $wp_filesystem;

            $lines = $wp_filesystem->get_contents_array( $fn );
            foreach( $lines as $line ) {

                list( $linePart1, $linePart2 ) = array_pad( explode( ':', $line, 2 ), 2, '' );
                list( $linePart2a, $linePart2b ) = array_pad( explode( ';', $linePart2, 2 ), 2, '' );
                $linePart2a = trim( $linePart2a );
                list( $linePart2a1, $linePart2a2, $linePart2a3 ) = array_pad( explode( '"', $linePart2a, 3 ), 3, '' );
                $ssparts = array_pad( explode( '#', $linePart2a2, 4 ), 4, '' );
                if( substr( $ssparts[ 1 ], 0, 3 ) === 'SS=' ) {
                    $id = substr( $ssparts[ 1 ], 3 );
                    $row = find_img( $id, substr( $ssparts[ 2 ], 0, 5 ) === "ssc1=" );
                    $ret .= $linePart1 . ":" . $linePart2a1 . " " . '"' . "https://stuff.swifty.online/static/" . $row[ 'file' ];
                    if( substr( $ssparts[ 2 ], 0, 5 ) === "ssc1=" ) {
                        $ret .= '?swifty=1';
                        $ret .= '&ssc1=' . substr( $ssparts[ 2 ], 5 );
                        $ret .= '&ssc2=' . substr( $ssparts[ 3 ], 5 );
                    } else {
//                        $ret .= '?swifty=1&ssw=600,1200,1800';
                        $ret .= '?swifty=1';
                        if( isset( $row[ 'focus_rect' ] ) ) {
                            $fr = explode( ',', $row[ 'focus_rect' ] );
                            $ret .= "" .
                                '&ssrx=' . $fr[ 0 ] .
                                '&ssry=' . $fr[ 1 ] .
                                '&ssrw=' . $fr[ 2 ] .
                                '&ssrh=' . $fr[ 3 ];
                        }
                    }
                    $ret .= '"' . $linePart2a3 . ";" . "\r\n";
                } else {
                    # Generate default vars for areas
                    if( substr( $line, 0, 17 ) === '@swifty_cfg_areas' ) {
                        $ssAreaParts = explode( ' ', $line );
                        foreach( $ssAreaParts as $ssAreaPart ) {
                            if( substr( $ssAreaPart, 0, 1 ) !== '@' ) {
                                $ssAreaParts2 = explode( ';', $ssAreaPart );
                                $cfgArea = $ssAreaParts2[ 0 ];
                                $cfgParts = array(
                                    'on',
                                    'x',
                                    'y',
                                    'flex_order',
                                    'width',
                                    'max_width',
                                    'height',
                                    'min_height',
                                    'margin',
                                    'margin_top',
                                    'margin_bottom',
                                    'margin_left',
                                    'margin_right',
                                    'padding',
                                    'padding_top',
                                    'padding_bottom',
                                    'padding_left',
                                    'padding_right',
                                    'background_color',
                                    'background_image',
                                    'background_size',
                                    'background_repeat',
                                    'background_attachment',
//                                    'border_top_width',
//                                    'border_top_color',
//                                    'border_top_style',
//                                    'border_bottom_width',
//                                    'border_bottom_color',
//                                    'border_bottom_style',
//                                    'border_left_width',
//                                    'border_left_color',
//                                    'border_left_style',
//                                    'border_right_width',
//                                    'border_right_color',
//                                    'border_right_style',
                                    'shadow',
                                    'font_family',
                                    'font_size',
                                    'font_color',
                                    'font_weight',
//                                    'breakout'
                                    'boxed'
                                );
                                foreach( $cfgParts as $cfgPart ) {
                                    $cfgVar = '@swifty_area_' . $cfgArea . '_' . $cfgPart;
                                    $cfgVal = "~''";#//"''";//'""';
                                    if( $cfgPart === 'on' ) {
                                        $cfgVal = '1';
                                    }
                                    #    //                                if( $cfgPart eq 'width' ) {
                                    #    //                                    $cfgVal = '@swifty_cfg_frame_width';
                                    #    //                                }
                                    if( substr( $cfgPart, 0, 6 ) === 'margin' ) {
                                        $cfgVal = '@swifty_margin';
                                    }
                                    if( substr( $cfgPart, 0, 7 ) === 'margin_' ) {
//                                        $cfgVal = 0;
                                        $cfgVal = '@swifty_area_' . $cfgArea . '_margin';
                                        if( ( $cfgArea === 'sidebar' || $cfgArea === 'extrasidebar' ) && ( $cfgPart === 'margin_top' || $cfgPart === 'margin_bottom' ) ) {
                                            $cfgVal = '@swifty_padding';
                                        }
                                    }
                                    if( substr( $cfgPart, 0, 7 ) === 'padding' ) {
                                        $cfgVal = '@swifty_padding';
                                    }
                                    if( substr( $cfgPart, 0, 7 ) === 'padding' && ( $cfgArea === 'body' || $cfgArea === 'frame' || $cfgArea === 'hub' || $cfgArea === 'header' ) ) {
                                        $cfgVal = '0';
                                    }
                                    if( substr( $cfgPart, 0, 8 ) === 'padding_' ) {
                                        $cfgVal = '@swifty_area_' . $cfgArea . '_padding';
                                    }
//                                    if( $cfgPart === 'border_top_width' || $cfgPart === 'border_bottom_width' || $cfgPart === 'border_left_width' || $cfgPart === 'border_right_width' ) {
//                                        $cfgVal = '0';
//                                    }
//                                    if( $cfgPart === 'breakout' ) {
//                                        $cfgVal = '0';
//                                    }
                                    if( $cfgPart === 'boxed' ) {
                                        $cfgVal = '0';
                                    }
                                    if( $cfgPart === 'width' ) {
//                                        if( $cfgArea === 'main' ) {
                                        if( $cfgArea === 'main' ) {
                                            $cfgVal = '100%';
                                        } else/* if( $cfgArea !== 'hub' )*/ {
                                            $cfgVal = '@swifty_cfg_width';
                                        }
                                    }
                                    if( $cfgPart === 'x' ) {
                                        $cfgVal = 'page_center';
                                    }
                                    $ret .= $cfgVar . ": " . $cfgVal . ";\r\n";
                                }

                                #                            $ret .= '@' . $ssAreaParts2[ 0 ] . ": test;\r\n";
                            }
                        }
                        #                    $line = '@@' . $line;
                    }
                    $ret .= $line;// . "\r";
                }
            }
        }
    }

    echo $ret . "\n\n////// tm_elapsed_secs = " . ( microtime( true ) - $tm_start );
    die();
}

add_action( 'wp_ajax_swifty_less_files', 'swifty_get_less_files' );

////////////////////////////////////////

function swifty_set_allow_external() {
    $input = $_POST[ 'allow' ];
    
    update_user_option( get_current_user_id(), 'swifty_allow_external', $input );
    
    echo $input;
    die();
}

add_action( 'wp_ajax_swifty_set_allow_external', 'swifty_set_allow_external' );

////////////////////////////////////////

function swifty_check_theme_inited() {
    // Set defaults if no theme is set
    if( get_theme_mod( 'ssd_css', '' ) === '' ) {
        // Apply default layout, style & color
        set_theme_mod( 'color_id', 'Shades_Of_Grey' );
        set_theme_mod( 'layout_id', 'Oogini_Wide' );
        set_theme_mod( 'style_id', 'Refined' );

        // Copy default header to hosting account
        $upload_dir = wp_upload_dir();
        $file = 'change-this-image.jpg';
        $filename = trailingslashit( $upload_dir[ 'path' ] ) . $file;
        if( get_user_option( 'swifty_allow_external' ) === 'allow' ) {
            copy( 'https://stuff.swifty.online/static/img/change-this-image.jpg?swifty=1', $filename );
        } else {
            copy(  get_template_directory_uri() . '/ssd/img/change-this-image.jpg?swifty=1', $filename );
        }

        // Replace the file url in the settings
        $upload_url = $upload_dir[ 'baseurl' ] . $upload_dir[ 'subdir' ] . '/' . $file;
        $ssd_settings_obj = swifty_read_text( get_template_directory_uri() . '/ssd/cfg/ssd_settings_obj.json' );
        $ssd_settings_obj = str_replace( '__CHANGETHISIMAGE__', str_replace( '\\', '\/',  $upload_url ), $ssd_settings_obj );

        // Apply SSD setting and css loaded from disk
        set_theme_mod( 'ssd_settings_obj', $ssd_settings_obj );
        set_theme_mod( 'ssd_css', swifty_read_text( get_template_directory_uri() . '/ssd/cfg/ssd_css.css' ) );
    }
}

add_action( 'swifty_check_theme_inited', 'swifty_check_theme_inited' );

////////////////////////////////////////

global $swifty_designer;
$swifty_designer = new SwiftySiteDesignerMain();
