<?php
function v_silo_builder_init(){
	$v_category_order = new V_Category_Order();
	$v_silo_builder = new V_Silo_Builder(); 	
}

if ( !class_exists('V_Silo_Builder') ) { 
	class V_Silo_Builder {
		/**
		 * Google API key to access YouTube API v3
		 *
		 * Get your api key https://developers.google.com/youtube/v3/getting-started#before-you-start
		 *
		 * @var string
		 */
		private $google_api_key = 'AIzaSyB00Nabr2ZCLJXW6uken0JhQUKxAk-kx0M';
		/**
		 * DB version option name
		 *
		 * @var string
		 */
		private $db_version_option = 'vsilobuilder_db_version';
		/**
		 * Current db version
		 *
		 * @var string
		 */
		private $db_version = '1';
		/**
		 * Added videos table name
		 */
		const added_videos_table = 'vsilobuilder_added_videos';
		private $_siloArray = array(
   		'dws_id' => '',
		'cat_ids' => ''
		);
		private $_siloStyles = array(
			'link_color'=>'#000000',
			'link_size'=>'13',
			'link_size_type'=>'px',
			'line_height'=>'1.5'
		);
		private $_siloOptions = array(
			'silo_title'=>'',
			'status'=>'draft',
			'shortcode' => 0,
			'silo-title'=>'primary_keyword_pagename',
			'silo-slug'=>'primary_keyword_pagename',
			'article-title'=>'Article_headline',
			'article-slug'=>'primary_keyword_pagename',
			'longtail-title'=>'Article_headline',
			'longtail-slug'=>'primary_keyword_pagename'				
		);
		private $_silo_styles = array();
		private $_silo_options = array();
		private $variables_buffer = array();
		 //Constructor
		public function __construct()
		{
			# only in admin
			if (is_admin())
			{
				# check if tables need to be installed
				if ($this->db_version != get_option($this->db_version_option))
				{
					$this->install_tables();
				}
			}
			
			# if option is not set
			if (false === get_option(V_PLUGIN_OPTIONS . '_youtube'))
			{
				# set defaults
				update_option(V_PLUGIN_OPTIONS . '_youtube', array(
					'channel' => '',
					'upload_date' => 'any',
					'duration' => 'any',
					'comments' => '1',
					'post_content' => "{embedHtml}\n\n",
				));
			}
			# 2 shortcodes
			add_shortcode('ne_shortcode1', array($this, 'dws_shortcode1_func'));
			add_shortcode('ne_shortcode2', array($this, 'dws_shortcode2_func'));
			# silo structure manual sorting
			add_action('wp_ajax_silo_structure_manual_sorting', array($this, 'silo_structure_manual_sorting_callback'));
			# add meta boxes
			add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
			# save post data late binding for overwriting category
			add_action('save_post', array($this, 'silostructure_save_postdata'), 11);
			add_action('vsilo-import', array($this, 'processSiloImport'), 10, 1);
			//$plugin_dir = basename(dirname(__FILE__));
 			//load_plugin_textdomain( 'wpus_silo', false, $plugin_dir );       
			$this->_silo_options = maybe_unserialize(get_option(V_PLUGIN_OPTIONS));
			$this->_silo_styles = maybe_unserialize(get_option(V_PLUGIN_STYLES));
			if(empty($this->_silo_options) || !is_array($this->_silo_options)) $this->_silo_options = $this->_siloOptions;
			if(empty($this->_silo_styles) || !is_array($this->_silo_styles)) $this->_silo_styles = $this->_siloStyles;
			add_action( 'admin_init', array(&$this,'wpu_silo_admin_init')); 
			add_action('admin_menu', array(&$this,'wpu_silo_admin_actions')); 
			add_action('widgets_init', array($this, 'closure'));
			include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			if(is_plugin_active("seo-ultimate/seo-ultimate.php")):else:
			add_action('add_meta_boxes', array(&$this,'add_seo'));
			add_action('save_post',  array(&$this,'save_seo'));	
			endif;		
		} // end contructor
		
		/**
		 * Add Meta Boxes
		 */
		public function add_meta_boxes()
		{
			# SILO PAGES (wordpress posts)
			add_meta_box(
				'silopages_meta_box',
				'Silo Structure',
				array($this, 'silopages_meta_box'),
				'post',
				'side',
				'high'
			);
		}
		
		/**
		 * Silo Pages meta box
		 */
		public function silopages_meta_box($post)
		{
			$category = '';
			
			# see if we are in silo
			if ('' != get_post_meta($post->ID, '_wpu_silo_dws', true))
			{
				# get post categories
				$categories = wp_get_post_categories($post->ID);
				
				# get silo category
				if (1 == count($categories))
					$category = $categories[0];
			}
			
			# nonce for verification
			wp_nonce_field(plugin_basename(__FILE__), 'silostructure_nonce');
	?>
	
	<select name="silo_structure_page" style="width: 100%">
		<option value="0">Not in Silo</option>
	
	<?php
	$args = array(
		'post_type' => 'page',
		'meta_key' => '_wpu_silo_dws',
		'parent' => 0,
		'sort_column' => 'menu_order',
		'sort_order' => 'asc'
	);
	
	$silo_pages = get_pages($args);
	foreach ($silo_pages as $silo_page):
		
		$listing_code .= "<optgroup label='$silo_page->post_title'>";
		
		if ($art_cat = get_post_meta($silo_page->ID ,'_wpu_article_dws', true)):
			$child_silo_cat_id = $art_cat;
		else:
			$child_silo_cat_id = get_cat_ID($silo_page->post_title);
		endif;
		
		if ($child_silo_cat_id === 0):
			$idObj = get_category_by_slug($silo_page->post_name); 
			$child_silo_cat_id = $idObj->term_id;
		endif;
		
		$categories = get_categories("child_of=$child_silo_cat_id&hide_empty=0");
		if ($categories):
			foreach ($categories as $cat)
			{
				$listing_code .= "<option value='$cat->cat_ID'" . selected($category, $cat->cat_ID, false) . ">$cat->name</option>";
			}
		endif;
		$listing_code .= "</optgroup>";
	endforeach;
	echo $listing_code;
	?>
	
	</select>
	
	<?php
		}
	
		/**
		 * Save post data
		 *
		 * @param string $post_id
		 */
		public function silostructure_save_postdata($post_id)
		{
			# if it's autosave
			if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
				return false;
		
			# verify it came from our plugin
			if (!isset($_POST['silostructure_nonce']) || !wp_verify_nonce($_POST['silostructure_nonce'], plugin_basename(__FILE__)))
				return false;
			
			# check permissions for posts
			if ('post' == $_POST['post_type'])
			{
				if (!current_user_can('edit_post', $post_id))
					return false;
			}
			# elseif ('page' == $_POST['post_type'])
			# {
			# 	if (!current_user_can('edit_page', $post_id))
			# 		return false;
			# }
			else
			{
				# for all other not our post types
				return false;
			}
			
			# new category
			$cat_id = isset($_POST['silo_structure_page']) ? (int) $_POST['silo_structure_page'] : 0;
			
			# if adding to silo structure
			if (0 != $cat_id)
			{
				# set dws if it wasn't set
				if ('' == get_post_meta($post_id, '_wpu_silo_dws', true))
				{
					# random number
					$dws_id = mt_rand(1000000, 9999999);
					
					update_post_meta($post_id, "_wpu_silo_dws", $dws_id);
				}
				
				# post current categories
				$post_categories = wp_get_post_categories($post_id);
				
				# if category is not the right one
				if (1 != count($post_categories) || false === array_search($cat_id, $post_categories))
				{
					# set new category
					wp_set_post_categories($post_id, array($cat_id));
				}
				
				# get post for menu order
				$thispost = get_post($post_id);
				
				# assign proper menu order
				if (0 == $thispost->menu_order)
				{
					# set the correct menu order
					$posts = get_posts("category=$cat_id&posts_per_page=-1");
					
					# get the biggest menu order
					$biggest_menu_order = 0;
					foreach ($posts as $post)
					{
						if ($post->menu_order > $biggest_menu_order)
							$biggest_menu_order = $post->menu_order;
					}
					
					# make it bigger
					$biggest_menu_order += 50000;
					
					remove_action('save_post', array($this, 'silostructure_save_postdata'), 11);
					
					# update post
					wp_update_post(array('ID' => $post_id, 'menu_order' => $biggest_menu_order));
					
					add_action('save_post', array($this, 'silostructure_save_postdata'), 11);
				}
			}
			# removing from silo structure
			elseif ('' != get_post_meta($post_id, '_wpu_silo_dws', true))
			{
				# remove _wpu_silo_dws
				delete_post_meta($post_id, '_wpu_silo_dws');
			}
		}
		
		/**
		 * Install database tables
		 */
		private function install_tables()
		{
			global $wpdb;
		
			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		
			$charset_collate = '';
		
			if (!empty($wpdb->charset))
				$charset_collate .= "DEFAULT CHARACTER SET $wpdb->charset";
			if (!empty($wpdb->collate))
				$charset_collate .= " COLLATE $wpdb->collate";
		
			# Added videos table
			$added_videos_table = $wpdb->prefix . self::added_videos_table;
		
			$sql = "CREATE TABLE $added_videos_table (
				video_id CHAR(11) NOT NULL,
				PRIMARY KEY  (video_id)
			) $charset_collate;";
		
			dbDelta($sql);
		
			# set db version option
			update_option($this->db_version_option, $this->db_version);
		}
		
		public function closure()
		{
			register_widget('V_Advanced_Silo');
		}
		
		function save_seo($post_id){
			// Bail if we're doing an auto save  
			if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; 
			 
			// if our nonce isn't there, or we can't verify it, bail 
			if( !isset( $_POST['meta_dws_nonce'] ) || !wp_verify_nonce( $_POST['meta_dws_nonce'], 'dws_meta_nonce' ) ) return; 
			 
			// if our current user can't edit this post, bail  
			if( !current_user_can( 'edit_post' ) ) return;  
			 // Make sure your data is set before trying to save it  
   
     if( isset( $_POST['dws_meta_title'] ) )  
		$dws_seo['title'] = $_POST['dws_meta_title'];
	 if( isset( $_POST['dws_meta_desc'] ) )  
		$dws_seo['desc'] = $_POST['dws_meta_desc'];
	 if( isset( $_POST['dws_meta_key'] ) )  
		$dws_seo['keywords'] = $_POST['dws_meta_key'];
		
        update_post_meta( $post_id, 'dws_seo_meta', maybe_unserialize($dws_seo ) );  
          
			
		}
		function add_seo(){
			if ( function_exists('add_meta_box') ) { 
			    add_meta_box('wpu-silo-meta', 'DWS Silo Builder', array(&$this,'meta_silo_builder'),'post', 'normal', 'high');
			 add_meta_box('wpu-silo-meta', 'DWS Silo Builder', array(&$this,'meta_silo_builder'),'page', 'normal', 'high');
			}
		}
		function meta_silo_builder(){
			 global $post; 
			  $values = get_post_custom( $post->ID );    
$seo = isset( $values['dws_seo_meta'] ) ? maybe_unserialize($values['dws_seo_meta'][0] ) : array(
	'title' => '', 'desc' => '', 'keywords' => ''
);  
			?>
            <style type="text/css">
				#dws-meta-wrap { background:#fff; padding:10px; border:#DDD 1px solid; }
				#dws-meta-wrap .title{ font-size:14px; }
				#dws-meta-wrap label { font-weight:bold; }
				#dws-meta-wrap .regular-text { width:100%; }
			</style>
            <div id="dws-meta-wrap">
            <span class="title">Meta Information</span>
            <table cellpadding="5" width="100%">
            <tr>
            <td align="right" valign="top"><label for="dws_meta_title">Title:</label></td>
            <td align="left" valign="top"><input type="text" name="dws_meta_title" id="dws_meta_title" class="regular-text" value="<?php echo $seo['title']; ?>" onkeyup="javascript:document.getElementById('dws_title_charcount').innerHTML = document.getElementById('dws_meta_title').value.length"><br />
            You've entered <strong id="dws_title_charcount"><?php echo strlen($seo['title']); ?></strong> characters. Most search engines use up to 70.
            </td>
            </tr>
            <tr>
            <td align="right" valign="top"><label for="dws_meta_desc">Description:</label></td>
            <td align="left" valign="top"><textarea name="dws_meta_desc" id="dws_meta_desc" class="regular-text" cols="60" rows="3" onkeyup="javascript:document.getElementById('dws_meta_description_charcount').innerHTML = document.getElementById('dws_meta_desc').value.length"><?php echo $seo['desc']; ?></textarea><br />
            You've entered <strong id="dws_meta_description_charcount"><?php echo strlen($seo['desc']); ?></strong> characters. Most search engines use up to 140.
            </td>
            </tr>
            <tr>
            <td align="right" valign="top"><label for="dws_meta_key">Keywords:</label></td>
            <td align="left" valign="top"><input type="text" name="dws_meta_key" id="dws_meta_key" value="<?php echo $seo['keywords']; ?>" class="regular-text"  /></td>
            </tr>
			</table>
            <?php // We'll use this nonce field later on when saving.  
    wp_nonce_field( 'dws_meta_nonce', 'meta_dws_nonce' );  ?>
           </div>
            <?php
		}
		 function wpu_silo_admin_init() {
			wp_register_style('wpu-silo-plugin-css',  V_PLUGIN_URL.'includes/css/wpu-silo-styles.css', $deps = array(), $ver = '1.0.0', $media = 'all');
			wp_register_style('wpu-silo-bootstrap-css',  V_PLUGIN_URL.'includes/css/bootstrap.min.css', $deps = array(), $ver = '1.0.0', $media = 'all');
			wp_register_style('wpu-silo-colorpicker',  V_PLUGIN_URL.'includes/css/jquery.miniColors.css', $deps = array(), $ver = '1.0.0', $media = 'all');

			wp_register_script( 'wpu-silo-colorpicker',  V_PLUGIN_URL.'includes/js/jquery.miniColors.min.js');
			wp_register_script( 'wpu-silo-script',  V_PLUGIN_URL.'includes/js/wpu-silo.js');
		}
		
		
		function wpu_silo_admin_actions() {  
			$silo_admin = add_menu_page(__(V_THEME_NAME." Theme Settings", V_TXT_DOMAIN),__(V_THEME_NAME, V_TXT_DOMAIN),
			 'edit_themes', 'v-silo-builder', array(&$this,'create_silo_setting'), '' , '7.1');
			 $silo_admin2 =  add_submenu_page('v-silo-builder', __('Settings', V_TXT_DOMAIN), __('Settings', V_TXT_DOMAIN),
		 	 'edit_themes', 'v-silo-builder' , array(&$this,'create_silo_setting'));
  			$silo_admin6 = add_submenu_page('v-silo-builder',__(V_THEME_NAME." - Manual Silo Builder", V_TXT_DOMAIN),
 			__('Manual Silo Builder', V_TXT_DOMAIN), 'edit_themes', 'v-silo-manual-builder', array(&$this,'create_manual_builder'));
			add_action('load-' . $silo_admin6, array($this, 'create_manual_builder_init'));
			 $silo_admin3 = add_submenu_page('v-silo-builder',__(V_THEME_NAME." - Silo Importer", V_TXT_DOMAIN),
			__('Silo Importer', V_TXT_DOMAIN), 'edit_themes', 'v-silo-importer', array(&$this,'create_silo_admin'));
			add_action('load-' . $silo_admin3, array($this, 'create_silo_admin_init'));
			$silo_admin7 = add_submenu_page('v-silo-builder',__(V_THEME_NAME." - Silo Map", V_TXT_DOMAIN),
			__('Silo Map', V_TXT_DOMAIN), 'edit_themes', 'v-silo-map', array(&$this,'create_silo_map'));
			$silo_admin4 = add_submenu_page('v-silo-builder',__(V_THEME_NAME." - Styles", V_TXT_DOMAIN),
			__('Silo Styles', V_TXT_DOMAIN), 'edit_themes', 'v-silo-styles', array(&$this,'create_style_admin'));
 			$silo_admin5 = add_submenu_page('v-silo-builder',__(V_THEME_NAME." - Help", V_TXT_DOMAIN),
			__('Help', V_TXT_DOMAIN), 'edit_themes', 'v-silo-help', array(&$this,'create_help'));
				// Admin print styles action when plugin is called
				add_action( 'admin_print_styles-'.$silo_admin, array(&$this, 'v_silo_load_style' ));
				add_action( 'admin_print_styles-'.$silo_admin2, array(&$this, 'v_silo_load_style' ));
				add_action( 'admin_print_styles-'.$silo_admin3, array(&$this, 'v_silo_load_style' ));
				add_action( 'admin_print_styles-'.$silo_admin4, array(&$this, 'v_silo_load_style' ));
				add_action( 'admin_enqueue_scripts',  array(&$this,'v_silo_load_script'));
		} // end wpu_silo_admin_actions
		
		/**
		 * Add YouTube Video
		 *
		 * @param bool $add_videos
		 * @param string $keyword
		 * @param string $video_id
		 * @param string $thumbnail_url
		 * @return string new video content
		 */
		public function add_video($add_videos, $keyword, &$video_id, &$thumbnail_url)
		{
			# if we add a video
			if (1 == $add_videos)
			{
				global $wpdb;
		
				@set_time_limit(300);
				@ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
				
				# get options
				$youtube = get_option(V_PLUGIN_OPTIONS . '_youtube');
				
				# on error return nothing
				if (!is_array($youtube))
					return '';
				
				$youtube_api_search_url = "https://www.googleapis.com/youtube/v3/search";
				$youtube_api_videos_url = "https://www.googleapis.com/youtube/v3/videos";
				$wp_remote_args = array(
					'user-agent' => $this->user_agent,
					'httpversion' => '1.1',
				);
				
				# get channel id if channel is not empty
				$channel_id = '';
				if (!empty($youtube['channel']))
				{
					# set params
					$params = array(
						'part' => 'id',
						'fields' => 'items/id/channelId',
						'q' => rawurlencode($youtube['channel']),
						'type' => 'channel',
						'maxResults' => 1,
						'key' => $this->google_api_key,
					);
			
					$content = wp_remote_get(add_query_arg($params, $youtube_api_search_url), $wp_remote_args);
			
					if (is_wp_error($content))
						return '';
			
					$content = json_decode(wp_remote_retrieve_body($content));
			
					# if we found channel id
					if (isset($content->items[0]->id->channelId))
						$channel_id = $content->items[0]->id->channelId;
				}
				
				# find new video
				$video_id = '';
				$video_count = 0;
				$totalResults = 0;
				$nextPageToken = '';
				do
				{
					# set params
					$params = array(
						'part' => 'id',
						'fields' => 'pageInfo/totalResults,nextPageToken,items/id/videoId',
						'q' => rawurlencode($keyword),
						'type' => 'video',
						'videoEmbeddable' => 'true',
						'maxResults' => 50,
						'key' => $this->google_api_key,
					);
			
					# add channel id if it's set
					if (!empty($channel_id))
						$params['channelId'] = $channel_id;
			
					# add published after if it's set
					if ('any' != $youtube['upload_date'])
					{
						# seconds to subtract from now
						switch ($youtube['upload_date'])
						{
							# Today
							case 'to':
								$seconds = 60 * 60 * 24;
								break;
					
							# This week
							case 'tw':
								$seconds = 60 * 60 * 24 * 7;
								break;
					
							# This month
							case 'tm':
								$seconds = 60 * 60 * 24 * 30;
								break;
					
							# This year
							case 'ty':
								$seconds = 60 * 60 * 24 * 365;
								break;
					
							# Last hour
							default:
								$seconds = 60 * 60;
						}
				
						$params['publishedAfter'] = str_replace("+00:00", "Z", date(DATE_RFC3339, time() - $seconds));
					}
			
					# add video duration if it's set
					if ('any' != $youtube['duration'])
						$params['videoDuration'] = $youtube['duration'];
			
					# add page token if it's not empty
					if (!empty($nextPageToken))
						$params['pageToken'] = $nextPageToken;
			
					$content = wp_remote_get(add_query_arg($params, $youtube_api_search_url), $wp_remote_args);
					
					if (is_wp_error($content))
						return '';
			
					$content = json_decode(wp_remote_retrieve_body($content));
			
					# check required variables
					if (!isset($content->pageInfo->totalResults)
						|| !isset($content->items))
						return '';
			
					$totalResults = $content->pageInfo->totalResults;
			
					# iterate over each video found
					foreach ($content->items as $v)
					{
						++$video_count;
				
						// if there is no such video, we have a unique one
						if (null == ($wpdb->get_row($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . self::added_videos_table . " WHERE video_id = '%s'", $v->id->videoId), ARRAY_A)))
						{
							$video_id = $v->id->videoId;
					
							// we break out of the loop... twice
							break 2;
						}
					}
			
					$nextPageToken = '';
					if (isset($content->nextPageToken))
						$nextPageToken = $content->nextPageToken;
				}
				while(!empty($nextPageToken));
				
				# if didn't find a video
				if (empty($video_id))
				{
					# stop here
					return '';
				}
				
				# proceed with adding a new video
				
				# add video to added videos table
				$wpdb->insert($wpdb->prefix . self::added_videos_table,
					# data
					array('video_id' => $video_id),
					# format
					array('%s')
				);
				
				# set params
				$params = array(
					'part' => 'snippet,player',
					'fields' => 'items(snippet(title,description,thumbnails),player/embedHtml)',
					'id' => $video_id,
					'maxResults' => 1,
					'key' => $this->google_api_key,
				);
		
				$content = wp_remote_get(add_query_arg($params, $youtube_api_videos_url), $wp_remote_args);
		
				if (is_wp_error($content))
					return '';
		
				$content = json_decode(wp_remote_retrieve_body($content));
				
				# check we have required variables
				if (!isset($content->items[0]->snippet->title)
					|| !isset($content->items[0]->snippet->description)
					|| !isset($content->items[0]->player->embedHtml)
					|| !isset($content->items[0]->snippet->thumbnails->medium->url))
					return '';
				
				# set thumbnail url
				$thumbnail_url = $content->items[0]->snippet->thumbnails->medium->url;
				
				# replace iframe ending, it breaks html design in wordpress
				$embedHtml = str_replace("/>", "></iframe>", $content->items[0]->player->embedHtml);
		
				# check there is post content
				if (!isset($youtube['post_content']))
					return '';
		
				/*
				{videoId} - $video_id
				{videoTitle} - $content->items[0]->snippet->title
				{videoDescription} - $content->items[0]->snippet->description
				{embedHtml} - $content->items[0]->player->embedHtml
				*/
		
				$patterns = array(
					'#\{videoId\}#i',
					'#\{videoTitle\}#i',
					'#\{videoDescription\}#i',
					'#\{embedHtml\}#i',
				);
		
				$replacements = array(
					$video_id,
					$content->items[0]->snippet->title,
					$content->items[0]->snippet->description,
					$embedHtml,
				);
		
				# create post content
				$post_content = preg_replace($patterns, $replacements, $youtube['post_content']);
				
				return $post_content;
			}
		}
		
		/**
		 * Set Featured Image from URL
		 *
		 * @param string $post_id
		 * @param string $thumbnail_url
		 * @param string $current_user_id
		 */
		public function set_featured_image($post_id, $thumbnail_url, $current_user_id)
		{
			# if something is empty, don't add anything
			if (empty($post_id) || empty($thumbnail_url) || empty($current_user_id))
				return false;
			
			$result = wp_remote_get($thumbnail_url);
			
			if (is_wp_error($result))
				return false;
			
			$content_type = wp_remote_retrieve_header($result, 'content-type');
			
			$file = wp_upload_bits(basename($thumbnail_url), null, wp_remote_retrieve_body($result));
			
			# if there is no error
			if (!$file['error'])
			{
				$attachment = array(
					'guid' => $file['url'],
					'post_title' => preg_replace('/\.[^.]+$/', '', basename($thumbnail_url)),
					'post_content' => '',
					'post_status' => 'inherit',
					'post_mime_type' => $content_type,
					'post_author' => $current_user_id,
				);
				
				$attach_id = wp_insert_attachment($attachment, $file['file'], $post_id);
				// you must first include the image.php file
				// for the function wp_generate_attachment_metadata() to work
				require_once(ABSPATH . 'wp-admin/includes/image.php');
				$attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
				wp_update_attachment_metadata($attach_id, $attach_data);
				
				# set featured image
				set_post_thumbnail($post_id, $attach_id);
			}
		}
		
		/**
		 * Add YouTube Video Comments
		 *
		 * @param bool $add_videos
		 * @param string $keyword
		 * @param string $video_id
		 * @return string new video content
		 */
		public function add_video_comments($post_id, $video_id)
		{
			# skip if empty
			if (empty($video_id))
				return true;
			
			# get options
			$youtube = get_option(V_PLUGIN_OPTIONS . '_youtube');
			
			# don't add comments
			if (1 != $youtube['comments'])
				return true;
			
			$content = wp_remote_get("http://gdata.youtube.com/feeds/api/videos/$video_id/comments", $wp_remote_args);
			
			if (is_wp_error($content))
				return false;
			
			// get video comments
			$video_comments = simplexml_load_string(wp_remote_retrieve_body($content));
			
			// gmt offset seconds
			$gmt_offset_seconds = get_option('gmt_offset') * 3600;
			
			foreach ($video_comments->entry as $entry)
			{
				$commentdata = array(
					'comment_post_ID' => $post_id,
					'comment_author' => $entry->author->name,
					'comment_author_email' => "vsilo@builder",
					'comment_author_IP' => '0.0.0.0', // none
					'comment_approved' => 1,
					'comment_content' => $entry->content,
					'user_ID' => 0,
					'comment_agent' => '',
					'comment_author_url' => '',
				);
				
				// get timestamp of 2007-09-19T05:36:50.000Z
				preg_match("/^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}).?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/", $entry->updated, $matches);
				
				$updated_gmt_seconds = mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]);
				
				// set local and GMT time
				$commentdata['comment_date']     = date("Y-m-d H:i:s", $updated_gmt_seconds + $gmt_offset_seconds);
				$commentdata['comment_date_gmt'] = date("Y-m-d H:i:s", $updated_gmt_seconds);
				
				// we need this
				$commentdata = wp_filter_comment($commentdata);
				
				# black list check
				if (wp_blacklist_check($commentdata['comment_author'], $commentdata['comment_author_email'], "", $commentdata['comment_content'], $commentdata['comment_author_IP'], ""))
				{
					$commentdata['comment_approved'] = 'spam';
				}
				
				wp_insert_comment($commentdata);
			}
		}
		
		/**
		 * Manual Silo Builder page init
		 */
		public function create_manual_builder_init()
		{
			$location = 'admin.php?page=v-silo-manual-builder';
			
			# define variables
			$page_sel = '';
			$add_videos = '1';
			$text_area = '';
			$errors = array();
			
			# if form was submitted and nonce verified
			if (isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], plugin_basename(__FILE__)))
			{
				if (!isset($_POST['page_selected']))
				{
					$errors[] = "A page should be selected.";
				}
				else
				{
					$page_sel = $_POST['page_selected'];
					$page_selected = explode("_", $_POST['page_selected']);
				}
				
				$text_area = stripslashes_deep($_POST['keywords']);
				$add_videos = (isset($_POST['add_videos']) && 1 == $_POST['add_videos']) ? 1 : 0;
				$keywords = trim($_POST['keywords']);
				
				$keywords = explode("\n", $keywords);
				
				$new_keywords = array();
				foreach ($keywords as $key => $value)
				{
					$value = preg_replace('/\r/', '', $value);
					
					if ('' != trim($value))
						$new_keywords[] = $value;
				}
				
				if (0 == count($new_keywords))
				{
					$errors[] = "Keywords should not be empty.";
				}
				
				if (2 == count($page_selected) && !$errors)
				{
					list($type, $parent_id) = $page_selected;
					
					$count_posts = 0;
					
					# add each keyword
					foreach ($new_keywords as $keyword)
					{
						if ($errors)
							continue;
						
						# add silo
						if ('silo' == $type)
						{
							$biggest_menu_order = 0;
						
							$args = array(
								'post_type' => 'page',
								'meta_key' => '_wpu_silo_dws',
								'posts_per_page' => -1,
								'orderby' => 'menu_order',
								'order' => 'ASC'
							);
							
							$silo_pages = new WP_Query($args);
							
							# get the biggest menu order
							while ($silo_pages->have_posts())
							{
								$silo_pages->the_post();
								
								$parent_id = get_post()->post_parent;
								
								if (0 == $parent_id)
								{
									# if such silo exists, skip
									if (get_post()->post_title == $keyword)
										continue 2;
									
									if ($biggest_menu_order < get_post()->menu_order)
										$biggest_menu_order = get_post()->menu_order;
								}
							}
						
							# make it bigger
							$biggest_menu_order += 500000;
							$video_id = '';
							$thumbnail_url = '';
							$mc_page_array = array(
								'menu_order' => $biggest_menu_order, //If new post is a page, sets the order should it appear in the tabs.
								'post_author' => get_current_user_id(), //The user ID number of the author.
								'post_content' => $this->add_video($add_videos, $keyword, $video_id, $thumbnail_url), //The full text of the post.
								'post_status' => 'publish', //Set the status of the new post. 
								'post_title' => ucwords($keyword), //The title of your post.
								'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
							);
							
							# remove filter to allow iframe tag
							remove_filter('content_save_pre', 'wp_filter_post_kses');
							
							$wpu_page_id = wp_insert_post($mc_page_array);
							
							# add removed filter back
							add_filter('content_save_pre', 'wp_filter_post_kses');
							
							if (1 == $add_videos)
							{
								$this->set_featured_image($wpu_page_id, $thumbnail_url, get_current_user_id());
								$this->add_video_comments($wpu_page_id, $video_id);
							}
							
							# random number
							$dws_id = mt_rand(1000000, 9999999);
							
							update_post_meta($wpu_page_id, "_wpu_silo_dws", $dws_id);
							$this->updateSEO($wpu_page_id, $keyword, $keyword, $keyword);
						
							$exist = term_exists(get_post($wpu_page_id)->post_name, 'category');
							$args = array('slug' => get_post($wpu_page_id)->post_name);
							if($exist):
								$silo_cat_id = wp_update_term($exist['term_id'], 'category', $args);
								$silo_cat_id = $silo_cat_id['term_id'];
							else:
								$silo_cat_id = wp_insert_term(ucwords($keyword), 'category', $args);
								$silo_cat_id = $silo_cat_id['term_id'];
							endif;
						
							update_metadata('term', $silo_cat_id, 'tax-order', $biggest_menu_order);
						}
						# add category
						elseif ('cat' == $type)
						{
							# get the biggest menu order
							$biggest_menu_order = 0;
							
							if ($art_cat = get_post_meta($parent_id,'_wpu_article_dws', true)):
								$child_silo_cat_id = $art_cat;
							else:
								$child_silo_cat_id = get_cat_ID(get_post($parent_id)->post_title);
							endif;
							
							$categories = get_categories("child_of=$child_silo_cat_id&hide_empty=0");
							if ($categories):
								foreach ($categories as $cat)
								{
									# if such category exists, skip
									if ($cat->name == $keyword)
										continue 2;
									
									if ($biggest_menu_order < $cat->tax_order)
										$biggest_menu_order = $cat->tax_order;
								}
							endif;
							
							# make it bigger
							$biggest_menu_order += 500000;
							$video_id = '';
							$thumbnail_url = '';
							$wpus_child_page_array = array(
								'menu_order' => $biggest_menu_order, //If new post is a page, sets the order should it appear in the tabs.
								'post_author' => get_current_user_id(), //The user ID number of the author.
								'post_content' => $this->add_video($add_videos, $keyword, $video_id, $thumbnail_url), //The full text of the post.
								'post_parent' => $parent_id,
								'post_status' => 'publish', //Set the status of the new post. 
								'post_title' => ucwords($keyword), //The title of your post.
								'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
							);
							
							# remove filter to allow iframe tag
							remove_filter('content_save_pre', 'wp_filter_post_kses');
							
							$wpus_page_id = wp_insert_post($wpus_child_page_array);
							
							# add removed filter back
							add_filter('content_save_pre', 'wp_filter_post_kses');
							
							if (1 == $add_videos)
							{
								$this->set_featured_image($wpus_page_id, $thumbnail_url, get_current_user_id());
								$this->add_video_comments($wpus_page_id, $video_id);
							}
							
							# random number
							$dws_id = mt_rand(1000000, 9999999);
							
							update_post_meta($wpus_page_id, "_wpu_silo_dws", $dws_id);
							$this->updateSEO($wpus_page_id, $keyword, $keyword, $keyword);
							
							$exist = term_exists(get_post($wpus_page_id)->post_name, 'category');
							$args = array('slug' => get_post($wpus_page_id)->post_name, 'parent'=> get_cat_ID(get_post($parent_id)->post_title));
							if($exist):
								$wpus_cat_id = wp_update_term($exist['term_id'] , 'category', $args);
								$wpus_cat_id = $wpus_cat_id['term_id'];
							else:
								$wpus_cat_id = wp_insert_term(ucwords($keyword), 'category', $args);
								$wpus_cat_id = $wpus_cat_id['term_id'];
							endif;
							
							update_post_meta($wpus_page_id, "_wpu_article_dws",(int)$wpus_cat_id);
							update_metadata('term', $wpus_cat_id, 'tax-order', $biggest_menu_order);
						}
						# add page
						elseif ('page' == $type)
						{
							# get the biggest menu order
							$biggest_menu_order = 0;
							
							query_posts("cat=$parent_id&posts_per_page=-1&orderby=menu_order&order=ASC");
							if(have_posts()):
								while (have_posts()): the_post();
									# if such post exists, skip
									if (get_post()->post_title == $keyword)
										continue 2;
									
									if ($biggest_menu_order < get_post()->menu_order)
										$biggest_menu_order = get_post()->menu_order;
								endwhile;
							endif;
							
							# make it bigger
							$biggest_menu_order += 500000;
							$video_id = '';
							$thumbnail_url = '';
							$mc_post_array = array(
								'menu_order' => $biggest_menu_order , //If new post is a page, sets the order should it appear in the tabs.
								'post_author' =>  get_current_user_id(), //The user ID number of the author.
								'post_category' =>  array($parent_id), //Add some categories.
								'post_content' => $this->add_video($add_videos, $keyword, $video_id, $thumbnail_url), //The full text of the post.
								'post_status' => 'publish', //Set the status of the new post. 
								'post_title' => ucwords($keyword), //The title of your post.
								'post_type' => 'post',  //You may want to insert a regular post, page, link, a menu item or some custom post type
							);
							
							# remove filter to allow iframe tag
							remove_filter('content_save_pre', 'wp_filter_post_kses');
							
							$wpu_child_page_id = wp_insert_post($mc_post_array);
							
							# add removed filter back
							add_filter('content_save_pre', 'wp_filter_post_kses');
							
							if (1 == $add_videos)
							{
								$this->set_featured_image($wpu_child_page_id, $thumbnail_url, get_current_user_id());
								$this->add_video_comments($wpu_child_page_id, $video_id);
							}
							
							# random number
							$dws_id = mt_rand(1000000, 9999999);
							
							update_post_meta($wpu_child_page_id, "_wpu_silo_dws", $dws_id);
							$this->updateSEO($wpu_child_page_id, $keyword, $keyword, $keyword);
						}
						++$count_posts;
					}
					
					if (!$errors)
					{
						# show messages
						if ('silo' == $type)
							$location = add_query_arg('silos', $count_posts, $location);
						elseif ('cat' == $type)
							$location = add_query_arg('cats', $count_posts, $location);
						elseif ('page' == $type)
							$location = add_query_arg('pages', $count_posts, $location);
					
						wp_redirect($location);
						die;
					}
				}
			}
			
			$this->variables_buffer = array(
				"errors" => $errors,
				"page_sel" => $page_sel,
				"add_videos" => $add_videos,
				"text_area" => $text_area,
			);
		}
		
		/**
		 * Manual Silo Builder page
		 */
		public function create_manual_builder()
		{
			global $title;
			
			# extract variables from buffer
			extract($this->variables_buffer);
			
			# messages
			$message = false;
			if (!empty($_GET['silos']) && 0 < ($silos = absint($_GET['silos'])))
			{
				$message = sprintf(_n('Silo added.', '%d silos added.', $silos), number_format_i18n($silos));
			}
			elseif (!empty($_GET['cats']) && 0 < ($cats = absint($_GET['cats'])))
			{
				$message = sprintf(_n('Category added.', '%d categories added.', $cats), number_format_i18n($cats));
			}
			elseif (!empty($_GET['pages']) && 0 < ($pages = absint($_GET['pages'])))
			{
				$message = sprintf(_n('Page added.', '%d pages added.', $pages), number_format_i18n($pages));
			}
?>

<?php if ($message): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif; ?>

<?php if ($errors): 
foreach ($errors as $error): ?>
<div id="error" class="error"><p><strong><?php echo $error ?></strong></p></div>
<?php endforeach;
endif; ?>

<div class="wrap">
<h2><?php echo esc_html($title) ?></h2>

<form method="post" action="admin.php?page=v-silo-manual-builder">
<?php wp_nonce_field(plugin_basename(__FILE__), '_wpnonce'); ?>

<div id="col-container">
	<div id="col-right" style="width: 255px">
		<iframe src="http://banners.networkempirenews.com/banners/" scrolling="no" style="width: 255px; height: 245px"></iframe><br /><br />
		<iframe src="http://banners.networkempirenews.com/banner-2/" scrolling="no" style="width: 255px; height: 155px"></iframe><br /><br />
		<iframe src="http://banners.networkempirenews.com/banner-3/" scrolling="no" style="width: 255px; height: 200px"></iframe>
	</div>
	
	<div id="col-left" style="width: 65%">
		<p>(New Feature!) You may click-drag-and-drop any item on the below manual silo builder (Except the Home Page)!</p>

<div class="control-group">
<div class="controls">
<style type="text/css">

	h5 {font-size:16px;color:#000 }
	h6 { font-size:14px;color:#222; }
	.wpus-siloing ul { color:#333;margin:5px 20px; list-style:disc outside none;
t-item; }

.a li{list-style-type:decimal;}
.b li{list-style-type:lower-alpha;}
.c li{list-style-type:lower-roman;}
	.wpus-article{ color:#444;}
	.wpus-article-post{color:#777;}

</style>
<blockquote>

<?php

$args = array(
	'post_type' => 'page',
	'meta_key' => '_wpu_silo_dws',
	'posts_per_page' => -1,
	'orderby' => 'menu_order',
	'order' => 'ASC'
);

$silo_pages = new WP_Query($args);
$listing_code = "<div class='wpus-siloing'>";
$listing_code .= "<h5><label><input type='radio' name='page_selected' value='silo_0'" . checked($page_sel, 'silo_0', false) . " /> HOME</label></h5>";
$listing_code .= "<ol class='wpus-silos a'>";

while ($silo_pages->have_posts()): $silo_pages->the_post();
	// $do_not_duplicate = $post->ID;
	$tmp_id = get_the_ID();
	$parent_id = get_post()->post_parent;
	
	if ($parent_id  == 0 )
	{
		$listing_code .= "<li>";
		$listing_code .= "<h6><label><input type='radio' name='page_selected' value='cat_" . get_the_ID() . "'" . checked($page_sel, 'cat_' . get_the_ID(), false) . " /> ". get_the_title()."</label></h6>";
		
		$child_page_title = get_the_title();
		//$idObj =  get_category_by_slug($child_page_title);
		
		//$child_silo_cat_id =  get_cat_ID( $child_page_title );
		if ($art_cat = get_post_meta($tmp_id,'_wpu_article_dws', true)):
			$child_silo_cat_id = $art_cat;
		else:
			$child_silo_cat_id = get_cat_ID($child_page_title);
		endif;
		
		if ($child_silo_cat_id === 0):
			$idObj = get_category_by_slug(get_post($tmp_id)->post_name); 
			$child_silo_cat_id = $idObj->term_id;
		endif;

		$listing_code .="<ol class=\"b\">";
		$categories = get_categories("child_of=$child_silo_cat_id&hide_empty=0");
		
		if ($categories):
			foreach ($categories as $cat)
			{
				$listing_code .="<li>";
				query_posts("cat=$cat->cat_ID&posts_per_page=-1&orderby=menu_order&order=ASC");
				$listing_code .= "<label><input type='radio' name='page_selected' value='page_" . $cat->cat_ID . "'" . checked($page_sel, 'page_' . $cat->cat_ID, false) . " /> <span class='wpus-article'>". single_cat_title('', false)."</span></label>";
				$listing_code .="<ol class=\"c\">";
				if (have_posts()):
					while (have_posts()): the_post();
						$listing_code .="<li><input type='hidden' name='page' value='" . get_the_ID() . "' /><span class='wpus-article-post'>".get_the_title()."</span></li>";
					endwhile;
				endif;
				$listing_code .="</ol>";
				$listing_code .="</li>";
			}
		endif;
		$listing_code .="</ol>";
		$listing_code .="</li>";
	}

endwhile;
$listing_code .="</ol>";
$listing_code .= "</div>";

echo $listing_code;
?>

</blockquote>
</div>

<p><label><input type="checkbox" id="add_videos" name="add_videos" value="1"<?php checked($add_videos, '1'); ?> /> Add Videos</label></p>

<p class="submit">
	<textarea name="keywords" rows="3" style="width: 300px"><?php echo esc_textarea($text_area); ?></textarea><br />
	<?php submit_button("Add New", 'primary', 'submit', false); ?>
</p>
</div>
</div>
</div>
</form>
</div>

<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function($)
{
	// add placeholder to empty lists
	$('.b').each(function (c)
	{
		// add placeholder if list is empty
		if (0 == $("> li", this).size())
		{
			$(this).css('height', '25px')
			// $(this).css('background-color', '#FFAA00')
		}
	})
	
	// add placeholder to empty lists
	$('.c').each(function (c)
	{
		// add placeholder if list is empty
		if (0 == $("> li", this).size())
		{
			$(this).css('height', '15px')
			// $(this).css('background-color', '#FF0000')
		}
	})
	
	$('.a').sortable({
		cursor: 'move',
		stop: function(e, ui)
		{
			var targt = e.originalEvent.target || e.srcElement
			
			var parent_id = -1
			
			var current_id = $('input:first', targt.innerHTML).val().split('_')[1]
			
			// set by default
			var previous_id = -1
			
			// get previuos id
			$('ol:first > li', targt.parentElement.parentElement.outerHTML).each(function(index)
			{
				if (current_id == $('input:first', this).val().split('_')[1])
				{
					return false
				}
				
				previous_id = $('input:first', this).val().split('_')[1]
			})
			
			silo_structure_save_order('a', parent_id, current_id, previous_id)
		}
	});
	
	$('.b').sortable({
		cursor: 'move',
		connectWith: $('.b'),
		receive: function(e, ui)
		{
			// remove placeholder
			$(this).css('height', 'auto')
			// $(this).css('background-color', 'transparent')
		},
		stop: function(e, ui)
		{
			var targt = e.originalEvent.target || e.srcElement
			
			// remove place holder if list is not empty
			if (0 < $("> li", this).size())
			{
				$(this).css('height', 'auto')
				// $(this).css('background-color', 'transparent')
			}
			
			var parent_id = $('input:first', targt.parentElement.parentElement.parentElement.parentElement.outerHTML).val().split('_')[1]
			
			var current_id = $('input:first', targt.parentElement.outerHTML).val().split('_')[1]
			
			// set by default
			var previous_id = -1
			
			// get previuos id
			$('ol:first > li', targt.parentElement.parentElement.parentElement.parentElement.outerHTML).each(function(index)
			{
				if (current_id == $('input:first', this).val().split('_')[1])
				{
					return false
				}
				
				previous_id = $('input:first', this).val().split('_')[1]
			})
			
			silo_structure_save_order('b', parent_id, current_id, previous_id)
		},
		change: function(e, ui)
		{
			// from list
			if (ui.sender == null)
			{
				// add placeholder if list is empty
				if (1 == $("> li", this).size())
				{
					$(this).css('height', '25px')
					// $(this).css('background-color', '#FFAA00')
				}
			}
		}
	});
	
	$('.c').sortable({
		cursor: 'move',
		connectWith: $('.c'),
		receive: function(e, ui)
		{
			// remove placeholder
			$(this).css('height', 'auto')
			// $(this).css('background-color', 'transparent')
		},
		stop: function(e, ui)
		{
			var targt = e.originalEvent.target || e.srcElement
			
			// remove place holder if list is not empty
			if (0 < $("> li", this).size())
			{
				$(this).css('height', 'auto')
				// $(this).css('background-color', 'transparent')
			}
			
			var parent_id = $('input:first', targt.parentElement.parentElement.parentElement.outerHTML).val().split('_')[1]
			
			var current_id = $('input:first', targt.parentElement.outerHTML).val()
			
			// set by default
			var previous_id = -1
			
			// get previuos id
			$('ol:first > li', targt.parentElement.parentElement.parentElement.outerHTML).each(function(index)
			{
				if (current_id == $('input:first', this).val())
				{
					return false
				}
				
				previous_id = $('input:first', this).val()
			})
			
			silo_structure_save_order('c', parent_id, current_id, previous_id)
		},
		change: function(e, ui)
		{
			// from list
			if (ui.sender == null)
			{
				// add placeholder if list is empty
				if (1 == $("> li", this).size())
				{
					$(this).css('height', '15px')
					// $(this).css('background-color', '#FF0000')
				}
			}
		}
	});
	
	function silo_structure_save_order(type, parent_id, current_id, previous_id)
	{
		if ('a' == type)
		{
			type = 'silo'
		}
		else if ('b' == type)
		{
			type = 'cat'
		}
		else if ('c' == type)
		{
			type = 'page'
		}
		
		var data = {
			action: 'silo_structure_manual_sorting',
			_ajax_nonce: '<?php echo wp_create_nonce(plugin_basename(__FILE__)) ?>',
			type: type,
			parent_id: parent_id,
			current_id: current_id,
			previous_id: previous_id
		};
		
		// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
		$.post(ajaxurl, data);
	}
});
</script>
<?php
		}
		
		/**
		 * Silo Structure Manual Sorting
		 *
		 * @return void
		 * @author Dennis
		 */
		public function silo_structure_manual_sorting_callback()
		{
			check_ajax_referer(plugin_basename(__FILE__), '_ajax_nonce');
			
			# die if required variables are not set
			if (!isset($_POST['type'], $_POST['parent_id'], $_POST['current_id'], $_POST['previous_id']))
			{
				die;
			}
			
			# set variables
			$parent_id = (int) $_POST['parent_id'];
			$current_id = (int) $_POST['current_id'];
			$previous_id = (int) $_POST['previous_id'];
			
			# SILO
			if ('silo' == $_POST['type'])
			{
				$pages = get_pages("parent=0&meta_key=_wpu_silo_dws&hierarchical=0&sort_column=menu_order&sort_order=ASC&exclude=$current_id");
				
				# if no cats belong to this parent
				if (0 == count($pages))
				{
					# set page to 0 menu order
					wp_update_post(array('ID' => $current_id, 'menu_order' => 0));
				}
				# set correct menu order for pages
				else
				{
					# get all page ids
					$page_ids = array();
					foreach ($pages as $v)
					{
						$page_ids[] = $v->ID;
					}
					
					# if it's put first in front of other cats
					if (-1 == $previous_id)
					{
						# prepend to the beginning of the arrays
						array_unshift($page_ids, $current_id);
					}
					# if it's put in between or at the end
					else
					{
						# get previous id key
						if (false === ($previous_id_key = array_search($previous_id, $page_ids)))
						{
							# if not found, there is an error
							die;
						}
						
						# add after previous page
						array_splice($page_ids, $previous_id_key + 1, 0, $current_id);
					}
					
					# set proper menu order for each page
					foreach ($page_ids as $k => $v)
					{
						# update page
						wp_update_post(array('ID' => $v, 'menu_order' => $k));
					}
				}
			}
			# CATEGORY
			else if ('cat' == $_POST['type'])
			{
				# get child category by id
				if (null == ($child_cat = get_category($current_id)))
					die;
				
				# get parent category
				if (null == ($parent_cat = get_category($child_cat->parent)))
					die;
				
				# get the page
				if (null == ($page = get_page_by_path($parent_cat->slug . '/' . $child_cat->slug)))
					die;
				
				# get parent page
				if (null == ($parent_page = get_post($parent_id)))
					die;
				
				# get new parent category
				if (false === ($new_parent_cat = get_category_by_slug($parent_page->post_name)))
					die;
				
				# set new parent
				wp_update_post(array('ID' => $page->ID, 'post_parent' => $parent_id));
				wp_update_term($child_cat->term_id, 'category', array('parent' => $new_parent_cat->term_id));
				
				
				$cats = get_categories(array('parent' => $new_parent_cat->term_id, 'hide_empty' => false, 'exclude' => $current_id));
				
				$pages = get_pages("parent=$parent_page->ID&hierarchical=0&sort_column=menu_order&sort_order=ASC&exclude=$page->ID");
				
				# if no cats belong to this parent
				if (0 == count($cats))
				{
					# set cat and page to 0 menu order
					update_metadata('term', $current_id, 'tax-order', 0);
					wp_update_post(array('ID' => $page->ID, 'menu_order' => 0));
				}
				# set correct menu order for categories and pages
				else
				{
					$previous_page_slug = '';
					
					# get all cat ids
					$cat_ids = array();
					foreach ($cats as $v)
					{
						# get previous page slug
						if (-1 != $previous_id && $v->term_id == $previous_id)
						{
							$previous_page_slug = $v->slug;
						}
						
						$cat_ids[] = $v->term_id;
					}
					
					# get all page ids
					$page_ids = array();
					foreach ($pages as $v)
					{
						# get previous page id
						if ($v->post_name == $previous_page_slug)
						{
							$previous_page_id = $v->ID;
						}
						
						$page_ids[] = $v->ID;
					}
					
					# if it's put first in front of other cats
					if (-1 == $previous_id)
					{
						# prepend to the beginning of the arrays
						array_unshift($cat_ids, $current_id);
						array_unshift($page_ids, $page->ID);
					}
					# if it's put in between or at the end
					else
					{
						# get previous id key
						if (false === ($previous_id_key = array_search($previous_id, $cat_ids)))
						{
							# if not found, there is an error
							die;
						}
						
						# add after previous cat
						array_splice($cat_ids, $previous_id_key + 1, 0, $current_id);
						
						# get previous page id key
						if (false === ($previous_page_id_key = array_search($previous_page_id, $page_ids)))
						{
							# if not found, there is an error
							die;
						}
						
						# add after previous page
						array_splice($page_ids, $previous_page_id_key + 1, 0, $page->ID);
					}
					
					# set proper menu order for each cat
					foreach ($cat_ids as $k => $v)
					{
						# update cat
						update_metadata('term', $v, 'tax-order', $k + 1);
					}
					
					# set proper menu order for each page
					foreach ($page_ids as $k => $v)
					{
						# update page
						wp_update_post(array('ID' => $v, 'menu_order' => $k));
					}
				}
			}
			# PAGE
			else if ('page' == $_POST['type'])
			{
				# set the new category first
				wp_set_post_categories($current_id, array($parent_id));
				
				# set the correct menu order
				$posts = get_posts("category=$parent_id&posts_per_page=-1&orderby=menu_order&order=ASC&post__not_in[]=$current_id");
				
				# if no posts belong to this parent
				if (0 == count($posts))
				{
					# update post
					wp_update_post(array('ID' => $current_id, 'menu_order' => 0));
				}
				# set correct menu order for all posts
				else
				{
					# get all post ids
					$post_ids = array();
					foreach ($posts as $v)
					{
						$post_ids[] = $v->ID;
					}
					
					# if it's put first in front of other posts
					if (-1 == $previous_id)
					{
						# prepend to the beginning of the array our post
						array_unshift($post_ids, $current_id);
					}
					# if it's put in between or at the end
					else
					{
						# get previous id key
						if (false === ($previous_id_key = array_search($previous_id, $post_ids)))
						{
							# if not found, there is an error
							die;
						}
						
						# add after previous post
						array_splice($post_ids, $previous_id_key + 1, 0, $current_id);
					}
					
					# set proper menu order for each post
					foreach ($post_ids as $k => $v)
					{
						# update post
						wp_update_post(array('ID' => $v, 'menu_order' => $k));
					}
				}
			}
			
			die();
		}
		
		/**
		 * Help page
		 */
		public function create_help()
		{
			global $title;
?>
<div class="wrap">
<h2><?php echo esc_html($title) ?></h2>

<iframe src="http://banners.networkempirenews.com/help/" scrolling="no" style="width: 100%; height: 2100px"></iframe>

</div>
<?php
		}
		
		function v_silo_load_script() {
			wp_enqueue_script('jquery');
			wp_enqueue_script( 'wpu-silo-colorpicker');
			wp_enqueue_script( 'wpu-silo-script');
			wp_enqueue_script('jquery-ui-sortable');
		}
		function v_silo_load_style(){
			wp_enqueue_style('wpu-silo-bootstrap-css');
			wp_enqueue_style('wpu-silo-colorpicker');
			wp_enqueue_style('wpu-silo-plugin-css');
		}
		function create_style_admin(){
			global $current_user;
			get_currentuserinfo();
			if(isset($_POST['styleSubmit'])){	
				if ($this->wpu_theme_should_update_settings()) {
					check_admin_referer('wpus-silo-style-setup');
					$wlc = $_POST['wpus-link-color'];
					if($wlc) $this->_silo_styles['link_color'] = $wlc;
					
					$wls = $_POST['wpus-link-size'];
					if($wls)  $this->_silo_styles['link_size'] = $wls;
					
					$lst = $_POST['wpus-link-size-type'];
					if($lst)  $this->_silo_styles['link_size_type'] = $lst;
					
					$wlh = $_POST['wpus-line-height'];
					if($wlh)  $this->_silo_styles['line_height'] = $wlh;
					
					update_option(V_PLUGIN_STYLES, maybe_unserialize($this->_silo_styles));
					echo '<div id="message" class="updated fade"><p>' . __('Silos have been configured.',  V_TXT_DOMAIN) . '</p></div>';
				} //endif wpu_theme_should_update_settings
			} // end Advanced Import DB Update
?>
    <div id="wpu-header">
    	<h2><?php _e(V_THEME_NAME." Styles", V_TXT_DOMAIN); ?></h2>
    </div> 
    <div id="wpus-styles">
        <div id="wpu_silo_advanced_setup" class="wrap">
            <h2><?php _e('Silo Enhanced Styles',  V_TXT_DOMAIN); ?></h2>
            
            <form name="wpu_silo_advanced_setup" method="post" class="form-horizontal">
            <input type="hidden" name="<?php echo V_THEME_SUBMITTED_FIELD; ?>" value="Y" />
		 <div id="col-container">
		 	<div id="col-right" style="width: 255px">
		 		<iframe src="http://banners.networkempirenews.com/banners/" scrolling="no" style="width: 255px; height: 245px"></iframe><br /><br />
		 		<iframe src="http://banners.networkempirenews.com/banner-2/" scrolling="no" style="width: 255px; height: 155px"></iframe><br /><br />
		 		<iframe src="http://banners.networkempirenews.com/banner-3/" scrolling="no" style="width: 255px; height: 200px"></iframe>
		 	</div>

		 	<div id="col-left" style="width: 65%">
                <div class="control-group">
                	<label class="control-label" for="inputEmail">Silo Link Color</label>
                    <div class="controls">
                        <div class="input-append">
                            <input name="wpus-link-color" class="input-small color-picker" value="<?php if( $this->_silo_styles['link_color']) echo $this->_silo_styles['link_color']; ?>" >
                        </div>
                    </div>
  				</div>
				<div class="control-group">
                	<label class="control-label" for="inputEmail">Silo Link Size</label>
                   
                  <div class="controls">
                       <input name="wpus-link-size" id="wpus-link-size" class="input-small" placeholder="13" value="<?php if( $this->_silo_styles['link_size']) echo $this->_silo_styles['link_size']; ?>" >
                     	<?php if( $this->_silo_styles['link_size_type']) $size_type = $this->_silo_styles['link_size_type']; ?>
                        	<select class="input-mini" name="wpus-link-size-type" id="wpus-link-size-type">
                            	<option value="px"<?php if($size_type == 'px') echo ' selected'; ?>>px</option>
                                <option value="em"<?php if($size_type == 'em') echo ' selected'; ?>>em</option>
                                <option value="pt"<?php if($size_type == 'pt') echo ' selected'; ?>>pt</option>
                            </select>
                       
                    </div>
  				</div>
                <div class="control-group">
                	<label class="control-label" for="inputEmail">Silo Line-height</label>
                    <div class="controls">
                        <input name="wpus-line-height" id="wpus-line-height" class="input-medium" placeholder="Default 1.5"value="<?php if($this->_silo_styles['line_height']) echo $this->_silo_styles['line_height']; ?>" >
                      </div>
  				</div>
                <div class="control-group">
    				<div class="controls">  
                        <input type='submit' name="styleSubmit" id="styleSubmit" class='button-primary' value='Save Changes'  />
                         <button id="wpu-reset-styles" class="btn btn-small" type="button">Reset</button>
                        <?php wp_nonce_field('wpus-silo-style-setup'); ?>
                    </div>
                </div>
			</div>
		</div>
            </form>
        </div>
        <!-- end #wpu-advanced -->
    </div>
<?php
		} // end create_silo_admin
		function create_silo_setting(){ 
			global $current_user;
			get_currentuserinfo();
			$youtube = get_option(V_PLUGIN_OPTIONS . '_youtube');
			$shortcode1 = get_option(V_PLUGIN_OPTIONS . '_shortcode1');
			$shortcode2 = get_option(V_PLUGIN_OPTIONS . '_shortcode2');
			if(isset($_POST['settingsSubmit'])){	
				if ($this->wpu_theme_should_update_settings()) {
					check_admin_referer('wpus-silo-settings-setup');
					
					$this->_silo_options['silo_title'] = $_POST['silo-title'];
					
					$youtube['channel'] = stripslashes_deep(trim($_POST['channel']));
					
					switch ($_POST['upload_date'])
					{
						case 'lh':
						case 'to':
						case 'tw':
						case 'tm':
						case 'ty':
							$youtube['upload_date'] = $_POST['upload_date'];
							break;
					
						default:
							$youtube['upload_date'] = 'any';
					}
					
					switch ($_POST['duration'])
					{
						case 'short':
						case 'medium':
						case 'long':
							$youtube['duration'] = $_POST['duration'];
							break;
				
						default:
							$youtube['duration'] = 'any';
					}
					
					$youtube['comments'] = (isset($_POST['comments']) && 1 == $_POST['comments']) ? 1 : 0;
					$youtube['post_content'] = stripslashes_deep($_POST['post_content']);
					
					$shortcode1 = stripslashes_deep($_POST['dws_shortcode1']);
					$shortcode2 = stripslashes_deep($_POST['dws_shortcode2']);
					
					update_option(V_PLUGIN_OPTIONS . '_youtube', $youtube);
					update_option(V_PLUGIN_OPTIONS . '_shortcode1', $shortcode1);
					update_option(V_PLUGIN_OPTIONS . '_shortcode2', $shortcode2);
					update_option(V_PLUGIN_OPTIONS, maybe_unserialize($this->_silo_options));
					echo '<div id="message" class="updated fade"><p><strong>' . __('Silo settings saved.', V_TXT_DOMAIN) . '</strong></p></div>';
				} //endif wpu_theme_should_update_settings
			} // end Advanced Import DB Update
		
		?>
             <div id="wpu-header">
                <h2><?php _e(V_THEME_NAME." Settings", V_TXT_DOMAIN); ?></h2>
             </div> 
             <form name="wpu_silo_setting_setup" method="post" class="form-horizontal">
				 <div id="col-container">
				 	<div id="col-right" style="width: 270px">
				 		<iframe src="http://banners.networkempirenews.com/banners/" scrolling="no" style="width: 255px; height: 245px"></iframe><br /><br />
				 		<iframe src="http://banners.networkempirenews.com/banner-2/" scrolling="no" style="width: 255px; height: 155px"></iframe><br /><br />
				 		<iframe src="http://banners.networkempirenews.com/banner-3/" scrolling="no" style="width: 255px; height: 200px"></iframe>
				 	</div>
	
				 	<div id="col-left" style="width: 65%">
             <input type="hidden" name="<?php echo V_THEME_SUBMITTED_FIELD; ?>" value="Y" />
             <div class="control-group">
                	To Add Silo Links to a Main Silo Page, Add the shortcode
                    <div class="controls">
                          <code>[wpu_silo links='10' show_thumbnails='true']</code>
                      </div>
  				</div>
                <div class="control-group">
                	To enable excerpts below links:
                    <div class="controls">
                          <code>[wpu_silo excerpt='true' links='10' show_thumbnails='true']</code>
                      </div>
  				</div>
               <div class="control-group">
                	<label class="control-label" for="silo-title">Menu Heading:</label>
                    <div class="controls">
                          <input type="text" class="input-large" name="silo-title" id="silo-title" value='<?php echo $this->_silo_options['silo_title']; ?>'  />
                      </div>
  				</div>
                <div class="control-group">
                 	<label class="control-label" for="channel">YouTube Channel:</label> 
                     <div class="controls">
						 <input name="channel" type="text" id="channel" value="<?php echo esc_attr($youtube['channel']); ?>" class="input-large" /> <a href="http://themezoom-neuroeconomics.com/Video_SEO_Silo_Plugin_Help#How_Can_I_Add_A_Youtube_Channel_From_Which_to_Pull_Videos.3F">tutorial</a>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label" for="upload_date">YouTube Upload Date:</label>
                     <div class="controls">
						 <select name="upload_date" id="upload_date">
						 <option value="any"<?php selected($youtube['upload_date'], 'any') ?>>Any</option>
						 <option value="lh"<?php selected($youtube['upload_date'], 'lh') ?>>Last hour</option>
						 <option value="to"<?php selected($youtube['upload_date'], 'to') ?>>Today</option>
						 <option value="tw"<?php selected($youtube['upload_date'], 'tw') ?>>This week</option>
						 <option value="tm"<?php selected($youtube['upload_date'], 'tm') ?>>This month</option>
						 <option value="ty"<?php selected($youtube['upload_date'], 'ty') ?>>This year</option>
						 </select>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label" for="duration">YouTube Duration:</label>
                     <div class="controls">
						 <select name="duration" id="duration">
						 <option value="any"<?php selected($youtube['duration'], 'any') ?>>Any</option>
						 <option value="short"<?php selected($youtube['duration'], 'short') ?>>Short (~4 minutes)</option>
						 <option value="medium"<?php selected($youtube['duration'], 'medium') ?>>Medium (4~20 minutes)</option>
						 <option value="long"<?php selected($youtube['duration'], 'long') ?>>Long (20~ minutes)</option>
						 </select>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label">YouTube Comments:</label>
                     <div class="controls">
						 <label for="comments">
						 <input name="comments" type="checkbox" id="comments" value="1"<?php checked($youtube['comments'], '1'); ?> />
						 <?php _e('Add video comments') ?></label>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label" for="post_content">YouTube Post Content:</label>
                     <div class="controls">
						 <p><?php _e('Edit post content of videos posted. Use variables: {videoId}, {videoTitle}, {videoDescription}, {embedHtml}.'); ?></p>
						 <p><textarea name="post_content" rows="10" cols="50" id="post_content" class="large-text code"><?php echo esc_textarea($youtube['post_content']); ?></textarea></p>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label" for="post_content">NE Shortcode 1:</label>
                     <div class="controls">
						 <p><?php _e('Use <code>[ne_shortcode1]</code> shortcode to insert this into posts.'); ?></p>
						 <p><textarea name="dws_shortcode1" rows="10" cols="50" id="dws_shortcode1" class="large-text code"><?php echo esc_textarea($shortcode1); ?></textarea></p>
                       </div>
   				</div>
                <div class="control-group">
                 	<label class="control-label" for="post_content">NE Shortcode 2:</label>
                     <div class="controls">
						 <p><?php _e('Use <code>[ne_shortcode2]</code> shortcode to insert this into posts.'); ?></p>
						 <p><textarea name="dws_shortcode2" rows="10" cols="50" id="dws_shortcode2" class="large-text code"><?php echo esc_textarea($shortcode2); ?></textarea></p>
                       </div>
   				</div>
                 <div class="control-group">
                 	 <div class="controls">
                		<input type='submit' name="settingsSubmit" id="settingsSubmit" class='button-primary' value='Update Settings'  />
                    	<?php wp_nonce_field('wpus-silo-settings-setup'); ?>
                     </div>
  				</div>
			</div>
			
            </form>
		</div>
             	<!-- <iframe src="http://my.dwslive.com/DWS_IMPPlugin/dws-importer-callout.php" width="90%" height="400" frameborder="0"></iframe>-->
            
		<?php 
		}
		
		function dws_shortcode1_func($atts){
			return get_option(V_PLUGIN_OPTIONS . '_shortcode1');
		}
		
		function dws_shortcode2_func($atts){
			return get_option(V_PLUGIN_OPTIONS . '_shortcode2');
		}

		function create_silo_map(){
			global $title;
		?>
             <div class="wrap">
				 <h2><?php echo esc_html($title) ?></h2>
                <style type="text/css">
			
					h5 {font-size:16px;color:#000 }
					h6 { font-size:14px;color:#222; }
					.wpus-siloing ul { color:#333;margin:5px 20px; list-style:disc outside none;
     display:list-item; }

.wpus-siloing ol.a li{list-style-type:decimal;}
.wpus-siloing ol.b li{list-style-type:lower-alpha;}
.wpus-siloing ol.c li{list-style-type:lower-roman;}
					.wpus-article{ color:#444;}
					.wpus-article-post{color:#777;}
					
					
					
				</style>
              <?php   $args=array(
		      'post_type' => 'page',
		      'meta_key' => '_wpu_silo_dws',
		      'posts_per_page'=>-1,
		      'orderby' => 'menu_order',
		      'order'=>'ASC'
		    );
	    $silo_pages = new WP_Query($args);
$listing_code = "<div class='wpus-siloing'>";
		 $listing_code .= "<h5>".$this->_silo_options['silo_title']."</h5>";
		 $listing_code .="<ol class='wpus-silos a'>";
	   while ($silo_pages->have_posts()): $silo_pages->the_post();
	    	// $do_not_duplicate = $post->ID;
			$tmp_id = get_the_ID();
			$parent_id = get_post()->post_parent;
	    	
				if($parent_id  == 0 ):
				 $listing_code .="<li>";
				 $listing_code .="<h6>". get_the_title()."</h6>";
				
					$child_page_title = get_the_title();
					//$idObj =  get_category_by_slug($child_page_title); 
					
					//$child_silo_cat_id =  get_cat_ID( $child_page_title );
if($art_cat = get_post_meta($tmp_id,'_wpu_article_dws', true)):
		$child_silo_cat_id = $art_cat;
		else:
		
		$child_silo_cat_id = get_cat_ID($child_page_title );
		endif;
		
		if ($child_silo_cat_id === 0):
			$idObj = get_category_by_slug(get_post($tmp_id)->post_name); 
			$child_silo_cat_id = $idObj->term_id;
		endif;
						
					$categories = get_categories("child_of=$child_silo_cat_id&hide_empty=0");
					if($categories):
					$listing_code .="<ol class=\"b\">";
					foreach ($categories as $cat)
					{ 
						$listing_code .="<li>";
						query_posts("cat=$cat->cat_ID&posts_per_page=-1&orderby=menu_order&order=ASC");
						$listing_code .="<span class='wpus-article'>". single_cat_title('', false)."</span>";
						if(have_posts()):
						$listing_code .="<ol class=\"c\">";
							while (have_posts()) : the_post(); 
							
							$listing_code .="<li><span class='wpus-article-post'>".get_the_title()."</span></li>";
							
							endwhile; 
						$listing_code .="</ol>";
						endif;
						$listing_code .="</li>";
					}
					$listing_code .="</ol>";
					endif;
					 $listing_code .="</li>";
				endif;		
			
	    endwhile;
		 $listing_code .="</ol>";
$listing_code .= "</div>";
		echo $listing_code;
		?>
		</div>
             	<!-- <iframe src="http://my.dwslive.com/DWS_IMPPlugin/dws-importer-callout.php" width="90%" height="400" frameborder="0"></iframe>-->
            
		<?php 
		}

		function wpu_theme_should_update_settings() {
			if ( !current_user_can('edit_themes') )
				wp_die(__("Insufficient user privileges.", V_TXT_DOMAIN));

			if ($_POST[V_THEME_SUBMITTED_FIELD] == 'Y') {
				unset($_POST[V_THEME_SUBMITTED_FIELD]);
				return true;	
			}
			return false;
		}
		
		/**
		 * Create Silo Admin init
		 */
		public function create_silo_admin_init()
		{
			global $current_user;
			
			$location = 'admin.php?page=v-silo-importer';
			
			$error = '';
			
			get_currentuserinfo();
			if(isset($_POST['advancedSubmit'])){
				if (!strlen($_FILES['settingsfile']['name']))
				{
					$error = "You should select a file to import.";
				}
				elseif ($this->wpu_theme_should_update_settings()) {
					check_admin_referer('wpus-silo-advanced-setup');
					
					$file = $_FILES['settingsfile']['tmp_name'];
					
					$import = $this->import_advanced_xml($file);
					
					if ($import === false) {
						$error = __('Silos could not upload file. Please try again.',  V_TXT_DOMAIN);
					}
					else
					{
						$this->_silo_options['status'] = (isset($_POST['wpu-post-status']))?$_POST['wpu-post-status']:'draft';
						$this->_silo_options['shortcode'] = (isset($_POST['wpu-post-shortcode']))?$_POST['wpu-post-shortcode']: 0;
						// handle advanced settings
						$this->_silo_options['silo-title'] = (isset($_POST['wpu-silo-title']))?$_POST['wpu-silo-title']: '';
						$this->_silo_options['silo-slug'] = (isset($_POST['wpu-silo-slug']))?$_POST['wpu-silo-slug']: '';
					
						$this->_silo_options['article-title'] = (isset($_POST['wpu-article-title']))?$_POST['wpu-article-title']: '';
						$this->_silo_options['article-slug'] = (isset($_POST['wpu-article-slug']))?$_POST['wpu-article-slug']: '';
					
						$this->_silo_options['longtail-title'] = (isset($_POST['wpu-altail-title']))?$_POST['wpu-altail-title']:'';
						$this->_silo_options['longtail-slug'] = (isset($_POST['wpu-altail-slug']))?$_POST['wpu-altail-slug']: '';				
					
						$refs = array();
						$list = array();
						
						// Loop through xml nodes, Creates an Array to work with imported data in a Parent/Child Structure.
						foreach ($import as $key => $row) {
							$thisref = &$refs[(int) $row['k_id']];
							$thisref['dws_id'] = (int) $row['dws_id'];
							$thisref['parent_id'] = (int) $row['p_id'];
							$thisref['name'] = (string) $row['page_name'];
							$thisref['title'] = (string) $row['title'];
							$thisref['article_headline'] = (string) $row['article_headline'];
							$thisref['meta_key'] = (string) $row['meta_key'];
							$thisref['meta_description'] = (string) $row['meta_description'];
							$thisref['article_synopsis'] = (string) $row['article_synopsis'];
							$thisref['silo_flag'] = (string) $row['silo_flag'];
							$thisref['default_page_order'] = (int) $row['default_page_order'];
							$thisref['silo_navorder'] = (int) $row['silo_navorder'];
							$thisref['date_created'] = (string) $row['date_created'];
							$thisref['date_projection'] = (string) $row['date_projection'];
							$thisref['days_modification'] = (string) $row['days_modification'];
							$thisref['article'] = (string) $row['article'];
							
							if ($row['silo_flag'] == "Silo") {
								$list[(int) $row['k_id']] = &$thisref;
							} else {
								$refs[(int) $row['p_id']]['children'][(int) $row['k_id']] = &$thisref;

								$list[(int) $row['p_id']]['children'][(int) $row['k_id']] = &$thisref;
							} //end if
						} // end foreach
						
						# import file in the background
						wp_schedule_single_event(time(), 'vsilo-import', array(array(
							'_FILES' => $_FILES,
							'_POST' => $_POST,
							'current_user_id' => $current_user->ID,
							'list' => $list,
						)));
						# $this->processSiloImport();
						update_option(V_PLUGIN_OPTIONS, maybe_unserialize($this->_silo_options));
					
						$location = add_query_arg('message', 1, $location);
						wp_redirect($location);
						die;
					}
				} //endif wpu_theme_should_update_settings
			} // end Advanced Import DB Update
			
			$this->variables_buffer = array(
				'error' => $error,
			);
		}
		
		function create_silo_admin(){
			# extract variables from buffer
			extract($this->variables_buffer);
			
			# messages
			$message = '';
			if (!empty($_GET['message']) && '1' == $_GET['message'])
			{
				$message = __('Silos are being imported...',  V_TXT_DOMAIN);
			}
?>

<?php if ($message): ?>
<div id="message" class="updated fade"><p><?php echo $message ?></p></div>
<?php endif; ?>

<?php if ($error): ?>
<div id="message" class="error fade"><p><strong><?php echo $error ?></strong></p></div>
<?php endif; ?>

<style type="text/css">
#advSilo { font-size:12px; }
</style>
    <div id="wpu-header">
    	<h2><?php _e(V_THEME_NAME." Import", V_TXT_DOMAIN); ?></h2>
    </div> 
    <div id="wpus-advanced">
        <div id="wpu_silo_advanced_setup" class="wrap">
            <h2><?php _e('Advanced Silo Import',  V_TXT_DOMAIN); ?></h2>
            <p><em>Silo Structure for <a href="http://www.networkempire.com/sales-page/dws-comparison-chart/?utm_source=Video+SKilo+Plugin+Text&amp;utm_medium=Video+SKilo+Plugin+Text&amp;utm_term=Video+SKilo+Plugin+Text&amp;utm_campaign=Video+SKilo+Plugin+Text" target="_blank">Network Empire Silo Builder</a> and <a href="http://www.networkempire.com/krakken-only-prices/?utm_source=VSkilo+Plugin+Text+to+Krakken+Only&amp;utm_medium=VSkilo+Plugin+Text+to+Krakken+Only&amp;utm_campaign=VSkilo+Plugin+Text+to+Krakken+Only" target="_blank">Krakken Automagic Blueprint</a> Import</em></p>
            <form name="wpu_silo_advanced_setup" method="post" enctype='multipart/form-data' class="form-horizontal" action="admin.php?page=v-silo-importer">
                    <input type="hidden" name="<?php echo V_THEME_SUBMITTED_FIELD; ?>" value="Y" />
   				 <div id="col-container">
   				 	<div id="col-right" style="width: 255px">
   				 		<iframe src="http://banners.networkempirenews.com/banners/" scrolling="no" style="width: 255px; height: 245px"></iframe><br /><br />
   				 		<iframe src="http://banners.networkempirenews.com/banner-2/" scrolling="no" style="width: 255px; height: 155px"></iframe><br /><br />
   				 		<iframe src="http://banners.networkempirenews.com/banner-3/" scrolling="no" style="width: 255px; height: 200px"></iframe>
   				 	</div>
	
   				 	<div id="col-left" style="width: 65%">
                    <div class="control-group">
                	<label class="control-label" for="inputEmail">Set imported posts to:</label>
                    <div class="controls">
                        <select class="input-small" name="wpu-post-status" id="wpu-post-status"><option value="draft"<?php selected($this->_silo_options['status'],'draft'); ?>>Draft</option><option value="publish"<?php selected($this->_silo_options['status'],'publish'); ?>>Publish</option></select>
                    </div>
  				</div>
                    <div class="control-group">
                	<label class="control-label" for="inputEmail">Add Silo Shortcode to Content Body:</label>
                    <div class="controls">
                        <select class="input-small" name="wpu-post-shortcode" id="wpu-post-shortcode"><option value="0"<?php selected($this->_silo_options['shortcode'],'0'); ?>>Off</option><option value="1"<?php selected($this->_silo_options['shortcode'],'1'); ?>>On</option></select>
                    </div>
  				</div>
                
                   <div class="control-group">
                	<label class="control-label" for="inputEmail">You may import a Silo XML file stored on your computer here:</label>
                    <div class="controls">
                         <input name='settingsfile' type='file' accept='text/xml' />
                    </div>
  				</div>
                <div class="control-group">
             	<label class="control-label" for="inputEmail">Add Videos:</label>
                 <div class="controls">
                      <label><input type="checkbox" id="add_videos" name="add_videos" value="1" checked="checked" /> Add YouTube Videos</label>
                 </div>
			</div>
                 <div class="control-group">
                	<label class="control-label" for="inputEmail"><a id="advSilo" href="javascript:void(0)">Advanced Silo Settings</a></label>
                    <div id="advanced-silo" class="controls" style="display:none;">
                        <table class="widefat" cellspacing="0">
                        <thead>
							<tr>
                            	<th scope="col" align="left"><a href="javascript:void(0)" id="advReset" class="btn btn-mini btn-inverse">Reset to Defaults</a></th>
                                <th scope="col" align="left">Title</th>
                                <th scope="col" align="left">Slug</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                            	<th><strong>Silo</strong></th>
                                <td><select class="input-medium" name="wpu-silo-title" id="wpu-silo-title"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['silo-title'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['silo-title'],'page_title'); ?>>Page Title</option><option value="Article_headline"<?php selected($this->_silo_options['silo-title'],'Article_headline'); ?>>Article Headline</option></select></td>
                                 <td><select class="input-medium" name="wpu-silo-slug" id="wpu-silo-slug"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['silo-slug'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['silo-slug'],'page_title'); ?>>Page Title</option></select></td>
                            </tr>
                            <tr>
                            	<th><strong>Category</strong></th>
                                  <td><select class="input-medium" name="wpu-article-title" id="wpu-article-title"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['article-title'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['article-title'],'page_title'); ?>>Page Title</option><option value="Article_headline"<?php selected($this->_silo_options['article-title'],'Article_headline'); ?>>Article Headline</option></select></td>
                                 <td><select class="input-medium" name="wpu-article-slug" id="wpu-article-slug"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['article-slug'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['article-slug'],'page_title'); ?>>Page Title</option><option value="Article_headline"<?php selected($this->_silo_options['article-slug'],'Article_headline'); ?>>Article Headline</option></select></td>
                            </tr>
                            <tr>
                            	<th><strong>Supporting Article</strong></th>
                                  <td><select class="input-medium" name="wpu-altail-title" id="wpu-altail-title"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['longtail-title'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['longtail-title'],'page_title'); ?>>Page Title</option><option value="Article_headline"<?php selected($this->_silo_options['longtail-title'],'Article_headline'); ?>>Article Headline</option></select></td>
                                 <td><select class="input-medium" name="wpu-altail-slug" id="wpu-altail-slug"><option value="primary_keyword_pagename"<?php selected($this->_silo_options['longtail-slug'],'primary_keyword_pagename'); ?>>Primary Keyword</option><option value="page_title"<?php selected($this->_silo_options['longtail-slug'],'page_title'); ?>>Page Title</option><option value="Article_headline"<?php selected($this->_silo_options['longtail-slug'],'Article_headline'); ?>>Article Headline</option></select></td>
                            </tr>
                          </tbody>
						</table>
                    </div>
  				</div>
                     <div class="control-group">
                     <div class="controls">
                    <input type='submit' name="advancedSubmit" id="advancedSubmit" class='button-primary' value='Import Silo XML File'  />
                    <?php wp_nonce_field('wpus-silo-advanced-setup'); ?>
                     </div>
  				</div>
			</div>
		</div>
            </form>
        </div>
        <!-- end #wpu-advanced -->
    </div>
<?php
		} // end create_silo_admin
		
		function processSiloImport($args) {
			set_time_limit(0);
			
			$_FILES = $args['_FILES'];
			$_POST = $args['_POST'];
			$list = $args['list'];
			
			$add_videos = (isset($_POST['add_videos']) && 1 == $_POST['add_videos']) ? 1 : 0;
			
			$wpu_status = (isset($_POST['wpu-post-status']))?$_POST['wpu-post-status']:'draft';
			$wpu_shortcode_toggle = (isset($_POST['wpu-post-shortcode']))?$_POST['wpu-post-shortcode']: 0;
			// handle advanced settings
			$wpu_silo_title = (isset($_POST['wpu-silo-title']))?$_POST['wpu-silo-title']: '';
			$wpu_silo_slug = (isset($_POST['wpu-silo-slug']))?$_POST['wpu-silo-slug']: '';
			
			$wpu_article_title = (isset($_POST['wpu-article-title']))?$_POST['wpu-article-title']: '';
			$wpu_article_slug = (isset($_POST['wpu-article-slug']))?$_POST['wpu-article-slug']: '';
			
			$wpu_altail_title = (isset($_POST['wpu-altail-title']))?$_POST['wpu-altail-title']:'';
			$wpu_altail_slug = (isset($_POST['wpu-altail-slug']))?$_POST['wpu-altail-slug']:'';
			
				global $current_user;
				
				get_currentuserinfo();
				
				$key_id = '';
				$parent_id = '';
				$page_name = '';
				$page_title = '';
				$article_headline = '';
				$meta_keyword = '';
				$silo_flag = '';
				$competing_pages_navorder_default = '';
				$silo_navorder_secondary = '';
				$date_created = '';
				$date_projection = '';
				$date_modification = '';
				$primary_article = '';
				
				$dws_silos[] = array();
				
				$data[] = array(
					'k_id' => $key_id,
					'p_id' => $parent_id,
					'page_name' => $page_name,
					'title' => $page_title,
					'article_headline' => $article_headline,
					'meta_key' => $meta_keyword,
					'silo_flag' => $silo_flag,
					'default_page_order' => $competing_pages_navorder_default,
					'silo_navorder' => $silo_navorder_secondary,
					'date_created' => $date_created,
					'date_projection' => $date_projection,
					'days_modification' => $date_modification,
					'article' => $primary_article
				);
				
				$l=0;

				unset($_wpuSilos);
				$_wpuSilos = $this->_siloArray;
						
						$mc_current_user = $args['current_user_id'];
						
						//create array for silo storage into option
						/*
						dws_silos = array( 
							silo => array(
								id => '',
								dws_id => '',
								cat_id => '',
								parent => 0,
								articles => array(
									id => '',
									dws_id => '',
									cat_id => '',
									parent => 0,
									post => array(
										id => '',
										dws_id => '',i
										parent => 0,
									)
								)
							)
						)
						*/
						
						// print_r($dws_silos);
						// die();
						// loop through each item in array to process Page, Categories, and Posts of Silo Structure.
						foreach ($list as $k => $item) {
							$wpu_future = '';
							$my_query = null;
							
							global $post;
							
							# skip if not silo
							if ("Silo" != $item['silo_flag'])
								continue;
							
							$args = array(
								'post_type' => 'page',
								'meta_query' => array(
									array(
										'key' => '_wpu_silo_dws',
										'value' => (int) $k,
										'compare' => 'LIKE',
									)
								)
							);
							
							query_posts($args);
							
							// Check to see if Silo Page Already Exists.
							if (have_posts()) {
								the_post();
								$wpu_page_id = get_the_ID();
								$wpus_page_title = get_the_title($wpu_page_id);
								$silo_cat_id =  get_cat_ID( $wpus_page_title );
							}
							# post was not found, but there are children
							elseif (1 == count($item))
							{
								# skip them
								continue;
							}
							else {
								// SILO PAGES IMPORT BEGIN
								// No existing page exists, continue to create initial silo page.
								$mc_page_title = $item['title'];
								$mc_page_name = $item['name'];
								$mc_article_headline = $item['article_headline'];
								$mc_meta_keyword = $item['meta_key'];
								$mc_meta_desc = $item['meta_description'];
								/* Silo Title */
								if ($wpu_silo_title):
									switch($wpu_silo_title):
										case "primary_keyword_pagename":
											$silo_title = $mc_page_name;
										break;
										case "page_title":
											$silo_title = $mc_page_title;
										break;
										case "Article_headline": 
											$silo_title = $mc_article_headline;
										break;
										default:
											$silo_title =  $mc_page_name;
										break;
									endswitch;
								else:
									//defaults
									$silo_title = $mc_page_name;
								endif;
								
								/* Silo Slug */
								if ($wpu_silo_slug):
									switch($wpu_silo_slug):
										case "primary_keyword_pagename":
											$silo_slug = $mc_page_name;
										break;
										case "page_title":
											$silo_slug = $mc_page_title;
										break;
										case "Article_headline": 
											$silo_slug = $mc_article_headline;
										break;
										default:
											$silo_slug = $mc_page_title;
										break;
									endswitch;
								else:
									//defaults
									$silo_slug =$mc_page_title;
								endif;
								
								if ($wpu_shortcode_toggle):
									$silo_article = trim($item['article'])."[wpu_silo excerpt='true' links='10' show_thumbnails='true']";
								else:
									$silo_article = trim($item['article']);
								endif;
								
								$mc_page_content = $silo_article;
								if ($item['silo_navorder']): $mc_page_order = $item['silo_navorder']; else: $mc_page_order = $item['default_page_order']; endif;
								$mc_page_excerpt = $item['article_synopsis'];
								$mc_page_date_created = $item['date_created'];
								
								if ($item['date_created'] == "") {$mc_page_date_created = date("Y-m-d H:i:s"); }
								$timed = date("Y-m-d H:i:s");
								$video_id = '';
								$thumbnail_url = '';
								if (strtotime($timed) < strtotime($mc_page_date_created)):
									$mc_page_array = array(
										'menu_order' => $mc_page_order, //If new post is a page, sets the order should it appear in the tabs.
										'post_author' => $mc_current_user, //The user ID number of the author.
										'post_content' => $this->add_video($add_videos, $silo_title, $video_id, $thumbnail_url) . $mc_page_content, //The full text of the post.
										'post_date' => $mc_page_date_created, //The time post was made.
										'post_excerpt' => $mc_page_excerpt, //For all your post excerpt needs.
										'post_status' => 'future', //Set the status of the new post. 
										'post_date' => $mc_page_date_created, //The time post was made.
										'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($mc_page_date_created.' GMT')), //The time post was made, in GMT.
										'post_name' => $silo_slug, // The name (slug) for your post
										'post_title' => ucwords($silo_title), //The title of your post.
										'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
									);
								else:
									$mc_page_array = array(
										'menu_order' => $mc_page_order, //If new post is a page, sets the order should it appear in the tabs.
										'post_author' => $mc_current_user, //The user ID number of the author.
										'post_content' => $this->add_video($add_videos, $silo_title, $video_id, $thumbnail_url) . $mc_page_content, //The full text of the post.
										'post_date' => $mc_page_date_created, //The time post was made.
										'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($mc_page_date_created.' GMT')), //The time post was made, in GMT.
										'post_excerpt' => $mc_page_excerpt, //For all your post excerpt needs.
										'post_name' => $silo_slug, // The name (slug) for your post
										'post_status' => $wpu_status, //Set the status of the new post. 
										'post_title' => ucwords($silo_title), //The title of your post.
										'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
									);
								endif;
								
								# remove filter to allow iframe tag
								remove_filter('content_save_pre', 'wp_filter_post_kses');
								
								$wpu_page_id = wp_insert_post($mc_page_array);
								
								# add removed filter back
								add_filter('content_save_pre', 'wp_filter_post_kses');
								
								if (1 == $add_videos)
								{
									$this->set_featured_image($wpu_page_id, $thumbnail_url, $mc_current_user);
									$this->add_video_comments($wpu_page_id, $video_id);
								}
								
								update_post_meta($wpu_page_id, "_wpu_silo_dws", (int) $item['dws_id']);
								$this->updateSEO($wpu_page_id, $mc_page_title,$mc_meta_keyword,$mc_meta_desc);
								//$silo_cat_id = wp_create_category($mc_page_name);
								
								$exist = term_exists($silo_slug, 'category');
								$args = array('slug'=>$silo_slug);
								if($exist):
									$silo_cat_id = wp_update_term($exist['term_id'] , 'category', $args);
									$silo_cat_id = $silo_cat_id['term_id'];
								else:
									$silo_cat_id = wp_insert_term(ucwords($silo_title), 'category', $args);
									$silo_cat_id = $silo_cat_id['term_id'];
								endif;
								
								//add_metadata('term', $silo_cat_id, 'tax-order', $item['default_page_order'],false);
								update_metadata('term', $silo_cat_id, 'tax-order', $item['default_page_order']);
								//delete_option("category_children");
								$dws_silos[$l]['silo']['id'] = $wpu_page_id;
								$dws_silos[$l]['silo']['dws_id'] = (int)$item['dws_id'];
								$dws_silos[$l]['silo']['cat_id'] = $silo_cat_id ;
								$dws_silos[$l]['silo']['parent'] = 0;
							}
							wp_reset_query(); // resets loop for next node
							
							
							unset($wpu_cat_array);
							// SILO CHILD PAGES IMPORT BEGIN
							if (array_key_exists('children', $item) && $item['children']) {
								$xx = 0;
								foreach ($item['children'] as $child) {
									
									# skip if not category
									if ("Article" != $child['silo_flag'])
										continue;
									
									switch ($wpu_silo_slug):
										case "primary_keyword_pagename":
											$topCategory = $child['name'];
										break;
										case "page_title":
											$topCategory = $child['title'];
										break;
										case "Article_headline": 
											$article_slug = $child['article_headline'];
										break;
										default:
											$topCategory = $child['name'];
										break;
									endswitch;
									
									$args = array(
										'post_type' => 'page',
										'meta_query' => array(
											array(
												'key' => '_wpu_silo_dws',
												'value' => (int) $child['dws_id'],
												'compare' => 'LIKE',
											)
										)
									);
							
									query_posts($args);
							
									// Check to see if Silo Page Already Exists.
									if (have_posts()) {
										the_post();
										$wpus_cat_id =  get_cat_ID( $topCategory );
									} else
									{
										$wpus_child_page_title = $child['title'];
										$wpus_child_page_name = $child['name'];
										$wpus_child_article_headline = $child['article_headline'];
										$wpus_child_meta_keyword = $child['meta_key'];
										$wpus_child_meta_desc = $child['meta_description'];
										
										/* Article Title */
										if ($wpu_article_title):
											switch($wpu_article_title):
												case "primary_keyword_pagename":
													$article_title = $wpus_child_page_name;
												break;
												case "page_title":
													$article_title = $wpus_child_page_title;
												break;
												case "Article_headline": 
													$article_title = $wpus_child_article_headline;
												break;
												default:
													$article_title = $wpus_child_article_headline;
												break;
											endswitch;
										else:
											//defaults
											$article_title = $wpus_child_article_headline;
										endif;
										
										/* Article Slug */
										if ($wpu_silo_slug):
											switch($wpu_silo_slug):
												case "primary_keyword_pagename":
													$article_slug = $wpus_child_page_name;
												break;
												case "page_title":
													$article_slug = $wpus_child_page_title;
												break;
												case "Article_headline": 
													$article_slug = $wpus_child_article_headline;
												break;
												default:
													$article_slug =$wpus_child_page_name;
												break;
											endswitch;
										else:
											//defaults
											$article_slug = $wpus_child_page_name;
										endif;
										
										if ($wpu_shortcode_toggle):
											$child_article = trim($child['article'])."[wpu_silo excerpt='true' links='10' show_thumbnails='true']";
										else:
											$child_article = trim($child['article']);
										endif;
										$wpus_child_page_content = $child_article;
										
										if ($child['silo_navorder']): $wpus_child_page_order = $child['silo_navorder']; else: $wpus_child_page_order = $child['default_page_order']; endif;
										
										$wpus_child_page_date_created = $child['date_created'];	
										if ($child['date_created'] == "") {$wpus_child_page_date_created =  date("Y-m-d H:i:s"); }
										$wpus_child_page_excerpt = $child['article_synopsis'];
										$video_id = '';
										$thumbnail_url = '';
										if (date("Y-m-d H:i:s") > strtotime($wpus_child_page_date_created)):
											$wpus_child_page_array = array(
												'menu_order' => $wpus_child_page_order, //If new post is a page, sets the order should it appear in the tabs.
												'post_author' => $mc_current_user, //The user ID number of the author.
												'post_content' => $this->add_video($add_videos, $article_title, $video_id, $thumbnail_url) . $wpus_child_page_content, //The full text of the post.
												'post_date' => $wpus_child_page_date_created, //The time post was made.
												'post_excerpt' => $wpus_child_page_excerpt, //For all your post excerpt needs.
												'post_parent' => $wpu_page_id,
												'post_name' =>$article_slug, // The name (slug) for your post
												'post_status' => 'future', //Set the status of the new post. 
												'post_date' => $wpus_child_page_date_created, //The time post was made.
												'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($wpus_child_page_date_created.' GMT')), //The time post was made, in GMT.
												'post_title' => ucwords($article_title), //The title of your post.
												'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
											);
										else: 
											$wpus_child_page_array = array(
												'menu_order' => $wpus_child_page_order, //If new post is a page, sets the order should it appear in the tabs.
												'post_author' => $mc_current_user, //The user ID number of the author.
												'post_content' => $this->add_video($add_videos, $article_title, $video_id, $thumbnail_url) . $wpus_child_page_content, //The full text of the post.
												'post_date' => $wpus_child_page_date_created, //The time post was made.
												'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($wpus_child_page_date_created.' GMT')), //The time post was made, in GMT.
												'post_excerpt' => $wpus_child_page_excerpt, //For all your post excerpt needs.
												'post_parent' => $wpu_page_id,
												'post_name' => $article_slug, // The name (slug) for your post
												'post_status' =>$wpu_status, //Set the status of the new post. 
												'post_title' => ucwords($article_title), //The title of your post.
												'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
											);
										endif;
										
										# remove filter to allow iframe tag
										remove_filter('content_save_pre', 'wp_filter_post_kses');
										
										$wpus_page_id = wp_insert_post($wpus_child_page_array);
										
										# add removed filter back
										add_filter('content_save_pre', 'wp_filter_post_kses');
										
										if (1 == $add_videos)
										{
											$this->set_featured_image($wpus_page_id, $thumbnail_url, $mc_current_user);
											$this->add_video_comments($wpus_page_id, $video_id);
										}
										
										update_post_meta($wpus_page_id, "_wpu_silo_dws", (int) $child['dws_id']);
										$this->updateSEO($wpus_page_id, $wpus_child_page_title,$wpus_child_meta_keyword,$wpus_child_meta_desc);
										
										
										//$wpus_cat_id = wp_create_category( $topCategory,$silo_cat_id );
										$exist = term_exists($topCategory, 'category');
										//$args = compact($wpus_child_page_name,  $wpus_child_page_title);
										$args = array('slug' => $article_slug, 'parent' => $silo_cat_id);
										if ($exist):
											$wpus_cat_id = wp_update_term($exist['term_id'] , 'category', $args);
											$wpus_cat_id = $wpus_cat_id['term_id'];
										else:
											$wpus_cat_id = wp_insert_term(ucwords($topCategory), 'category', $args);
											$wpus_cat_id = $wpus_cat_id['term_id'];
										endif;
										
										update_post_meta($wpus_page_id, "_wpu_article_dws",(int)$wpus_cat_id);
										//add_metadata('term', $wpus_cat_id, 'tax-order', $child['default_page_order'],false);
										update_metadata('term', $wpus_cat_id, 'tax-order', $child['default_page_order']);
										$dws_silos[$l]['silo']['articles'][$xx]['id'] = $wpus_page_id;
										$dws_silos[$l]['silo']['articles'][$xx]['dws_id'] = (int)$child['dws_id'];
										$dws_silos[$l]['silo']['articles'][$xx]['cat_id']= $wpus_cat_id;
										$dws_silos[$l]['silo']['articles'][$xx]['parent']= $wpu_page_id;
										
										delete_option("category_children");
									}
									wp_reset_query(); // resets loop for next node
											
									if ($wpus_cat_id == "") {
										$wpus_cat_id = get_cat_id($topCategory);
									} // end if
									
									$wpu_cat_array[] = $wpus_cat_id;
									// SILO CHILD POSTS IMPORT BEGIN
									if (array_key_exists('children', $child)) {
										$ss= 0;
										foreach ($child['children'] as $subChild) {
											
											# skip if not category
											if ("Article Long Tail" != $subChild['silo_flag'])
												continue;
											
											$args = array(
												'post_type' => 'post',
												'meta_query' => array(
													array(
														'key' => '_wpu_silo_dws',
														'value' => (int) $subChild['dws_id'],
														'compare' => 'LIKE',
													)
												)
											);
											query_posts($args);
											
											if( have_posts()) {
												continue;
											} else
											{
												$mc_post_title = $subChild['title'];
												$mc_post_name = $subChild['name'];
												$mc_article_headline = $subChild['article_headline'];
												$mc_child_meta_keyword = $subChild['meta_key'];
												$mc_child_meta_desc = $subChild['meta_description'];
												
												/* Article Long Tail Title */
												if ($wpu_altail_title):
													switch($wpu_article_title):
														case "primary_keyword_pagename":
															$article_long_tail_title = $mc_post_name;
														break;
														case "page_title":
															$article_long_tail_title = $mc_post_title;
														break;
														case "Article_headline": 
															$article_long_tail_title = $mc_article_headline;
														break;
														default:
															$article_long_tail_title = $mc_article_headline;
														break;
													endswitch;
												else:
													//defaults
													$article_long_tail_title = $mc_article_headline;
												endif;
												
												/* Article Long Tail Slug */
												if ($wpu_altail_slug):
													switch($wpu_altail_slug):
														case "primary_keyword_pagename":
															$article_long_tail_slug = $mc_post_name;
														break;
														case "page_title":
															$article_long_tail_slug = $mc_post_title;
														break;
														case "Article_headline": 
															$article_long_tail_slug = $mc_article_headline;
														break;
														default:
															$article_long_tail_slug = $mc_post_title;
														break;
													endswitch;
												else:
													//defaults
													$article_long_tail_slug = $mc_post_title;
												endif;
												
												if ($mc_post_title == "" && $mc_post_name != ""){ $mc_post_title = $mc_post_name; }
												$mc_posts = trim($subChild['article']);
												$mc_category = $wpus_cat_id;
												
												if ($subChild['silo_navorder']): $mc_post_order = $subChild['silo_navorder']; else: $mc_post_order = $subChild['default_page_order']; endif;
								
												$mc_date_created = $subChild['date_created'];
												if ($subChild['date_created'] == "") {$mc_date_created =  date("Y-m-d H:i:s"); }
												if (date("Y-m-d H:i:s") > strtotime($mc_date_created) ): $wpu_future = 'future'; else: $wpu_future= $wpu_status; endif;	
												$mc_excerpt = $subChild['article_synopsis'];
												if ($wpu_future == 'future'): 
													$video_id = '';
													$thumbnail_url = '';
													$mc_post_array = array(
														'menu_order' => $mc_post_order , //If new post is a page, sets the order should it appear in the tabs.
														'post_author' =>  $mc_current_user, //The user ID number of the author.
														'post_category' =>  array($mc_category), //Add some categories.
														'post_content' => $this->add_video($add_videos, $article_long_tail_title, $video_id, $thumbnail_url) . $mc_posts, //The full text of the post.
														'post_date' => $mc_date_created, //The time post was made.
														'post_excerpt' => $mc_excerpt, //For all your post excerpt needs.
														'post_name' => $article_long_tail_slug, // The name (slug) for your post
														'post_status' => 'future', //Set the status of the new post. 
														'post_date' => $mc_date_created, //The time post was made.
														'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($mc_date_created.' GMT')), //The time post was made, in GMT.
														'post_title' => ucwords($article_long_tail_title), //The title of your post.
														'post_type' => 'post',  //You may want to insert a regular post, page, link, a menu item or some custom post type
													); 
												else:
													$mc_post_array = array(
														'menu_order' => $mc_post_order , //If new post is a page, sets the order should it appear in the tabs.
														'post_author' =>  $mc_current_user, //The user ID number of the author.
														'post_category' =>  array($mc_category), //Add some categories.
														'post_content' => $this->add_video($add_videos, $article_long_tail_title, $video_id, $thumbnail_url) . $mc_posts, //The full text of the post.
														'post_date' => $mc_date_created, //The time post was made.
														'post_date_gmt' => gmdate("Y-m-d H:i:s", strtotime($mc_date_created.' GMT')), //The time post was made, in GMT.
														'post_excerpt' => $mc_excerpt, //For all your post excerpt needs.
														'post_name' => $article_long_tail_slug, // The name (slug) for your post
														'post_status' => $wpu_status, //Set the status of the new post. 
														'post_title' => ucwords($article_long_tail_title), //The title of your post.
														'post_type' => 'post',  //You may want to insert a regular post, page, link, a menu item or some custom post type
													);
												endif;
												//print_r(date("Y-m-d H:i:s") > strtotime($mc_date_created) );die();
												
												# remove filter to allow iframe tag
												remove_filter('content_save_pre', 'wp_filter_post_kses');
												
												$wpu_child_page_id = wp_insert_post($mc_post_array);
												
												# add removed filter back
												add_filter('content_save_pre', 'wp_filter_post_kses');
												
												if (1 == $add_videos)
												{
													$this->set_featured_image($wpu_child_page_id, $thumbnail_url, $mc_current_user);
													$this->add_video_comments($wpu_child_page_id, $video_id);
												}
												
												update_post_meta($wpu_child_page_id, "_wpu_silo_dws", (int) $subChild['dws_id']);
												$dws_silos[$l]['silo']['articles'][$xx]['post'][$ss]['id'] = $wpu_child_page_id;
												$dws_silos[$l]['silo']['articles'][$xx]['post'][$ss]['dws_id'] = (int)$subChild['dws_id'];
												$dws_silos[$l]['silo']['articles'][$xx]['post'][$ss]['parent'] = $wpus_page_id;
												$this->updateSEO($wpu_child_page_id, $mc_post_title,$mc_child_meta_keyword,$mc_child_meta_desc);
											}
											wp_reset_query();
											$ss++;
										} // end foreach
									} // endif
									
									update_post_meta($wpu_page_id, "_wpu_silo_children", $wpu_cat_array);
									
									$xx++;
								} // end foreach (children)
							} // end if(children)
							$l++;
						}  // end foreach
						
						// SILO HOME PAGE BEGIN
						// Create Home Page for DWS Import
						$silo_home_check = get_page_by_title("Home");
						
						if (!isset($silo_home_check->ID)) {
							$silo_home_array = array(
								'post_author' =>  $mc_current_user, //The user ID number of the author.
								'post_content' => "[wpu_silo excerpt='true' links='10' show_thumbnails='true']", //The full text of the post.
								'post_status' => $wpu_status, //Set the status of the new post.
								'post_title' => "Home", //The title of your post.
								'post_type' => 'page'  //You may want to insert a regular post, page, link, a menu item or some custom post type
							);
							$home_page_id = wp_insert_post($silo_home_array);
							update_option( 'page_on_front', $home_page_id );
							update_option( 'show_on_front', 'page' );
						} // endif Page Id does not exist for silo home
						$menuname = 'WPU Silo';
						$bpmenulocation = 'wpusmenu';
						// Does the menu exist already?
						$menu_exists = wp_get_nav_menu_object( $menuname );
						
						// If it doesn't exist, let's create it.
						if (!$menu_exists) {
							$menu_id = wp_create_nav_menu($menuname);
							
							wp_update_nav_menu_item($menu_id, 0, array(
								'menu-item-title' =>  __('Home'),
								'menu-item-classes' => 'home',
								'menu-item-url' => home_url( '/' ),
								'menu-item-status' => 'publish')
							);
						} else {
							$menu_id = $menu_exists->term_id;
						}
						# $menu_post = get_posts( array( 'meta_key' => '_wpu_silo_dws','post_type'=> 'page' ,'numberposts'=>-1) );
# 						$dws_meta_key = '';
# 						$i = 0;
# 						$menu_items = wp_get_nav_menu_items($menu_id);
# 						foreach ((array) $menu_items as $key => $menu_item) {
# 							$title[] = $menu_item->title;
# 						}
# 						foreach ($menu_post as $post):
# 							setup_postdata($post);
# 							$new_post_slug = $post->post_name;
# 							$new_post_slug = str_replace('-', ' ', $new_post_slug);
# 							
# 							$new_post_slug =  ucwords(strtolower($new_post_slug));
# 							if (in_array($new_post_slug, $title)) continue;
# 							if (0 == $post->post_parent):
# 								$parent = $post->ID;
# 								
# 								$parent_id = wp_update_nav_menu_item($menu_id, 0, array(
# 									'menu-item-object-id' => $post->ID,
# 									'menu-item-parent-id' => 0,
# 									'menu-item-object' => 'page',
# 									'menu-item-type'      => 'post_type',
# 									'menu-item-title' =>  $new_post_slug,
# 									'menu-item-status' => 'publish')
# 								);
# 								
# 								$args = array(
# 									'orderby' => 'menu_order',
# 									'posts_per_page' => -1,
# 									'post_type' => 'page',
# 									'post_parent' => $post->ID
# 								);
# 								
# 								$childpages = new WP_Query($args);
# 								if ($childpages->post_count > 0) {
# 									while ($childpages->have_posts()) {
# 										$childpages->the_post();
# 										$new_child_slug = $childpages->post->post_name;
# 										$new_child_slug = str_replace('-', ' ', $new_child_slug);
# 										$new_child_slug =  ucwords($new_child_slug);
# 										$item_ids[] = wp_update_nav_menu_item($menu_id, 0, array(
# 											'menu-item-object-id' =>  $childpages->post->ID,
# 											'menu-item-parent-id' => $parent_id,
# 											'menu-item-object' => 'page',
# 											'menu-item-type' => 'post_type',
# 											'menu-item-title' =>  $new_child_slug,
# 											'menu-item-status' => 'publish')
# 										);
# 									}
# 								}
# 							endif;
# 						endforeach;
					if (!empty($dws_silos)) update_option("_wpu_all_silos", maybe_unserialize(array_values($dws_silos)));
		} // end processSiloImport
		
		function updateSEO($id,$titletag='',$metakeyword = '',$description = '') {
			if (is_plugin_active("seo-ultimate/seo-ultimate.php")) {
				if ($titletag) update_post_meta($id, "_su_title",$titletag);
				if ($metakeyword) update_post_meta($id,"_su_keywords",$metakeyword);
				if ($description) update_post_meta($id,"_su_description",$description);	
			} else {
				if ($titletag) $seo['title'] = $titletag;
				if ($metakeyword) $seo['keywords'] = $metakeyword;
				if ($description) $seo['desc'] = $description;
				update_post_meta($id, "dws_seo_meta", $seo);
			}
		} // end updateSEO
		
		function import_advanced_xml($path) {
			if (!is_readable($path)) return false;
			
			$result = array();
			if (file_exists($path)) {
				//Open the xml file
				$xml = simplexml_load_file($path);
			
				if ($xml === FALSE) {
					return false;
				} else {
						
					foreach ($xml->BPNode as $bundle) // loop through our silos
					{
						// pull in each node from the XML	
						$key_id = $bundle->keyword_id;
						$parent_id = $bundle->parent_keyword_id;
						$page_name = $bundle->primary_keyword_pagename;
						$page_title = $bundle->page_title; 
						$article_headline = $bundle->Article_headline;
						$meta_keyword = $bundle->meta_keywords;
						$meta_description = $bundle->meta_description;
						$silo_flag = $bundle->silo_flag;
						$article_synopsis = $bundle->article_synopsis;
						$competing_pages_navorder_default = $bundle->competing_pages_navorder_default;
						$silo_navorder_secondary = $bundle->silo_navorder_secondary;
						$date_created = $bundle->default_date_created;
						$date_projection = $bundle->date_projection;
						$date_modification = $bundle->date_projection_days_modification;
						$primary_article = $bundle->primary_article;
						
						$result[] = array(
							'k_id' => $key_id,
							'dws_id' => $key_id,
							'p_id' => $parent_id,
							'page_name' => $page_name,
							'title' => $page_title,
							'article_headline' => $article_headline,
							'meta_key' => $meta_keyword,
							'meta_description' => $meta_description,
							'article_synopsis' => $article_synopsis,
							'silo_flag' => $silo_flag,
							'default_page_order' => $competing_pages_navorder_default,
							'silo_navorder' => $silo_navorder_secondary,
							'date_created' => $date_created,
							'date_projection' => $date_projection,
							'days_modification' => $date_modification,
							'article' => $primary_article
						);
					} //end foreach	
				}
			} else {
				return false;
			}
			
			return $result;
		} // end import_advanced_xml
		
	} // end Class
}
//init plugin class

register_deactivation_hook(__FILE__,'v_silo_deactivate');
function v_silo_deactivate() {   
     update_option( 'page_on_front', 0);
     update_option( 'show_on_front', 'posts' );
}

add_action('plugins_loaded', 'v_silo_builder_init');

function v_silo_callback($atts){
	
	extract( shortcode_atts( array(
		'excerpt' => false,
		'links' => 10,
		'show_thumbnails' => true,
	), $atts ) );
	$show_thumbnails = ('false' == $show_thumbnails || '0' == $show_thumbnails) ? false : true;
	$excerpt = ('false' == $excerpt || '0' == $excerpt) ? false : true;
	// SHORT CODE HOME PAGE
   if(vdisplaySilo($excerpt,false, $links))
   {
	   # if excerpt is empty, don't include content in it
	   remove_filter( 'get_the_excerpt', 'wp_trim_excerpt'  );
	   
	   $txt = vdisplaySilo($excerpt,false, $links);
	   
	   # revert to how it used to be
	   add_filter( 'get_the_excerpt', 'wp_trim_excerpt'  );
	   
	   return $txt;
   }
}

/**
 * Adds V_Advanced_Silo widget
 */
class V_Advanced_Silo extends WP_Widget
{
	public function __construct()
	{
		parent::__construct(
			'dws_advanced_silo', // Base ID
			'DWS Advanced Silo', // Name
			array('description' => __('DWS Advanced Silo')) // Args
		);
	}
	
	/**
	 * Front-end display of widget
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget($args, $instance)
	{
		$title = apply_filters('widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base);
		
		$home_title = empty( $instance['home_title'] ) ? 'Home' : $instance['home_title'];
		
		if (empty($instance['number']) || ! $number = absint($instance['number']))
 			$number = 10;
		
		$show_thumbnails = isset($instance['show_thumbnails']) ? $instance['show_thumbnails'] : true;
		
		echo $args['before_widget'];
		if ($title) echo $args['before_title'] . $title . $args['after_title'];
		if(vdisplaySilo(false, true, $number, $show_thumbnails, $home_title)) echo vdisplaySilo(false, true, $number, $show_thumbnails, $home_title);
		echo $args['after_widget'];
	}
	
	/**
	 * Back-end widget form
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form($instance)
	{
		$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
		$home_title = isset($instance['home_title']) ? esc_attr($instance['home_title']) : 'Home';
		$number = isset($instance['number']) ? absint($instance['number']) : 10;
		$show_thumbnails = isset($instance['show_thumbnails']) ? (bool) $instance['show_thumbnails'] : true;
		?>
		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
		
		<p><label for="<?php echo $this->get_field_id('home_title'); ?>"><?php _e('Home Page Title:'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('home_title'); ?>" name="<?php echo $this->get_field_name('home_title'); ?>" type="text" value="<?php echo $home_title; ?>" /></p>
		
		<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of links to show:'); ?></label>
		<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
		
		<p><input class="checkbox" type="checkbox" <?php checked($show_thumbnails); ?> id="<?php echo $this->get_field_id('show_thumbnails'); ?>" name="<?php echo $this->get_field_name('show_thumbnails'); ?>" />
		<label for="<?php echo $this->get_field_id('show_thumbnails'); ?>"><?php _e('Show thumbnails'); ?></label></p>
		<?php
	}
	
	/**
	 * Sanitize widget form values as they are saved
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['home_title'] = strip_tags($new_instance['home_title']);
		$instance['number'] = absint($new_instance['number']);
		$instance['show_thumbnails'] = isset($new_instance['show_thumbnails']) ? (bool) $new_instance['show_thumbnails'] : false;
		
		return $instance;
	}
}

function & vdisplaySilo($excerpt = false, $sidebar = false, $links = 0, $show_thumbnails = true, $home_title = "Home"){
	global $wpdb, $post, $table_prefix,$wp_query;
	
	$before='<strong>';
	$after='</strong>';
	
	$count_links = 0;
	$links = absint($links);
	
	$tmp_post = $post;
	
	if (is_home() || is_front_page() && !get_post_meta($post->ID,'_wpu_silo_dws', true))
	{
		$args = array(
			'post_type' => 'page',
			'post_status' => 'publish',
			'meta_key' => '_wpu_silo_dws',
			'post_parent' => 0,
			'posts_per_page' => -1,
			'orderby' => 'menu_order',
			'order' => 'ASC'
		);
		
		$silo_pages = new WP_Query($args);
		
		if (false == $sidebar)
			$listing_code = "<div class=\"wpus-listings\">";
		else
			$listing_code = "<ul>";
		
		while ($silo_pages->have_posts())
		{
			$silo_pages->the_post();
			$do_not_duplicate = $post->ID;
			
			# set featured image
			$featured_image = '';
			# shortcode
			if ($show_thumbnails && !$sidebar)
			{
				$featured_image = get_the_post_thumbnail($post->ID);
			}
			# widget
			elseif ($show_thumbnails && $sidebar)
			{
				if (has_post_thumbnail($post->ID))
					$featured_image = get_the_post_thumbnail($post->ID, array(32,32)) . ' ';
				else
					$featured_image = '<span style="display: inline-block; width: 32px"></span> ';
			}
			
			if (false == $sidebar)
				$listing_code .= "<div class=\"wpus-related\">";
			else
				$listing_code .= "<li><div xmlns:v=\"http://rdf.data-vocabulary.org/#\"> ";
			
			if ($excerpt)
				$listing_code .= "<h2>";
			
			$new_slug = $post->post_name;
			$new_slug = str_replace('-', ' ', $new_slug);
			$new_slug = ucwords($new_slug);
			if (!$excerpt)
				if (true == $sidebar)
					$listing_code .= "$featured_image<span typeof=\"v:Breadcrumb\"><a href=\"".get_permalink( $post->ID )."\" rel=\"v:url\" property=\"v:title\">". $new_slug."</a></span>";
				else
					$listing_code .= "$featured_image<a href=\"".get_permalink( $post->ID )."\">". $new_slug."</a>";
			else
				if (true == $sidebar)
					$listing_code .= "<span typeof=\"v:Breadcrumb\"><a href=\"".get_permalink( $post->ID )."\" rel=\"v:url\" property=\"v:title\">". $new_slug."</a></span>";
				else
					$listing_code .= "<a href=\"".get_permalink( $post->ID )."\">". $new_slug."</a>";
			
			if ($excerpt)
				$listing_code .= "</h2>$featured_image<br />".get_the_excerpt();
			
			if (false == $sidebar)
				$listing_code .= "</div>";
			else
				$listing_code .= "</div></li>";
			
			++$count_links;
			
			# end here
			if ($count_links == $links)
				break;
		}
		
		if (false == $sidebar)
			$listing_code .= "</div>";
		else
			$listing_code .= "</ul>";
		
		$post = $tmp_post;
		
		return $listing_code;
	}
	elseif ($post->ID)
	{
		$tmp_page_id = $post->ID;
		
		$tmp_post = $post;
		
		if (get_post_meta($tmp_page_id,'_wpu_silo_dws', true))
		{
			$_silo_options = maybe_unserialize(get_option(V_PLUGIN_OPTIONS));
			
			if (false == $sidebar)
				$wpu_silo_links_return = '<div class="wpuss-related">' .$before.$_silo_options['silo_title'].$after; 
			else
				$wpu_silo_links_return = '<div>';
			
			$wpus_page_title = get_the_title($tmp_page_id);
			
			if ($art_cat = get_post_meta($tmp_page_id,'_wpu_article_dws', true)):
				$silo_cat_id = $art_cat;
			else:
				$silo_cat_id = get_cat_ID( $wpus_page_title );
			endif;
			
			if ($silo_cat_id === 0):
				$silo_cat_id = get_the_category($tmp_page_id); 
				$new_cat_page = $silo_cat_id[0]->name;
				$silo_cat_id  = $silo_cat_id[0]->cat_ID;
			endif;
			
			if ($post->post_parent != 0):
				$wpu_silo_links_return .= "<ul><li>";
				
				if ($excerpt):
					$wpu_silo_links_return .="<h2>";
				endif;
				
				++$count_links;
				
				if (is_page()):
					if ($show_thumbnails) if (has_post_thumbnail($post->post_parent)) $wpu_silo_links_return .= get_the_post_thumbnail($post->post_parent, array(32, 32)) . ' '; else $wpu_silo_links_return .= '<span style="display: inline-block; width: 32px"></span> ';
					
					$wpu_silo_links_return .= "<a href='". get_permalink($post->post_parent)."' title='".$wpus_page_title."'>".get_the_title($post->post_parent)."</a>";
				else:
					if ($show_thumbnails) if (has_post_thumbnail($post->ID)) $wpu_silo_links_return .= get_the_post_thumbnail($post->ID, array(32, 32)) . ' '; else $wpu_silo_links_return .= '<span style="display: inline-block; width: 32px"></span> ';
					
					$wpu_silo_links_return .= "<a href='". get_permalink($post->ID)."' title='".$wpus_page_title."'>".get_the_title($post->ID)."</a>";
				endif;
				
				if ($excerpt):
					$wpu_silo_links_return .= "</h2>";
				endif;
				
				# end here
				if ($count_links == $links)
					return $wpu_silo_links_return;
				
				$wpu_silo_links_return .= "<ul>";
			else:
				++$count_links;
				
				if (is_single()):
					$new_cat_page = get_page_by_title($new_cat_page);
					
					$featured_image = '';
					if ($show_thumbnails) if (has_post_thumbnail($new_cat_page->ID)) $featured_image = get_the_post_thumbnail($new_cat_page->ID, array(32, 32)) . ' '; else $featured_image = '<span style="display: inline-block; width: 32px"></span> ';
					
					$wpu_silo_links_return .= "<ul><li>$featured_image<a href='". get_permalink($new_cat_page->ID) ."' title='". $new_cat_page->post_title ."'>". $new_cat_page->post_title ."</a><ul>";
				else:
					$featured_image = '';
					if ($show_thumbnails && 'page' == get_option('show_on_front') && get_option('page_on_front')) if (has_post_thumbnail(get_option('page_on_front'))) $featured_image = get_the_post_thumbnail(get_option('page_on_front'), array(32, 32)) . ' '; else $featured_image = '<span style="display: inline-block; width: 32px"></span> ';
					
					if (false == $sidebar)
						$wpu_silo_links_return .= "<ul><li>$featured_image<a href='". get_home_url()."' title='".get_bloginfo('name')."'>".get_bloginfo('name')."</a><ul>";
					else
						$wpu_silo_links_return .= "<ul><li>$featured_image<a href='". get_home_url()."' title='". $home_title ."'>". $home_title ."</a><ul>";
				endif;
			endif;
			
			# end here
			if ($count_links == $links)
				return $wpu_silo_links_return;
			
			$silo_child_query = '';
			if (is_page() && ($post->post_parent==0)):
				// Query for Parent Silo page
				$silo_query = new WP_Query( 'posts_per_page=-1&post_type=page&post_status=publish&orderby=menu_order&order=ASC&post_parent='.$tmp_page_id);
			else:
				// Main Query for Children.
				if (!is_single()):
					// Query for Child of Parent Silo. The sub-category listing.
					$silo_query = new WP_Query( 'posts_per_page=-1&post_type=page&post_status=publish&orderby=menu_order&order=ASC&post_parent='.$post->post_parent);
				else:
					// Query for final tier of silo, post level
					$silo_query = new WP_Query( 'posts_per_page=-1&orderby=menu_order&order=ASC&post_status=publish&cat='. $silo_cat_id);
				endif;
			endif;
			
			if ($silo_query):
				while ($silo_query->have_posts()):
					$silo_query->the_post();
					$do_not_duplicate = $silo_query->post->ID;
					
					$wpu_silo_links_return .= "<li class=\"related-listings\">";
					
					if ($excerpt):
						$wpu_silo_links_return .= "<h2>";
					endif;
					
					if ($show_thumbnails) if (has_post_thumbnail($silo_query->post->ID)) $wpu_silo_links_return .= get_the_post_thumbnail($silo_query->post->ID, array(32, 32)) . ' '; else $wpu_silo_links_return .= '<span style="display: inline-block; width: 32px"></span> ';
					
					$wpu_silo_links_return .= "<a href=\"".get_permalink( $silo_query->post->ID )."\">".get_the_title()."</a>";
					
					if ($excerpt):
						$wpu_silo_links_return .= "</h2>";
						
						if ($silo_query->post->post_parent == $tmp_page_id):
							$wpu_silo_links_return .= "<br />".get_the_excerpt();
						endif;
					endif;
					
					++$count_links;
					
					# end here
					if ($count_links == $links)
						break;
					
					if ($silo_query->post->post_parent != $tmp_page_id):
						if(!is_single()):
							if($tmp_page_id == $silo_query->post->ID):
								$child_page_title = get_the_title($silo_query->post->ID);
								
								$child_silo_cat_id = get_post_meta($silo_query->post->ID,"_wpu_article_dws", true);
								
								//$child_silo_cat_id =  get_cat_ID( $child_page_title );
								
								$silo_child_query = new WP_Query( 'posts_per_page=-1&orderby=menu_order&order=ASC&post_status=publish&cat='.$child_silo_cat_id);
								
								if($silo_child_query->have_posts()):
									$wpu_silo_links_return .="<ul>";
									
									while ($silo_child_query->have_posts()):
										$silo_child_query->the_post();
										$do_not_duplicate = $silo_child_query->post->ID;
										$wpu_silo_links_return .="<li class=\"related-child-listings\">";
										if($excerpt):
											$wpu_silo_links_return .= "<h2>";
										endif;
										if ($show_thumbnails) if (has_post_thumbnail($silo_child_query->post->ID)) $wpu_silo_links_return .= get_the_post_thumbnail($silo_child_query->post->ID, array(32, 32)) . ' '; else $wpu_silo_links_return .= '<span style="display: inline-block; width: 32px;"></span> ';
										$wpu_silo_links_return .="<a href=\"".get_permalink( $silo_child_query->post->ID )."\">".get_the_title()."</a>";
										if($excerpt):
											$wpu_silo_links_return .= "</h2><br />".get_the_excerpt();
										endif;
										$wpu_silo_links_return .="</li>";
										
										++$count_links;
										
										# end here
										if ($count_links == $links)
											break;
									endwhile;
									$wpu_silo_links_return .="</ul>";
									
									# end here
									if ($count_links == $links)
										break;
								endif;
							endif;
						endif;
					endif;
					
					$wpu_silo_links_return .="</li>";
				endwhile;
			endif;
			
			$wpu_silo_links_return .= "</ul></li>";
			$wpu_silo_links_return .= "</ul>";
			
			if (false == $sidebar)
				$wpu_silo_links_return .= "</div>";
			else
				$wpu_silo_links_return .= "</div>";
			
			$post = $tmp_post;
			
			return $wpu_silo_links_return;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

function v_excerpt_length( $length ) {
	// lengthen the default wordpress exceprt length. Matches DWS Excerpt Limit.
    return 500;
}
add_filter( 'excerpt_length', 'v_excerpt_length', 999 );
function v_silo_styles(){ 
$_silo_styles = maybe_unserialize(get_option(V_PLUGIN_STYLES));
?>
<style type="text/css">
.wpuss-related li {
	padding: 5px 0;
}
<?php if($_silo_styles['line_height']): ?>
.wpus-listings { line-height: <?php echo $_silo_styles['line_height']; ?> !important;}
<?php endif; ?>

<?php if($_silo_styles['link_color'] || $_silo_styles['link_size']): ?>
.wpus-related a,.widget-area .widget .wpus-related a, .related-listings a, .widget a, .widget-area .widget .related-listings a {
	<?php if($_silo_styles['link_color']) echo "color: ".$_silo_styles['link_color']. " !important;"; ?>
	 <?php if($_silo_styles['link_size']) echo "font-size: ".$_silo_styles['link_size']. $_silo_styles['link_size_type']. " !important;";  ?>
	}
<?php endif; ?>	
.wpus-related {}
</style>
<?php }
add_action('wp_head', 'v_silo_styles');

// enable shortcode call wpu_silo_home_links
add_shortcode( 'wpu_silo',  'v_silo_callback' );
function v_wp_title(){
	global $post, $paged;
 	$values = get_post_custom( $post->ID );    
			
	$seo = isset( $values['dws_seo_meta'] ) ? maybe_unserialize($values['dws_seo_meta'][0] ) : '';
	if ( is_feed() )
		return $title;
if(isset($seo['title']))
	$filtered_title = $seo['title'] . ' | ';
	$filtered_title .= ( 2 <= $paged || 2 <= $paged ) ? ' | ' . sprintf( __( 'Page %s' ), max( $paged, $page ) ) : '';

	return $filtered_title;
}
add_filter( 'wp_title', 'v_wp_title' );
function v_seo(){
global $post, $paged;
 	$values = get_post_custom( $post->ID );    
			
	$seo = isset( $values['dws_seo_meta'] ) ? maybe_unserialize($values['dws_seo_meta'][0] ) : '';
	$keys =isset( $seo['keywords'] ) ? $seo['keywords']: '';
	$desc = isset( $seo['desc']) ? $seo['desc']: '';
	echo "\t<meta name='keywords' content='".$keys."' />\n";
	echo "\t<meta name='description' content='".$desc."' />\n";
}
add_action('wp_head', 'v_seo',0);

?>