<?php

	/* ------------------------------------
	
	::	Core Functions
	
	------------------------------------ */	

	/*
	 * for 'textarea' sanitization and $allowedposttags + embed and script.
	 */
	 
	add_action('admin_init','optionscheck_change_santiziation', 100);
	
	function optionscheck_change_santiziation()
	{
		remove_filter( 'of_sanitize_textarea', 'of_sanitize_textarea' );
		add_filter( 'of_sanitize_textarea', 'custom_sanitize_textarea' );
	}
	
	function custom_sanitize_textarea($input)
	{
		global $allowedposttags;
		$custom_allowedtags["embed"] = array(
		  "src" => array(),
		  "type" => array(),
		  "allowfullscreen" => array(),
		  "allowscriptaccess" => array(),
		  "height" => array(),
			  "width" => array()
		  );
		  $custom_allowedtags["script"] = array();
		  $custom_allowedtags = array_merge($custom_allowedtags, $allowedposttags);
		  $output = wp_kses( $input, $custom_allowedtags);
		return $output;
	}

	// Find the XML value from XML Object
	function find_xml_value($xml, $field)
	{
		if(!empty($xml))
		{
			foreach($xml->childNodes as $xmlChild)
			{
				if($xmlChild->nodeName == $field)
				{
					if( is_admin() )
					{
						return $xmlChild->nodeValue;
					}
					else
					{
						return __($xmlChild->nodeValue, 'NorthVantage');
					}
				}
			}
		}
		
		return '';
	}
	
	// Find the XML node from XML Object
	function find_xml_node($xml, $node)
	{
		if(!empty($xml))
		{
			foreach($xml->childNodes as $xmlChild)
			{
				if($xmlChild->nodeName == $node)
				{
					return $xmlChild;	
				}
			}
		}
		
		return '';
	}
	
	// Create tag string from nodename and value
	function create_xml_tag($node, $value)
	{
		return '<' . $node . '>' . $value . '</' . $node . '>';	
	}


	// Populate Data Source List
	function data_source_list()
	{
		$data_source_array = array(
			array( 'name' => 'Select Source', 'value' => '', ),
			array( 'name' => 'Slide Manager Sets', 'value' => 'data-4' ),
			array( 'name' => 'Attached Media', 'value' => 'data-1' ),
			array( 'name' => 'Portfolio Categories', 'value' => 'data-6' ),
			array( 'name' => 'Post Categories', 'value' => 'data-2' ),
		);
		
		if( class_exists('Woocommerce') || class_exists('WPSC_Query') )
		{
			$data_source_array[] = array( 'name' => 'Product Categories', 'value' => 'data-5' );
		}
		
		if( of_get_option('flickr_userid') )
		{
			$data_source_array[] = array( 'name' => 'Flickr', 'value' => 'data-3' );			
		}
		
		return $data_source_array;
	}


	// Get Post Category Function
	function get_data_source($data_type, $type = '')
	{
		$arr = array();
		
		if( $data_type == 'data-2' ) // Post Categories
		{
			$arr = get_categories();
		}
		elseif( $data_type == 'data-2-formats' ) // Post Formats
		{
			$post_formats = get_theme_support( 'post-formats' );
			$arr = $post_formats[0];
			array_unshift($arr, "Select Filter");
		}
		elseif( $data_type == 'data-3' ) // Flickr
		{
			if( of_get_option('flickr_userid') !='' )
			{
				require_once(NV_FILES."/adm/inc/phpFlickr/phpFlickr.php");
				//$f = new phpFlickr(of_get_option('flickr_apikey'));
				$f = new phpFlickr('7caca0370ede756c26832c28b266ead5');
				$user = of_get_option('flickr_userid');
				$ph_sets = $f->photosets_getList($user);	
				
				$arr = $ph_sets['photoset'];
				if( $arr !='' )
				{
					array_unshift($arr, "Select Flickr Set");
				}
			}
		}
		elseif( $data_type == 'data-4' ) // Slide Sets
		{
			$args = array(
				'numberposts' => -1,
				'post_type' => 'slide-sets',
				'post_status' => 'publish'
			);
			
			$arr = get_posts ( $args );
		}		
		elseif( $data_type == 'data-5' ) // Woocommerce / WP e-commerce
		{
			if( class_exists('Woocommerce') )
			{
				$arr = get_terms('product_cat', 'orderby=name&hide_empty=0');
			}
			else
			{ 
				$arr = get_terms('wpsc_product_category', 'orderby=name&hide_empty=0');  
			}
		}
		elseif( $data_type == 'data-5-tags' ) // Woocommerce / WP e-commerce TAGS
		{
			$arr = get_terms('product_tag', 'orderby=name&hide_empty=1');
		}				
		elseif( $data_type == 'data-6' ) // Gallery Media Categories
		{
			$arr = get_terms('portfolio-category', 'orderby=name&hide_empty=0');
		}
		
		// Set the options array
		if( is_array( $arr ) )
		{
			foreach ( $arr as $val )
			{
				if( $data_type == 'data-2' )
				{
					if( $type == 'shortcode' )
					{
						$options_array[htmlspecialchars($val->cat_name)] = $val->cat_name;
					}
					else
					{
						$options_array[htmlspecialchars($val->term_id)] = $val->cat_name;
					}
				}
				elseif( $data_type == 'data-3' )
				{
					if( $type == 'shortcode' )
					{
						if( $val == 'Select Flickr Set' )
						{
							$options_array[htmlspecialchars($val)] = '';
						}
						else
						{						
							$options_array[$val['title']] = $val['id'];
						}
					}
					else
					{
						$options_array[$val['id']] = $val['title'];
					}
				}			
				elseif( $data_type == 'data-4' )
				{
					if( $type == 'shortcode' )
					{				
						$options_array[htmlspecialchars($val->post_title)] = $val->post_title;
					}
					else
					{
						$options_array[htmlspecialchars($val->ID)] = $val->post_title;
					}					
				}
				elseif( $data_type == 'data-2-formats' )
				{
					if( $type == 'shortcode' )
					{	
						if( $val == 'Select Filter' )
						{
							$options_array[htmlspecialchars($val)] = '';
						}
						else
						{
							$options_array[htmlspecialchars($val)] = $val;
						}
					}
					elseif( $type == 'blog' )
					{	
						if( $val != 'Select Filter' )
						{
							$options_array[htmlspecialchars($val)] = $val;
						}
					}					
					else
					{				
						if( $val == 'Select Filter' )
						{
							$options_array[] = array(
								'name' => $val,
								'value' => ''
							);					
						}
						else
						{
							$options_array[] = array(
								'name' => $val,
								'value' => $val
							);
						}
					}
				}						
				else
				{
					$options_array[htmlspecialchars($val->name)] = $val->name;
				}
			}
		}
		
		if( empty($options_array) ) $options_array[''] = 'No Data Found';
		
		return $options_array;
	}

	// Social Icons Data
	function social_icon_data()
	{
		$social_icon_array = array(
			'sociallink_digg' => array(
				'path' => 'http://www.digg.com/submit?phase=2&amp;url=[get_permalink]&amp;title=[get_the_title]',
				'name' => 'Digg'
			),
			'sociallink_fb' => array(
				'path' => 'http://www.facebook.com/sharer.php?u=[get_permalink]&amp;t=[get_the_title]',
				'name' => 'Facebook'
			),	
			'sociallink_linkedin' => array(
				'path' => 'http://www.linkedin.com/shareArticle?mini=true&amp;url=&amp;title=[get_the_title]&amp;source=[get_blogurl]',
				'name' => 'LinkedIn'
			),
			'sociallink_deli' => array(
				'path' => 'http://del.icio.us/post?url=[get_permalink]&amp;title=[get_the_title]',
				'name' => 'Del.icio.us'
			),
			'sociallink_reddit' => array(
				'path' => 'http://www.reddit.com/submit?url=[get_permalink]',
				'name' => 'Reddit'
			),
			'sociallink_stumble' => array(
				'path' => 'http://www.stumbleupon.com/submit?url=[get_permalink]&amp;title=[get_the_title]',
				'name' => 'Stumble'
			),
			'sociallink_twitter' => array(
				'path' => 'http://twitter.com/share?text=[get_the_title]&amp;url=[get_permalink]',
				'name' => 'Twitter'
			),
			'sociallink_google' => array(
				'path' => 'https://m.google.com/app/plus/x/?v=compose&content=[get_the_title] - [get_permalink]',
				'name' => 'Google'
			),
			'sociallink_rss' => array(
				'path' => '[get_permalink]feed/rss/',
				'name' => 'RSS'
			),
			'sociallink_youtube' => array(
				'path' => 'http://www.youtube.com/user/',
				'name' => 'YouTube'
			),
			'sociallink_vimeo' => array(
				'path' => 'http://vimeo.com/',
				'name' => 'Vimeo'
			),
			'sociallink_pinterest' => array(
				'path' => 'http://pinterest.com/',
				'name' => 'Pinterest'
			),
			'sociallink_soundcloud' => array(
				'path' => 'http://soundcloud.com',
				'name' => 'Soundcloud'
			),
			'sociallink_instagram' => array(
				'path' => 'http://instagram.com',
				'name' => 'Instagram'
			),
			'sociallink_flickr' => array(
				'path' => 'http://flickr.com',
				'name' => 'Flickr'
			),
			'sociallink_email' => array(
				'path' => 'mailto:example@email.com',
				'name' => 'Email'
			),												
		);
		
		return $social_icon_array;
	}


	// Get WP Media Library 
	add_action('wp_ajax_get_media_image','get_media_library');
	
	function get_media_library(){
	
		$image_width = 70;
		$image_height = 70;
		
		$paged = (isset($_POST['page']))? $_POST['page'] : 1; 	
		
		if($paged == '')
		{
			$paged = 1;
		}
		
		$statement = array('post_type' => 'attachment',
			'post_mime_type' =>'image, video/mp4, application/flash',
			'post_status' => 'inherit', 
			'posts_per_page' => 11,
			'paged' => $paged);
		
		$media_query = new WP_Query($statement);
		
		echo '<div class="media-gallery-nav" id="media-gallery-nav">';
		echo '<ul>';
		echo '<a><li class="nav-first" rel="1" ></li></a>';
		
		for( $i=1 ; $i<=$media_query->max_num_pages; $i++){
		
			if($i == $paged)
			{
				echo '<li rel="' . $i . '">' . $i . '</li>';
			}
			else if( ($i <= $paged+2 && $i >= $paged-2) || $i%10 == 0)
			{
				echo '<a><li rel="' . $i . '">' . $i . '</li></a>';		
			}
			
		}
		echo '<a><li class="nav-last" rel="' . $media_query->max_num_pages . '"></li></a>';
		echo '</ul>';
		echo '</div><br class=clear>';
	
		echo '<ul>';
		
		foreach( $media_query->posts as $image )
		{ 
		
			$thumb_src = wp_get_attachment_image_src( $image->ID, '150x150');
			$thumb_src_preview = wp_get_attachment_image_src( $image->ID, '100x69');

			// assign default image if path is empty
			if( empty($thumb_src[0]) ) 
			{
				$thumbnail = get_template_directory_uri() . '/lib/adm/images/layout-1.png';
			}
			else 
			{
				$thumbnail = $thumb_src[0];
			}
							
			echo '<li><img src="' . $thumbnail .'" title="' . $image->post_title . '" attid="' . $image->ID . '" rel="' . $thumb_src_preview[0] . '"/></li>';			
		
		}
		
		echo '</ul><br class=clear>';
		
		if(isset($_POST['page'])){ die(''); }
			
					
	}

	// Social Meta Options
	function get_social_options()
	{
		$prefix = '_cmb_';
		
		$social_icon_array = social_icon_data();

		$social_icon_options = array();
		
		$social_icon_options[] = array(
			'name'    => 'Twitter Cycle',
			'id'      => $prefix . 'twitter',
			'type'    => 'radio_inline',
			'std'		  => 'none',
			'options' => array(
				array( 'name' => 'Default', 'value' => 'none', ),
				array( 'name' => 'Disable', 'value' => 'disable', ),
				array( 'name' => 'Top', 'value' => 'pagetop', ),
				array( 'name' => 'Bottom', 'value' => 'pagebot', ),
			),
		);

		$social_icon_options[] = array(
			'name'    => 'Icon Color',
			'id'      => $prefix . 'socialicons_color',
			'type'    => 'select',
			'std'		  => '',
			'options' => array(
				array( 'name' => 'Default', 'value' => '', ),
				array( 'name' => 'Light', 'value' => 'light', ),
				array( 'name' => 'Dark', 'value' => 'dark', ),
				array( 'name' => 'Color', 'value' => 'color', ),
			),
		);			

		$social_icon_options[] = array(
			'name'    => 'Social Icons',
			'id'      => $prefix . 'socialicons',
			'type'    => 'radio_inline',
			'std'		  => '',
			'options' => array(
				array( 'name' => 'Default', 'value' => '', ),
				array( 'name' => 'Enable', 'value' => 'yes', ),
				array( 'name' => 'Disable', 'value' => 'disable', ),
			),
		);
		
		/*
		$social_icon_options[] = array(
			'name'    => 'Social Icons',
			'id'      => $prefix . 'socialicons',
			'type'    => 'switch',
			'std'		  => '',
			'options' => array(
				array( 'name' => 'Off', 'value' => '', ),
				array( 'name' => 'On', 'value' => 'yes', ),
			),
		);
		*/
			
		$social_icon_options[] = array(
			'name'    => 'Share Icon',
			'id'      => $prefix . 'disableheart',
			'type'    => 'radio_inline',
			'std'		  => '',
			'options' => array(
				array( 'name' => 'Default', 'value' => '', ),
				array( 'name' => 'Enable', 'value' => 'enable', ),
				array( 'name' => 'Disable', 'value' => 'yes', ),
			),
		);

		
		foreach ( $social_icon_array as $key => $socialicon )
		{
			$social_icon_options[] = array(
				'name'    => $socialicon['name'],
				'id'      => $prefix . $key,
				'type'    => 'switch',
				'std'		  => '',
				'options' => array(
					array( 'name' => 'Off', 'value' => 'yes', ),
					array( 'name' => 'On', 'value' => '', ),
				),
			);
		}
		
		return $social_icon_options;
		
	}	
	
	function hexLighter($hex,$factor = 80) { 
		$new_hex = ''; 
		 
		$base['R'] = hexdec($hex{0}.$hex{1}); 
		$base['G'] = hexdec($hex{2}.$hex{3}); 
		$base['B'] = hexdec($hex{4}.$hex{5}); 
		 
		foreach ($base as $k => $v) 
			{ 
			$amount = 255 - $v; 
			$amount = $amount / 100; 
			$amount = round($amount * $factor); 
			$new_decimal = $v + $amount; 
		 
			$new_hex_component = dechex($new_decimal); 
			if(strlen($new_hex_component) < 2) 
				{ $new_hex_component = "0".$new_hex_component; } 
			$new_hex .= $new_hex_component; 
			} 
			 
		return $new_hex;     
	} 
	
	function hexDarker($hex,$factor = 30){
        $new_hex = '';
        
        $base['R'] = hexdec($hex{0}.$hex{1});
        $base['G'] = hexdec($hex{2}.$hex{3});
        $base['B'] = hexdec($hex{4}.$hex{5});
        
        foreach ($base as $k => $v)
                {
                $amount = $v / 100;
                $amount = round($amount * $factor);
                $new_decimal = $v - $amount;
        
                $new_hex_component = dechex($new_decimal);
                if(strlen($new_hex_component) < 2)
                        { $new_hex_component = "0".$new_hex_component; }
                $new_hex .= $new_hex_component;
                }
                
        return $new_hex;        
    }