<?php
	add_theme_support( 'post-thumbnails' );
	add_theme_support('menus');
	add_theme_support( "title-tag" );
	add_theme_support( 'automatic-feed-links' );
	get_template_part( 'includes/theme-options' );
	function activehost_add_bb_data(){
		$bbsettings = array (
		  'show_default_heading' => '0',
		  'default_heading_selector' => '.fl-post-header',
		  'row_margins' => '0',
		  'row_padding' => '60',
		  'row_width' => '1170',
		  'module_margins' => '0',
		  'responsive_enabled' => '1',
		  'medium_breakpoint' => '992',
		  'responsive_breakpoint' => '768',
		);
		$bbposttypes = array (
			0 => 'post',
			1 => 'page',
			2 => 'slide',
			3 => 'footer',
		);
		add_option( '_fl_builder_settings' , $bbsettings );
		add_option( '_fl_builder_post_types' , $bbposttypes );
	}
	add_action( 'after_switch_theme', 'activehost_add_bb_data' );
	function activehost_update_data(){
		global $wp_filesystem;
		if (empty($wp_filesystem)) {
			require_once (ABSPATH . '/wp-admin/includes/file.php');
			WP_Filesystem();
		}
		$file = get_template_directory().'/includes/demo_data.xml';
		$data = $wp_filesystem->get_contents($file);
		$upload_dir = wp_upload_dir();
		$base_url = $upload_dir['baseurl'];
		
		$search  = array(	's:112:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/pentagon-blueproper.png', 
							's:113:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/pentagon-greenproper.png', 
							's:114:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/pentagon-purpleproper.png', 
							's:111:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/pentagon-redproper.png', 
							's:101:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/wet_snow.png',
							's:114:"http://royaltemplates.com/themes/projects/ActiveHostWordPress/wp-content/uploads/2014/12/section-bg32-1024x484.jpg'
							);
							
		$str1 = $base_url.'/2014/12/pentagon-blueproper.png';
		$str2 = $base_url.'/2014/12/pentagon-greenproper.png';
		$str3 = $base_url.'/2014/12/pentagon-purpleproper.png';
		$str4 = $base_url.'/2014/12/pentagon-redproper.png';
		$str5 = $base_url.'/2014/12/wet_snow.png';
		$str6 = $base_url.'/2014/12/section-bg32-1024x484.jpg';
		
		$count1 = strlen($str1);
		$count2 = strlen($str2);
		$count3 = strlen($str3);
		$count4 = strlen($str4);
		$count5 = strlen($str5);
		$count6 = strlen($str6);
		
    	$replace = array(	's:'.$count1.':"'.$base_url.'/2014/12/pentagon-blueproper.png', 
							's:'.$count2.':"'.$base_url.'/2014/12/pentagon-greenproper.png', 
							's:'.$count3.':"'.$base_url.'/2014/12/pentagon-purpleproper.png', 
							's:'.$count4.':"'.$base_url.'/2014/12/pentagon-redproper.png', 
							's:'.$count5.':"'.$base_url.'/2014/12/wet_snow.png',
							's:'.$count6.':"'.$base_url.'/2014/12/section-bg32-1024x484.jpg',
							);
							
		$data = str_replace($search, $replace, $data);
		$newfile = str_replace("demo_data","demo_data_updated", $file);
		$wp_filesystem->put_contents($newfile, $data);
		
	}
	add_action( 'after_switch_theme', 'activehost_update_data' );
	
	function activehost_theme_setup(){
	//define( 'ACF_LITE', true );
	load_theme_textdomain( 'activehost', TEMPLATEPATH.'/languages' );
	$locale = get_locale();
	$locale_file = TEMPLATEPATH."/languages/$locale.php";
	if ( is_readable($locale_file) )
		require_once($locale_file);
	
	get_template_part( 'class-tgm-plugin-activation' );
	get_template_part( 'includes/plugins' );
		function activehost_excerpt_more( $more ) {
			return '';
		}

		add_filter('widget_text', 'do_shortcode');
		add_filter('excerpt_more', 'activehost_excerpt_more');
		
		if ( ! isset( $content_width ) ) $content_width = 778;
		function activehost_scripts_method() {
	
			if ( is_singular() && isset($commentreply) && $commentreply == "on"){
				wp_enqueue_script( "comment-reply" );
			}
			$template_directory = get_template_directory_uri();	
			wp_dequeue_style( 'ot-dynamic-dynamic-css' );
			wp_enqueue_style( 'ot-dynamic-dynamic-css', get_stylesheet_directory_uri().'/dynamic.css' ,array('main') );
			wp_enqueue_script('jquery');
			wp_enqueue_script('bootstrap',$template_directory.'/js/bootstrap.min.js' ,array( 'jquery' ),"1",true);
			wp_enqueue_script('isotope',$template_directory.'/js/isotope.js' ,array( 'jquery' ),"1",true);
			wp_enqueue_script('scrollto',$template_directory.'/js/jquery-scrollto.js' ,array( 'jquery' ),"1",true);
			wp_enqueue_script('progress',$template_directory.'/js/progress.js' ,array( 'jquery' ),"1",true);
			wp_enqueue_script('custom',$template_directory.'/custom.js' ,array( 'jquery' ),"1",true);
			wp_enqueue_style( 'fontawesome', get_stylesheet_directory_uri().'/css/font-awesome.min.css');
			wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri().'/css/bootstrap.min.css');
			wp_enqueue_style( 'core', get_stylesheet_directory_uri().'/css/core.css');
			wp_enqueue_style( 'main', get_stylesheet_directory_uri().'/style.css' , array('bootstrap'));
			wp_enqueue_style( 'progress', get_stylesheet_directory_uri().'/css/progress.css');
		}

		add_action( 'wp_enqueue_scripts', 'activehost_scripts_method' );
		function activehost_fonts() {
			$protocol = is_ssl() ? 'https' :
			'http';
			wp_enqueue_style( 'mytheme-opensans', "$protocol://fonts.googleapis.com/css?family=Open+Sans:400,700" );
		}

		add_action( 'wp_enqueue_scripts', 'activehost_fonts' );
		add_action( 'init', 'register_my_menus' );
		function register_my_menus() {
			register_nav_menus(array('main-menu' => __( 'Main Menu', 'main-menu' ), ));
			register_nav_menus(array('support-links' => __( 'Support Links', 'support-links' ), ));
		}

		function add_menuid ($page_markup) {
		preg_match('/^<div class=\"([a-z0-9-_]+)\">/i', $page_markup, $matches);
		$divclass = $matches[1];
		$toreplace = array('<div class="'.$divclass.'">', '</div>');
		$new_markup = str_replace($toreplace, '', $page_markup);
		$new_markup = preg_replace('/^<ul>/i', '<ul id="navigation">', $new_markup);
		return $new_markup; }
		
		add_filter('wp_page_menu', 'add_menuid');
		function activehost_widgets_init() {
			
			if(function_exists('register_sidebar')) :
			register_sidebar(array(        'name' => 'single-sidebar','id' => 'sidebar-1','before_widget' => '<div id="%1$s" class="widget %2$s">',        'after_widget' => '</div>',        'before_title' => '<h4>',        'after_title' => '</h4>',    ));
			register_sidebar(array(        'name' => 'page-sidebar','id' => 'sidebar-2','before_widget' => '<div id="%1$s" class="widget %2$s">',        'after_widget' => '</div>',        'before_title' => '<h4>',        'after_title' => '</h4>',    ));
			endif;
		}

		add_action( 'widgets_init', 'activehost_widgets_init' );
		function activehost_customReplace($input, $display = false){
			
			if($display == false){
				$output = str_replace(array("@tick@","@cross@"),array('<span class="glyphicon glyphicon-ok"></span>', '<span class="glyphicon glyphicon-remove"></span>'),$input);
			} else {
				$output = str_replace(array("@tick@","@cross@"),array('<i class="glyphicon glyphicon-ok"></i>', '<i class="glyphicon glyphicon-remove"></i>'),$input);
			}

			return $output;
		}

		
		function activehost_displayTopbar(){
			
			if(is_page_template("page-homepage.php")){
				
				if(function_exists( 'ot_get_option' ) && ot_get_option('homepage_page_type')=="on"){
					echo ' barvisible';
				}

			}

			elseif(is_page()){
				
				if(function_exists( 'ot_get_option' ) && ot_get_option('page')=="on"){
					echo ' barvisible';
				}

			}

			
			if(is_single()){
				
				if(function_exists( 'ot_get_option' ) && ot_get_option('post')=="on"){
					echo ' barvisible';
				}

			}

			
			if(is_archive()){
				
				if(function_exists( 'ot_get_option' ) && ot_get_option('archive')=="on"){
					echo ' barvisible';
				}

			}

		}
		function activehost_displayToggle(){
			if(is_page_template("page-homepage.php")){
				if(function_exists( 'ot_get_option' ) && ot_get_option('homepage_page_type')=="on"){
					echo ' open';
				}
			}
			elseif(is_page()){
				if(function_exists( 'ot_get_option' ) && ot_get_option('page')=="on"){
					echo ' open';
				}
			}
			if(is_single()){
				if(function_exists( 'ot_get_option' ) && ot_get_option('post')=="on"){
					echo ' open';
				}
			}
			if(is_archive()){
				if(function_exists( 'ot_get_option' ) && ot_get_option('archive')=="on"){
					echo ' open';
				}
			}
		}

		
		function activehost_get_the_content_by_id( $post_id=0, $more_link_text = null, $stripteaser = false ){
			$post = get_post($post_id);
			setup_postdata( $post, $more_link_text, $stripteaser );
			return get_the_content();
			wp_reset_postdata();
		}

		add_filter( 'post_thumbnail_html', 'activehost_remove_thumbnail_dimensions', 10, 3 );
		function activehost_remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
			$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
			return $html;
		}

		
		function activehost_custom_excerpt_length( $length ) {
			return 20;
		}

		add_filter( 'excerpt_length', 'activehost_custom_excerpt_length', 999 );
		function activehost_acf_save_post( $post_id ){
			$fields = false;
			global $wp_filesystem;
			// Initialize the WP filesystem, no more using 'file-put-contents' function
			if (empty($wp_filesystem)) {
				require_once (ABSPATH . '/wp-admin/includes/file.php');
				WP_Filesystem();
			}
			if( isset($_POST['fields']["field_54a2dd1711c86"]) ) // archive
				{
				$fields = $_POST['fields'];
				
				if($fields["field_54a2dd1711c86"] == 1 && $fields["field_54a2e1701f72e"] == 1){
					$ss_dir = get_template_directory();
					
					if(!isset($fields["field_54a2e34482479"]) && isset($fields["field_54a2e31b82477"])){
						// if background color
						$style = '#blog{background:'.$fields["field_54a2e31b82477"].';}#blog:before{display:none;}';
					}

					
					if(!empty($fields["field_54a2e34482479"])){
						// if background image
						$image = wp_get_attachment_image_src($fields["field_54a2e34482479"], "full");
						
						if($fields["field_54a2e49382483"] == "None"){
							$field["field_54a2e49382483"] = "";
						}

						$style = '#blog{background: url('.$image[0].') '.$fields["field_54a2e36c8247b"].' '.$fields["field_54a2e3e782480"].' '.$fields["field_54a2e31b82477"].'; background-size:'.$fields["field_54a2e49382483"].';}#blog:before{display:none;}';
					}

					file_put_contents($ss_dir . '/custom-styles/archive-'.$post_id.'.css', $style);
					// Save it as a css file
				}

			}

			
			if( !empty($_POST['fields']["field_54a6bec87a57a"]) ) // single post
				{
				$fields = $_POST['fields'];
				$ss_dir = get_template_directory();
				
				if(!isset($fields["field_54a2e34482479"]) && isset($fields["field_54a2e31b82477"])){
					// if background color
					$style = '#blog{background:'.$fields["field_54a2e31b82477"].';}#blog:before{display:none;}';
				}

				
				if(!empty($fields["field_54a2e34482479"])){
					// if background image
					$image = wp_get_attachment_image_src($fields["field_54a2e34482479"], "full");
					
					if($fields["field_54a2e49382483"] == "None"){
						$field["field_54a2e49382483"] = "";
					}

					$style = '#blog{background: url('.$image[0].') '.$fields["field_54a2e36c8247b"].' '.$fields["field_54a2e3e782480"].' '.$fields["field_54a2e31b82477"].'; background-size:'.$fields["field_54a2e49382483"].';}#blog:before{display:none;}';
				}

				file_put_contents($ss_dir . '/custom-styles/single-'.$post_id.'.css', $style);
				// Save it as a css file
			}

			
			if( !empty($_POST['fields']["field_54a6c033eae42"]) ) // homepage
				{
				$fields = $_POST['fields'];
				$ss_dir = get_template_directory();
				
				if(empty($fields["field_550b3f8d7953e"]) && !empty($fields["field_54a2e31b82477"])){
					// if background color
					$style = '#topcontent{background:'.$fields["field_54a2e31b82477"].';}';
				}

				
				if(!empty($fields["field_550b3f8d7953e"])){
					// if background image
					$image = wp_get_attachment_image_src($fields["field_550b3f8d7953e"], "full");
					
					if($fields["field_54a2e49382483"] == "None"){
						$field["field_54a2e49382483"] = "";
					}

					$style = '#topcontent{background: url('.$image[0].') '.$fields["field_54a2e36c8247b"].' '.$fields["field_54a2e3e782480"].' '.$fields["field_54a2e31b82477"].'; background-size:'.$fields["field_54a2e49382483"].';}';
				}

				file_put_contents($ss_dir . '/custom-styles/homepage-'.$post_id.'.css', $style);

				// Save it as a css file
			}

		}

		add_action('acf/save_post', 'activehost_acf_save_post', 20);
		function activehost_custom_style(){
			
			if(is_archive()){
				$cat = get_query_var('cat');
				$thiscat = get_category ($cat);
				
				if(function_exists("get_field") && get_field("sticky_posts_section", $thiscat) && get_field("custom_styling", $thiscat)){
					wp_enqueue_style( 'custom-styles', $template_directory . '/custom-styles/archive-'.$thiscat->taxonomy."_".$thiscat->term_id.'.css',array('main') );
				}

			}

			
			if(is_single()){
				
				if(function_exists( 'get_field' ) && get_field("top_custom_styling", get_the_id())){
					wp_enqueue_style( 'custom-styles', $template_directory . '/custom-styles/single-'.get_the_id().'.css',array('main') );
				}

			}

			
			if(function_exists("get_field") && is_page_template("page-homepage.php") ){
				$upload_dir = wp_upload_dir();
				// load all slide css
				$slides = get_field("slides", get_the_id());
				foreach($slides as $slide){
					$args = array('p'   => $slide,'post_type' => 'slide','posts_per_page' => 1);
					query_posts( $args );
					while ( have_posts() ) :
					the_post();
					wp_enqueue_style( 'ftl-build-'.get_the_id().'', $upload_dir['baseurl'].'/bb-plugin/cache/'.get_the_id().'-layout.css',array('main'));
					endwhile;
					wp_reset_query();
				}

				
				if(function_exists("get_field") && get_field("homepage_custom_styling", get_the_id())){
					wp_enqueue_style( 'custom-styles', $template_directory . '/custom-styles/homepage-'.get_the_id().'.css',array('main') );
				}

			}

		}

		add_action('wp_enqueue_scripts', 'activehost_custom_style');
		function activehost_get_custom_footer(){
			
			if(is_page_template("page-homepage.php") && function_exists( 'ot_get_option' ) && ot_get_option( 'homepage_footer' )){
				$footerid =  ot_get_option( 'homepage_footer' );
			}

			
			if(is_page() && function_exists( 'ot_get_option' ) && ot_get_option( 'page_footer_' ) && !is_page_template("page-homepage.php")){
				$footerid =  ot_get_option( 'page_footer_' );
			}

			
			if(is_single() && function_exists( 'ot_get_option' ) && ot_get_option( 'post_footer' )){
				$footerid =  ot_get_option( 'post_footer' );
			}

			
			if(is_archive() && function_exists( 'ot_get_option' ) && ot_get_option( 'archive_footer' )){
				$footerid =  ot_get_option( 'archive_footer' );
			}

			
			if(function_exists("getCurrency") && function_exists( 'ot_get_option' ) && ot_get_option( 'whmcs_footer' )){
				$footerid =  ot_get_option( 'whmcs_footer' );
			}

			
			if(empty($footerid) && function_exists( 'ot_get_option' )){
				$footerid = ot_get_option( 'default' );
			}

			$upload_dir = wp_upload_dir();
			// load all slide css
			if(isset($footerid)){
			$args = array('post_type' => 'footer','posts_per_page' => 1, 'p' => $footerid);
			query_posts( $args );
			while ( have_posts() ) :
			the_post();
			wp_enqueue_style( 'ftl-build-'.get_the_id().'', $upload_dir['baseurl'].'/bb-plugin/cache/'.get_the_id().'-layout.css',array('main'));
			endwhile;
			wp_reset_query();
			}
		}

		add_action('wp_enqueue_scripts', 'activehost_get_custom_footer');
		function activehost_buildBaseString($baseURI, $method, $params) {
			$r = array();
			ksort($params);
			foreach($params as $key=>$value){
				$r[] = "$key=" . rawurlencode($value);
			}

			return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
		}

		
		function activehost_buildAuthorizationHeader($oauth) {
			$r = 'Authorization: OAuth ';
			$values = array();
			foreach($oauth as $key=>$value)        $values[] = "$key=\"" . rawurlencode($value) . "\"";
			$r .= implode(', ', $values);
			return $r;
		}

		
		function activehost_timeago($timestamp){
			//type cast, current time, difference in timestamps
			$timestamp      = (int) $timestamp;
			$current_time   = time();
			$diff           = $current_time - $timestamp;
			//intervals in seconds
			$intervals      = array (        'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute'=> 60    );
			//now we just find the difference
			
			if ($diff == 0)    {
				return 'just now';
			}

			
			if ($diff < 60)    {
				return $diff == 1 ? $diff . ' second ago' :
				$diff . ' seconds ago';
			}

			
			if ($diff >= 60 && $diff < $intervals['hour'])    {
				$diff = floor($diff/$intervals['minute']);
				return $diff == 1 ? $diff . ' minute ago' :
				$diff . ' minutes ago';
			}

			
			if ($diff >= $intervals['hour'] && $diff < $intervals['day'])    {
				$diff = floor($diff/$intervals['hour']);
				return $diff == 1 ? $diff . ' hour ago' :
				$diff . ' hours ago';
			}

			
			if ($diff >= $intervals['day'] && $diff < $intervals['week'])    {
				$diff = floor($diff/$intervals['day']);
				return $diff == 1 ? $diff . ' day ago' :
				$diff . ' days ago';
			}

			
			if ($diff >= $intervals['week'] && $diff < $intervals['month'])    {
				$diff = floor($diff/$intervals['week']);
				return $diff == 1 ? $diff . ' week ago' :
				$diff . ' weeks ago';
			}

			
			if ($diff >= $intervals['month'] && $diff < $intervals['year'])    {
				$diff = floor($diff/$intervals['month']);
				return $diff == 1 ? $diff . ' month ago' :
				$diff . ' months ago';
			}

			
			if ($diff >= $intervals['year'])    {
				$diff = floor($diff/$intervals['year']);
				return $diff == 1 ? $diff . ' year ago' :
				$diff . ' years ago';
			}

		}

		
		function activehost_whmcs_connect(){
			if(function_exists( 'ot_get_option' ) && ot_get_option( 'whmcs_dbconnect_path' )){
			if(!function_exists("gracefulcorerequiredfileinclude")){
				$wordpresspage = "yes";
				require_once(ot_get_option( 'whmcs_dbconnect_path' ));
			} else {
				$wordpresspage = "no";
			}
			}
		}

		add_action('wp_head', 'activehost_whmcs_connect');
		function activehost_wp_title( $title, $sep ) {
			
			if ( is_feed() ) {
				return $title;
			}

			global $page, $paged;
			$currentpage = $title;
			$title = "";
			// Add the blog name
			$title .= get_bloginfo( 'name', 'display' )." | ";
			// Add the blog description for the home/front page.
			$site_description = get_bloginfo( 'description', 'display' );
			
			if ( $site_description && ( is_home() || is_front_page() ) ) {
				$title .= "$site_description";
			}

			// Add a page number if necessary:
			
			if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
				$title .= sprintf( __( 'Page %s', '_s' ), max( $paged, $page ) );
			}

			$title .= $currentpage;
			return $title;
		}

		add_filter( 'wp_title', 'activehost_wp_title', 10, 2 );
	
	
		if(function_exists( 'ot_get_option' )){$googlefontapi = ot_get_option('google_api');}
	if( class_exists( 'OT_Loader' ) ):
		global $ot_options;
		$ot_options = get_option( 'option_tree' );
		
		$default_theme_fonts = array(  'arial' => 'Arial, Helvetica, sans-serif',  'helvetica' => 'Helvetica, Arial, sans-serif',  'georgia' => 'Georgia, "Times New Roman", Times, serif',  'tahoma' => 'Tahoma, Geneva, sans-serif',  'times' => '"Times New Roman", Times, serif',  'trebuchet' => '"Trebuchet MS", Arial, Helvetica, sans-serif',  'verdana' => 'Verdana, Geneva, sans-serif',  );
		defined('OT_FONT_DEFAULTS') or define('OT_FONT_DEFAULTS', serialize($default_theme_fonts));
		defined('OT_FONT_API_KEY') or define('OT_FONT_API_KEY', $googlefontapi);
		defined('OT_FONT_CACHE_INTERVAL') or define('OT_FONT_CACHE_INTERVAL', 0);
		include_once( get_template_directory().'/ot-google-fonts.php' );
		global $google_font_array;
		$google_font_array = ot_get_google_font(OT_FONT_API_KEY, OT_FONT_CACHE_INTERVAL);
		
		function ot_filter_recognized_font_families( $array, $field_id ) {
			global $google_font_array;
			if(function_exists( 'ot_get_option' )){
				$googlefontapi = ot_get_option('google_api');
			}else{
				$googlefontapi = "";
			}
			$font_array = array();
			if($google_font_array){
				foreach($google_font_array as $index => $value){
					$font_array[$index] = $value['family'];
				}
	
			}
			$array = array_merge(unserialize(OT_FONT_DEFAULTS), $font_array);
			return $array;
		}
	
		add_filter( 'ot_recognized_font_families', 'ot_filter_recognized_font_families', 1, 2 );
		endif;
	}
	add_action( 'after_setup_theme', 'activehost_theme_setup' );
