<?php
/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

/**
 * Init active InnoThemes's theme.
 *
 * @package  IT_Theme_Framework
 * @since    1.0.0
 */
class IT_Init_Theme {
	/**
	 * Assets to be registered.
	 *
	 * @var  array
	 */
	protected static $assets = array(
		/**
		 * Third party assets.
		 */
		'it-bootstrap-js' => array(
			'src'  => 'assets/3rd-party/bootstrap/js/bootstrap.min.js',
			'deps' => array( 'jquery' ),
			'ver'  => '2.3.2',
		),

		'it-bootstrap-modal-js' => array(
			'src'  => 'assets/3rd-party/bootstrap/js/bootstrap-modal.js',
			'deps' => array( 'it-bootstrap-js' ),
			'ver'  => '2.3.2',
		),

		'it-bootstrap-transition-js' => array(
			'src'  => 'assets/3rd-party/bootstrap/js/bootstrap-transition.js',
			'deps' => array( 'it-bootstrap-js' ),
			'ver'  => '2.3.2',
		),

		'it-chosen-css' => array(
			'src' => 'assets/3rd-party/chosen/chosen.min.css',
			'ver' => '0.10.0',
		),

		'it-chosen-js' => array(
			'src'  => 'assets/3rd-party/chosen/chosen.jquery.min.js',
			'deps' => array( 'jquery' ),
			'ver'  => '0.10.0',
		),

		'it-classygradient-css' => array(
			'src'  => 'assets/3rd-party/classygradient/css/jquery.classygradient.css',
			'deps' => array( 'it-colorpicker-css' ),
			'ver'  => '1.0.0',
		),

		'it-classygradient-js' => array(
			'src'  => 'assets/3rd-party/classygradient/js/jquery.classygradient.js',
			'deps' => array( 'jquery-ui-draggable', 'it-colorpicker-js' ),
			'ver'  => '1.0.0',
		),

		'it-colorpicker-css' => array(
			'src' => 'assets/3rd-party/colorpicker/css/colorpicker.css',
		),

		'it-colorpicker-js' => array(
			'src'  => 'assets/3rd-party/colorpicker/js/colorpicker.js',
			'deps' => array( 'jquery' )
		),

		'it-font-icomoon-css' => array(
			'src' => 'assets/3rd-party/font-icomoon/css/icomoon.css',
		),

		'it-font-ello-css' => array(
			'src' => 'assets/3rd-party/fontello/css/fontello.css',
		),

		'it-joomlashine-css' => array(
			'src'  => 'assets/3rd-party/joomlashine/css/jsn-gui.css',
		),

		'it-jquery-json-js' => array(
			'src' => 'assets/3rd-party/jquery-json/jquery.json-2.3.min.js',
			'ver' => '2.3',
		),

		'it-jquery-tipsy-css' => array(
			'src' => 'assets/3rd-party/jquery-tipsy/tipsy.css',
			'ver' => '1.0.0a',
		),

		'it-jquery-tipsy-js' => array(
			'src'  => 'assets/3rd-party/jquery-tipsy/jquery.tipsy.js',
			'deps' => array( 'jquery' ),
			'ver'  => '1.0.0a',
		),

		'it-jquery-ui-css' => array(
			'src' => 'assets/3rd-party/jquery-ui/css/ui-bootstrap/jquery-ui-1.9.0.custom.css',
			'ver' => '1.9.0',
		),

		'it-load-post-js' => array(
			'src' => 'assets/3rd-party/innothemes/js/load-more.js',
			'ver' => '1.0.0',
		),

		'it-menu-advance-js' => array(
			'src' => 'assets/3rd-party/menu-advance.js',
			'ver' => '1.0.0',
		),

		'it-menu-sticky-js' => array(
			'src' => 'assets/3rd-party/menu-sticky.js',
			'ver' => '1.0.0',
		),

		/**
		 * InnoThemes assets.
		 */
		'it-theme-admin-css' => array(
			'src'  => 'assets/innothemes/css/admin.css',
			'deps' => array( 'it-joomlashine-css', 'it-font-ello-css' ),
			'ver'  => '1.0.0',
		),

		'it-theme-admin-js' => array(
			'src'  => 'assets/innothemes/js/theme-admin.js',
			'deps' => array( 'it-form-js', 'it-sample-data-js', 'it-jquery-json-js' ),
			'ver'  => '1.0.0',
		),

		'it-page-admin-css' => array(
			'src'  => 'assets/innothemes/css/page-options.css',
			'deps' => array( 'it-joomlashine-css', 'it-font-ello-css' ),
			'ver'  => '1.0.0',
		),

		'it-page-admin-js' => array(
			'src'  => 'assets/innothemes/js/page-admin.js',
			'deps' => array( 'it-form-js', 'it-sample-data-js', 'it-jquery-json-js' ),
			'ver'  => '1.0.0',
		),

		'it-column-settings-js' => array(
			'src'  => 'assets/innothemes/js/column-settings.js',
			'deps' => array( 'jquery' ),
			'ver'  => '1.0.0',
		),

		'it-form-css' => array(
			'src'  => 'assets/innothemes/css/form.css',
			'deps' => array( 'it-joomlashine-css', 'it-jquery-ui-css', 'it-jquery-tipsy-css' ),
			'ver'  => '1.0.0',
		),

		'it-form-js' => array(
			'src'  => 'assets/innothemes/js/form.js',
			'deps' => array( 'jquery-ui-tabs', 'jquery-ui-accordion', 'it-jquery-tipsy-js', 'it-column-settings-js', 'it-media-selector-js', 'it-profile-js', 'it-social-channels-js', 'it-text-logo-js' ),
			'ver'  => '1.0.0',
		),

		'it-media-selector-js' => array(
			'src'  => 'assets/innothemes/js/media-selector.js',
			'deps' => array( 'jquery-ui-dialog' ),
			'ver'  => '1.0.0',
		),

		'it-profile-js' => array(
			'src'  => 'assets/innothemes/js/profile.js',
			'deps' => array( 'jquery' ),
			'ver'  => '1.0.0',
		),

		'it-radio-image-js' => array(
			'src'  => 'assets/innothemes/js/radio-image.js',
			'deps' => array( 'jquery-ui-dialog' ),
			'ver'  => '1.0.0',
		),

		'it-sample-data-js' => array(
			'src'  => 'assets/innothemes/js/sample-data.js',
			'deps' => array( 'jquery-ui-dialog' ),
			'ver'  => '1.0.0',
		),

		'it-social-channels-js' => array(
			'src'  => 'assets/innothemes/js/social-channels.js',
			'deps' => array( 'jquery-ui-sortable', 'jquery-ui-dialog' ),
			'ver'  => '1.0.0',
		),

		'it-text-logo-js' => array(
			'src'  => 'assets/innothemes/js/text-logo.js',
			'deps' => array( 'jquery-ui-dialog' ),
			'ver'  => '1.0.0',
		),

		'it-theme-style-css' => array(
			'src' => 'assets/innothemes/css/style.css',
			'ver' => '1.0.0',
		),

		'it-air-style-css' => array(
			'src' => 'assets/innothemes/air/css/style.css',
			'ver' => '1.0.0',
		),

		'it-theme-desktop-css' => array(
			'src' => 'assets/innothemes/css/desktop.css',
			'ver' => '1.0.0',
		),

		'it-theme-smartphone-css' => array(
			'src' => 'assets/innothemes/css/smartphone.css',
			'ver' => '1.0.0',
		),

		'it-theme-tablet-css' => array(
			'src' => 'assets/innothemes/css/tablet.css',
			'ver' => '1.0.0',
		),

	);

	/**
	 * Menus to be registered.
	 *
	 * @var  array
	 */
	protected static $menus = array(
		'top_menu'      => 'Top Menu',
		'main_menu'     => 'Main Menu',
		'footer_menu'   => 'Footer Menu',
		'404_page_menu' => '404 Page Menu',
	);

	/**
	 * Sidebars to be registered.
	 *
	 * @var  array
	 */
	protected static $sidebars = array(
		array(
			'id'            => 'promo-1',
			'name'          => 'Promo 1',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'promo-2',
			'name'          => 'Promo 2',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'promo-3',
			'name'          => 'Promo 3',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'promo-4',
			'name'          => 'Promo 4',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'left-sidebar',
			'name'          => 'Left Sidebar',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'right-sidebar',
			'name'          => 'Right Sidebar',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'bottom-1',
			'name'          => 'Bottom 1',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'bottom-2',
			'name'          => 'Bottom 2',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'bottom-3',
			'name'          => 'Bottom 3',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),

		array(
			'id'            => 'bottom-4',
			'name'          => 'Bottom 4',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		),
	);

	/**
	 * Define necessary theme related constants.
	 *
	 * @return  void
	 */
	public static function defines() {
		$definition = apply_filters(
			'it_theme_defines',
			array(
				'theme_name'       => 'IT Theme Framework',
				'theme_id'         => 'it-thmfw',
				'theme_path'       => get_template_directory(),
				'theme_uri'        => get_template_directory_uri(),
				'theme_textdomain' => 'it-thmfw',
			)
		);

		foreach ( $definition as $key => $value ) {
			$key = 'IT_' . strtoupper( $key );

			if ( 'PATH' == substr( $key, -4 ) ) {
				$value = str_replace( '\\', '/', $value );
			}

			if ( ! defined( $key ) ) {
				define( $key, $value );
			}
		}
	}

	/**
	 * Do some initialization before rendering.
	 *
	 * @return  void
	 */
	public static function prepare() {
		// Prepare theme options
		global $it_options;

		$it_options = IT_Theme_Options::prepare();

		// Load theme framework text domain
		load_theme_textdomain( IT_THEME_TEXTDOMAIN, IT_THEME_PATH . '/languages' );

		if ( IT_THEME_TEXTDOMAIN != IT_THEME_TEXTDOMAIN ) {
			// Load theme text domain
			load_theme_textdomain( IT_THEME_TEXTDOMAIN, IT_THEME_PATH . '/languages' );
		}
	}

	/**
	 * Hook theme into WordPress system.
	 *
	 * @return  void
	 */
	public static function hook() {
		// Register framework features with proper actions
		$classes = array(
			'Gadget_Base',
			'Init_Assets',
			'Init_Meta_Box',
			'Init_Post_Type',
			'Theme_Render',
			'Theme_Customizer',
		);

		foreach ( $classes as $class ) {
			if ( class_exists( "IT_{$class}" ) && method_exists( "IT_{$class}", 'hook' ) ) {
				call_user_func( array( "IT_{$class}", 'hook' ) );
			}
		}

		// Do it_theme_pre_init action
		do_action( 'it_theme_pre_init' );

		// Add theme supports
		self::add_supports();

		// Add necessary actions
		self::add_actions();

		// Add necessary filters
		self::add_filters();

		// Do it_theme_post_init action
		do_action( 'it_theme_post_init' );
	}

	/**
	 * Add theme supports.
	 *
	 * @return  void
	 */
	protected static function add_supports() {
		add_theme_support( 'custom-header'        );
		add_theme_support( 'custom-background'    );
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'post-thumbnails'      );
	}

	/**
	 * Add necessary actions.
	 *
	 * @return  void
	 */
	protected static function add_actions() {
		// Register menus and sidebars
		add_action( 'init', array( __CLASS__, 'register_menus'     ) );
		add_action( 'init', array( __CLASS__, 'register_sidebars'  ) );

		// Register meta boxes
		add_action( 'wp_loaded', array( __CLASS__, 'register_meta_boxes' ) );

		// Load theme framework and child theme text domain
		add_action( 'after_setup_theme', array( __CLASS__, 'load_language' ) );

		// Hande theme options saving
		add_action( 'customize_save_after', array( 'IT_Theme_Options', 'finalize' ) );

		// Handle theme options update from outside, e.g. menu location assignment
		add_action( 'updated_option', array( __CLASS__, 'update_option' ), 10, 3 );

		// Load jQuery library for front end
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_jquery' ), 11 );

		// Setup custom login page logo
		add_action( 'login_enqueue_scripts', array( 'IT_Theme_Render', 'login_logo' ) );

		// Register under construction page
		add_action( 'template_redirect', array( __CLASS__, 'under_construction_page' ) );
	}

	/**
	 * Add necessary filters.
	 *
	 * @return  void
	 */
	protected static function add_filters() {
		// Add filter to register assets
		add_filter( 'it_assets_register', array( __CLASS__, 'apply_assets' ) );

		// Register navigation menu related filters
		add_filter( 'wp_nav_menu_args'   , array( __CLASS__, 'wp_nav_menu_args'    ) );
		add_filter( 'wp_nav_menu_objects', array( __CLASS__, 'wp_nav_menu_objects' ) );

		// Register excerpt related filters
		add_filter( 'excerpt_more'  , array( __CLASS__, 'excerpt_more'   )      );
		add_filter( 'excerpt_length', array( __CLASS__, 'excerpt_length' ), 999 );

		// Add specific CSS class for body tag
		add_filter( 'body_class', array( __CLASS__, 'body_class' ) );
	}

	/**
	 * Register navigation menus.
	 *
	 * @return  void
	 */
	public static function register_menus() {
		if ( function_exists( 'register_nav_menus' ) ) {
			// Filter menus to be registered
			$menus = apply_filters( 'it_theme_menu_register', self::$menus );

			foreach ( $menus as $id => $name ) {
				$menus[ $id ] = esc_html__( $name, IT_THEME_TEXTDOMAIN );
			}

			register_nav_menus( $menus );
		}
	}

	/**
	 * Register sidebars.
	 *
	 * @return  void
	 */
	public static function register_sidebars() {
		if ( function_exists( 'register_sidebar' ) ) {
			// Filter sidebars to be registered
			$sidebars = apply_filters( 'it_theme_sidebar_register', self::$sidebars );

			foreach ( $sidebars as $sidebar ) {
				$sidebar['name'] = esc_html__( $sidebar['name'], IT_THEME_TEXTDOMAIN );

				register_sidebar( $sidebar );
			}
		}
	}

	/**
	 * Register meta boxes.
	 *
	 * @return  void
	 */
	public static function register_meta_boxes() {
		// Get all registered post types
		$post_types = get_post_types( array( 'public' => true ) );

		// Add metabox for page options
		IT_Init_Meta_Box::add(
			array(
				'id'        => 'it_page_options',
				'title'     => 'IT Page Options',
				'callback'  => array( 'IT_Theme_Options', 'render_page_options' ),
				'save_post' => array( 'IT_Theme_Options', 'update_page_options' ),
				'post_type' => $post_types,
			)
		);
	}

	/**
	 * Load language translation.
	 *
	 * @return  void
	 */
	public static function load_language() {
		// Load theme framework text domain
		load_theme_textdomain( IT_THEME_TEXTDOMAIN, IT_THEME_PATH . '/languages' );
	}

	/**
	 * Handle theme options update from outside.
	 *
	 * @param   string  $option_name  Name of updated option.
	 * @param   mixed   $old_value    Old option value.
	 * @param   mixed   $new_value    New option value.
	 *
	 * @return  void
	 */
	public static function update_option( $option_name, $old_value, $new_value ) {
		if ( strcmp( $option_name, 'theme_mods_' . IT_THEME_ID ) != 0 ) {
			return;
		}

		// Get active theme option profile
		$profile = get_theme_mod( 'profile' );

		// Check to see if any linked option has been updated
		global $pagenow;

		if ( 'nav-menus.php' == $pagenow && in_array( $_REQUEST['action'], array( 'update', 'locations' ) ) ) {
			// Check if menu location assignment has been changed
			if ( $old_value['nav_menu_locations'] != $new_value['nav_menu_locations'] ) {
				// Reset old menu location assignments
				foreach ( array_merge( $old_value['nav_menu_locations'], $new_value['nav_menu_locations'] ) as $location => $menu_id ) {
					if ( isset( $old_value['nav_menu_locations'][ $location ] ) && ! isset( $new_value['nav_menu_locations'][ $location ] ) ) {
						$menu_id = '';
					}

					set_theme_mod( "{$location}_{$profile}", $menu_id );
				}
			}
		} elseif ( 'admin-ajax.php' == $pagenow && 'customize_save' == $_POST['action'] ) {
			// Generate Apple icons
			$path = IT_THEME_PATH . '/images';

			// Get new value
			if ( isset( $new_value["apple_icon_{$profile}"] ) ) {
				$src = $new_value["apple_icon_{$profile}"];
			}

			if ( isset( $src ) && ! empty( $src ) ) {
				$upload_location = wp_upload_dir();

				// Convert image URL to server path
				$src = str_replace( $upload_location['baseurl'], $upload_location['basedir'], $src );

				// Generate icon for Apple iPhone
				$icon = wp_get_image_editor( $src );

				$icon->resize( '57', '57', true );
				$icon->save( "{$path}/apple-touch-icon-iphone.png", 'image/png' );

				// Generate icon for Apple iPhone with Retina screen
				$icon = wp_get_image_editor( $src );

				$icon->resize( '114', '114', true );
				$icon->save( "{$path}/apple-touch-icon-iphone4.png", 'image/png' );

				// Generate icon for Apple iPad
				$icon = wp_get_image_editor( $src );

				$icon->resize( '72', '72', true );
				$icon->save( "{$path}/apple-touch-icon-ipad.png", 'image/png' );

				// Generate icon for Apple iPad with Retina screen
				$icon = wp_get_image_editor( $src );

				$icon->resize( '144', '144', true );
				$icon = $icon->save( "{$path}/apple-touch-icon-ipad3.png", 'image/png' );
			}

			// Filter menus to be registered
			$menus = apply_filters( 'it_theme_menu_register', self::$menus );

			// Check if menu location assignment has been changed
			foreach ( array_keys( $menus ) as $location ) {
				$nav_menu_locations[ $location ] = $new_value["{$location}_{$profile}"];

				if ( $old_value["{$location}_{$profile}"] != $new_value["{$location}_{$profile}"] ) {
					$update = true;
				}
			}

			if ( isset( $update ) && $update ) {
				set_theme_mod( 'nav_menu_locations', $nav_menu_locations );
			}
		}
	}

	/**
	 * Enqueue jQuery library for the front end.
	 *
	 * @return  void
	 */
	public static function enqueue_jquery() {
		wp_enqueue_script( 'jquery' );
	}

	/**
	 * Redirect to under construction page
	 *
	 * @return  void
	 */
	public static function under_construction_page() {
		global $it_options;

		// Check if coming soon page is enabled
		if ( $it_options['coming_soon_page'] ) {
			if ( ! is_feed() ) {
				// Check if user is not logged in
				if ( ! is_user_logged_in() ) {
					// Load coming soon page
					include IT_Loader::get_path( '../under-construction.php' );

					exit;
				}
			}

			// Check if user is logged in
			if ( is_user_logged_in() ) {
				global $current_user;

				// Get user role
				get_currentuserinfo();

				$loggedInUserID = $current_user->ID;
				$userData = get_userdata( $loggedInUserID );

				// If user role is not 'administrator' then redirect to coming soon page
				if ( 'administrator' != $userData->roles[0] ) {
					if ( ! is_feed() ) {
						include IT_Loader::get_path( '../under-construction.php' );

						exit;
					}
				}
			}
		}
	}

	/**
	 * Filter to register supported assets.
	 *
	 * @param   array  $assets  Current assets.
	 *
	 * @return  array
	 */
	public static function apply_assets( $assets = array() ) {
		foreach ( self::$assets as $key => $value ) {
			if ( ! isset( $assets[ $key ] ) ) {
				// Fine-tune asset location
				if ( ! preg_match( '#^(https?:)?/#', $value['src'] ) && @is_file( IT_THEME_PATH . '/' . $value['src'] ) ) {
					$value['src'] = IT_THEME_URI . '/' . $value['src'];
				}

				$assets[ $key ] = $value;
			}
		}

		return $assets;
	}

	/**
	 * Apply 'wp_nav_menu_args' filter.
	 *
	 * @param   array  $args  Arguments to pass to 'wp_nav_menu' function.
	 *
	 * @return  array
	 */
	public static function wp_nav_menu_args( $args = '' ) {
		$args['container'] = false;

		return $args;
	}

	/**
	 * Apply 'wp_nav_menu_objects' filter.
	 *
	 * @param   array  $items  Array of menu items.
	 *
	 * @return  array
	 */
	public static function wp_nav_menu_objects( $items ) {
		// Get parents
		$parents = array();

		foreach ( $items as $item ) {
			if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
				$parents[] = $item->menu_item_parent;
			}
		}

		// Set class for parents
		foreach ( $items as $item ) {
			if ( in_array( $item->ID, $parents ) ) {
				$item->classes[] = 'menu-parent-item';
			}
		}

		return $items;
	}

	/**
	 * Apply 'excerpt_more' filter.
	 *
	 * @param   string  $more  Excerpt more string.
	 *
	 * @return  string
	 */
	public static function excerpt_more( $more ) {
		ob_start();
		IT_Theme_Render::read_more();
		return ob_get_clean();
	}

	/**
	 * Apply 'excerpt_length' filter.
	 *
	 * @param   integer  $length  Current excerpt length.
	 *
	 * @return  integer
	 */
	public static function excerpt_length( $length ) {
		return 20;
	}

	/**
	 * Apply 'body_class' filter.
	 *
	 * @param   array  $classes A list of existing body class values
	 *
	 * @return  array
	 */
	public static function body_class( $classes ) {
		global $it_options;

		if ( 'boxed' == $it_options['page_layout'] ) {
			$classes[] = 'it-layout-boxed';
		} elseif ( 'full_width' == $it_options['page_layout'] ) {
			$classes[] = 'it-layout-fullwidth';
		}
		return $classes;
	}
}
