<?php

/*
 * Copyright 2013-2015, Theia Sticky Sidebar, WeCodePixels, http://wecodepixels.com
 */

add_action( 'wp_enqueue_scripts', 'TssMisc::wp_enqueue_scripts' );
add_action( 'admin_enqueue_scripts', 'TssMisc::admin_enqueue_scripts' );
add_action( 'wp_footer', 'TssMisc::wp_footer' );

class TssMisc {
	public static function wp_enqueue_scripts() {
		if ( self::isDisabled() ) {
			return;
		}

		// Sidebar JS
		wp_register_script( 'theia-sticky-sidebar.js', plugins_url( 'js/theia-sticky-sidebar.js', __FILE__ ), array( 'jquery' ), TSS_VERSION, true );
		wp_enqueue_script( 'theia-sticky-sidebar.js' );
	}

	public static function admin_enqueue_scripts() {
		// Admin CSS
		wp_register_style( 'theiaStickySidebar-admin', plugins_url( 'css/admin.css', __FILE__ ), TST_VERSION );
		wp_enqueue_style( 'theiaStickySidebar-admin' );
	}

	public static function wp_footer() {

		$sidebar_selector = TssOptions::get( 'sidebarSelector' );

		$options = array(
			'containerSelector'      => TssOptions::get( 'containerSelector' ),
			'additionalMarginTop'    => TssOptions::get( 'additionalMarginTop' ),
			'additionalMarginBottom' => TssOptions::get( 'additionalMarginBottom' ),
			'updateSidebarHeight'    => TssOptions::get( 'updateSidebarHeight' ),
			'minWidth'               => TssOptions::get( 'minWidth' )
		);
		if ( self::isDisabled() ) {
			return;
		}
		if ( $sidebar_selector == '' ) {
			$sidebar_selector = '#secondary, #sidebar, .sidebar, #primary';
		}

		if ( $customCss = TssOptions::get( 'customCss' ) ) {
			echo "\n<style>\n" . $customCss . "\n</style>\n";
		}

		?>
		<script type="text/javascript">
			jQuery(document).ready(function () {
				jQuery(<?php echo json_encode($sidebar_selector); ?>).theiaStickySidebar(<?php echo json_encode($options); ?>);
			});
		</script>
	<?php
	}

	public static function isDisabled() {
		return
			( TssOptions::get( 'disableOnHomePage' ) && is_home() ) ||
			( TssOptions::get( 'disableOnCategoryPages' ) && is_category() ) ||
			( TssOptions::get( 'disableOnPages' ) && is_page() ) ||
			( TssOptions::get( 'disableOnPosts' ) && is_single() );
	}

	public static function get_request_scheme() {
		$scheme = stripos( $_SERVER['SERVER_PROTOCOL'], 'https' ) === true ? 'https' : 'http';

		return $scheme;
	}
}
