<?php
$CarsGallery = get_option('CarsGallery_mode');
if($CarsGallery != 'New'){
$args = array('post_type'=>'gtcd' ,'posts_per_page'=>-1 );
	$myposts = get_posts( $args );
	foreach( $myposts as $post ){
		if ( $images = get_children(array(
			'post_parent' => $post->ID,
			'post_type' => 'attachment',
			'order' => 'ASC',
			'orderby' => 'menu_order',
			'post_mime_type' => 'image',
			)))
		{
			$Gallery = array();
			foreach( $images as $image ) {
				$Gallery[] = $image->ID;
			}
			$Gallery = implode(',',$Gallery);
			if($Gallery!=''){
				update_post_meta($post->ID, 'CarsGallery', $Gallery);
			}
		}
	}
	
	add_option('CarsGallery_mode', 'New', '', 'yes' );
}		
function implement_ajax_name()
		{
			if ( isset($_POST[ 'main_catid' ]) ) {
				$categories = get_categories('child_of=' . $_POST[ 'main_catid' ] . '&hide_empty=0&taxonomy=makemodel');
				foreach ( $categories as $cat ) {
					$option .= '<option value="' . $cat->name . '" data-value="' . $cat->term_id . '">';
					$option .= $cat->cat_name;
					$option .= ' (' . $cat->category_count . ')';
					$option .= '</option>';
				}
				echo '<option value="" selected="selected" data-value="-1">Select Model</option>' . $option;
				die();
			} // end if

		}

		add_action('wp_ajax_my_special_ajax_name_call' , 'implement_ajax_name');
		add_action('wp_ajax_nopriv_my_special_ajax_name_call' , 'implement_ajax_name'); //for users that are not logged in.


function wp_dropdown_categories_custom($args = '')
		{
			$defaults = array(
				'show_option_all' => '' , 'show_option_none' => '' ,
				'orderby' => 'id' , 'order' => 'ASC' ,
				'show_last_update' => 0 , 'show_count' => 0 ,
				'hide_empty' => 1 , 'child_of' => 0 ,
				'exclude' => '' , 'echo' => 1 ,
				'selected' => 0 , 'hierarchical' => 0 ,
				'name' => 'cat' , 'id' => '' ,
				'class' => 'postform' , 'depth' => 0 ,
				'tab_index' => 0 , 'taxonomy' => 'category' ,
				'hide_if_empty' => false
			);

			$defaults[ 'selected' ] = ( is_category() ) ? get_query_var('cat') : 0;

			// Back compat.
			if ( isset($args[ 'type' ]) && 'link' == $args[ 'type' ] ) {
				_deprecated_argument(__FUNCTION__ , '3.0' , '');
				$args[ 'taxonomy' ] = 'link_category';
			}

			$r = wp_parse_args($args , $defaults);

			if ( !isset($r[ 'pad_counts' ]) && $r[ 'show_count' ] && $r[ 'hierarchical' ] ) {
				$r[ 'pad_counts' ] = true;
			}

			$r[ 'include_last_update_time' ] = $r[ 'show_last_update' ];
			extract($r);

			$tab_index_attribute = '';
			if ( ( int ) $tab_index > 0 ) $tab_index_attribute = " tabindex=\"$tab_index\"";

			$categories = get_terms($taxonomy , $r);
			$name = esc_attr($name);
			$class = esc_attr($class);
			$id = $id ? esc_attr($id) : $name;

			if ( !$r[ 'hide_if_empty' ] || !empty($categories) ) $output = "<select name='$name' id='$id' class='$class' $tab_index_attribute>\n";
			else $output = '';

			if ( empty($categories) && !$r[ 'hide_if_empty' ] && !empty($show_option_none) ) {
				$show_option_none = apply_filters('list_cats' , $show_option_none);
				$output .= "\t<option value='' selected='selected' data-value='-1'>$show_option_none</option>\n";
			}

			if ( !empty($categories) ) {

				if ( $show_option_all ) {
					$show_option_all = apply_filters('list_cats' , $show_option_all);
					$selected = ( '0' === strval($r[ 'selected' ]) ) ? " selected='selected'" : '';
					$output .= "\t<option value='0'$selected data-value='0'>$show_option_all</option>\n";
				}

				if ( $show_option_none ) {
					$show_option_none = apply_filters('list_cats' , $show_option_none);
					$selected = ( '-1' === strval($r[ 'selected' ]) ) ? " selected='selected'" : '';
					$output .= "\t<option value='' $selected  data-value='-1'>$show_option_none</option>\n";
				}

				if ( $hierarchical ) $depth = $r[ 'depth' ];  // Walk the full depth.
				else $depth = -1; // Flat.

				$output .= walk_category_dropdown_tree($categories , $depth , $r);
			}
			if ( !$r[ 'hide_if_empty' ] || !empty($categories) ) $output .= "</select>\n";


			$output = apply_filters('wp_dropdown_cats' , $output);

			if ( $echo ) echo $output;

			return $output;

		}
class Walker_CategoryDropdown_Custom extends Walker_CategoryDropdown
        {
            function start_el(&$output , $category , $depth , $args)
            {
                $pad = str_repeat(' ' , $depth * 3);

                $cat_name = apply_filters('list_cats' , $category->name , $category);
                $output .= "\t<option class=\"level-$depth\" value=\"" . $category->name . "\" data-value=\"" . $category->term_id . "\"";
                if ( $category->term_id == $args[ 'selected' ] ) $output .= ' selected="selected"';
                $output .= '>';
                $output .= $pad . $cat_name;
                if ( $args[ 'show_count' ] ) $output .= '  (' . $category->count . ')';
                if ( array_key_exists('show_last_update', $args) && $args[ 'show_last_update' ] ) {
                    $format = 'Y-m-d';
                    $output .= '  ' . gmdate($format , $category->last_update_timestamp);
                }
                $output .= "</option>\n";

            }

        }


add_filter( 'request', 'mi_request_filter' );
function mi_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    }
    return $query_vars;
}
		define('AUTODEALER_INCLUDES', get_template_directory() . '/includes/');
		define('THEME_FUNCTIONS', get_template_directory() . '/functions/');
		define('THEME_WIDGETS', get_template_directory() . '/widgets/');	
		define('THEME_NAME', 'CARDEALER');
		define('THEME_DIR', get_bloginfo('template_directory'));	
		require_once(THEME_FUNCTIONS.'basic-theme-setup.php');
		require_once(THEME_FUNCTIONS . 'file/functions.php' );
		require_once(get_template_directory().'/includes/meta-box.php');
		require_once(THEME_FUNCTIONS.'gtcd-post-type.php');
		require_once(THEME_FUNCTIONS.'user-post-type.php');
		require_once(THEME_FUNCTIONS.'menu-and-settings-page.php');
		require_once(THEME_FUNCTIONS.'validate-fields.php');
		require_once(THEME_FUNCTIONS.'meta-boxes-code.php');
		require_once(THEME_FUNCTIONS.'custom-taxonomies.php');
		require_once(THEME_FUNCTIONS.'dashboard-widgets.php');	
		require_once(THEME_WIDGETS.'register-sidebars.php');
		require_once(THEME_FUNCTIONS.'search-code.php');
		require_once(get_template_directory(). '/widgets/theme-widgets.php');
	
if (!function_exists('load_theme_scripts')) {
	function load_theme_scripts() {
	if (!is_admin() && is_page_template( 'cdform.php' ) ) 
	{
	$mjscriptURL = get_template_directory_uri().'/foundationFramework/javascripts/';
	$jscriptURL = get_template_directory_uri().'/js/';
	wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
    wp_enqueue_script( 'jquery' );	
	wp_register_script('myScript', ($jscriptURL.'scripts-form.js'), array('jquery'), NULL, true );
	wp_enqueue_script('myScript');
	wp_register_script('jselectBox', ($jscriptURL.'jquery.selectBox.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jselectBox');
	wp_register_script('jvalidate', ($jscriptURL.'jquery.validate.min.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jvalidate');
	wp_register_script('mediaQueryToggle', ($mjscriptURL.'jquery.foundation.mediaQueryToggle.js'), array('jquery'), NULL, true );
	wp_enqueue_script('mediaQueryToggle');	
	wp_register_script('navigation', ($mjscriptURL.'jquery.foundation.navigation.js'), array('jquery'), NULL, true );
	wp_enqueue_script('navigation');	
	wp_register_script('topbar', ($mjscriptURL.'jquery.foundation.topbar.js'), array('jquery'), NULL, true );
	wp_enqueue_script('topbar');	
	wp_register_script('reveal', ($mjscriptURL.'jquery.foundation.reveal.js'), array('jquery'), NULL, true );
	wp_enqueue_script('reveal');	
	wp_register_script('app', ($mjscriptURL.'app.js'), array('jquery'), NULL, true );
	wp_enqueue_script('app');	
	wp_register_script('mobileScript', ($mjscriptURL.'mobileScript.js'), array('jquery'), NULL, true );
	wp_enqueue_script('mobileScript');	
	wp_register_script('modernizr', ($mjscriptURL.'touch_slider/modernizr.custom.17475.js'), array('jquery'), NULL, true );
	wp_enqueue_script('modernizr');
	wp_register_script('elastislide', ($mjscriptURL.'touch_slider/jquery.elastislide.js'), array('jquery'), NULL, true );
	wp_enqueue_script('elastislide');	
	wp_register_script('jquerypp', ($mjscriptURL.'touch_slider/jquerypp.custom.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jquerypp');	
	
		
	} else {
	$mjscriptURL = get_template_directory_uri().'/foundationFramework/javascripts/';	
	$jscriptURL = get_template_directory_uri().'/js/';
	wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
    wp_enqueue_script( 'jquery' );
	wp_register_script('jsEasing', ($jscriptURL.'jquery.easing.1.3.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jsEasing');			
	wp_register_script('jcolorbox', ($jscriptURL.'jquery.colorbox-min.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jcolorbox');		
	wp_register_script('myScript', ($jscriptURL.'script.js'), array('jquery'), NULL, true );
	wp_enqueue_script('myScript');
	wp_register_script('mySlides', ($jscriptURL.'slides.min.jquery.js'), array('jquery'), NULL, true );
	wp_enqueue_script('mySlides');
	wp_register_script('myCycle', ($jscriptURL.'jquery.cycle.min.js'), array('jquery'), NULL, true );
	wp_enqueue_script('myCycle');
	wp_register_script('jselectBox', ($jscriptURL.'jquery.selectBox.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jselectBox');
	wp_register_script('jvalidate', ($jscriptURL.'jquery.validate.min.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jvalidate');
	wp_register_script('janimate', ($jscriptURL.'jquery.animate.js'), array('jquery'), NULL, true );
	wp_enqueue_script('janimate');
	wp_register_script('janchorScroll', ($jscriptURL.'jquery.anchorScroll.js'), array('jquery'), NULL, true );
	wp_enqueue_script('janchorScroll');
	wp_register_script('mediaQueryToggle', ($mjscriptURL.'jquery.foundation.mediaQueryToggle.js'), array('jquery'), NULL, true );
	wp_enqueue_script('mediaQueryToggle');	
	wp_register_script('navigation', ($mjscriptURL.'jquery.foundation.navigation.js'), array('jquery'), NULL, true );
	wp_enqueue_script('navigation');	
	wp_register_script('topbar', ($mjscriptURL.'jquery.foundation.topbar.js'), array('jquery'), NULL, true );
	wp_enqueue_script('topbar');	
	wp_register_script('reveal', ($mjscriptURL.'jquery.foundation.reveal.js'), array('jquery'), NULL, true );
	wp_enqueue_script('reveal');	
	wp_register_script('app', ($mjscriptURL.'app.js'), array('jquery'), NULL, true );
	wp_enqueue_script('app');	
	wp_register_script('mobileScript', ($mjscriptURL.'mobileScript.js'), array('jquery'), NULL, true );
	wp_enqueue_script('mobileScript');	
	wp_register_script('modernizr', ($mjscriptURL.'touch_slider/modernizr.custom.17475.js'), array('jquery'), NULL, true );
	wp_enqueue_script('modernizr');	
	wp_register_script('elastislide', ($mjscriptURL.'touch_slider/jquery.elastislide.js'), array('jquery'), NULL, true );
	wp_enqueue_script('elastislide');	
	wp_register_script('jquerypp', ($mjscriptURL.'touch_slider/jquerypp.custom.js'), array('jquery'), NULL, true );
	wp_enqueue_script('jquerypp');	
	}
	}
}
add_action('wp_enqueue_scripts', 'load_theme_scripts');   
// custom menu support
	add_theme_support( 'menus' );
	if ( function_exists( 'register_nav_menus' ) ) {
	  	register_nav_menus(
	  		array(
	  		  'header-menu' => 'Header Menu',
			  'main-menu' => 'Main Menu',
			  
	  		)
	  	);
	}
	// post thumbnail support
	add_theme_support( 'post-thumbnails' );		
	// theme pagination method
	function theme_pagination($pages = ''){
		global $paged;		
		if(empty($paged))$paged = 1;		
		$prev = $paged - 1;							
		$next = $paged + 1;	
		$range = 3; // only change it to show more links
		$showitems = ($range * 2)+1;		
		if($pages == '')
		{	
			global $wp_query;
			$pages = $wp_query->max_num_pages;
			if(!$pages)
			{
				$pages = 1;
			}
		}		
		if(1 != $pages){
			echo "<div id='pagination'>";
			echo ($paged > 2 && $paged > $range+1 && $showitems < $pages)? "<a href='".get_pagenum_link(1)."' class='btn'>&laquo; First</a> ":"";
			echo ($paged > 1 && $showitems < $pages)? "<a href='".get_pagenum_link($prev)."' class='btn'>&laquo; Previous</a> ":"";				
			for ($i=1; $i <= $pages; $i++){
				if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )){
					echo ($paged == $i)? "<a href='".get_pagenum_link($i)."' class='btn current'>".$i."</a> ":"<a href='".get_pagenum_link($i)."' class='btn'>".$i."</a> "; 
				}
			}			
			echo ($paged < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($next)."' class='btn'>Next &raquo;</a> " :"";
			echo ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($pages)."' class='btn'>Last &raquo;</a> ":"";
			echo "</div>";
			}
	}	
	// pie fix for wordpress
	function render_ie_pie() {
		echo '<!--[if lte IE 8]>
				<style type="text/css" media="screen">
					.search-form-wrapper,
					.search-form-wrapper .find-btn:hover,
					#slides,
					#slides img,
					.image-container img,
					.tricol-product-list li .image-container img,
					.tricol-product-list li a:hover,
					.find-wrapper,
					.find-nav li a,
					.cars-list li a img:hover,
					.right-white-block,
					.right-white-block .side-block-btn:hover,
					.side-lift-block .search-btn:hover,
					.detail-page-content .big-view img,
					.thumbnails li img,
					.thumbnails li img:hover,
					.side-product-wrapper .image-container img,
					.side-product-wrapper  a:hover,
					.result-car,
					.result-car img,
					.learn-more-btn:hover,
					.more-news:hover,
					.footer-bubmit-btn:hover,
					#pagination a.btn
					{
						behavior: url('.trailingslashit(get_bloginfo('template_url')).'js/PIE.php);
					}
				</style>
			<![endif]-->';
	}		
	add_action('wp_head', 'render_ie_pie' );
	
		
	function gorilla_img ($post_id,$size) {		
	$saved = get_post_custom_values('CarsGallery', $post_id);
	$saved = explode(',',$saved[0]);
	if ( $r=count($saved)>0){

	 $image = $saved[0];
	if($image==NULL)	
		{return 0;
		}
			$attachmenturl=wp_get_attachment_url($image);
			$attachmentimage= wp_get_attachment_image($image, $size );
			$bigp = wp_get_attachment_image($image, $size );
				?><?php echo $attachmentimage; ?><?php
			
} else {
		echo "";
		
	}
?>
  <?php 
return count($saved);
	}
	
	function arrivals_img ($post_id,$size) {		
	
	
	if ( $images = get_children(array(
		'post_parent' => get_the_ID(),
		'post_type' => 'attachment',
		'order' => 'ASC',
		'posts_per_page' => 1,
		'orderby' => 'menu_order',
		'post_mime_type' => 'image',
		)))
	{	foreach( $images as $image ) {
			$attachmenturl=wp_get_attachment_url($image->ID);
			$attachmentlink=wp_get_attachment_url($image->ID);
			$attachmentimage= wp_get_attachment_image($image->ID, $size );
			$img_title = $image->post_title;
			$img_desc = $image->post_excerpt;
			
				?><?php echo $attachmentimage; ?><?php			
			
						
		}
	} else {
		echo "";
	}
}


	function gallery_img ($size) {		
	global $post;
	$tmp_post = $post;			
	$args = array(
   'post_type' => 'attachment',
	'numberposts' => 1,
   'orderby' => 'menu_order',
   'order' => 'ASC',
   'post_parent' => $post->ID
  );
  $attachments = get_posts( $args );
     if ( $attachments ) {
        foreach ( $attachments as $attachment ): setup_postdata($post);  
       
        $img_title = $attachment->post_title;		
		$img_desc = $attachment->post_excerpt;
		$attachmentlink=wp_get_attachment_url($attachment->ID);
		$imageUrl = wp_get_attachment_image_src( $attachment->ID, $size );
		?>


<a href ="<?php echo $imageUrl[0];?> "><img src="<?php echo $imageUrl[0]; ?>"/></a>



	

  <?php endforeach; $post = $tmp_post;
	}
}

	
if(!get_option("medium_crop"))
    add_option("medium_crop", "1");
	else
    update_option("medium_crop", "1");
	if(!get_option("large_crop"))
    add_option("large_crop", "1");
	else
    update_option("large_crop", "1");	
    if( FALSE === get_option("thumbnail_large_size_w") )
	{	
	add_option("featured_size_w", "738");
	add_option("featured_large_size_h", "300");
	add_option("featured_large_crop", "1");	
	add_option("thumbnail_large_size_w", "266");
	add_option("thumbnail_large_size_h", "166");
	add_option("thumbnail_large_crop", "1");	
	add_option("thumbnail_medium_size_w", "132");
	add_option("thumbnail_medium_size_h", "100");
	add_option("thumbnail_medium_crop", "1");	
	add_option("admin_photo_size_w", "220");
	add_option("admin_photo_size_h", "140");
	add_option("admin_photo_crop", "1");	
	add_option("thumbnail_results_size_w", "216");
	add_option("thumbnail_results_size_h", "140");
	add_option("thumbnail_results_crop", "1");	
	add_option("arrivals_size_w", "227");
	add_option("arrivals_size_h", "148");
	add_option("arrivals_crop", "1");	
	add_option("gallery_size_w", "500");
	add_option("gallery_size_h", "310");
	add_option("gallery_crop", "1");	
	add_option("thumbnail_gallery_size_w", "77");
	add_option("thumbnail_gallery_size_h", "60");
	add_option("thumbnail_gallery_crop", "1");		
	}
	else
	{	
	update_option("featured_size_w", "738");
	update_option("featured_size_h", "300");
	update_option("featured_crop", "1");	
	update_option("thumbnail_large_size_w", "266");
	update_option("thumbnail_large_size_h", "166");
	update_option("thumbnail_large_crop", "1");	
	update_option("thumbnail_medium_size_w", "132");
	update_option("thumbnail_medium_size_h", "100");
	update_option("thumbnail_medium_crop", "1");	
	update_option("admin_photo_size_w", "220");
	update_option("admin_photo_size_h", "140");
	update_option("admin_photo_crop", "1");		
	update_option("thumbnail_results_size_w", "216");
	update_option("thumbnail_results_size_h", "140");
	update_option("thumbnail_results_crop", "1");	
	update_option("arrivals_size_w", "227");
	update_option("arrivals_size_h", "148");
	update_option("arrivals_crop", "1");	
	update_option("gallery_size_w", "500");
	update_option("gallery_size_h", "310");
	update_option("gallery_crop", "1");	
	update_option("thumbnail_gallery_size_w", "77");
	update_option("thumbnail_gallery_size_h", "60");
	update_option("thumbnail_gallery_crop", "1");		
	}

function additional_image_sizes( $sizes ){
	$sizes[] = "featured";
	$sizes[] = "arrivals";
	$sizes[] = "gallery";
	$sizes[] = "admin_photo";
	$sizes[] = "thumbnail_large";
	$sizes[] = "thumbnail_gallery";
	$sizes[] = "thumbnail_medium";
	$sizes[] = "thumbnail_results";
	return $sizes;
	}
add_filter( 'intermediate_image_sizes', 'additional_image_sizes' );
	function remove_quick_edit( $actions ) {
	unset($actions['inline hide-if-no-js']);
	return $actions;
	}
	add_filter('post_row_actions','remove_quick_edit',10,1);
function cps_show_title(){
	global $CPS_OPTIONS;	
	$i = 0;
	// Taxonomies:
	if( isset($CPS_OPTIONS['taxonomies']) && !empty($CPS_OPTIONS['taxonomies']) ){
		foreach($CPS_OPTIONS['taxonomies'] as $taxonomy){
			if(isset($_GET[$taxonomy]) && trim($_GET[$taxonomy] != '')){
				$separator = $i ? '/': ' ';
				echo $separator . $taxonomy .'-'.$_GET[$taxonomy];
	// echo $separator . $_GET[$taxonomy];
				$i++;
			}
		}
	}
	foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes){
		
		foreach($meta_boxes as $metaBox){
			if(isset($_GET[$metaBox['name']]) && trim($_GET[$metaBox['name']]) != ''){
				$separator = $i ? '/': ' ';
				echo $separator. $metaBox['name'] .'-'.  $_GET[$metaBox['name']];
				$i++;
				
			}
		}
	}
}
function get_hierarchical_terms($taxonomy, $parent = 0, $level = 0) 
	{
		$sPadding = '';
		
		for ($i = 0; $i <= $level; $i++) 
		{
			$sPadding .= '&nbsp;';
		}		
		$aTerms = get_terms($taxonomy, 'orderby=name&hide_empty=0&parent=' . (int)$parent);
		if($aTerms)
		{
			$aResults = array();
			foreach($aTerms as $oTerm) 
			{
				
				$oTerm->title = $sPadding . $oTerm->name;
				
				$aResults[] = $oTerm;
				
				$aChildren = get_hierarchical_terms($taxonomy, $oTerm->term_id, ((int)$level)+3);
				
				if ($aChildren) 
				{
					$aResults[] = $aChildren;
				}
			}
			return $aResults;
		}
		
		return false;
	}

add_action( 'show_user_profile', 'email_notification' );
add_action( 'edit_user_profile', 'email_notification' );

function email_notification( $user ) { ?>

	<h3><?php _e('E-mail Notification of New Listings Submitted for Approval','language');?></h3>
	<table class="form-table">
		<tr>
			<th>
				<label FOR="checktest"><?php _e('I want to be notified by e-mail','language');?></label>
			</th>
			<td>
			<?php $status = get_the_author_meta( 'emailmsg', $user->ID ); ?>
			<input type="hidden" name="emailmsg" value="0"/>		
			<input TYPE="checkbox" name="emailmsg" value="1" <?php checked( $status, 1 ); ?> /><br />
			</td>
		</tr>
	</table>	
<?php //if( !get_the_author_meta( 'emailmsg', $user->ID ) )  { 
//echo ''; 
//} else {
//echo get_the_author_meta( 'user_email', $user->ID );
//};
?>
<?php }
add_action( 'personal_options_update', 'save_email_option' );
add_action( 'edit_user_profile_update', 'save_email_option' );

function save_email_option( $user_id ) {

		if ( !current_user_can( 'edit_user', $user_id ) )
		
		{ return false; } else {if (isset($_POST['emailmsg'])) {
    update_user_meta( $user_id, 'emailmsg', $_POST['emailmsg'] );
}
	
	
}}
function remove_post_custom_fields() {
		remove_meta_box( 'postcustom' , 'gtcd' , 'normal' ); 
		}
		add_action( 'admin_menu' , 'remove_post_custom_fields' );
		function extended_contact_info($user_contactmethods) {  
		$user_contactmethods = array(
		'phone' => __('Phone','language'),
		'skype' => __('Skype','language'),
		'gtalk' => __('Gtalk','language')
		);  
		return $user_contactmethods;
	}  
	
	add_filter('user_contactmethods', 'extended_contact_info');
	
function custom_title_text( $title ){
		$screen = get_current_screen();
		if ( 'gtcd' == $screen->post_type ) {
		$title = __('Enter Vehicle Year & Model Here','language');
		}
		return $title;
	}
	add_filter( 'enter_title_here', 'custom_title_text' );

function admin_del_options() {
	   global $_wp_admin_css_colors;
	   $_wp_admin_css_colors = 0;
	}
	add_action('admin_head', 'admin_del_options');
	
	remove_filter('pre_user_description', 'wp_filter_kses');
function new_excerpt_more($more) {
		 global $post;
		return '...<a  class="more" href="'. get_permalink($post->ID) . '">'.__('Read More','language').'</a>';
	}
	add_filter('excerpt_more', 'new_excerpt_more');
	
function new_excerpt_length($length) {
		return 34;
	}


	add_filter('excerpt_length', 'new_excerpt_length');

function remove_menus () {
		global $current_user;
			 get_currentuserinfo();
		     if ($current_user->user_level < 8){
			global $menu;
			$restricted = array(__('Dashboard','language'), __('Media','language'), __('Links','language'), __('Pages','language'), __('Appearance','language'), __('Tools','language'), __('Users','language'), __('Settings','language'), __('Comments','language'), __('Plugins','language'));
			end ($menu);
			while (prev($menu)){
				$value = explode(' ',$menu[key($menu)][0]);
				if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
		}}
	}
	add_action('admin_menu', 'remove_menus');
function gt_restrict_manage_authors() {
		  if (isset($_GET['post_type']) && post_type_exists($_GET['post_type']) && in_array(strtolower($_GET['post_type']), array('your_custom_post_types', 'here'))) {
			    wp_dropdown_users(array(
					'show_option_all'       => 'Show all Authors',
					'show_option_none'      => false,
					'name'                  => 'author',
					'selected'              => !empty($_GET['author']) ? $_GET['author'] : 0,
					'include_selected'      => false
			    ));
		  }
	}
	add_action('restrict_manage_posts', 'gt_restrict_manage_authors');
function custom_feed_request( $vars ) {
	 if (isset($vars['feed']) && !isset($vars['post_type']))
	  $vars['post_type'] = array( 'post', 'gtcd' );
	 return $vars;
	}
	add_filter( 'request', 'custom_feed_request' );


function prefix_filter_gettext( $translated, $original, $domain ) {
 

    $strings = array(
        'View all posts filed under %s' => 'See all articles filed under %s',
        'Howdy, %1$s' => 'Greetings, %1$s!',
     
    );

    if ( isset( $strings[$original] ) ) {
        $translations = &get_translations_for_domain( $domain );
        $translated = $translations->translate( $strings[$original] );
    }
 
    return $translated;
}
 
add_filter( 'gettext', 'prefix_filter_gettext', 10, 3 );
add_action('admin_init','my_init_method');
add_action( 'add_meta_boxes', 'video_meta_box_add' );	
	function video_meta_box_add()
	{
		add_meta_box( 'video-meta-box-id', 'Video Meta Box', 'video_meta_box_cb', 'gtcd', 'side', 'core' );
	}	
	function video_meta_box_cb( $post )
	{
		$values = get_post_custom( $post->ID );
		
		$videoid = isset( $values['video_meta_box_videoid'] ) ? esc_attr( $values['video_meta_box_videoid'][0] ) : '';
		$source = isset( $values['video_meta_box_source'] ) ? esc_attr( $values['video_meta_box_source'][0] ) : '';
		
		wp_nonce_field( 'video_meta_box_nonce', 'meta_box_nonce' );
		?>
		<p>
			<label for="video_meta_box_videoid"><?php _e('Video ID','language')?></label>
			<input type="text" name="video_meta_box_videoid" id="video_meta_box_videoid" value="<?php echo $videoid; ?>" />
		</p>		
		<p>
			<label for="video_meta_box_source"><?php _e('Video Source','language')?></label>
			<select name="video_meta_box_source" id="video_meta_box_source">
				<option value="youtube" <?php selected( $source, 'youtube' ); ?>><?php _e('YouTube','language')?></option>
				<option value="vimeo" <?php selected( $source, 'vimeo' ); ?>><?php _e('Vimeo','language')?></option>
			</select>
		</p>		
		<?php	
	}	
	add_action( 'save_post', 'video_meta_box_save' );	
	function video_meta_box_save( $post_id )
	{


		if( isset( $_POST['video_meta_box_videoid'] ) )
			update_post_meta( $post_id, 'video_meta_box_videoid', wp_kses( $_POST['video_meta_box_videoid'], $allowed ) );
			
		if( isset( $_POST['video_meta_box_source'] ) )
			update_post_meta( $post_id, 'video_meta_box_source', esc_attr( $_POST['video_meta_box_source'] ) );	
} ?>
<?php function my_query_post_type($query) {
    if ( is_category() && false == $query->query_vars['suppress_filters'] )
        $query->set( 'post_type', array( 'post', 'gtcd', ) );
    return $query;
}
add_filter('pre_get_posts', 'my_query_post_type');

add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );
function my_restrict_manage_posts()
{
    // only display these taxonomy filters on desired custom post_type listings
    global $typenow;
    if ($typenow == 'gtcd')
   {
      $filters = get_taxonomies();
   
        foreach ($filters as $tax_slug)
      {
         //creates drop down menu only for makemodel and features
         if($tax_slug == 'makemodel')
         {
            // retrieve the taxonomy object
            $tax_obj = get_taxonomy($tax_slug);
            $tax_name = $tax_obj->labels->name;
            // retrieve array of term objects per taxonomy
            $terms = get_terms($tax_slug, array( 'parent' => 0 ) );
            
   
            // output html for taxonomy dropdown filter
            echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
            echo "<option value=''>View  $tax_name</option>";
            foreach ($terms as $term)
            {
               // output each select option line, check against the last $_GET to show the current option selected
               echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
            }
            echo "</select>";
         }//end if
      }//end foreach
      
    }//end if
   
}//end function
// add conditional statements
function is_ipad() { // if the user is on an iPad
	$is_ipad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');
	if ($is_ipad)
		return true;
	else return false;
}
function is_iphone() { // if the user is on an iPhone
	$cn_is_iphone = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPhone');
	if ($cn_is_iphone)
		return true;
	else return false;
}
function is_ipod() { // if the user is on an iPod Touch
	$cn_is_iphone = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPod');
	if ($cn_is_iphone)
		return true;
	else return false;
}
function is_ios() { // if the user is on any iOS Device
	if (is_iphone() || is_ipad() || is_ipod())
		return true;
	else return false;
}
function is_android() { // detect ALL android devices
	$is_android = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'Android');
	if ($is_android)
		return true;
	else return false;
}
function is_android_mobile() { // detect only Android phones
	$is_android   = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'Android');
	$is_android_m = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'Mobile');
	if ($is_android && $is_android_m)
		return true;
	else return false;
}
function is_android_tablet() { // detect only Android tablets
	if (is_android() && !is_android_mobile())
		return true;
	else return false;
}
function is_mobile_device() { // detect Android Phones, iPhone or iPod
	if (is_android_mobile() || is_iphone() || is_ipod())
		return true;
	else return false;
}
function is_tablet() { // detect Android Tablets and iPads
	if ((is_android() && !is_android_mobile()) || is_ipad())
		return true;
	else return false;
}
add_action('admin_head', 'edmunds_javascript');
function edmunds_javascript() {
?>
<script type="text/javascript" > 
function get_api_data(){w
		if (jQuery("#VIN_Code").val()==''){
			jQuery("#API_message").html('<div class="error"><p>Please type your vehicle VIN code first!</p></div>');
			jQuery("#API_message").show();
			return;
		}

		if (jQuery("#VIN_Code").val().length != 17){
			jQuery("#API_message").html('<div class="error"><p>Please type correct vehicle VIN code first!</p></div>');
			jQuery("#API_message").show();		
			return;
		}

		jQuery('#API_message').hide();		
		
		jQuery("#poststuff :input").attr("disabled", true);
		jQuery("#MyLoading").css({'display': 'inline'});
		jQuery("#GetData").hide();
		jQuery.ajax({
				type: "POST",
				data: ({action : 'rw_api_data', vin : jQuery("#VIN_Code").val()}),
				url: ajaxurl,				
				success: function(data)
				{
					jQuery("#poststuff :input").attr("disabled", false);
					var result = jQuery.parseJSON(data);
					jQuery.each(result, function(k, v) {
						if (k != 'makemodel-all'){
							if(jQuery('[name="' + k + '"]').is("select")) {
								//alert(k + ':' + v);
							}					
							if (k!='post_title'){
								jQuery('[name="' + k + '"]').val(v)								
							}else{
								if (jQuery('[name="post_title"]').val() == ''){
									jQuery('[name="post_title"]').val(v)
									jQuery("#title-prompt-text").hide()																								
								}
							}
						}else{
							jQuery('#' + k ).html(v)
						}
					});
						
					jQuery("#VIN_Code").val('');					
					jQuery("#MyLoading").css({'display': 'none'});					
					jQuery("#GetData").show();

				}
			});					
}

function messagebox(txt){
	jQuery("#messageBox").removeClass().addClass("confirmbox").html(txt).fadeIn(1000).fadeOut(1000);
}
function alertbox(txt){
	jQuery("#messageBox").removeClass().addClass("errorbox").html(txt).fadeIn(1000).fadeOut(1000);
}
// Delete image
function deletePost(id){
	var post_id = jQuery('#post_ID').val();		
    jQuery.ajax({
      url: ajaxurl,
      type: "post",
      data: ({action : 'rw_delete_file',postid: post_id, image_id: id, nonce: "<?php echo wp_create_nonce("DelGalImage");?>"}),
      success: function(data){
		  if (data=='0'){
			 messagebox('Image has been removed!');
			jQuery("#item_"+id).remove();

			var str = jQuery('#tgm-new-media-image').val();
			var exploded = str.split(',');
			jQuery.each(exploded, function (key, value) {
				if(value==id){
					exploded.splice(key,1)
				}
			});
			jQuery('#tgm-new-media-image').val(exploded.join(','));

		  }else{
			 alertbox('Image removal failed!');
		  }
		  
      },
      error:function(){
			 alertbox('Connection failed. please try again later!');
      }   
	});
}

// Save image gallery
function update_gallery(){
	jQuery('#rw-images-').empty();	
	var IDs = jQuery('#tgm-new-media-image').val();
	var id = jQuery('#post_ID').val();	
    jQuery.ajax({
      url: ajaxurl,
      type: "post",
      data: ({action : 'rw_save_gallery',post_id: id, Gallery_IDs: IDs, nonce: "<?php echo wp_create_nonce("AddGalImage");?>"}),
      success: function(data){
			messagebox("Gallery updated!");
			jQuery('#rw-images-').append(data);
      },
      error:function(){
			 alertbox('Connection failed. Gallery update didn\'t completed!');
      }   
	});
}	
jQuery(document).ready(function($) {
	// reorder images
	$('.rw-images').each(function(){
		var $this = $(this),
			order, data;
		$this.sortable({
			placeholder: 'ui-state-highlight',
			update: function (){
				order = $this.sortable('serialize');
				data = order + '|' + $('.rw-images-data').val();			
				$.post(ajaxurl, {action: 'rw_reorder_images', data: data}, function(response){																					
					if (response == '0'){
						messagebox("Images have been reordered");
					}else{
						alertmessage("You don't have permission to reorder images.");
					}
				});
			}
		});
	});

});
</script>
<?php
}
add_action( 'save_post', 'save_mademodel_meta');
function save_mademodel_meta(){
	if (isset($_POST['Vehicle_Make']) AND isset($_POST['Vehicle_model'])){
		$ID = $_POST['ID'];
		
		//Add new Made
		$term = term_exists($_POST['Vehicle_Make'], 'makemodel');
		
		if ($term !== 0 && $term !== null) {
			$Vehicle_Make_Id = intval($term['term_id']);
		}else{
			$term = wp_insert_term(
			  $_POST['Vehicle_Make'], // the term 
			  'makemodel', // the taxonomy
			  array(
				'parent'=> 0
			  )
			  );
			$Vehicle_Make_Id = $term['term_id'];
		}


		//Add new Model
		$term = term_exists($_POST['Vehicle_model'], 'makemodel');
		
		if ($term !== 0 && $term !== null) {
			$Vehicle_model_Id = intval($term['term_id']);
		}else{
			$term = wp_insert_term(
			  $_POST['Vehicle_model'], // the term 
			  'makemodel', // the taxonomy
			  array(
				'parent'=> $Vehicle_Make_Id
			  )
			  );
			$Vehicle_model_Id = $term['term_id'];
		}

		force_flush_term_cache('makemodel');
		$cat_ids = array($Vehicle_Make_Id,$Vehicle_model_Id);
		wp_set_object_terms($ID, $cat_ids, 'makemodel');
	}
	
}

function force_flush_term_cache( $taxonomy = 'category' ) {
	if ( !taxonomy_exists( $taxonomy ) ) return FALSE;

	wp_cache_set( 'last_changed', time( ) - 1800, 'terms' );
	wp_cache_delete( 'all_ids', $taxonomy );
	wp_cache_delete( 'get', $taxonomy );
	delete_option( "{$taxonomy}_children" );
	_get_term_hierarchy( $taxonomy );
	return TRUE;
}

/**chk box code */
/*
function sl_meta_box_sidebar(){
    global $post;
    $custom = get_post_custom($post->ID);
    $sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0]; 
?>
<input type="checkbox" name="sl-meta-box-sidebar" <?php if( $sl_meta_box_sidebar == true ) { ?>checked="checked"<?php } ?> />  Check the Box.
<?php } 

<?php
add_action('save_post', 'save_details');

function save_details($post_ID = 0) {
    $post_ID = (int) $post_ID;
    $post_type = get_post_type( $post_ID );
    $post_status = get_post_status( $post_ID );

    if ($post_type) {
    update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]);
    }
   return $post_ID;
} */
/*My code*/
$prefix = 'wp_';
$meta_box = array(
    'id' => 'my-benefits-box',
    'title' => 'Benefits meta box',
    'page' => 'gtcd',
    'context' => 'normal',
    'priority' => 'default',
    'fields' => array(
        array(
            'name' => 'Down payment',
            'desc' => 'Enter Downpayment ($) here',
            'id' => $prefix . 'text_1',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Weekly payment',
            'desc' => 'Enter Weekly Payment($) here',
            'id' => $prefix . 'text_2',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Feature',
            'desc' => 'Feature',
            'id' => $prefix . 'text_3',
            'type' => 'text',
            'std' => 'This Vehicle Qualifies for our Certified Vehicle Program!'
        ),
 array(
            'name' => 'Amount Financed $',
            'desc' => 'Amount Financed after Downpayment',
            'id' => $prefix . 'text_4',
            'type' => 'text',
             'std' => ''
        ),
	array(
            'name' => '# Weekly Payments',
            'desc' => 'Number of Weekly Payments',
            'id' => $prefix . 'text_5',
            'type' => 'text',
             'std' => ''
        ),
	array(
            'name' => 'Interest Rate %',
            'desc' => 'Interest Rate in %',
            'id' => $prefix . 'text_6',
            'type' => 'text',
             'std' => ''
        ),
		
       array(
            'name' => 'Home Page display',
            'desc' => 'Show on Front',
            'id' => $prefix . 'text_7',
            'type' => 'checkbox',
              'std' => ''
        ),
	array(
            'name' => 'No In-House Finance',
            'desc' => 'Select to Disable Financing Options for this Vehicle',
            'id' => $prefix . 'text_8',
            'type' => 'checkbox',
            'std' => ''
        ),
		/*
       array(
            'name' => 'Benefit 5',
            'desc' => 'Enter Benefit 5 here',
            'id' => $prefix . 'text_9',
            'type' => 'text',
            'std' => ''
        ),*/
    )
);

add_action('admin_menu', 'mytheme_add_box');
// Add meta box
function mytheme_add_box() {
    global $meta_box;
    add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}
// Callback function to show fields in meta box
function mytheme_show_box() {
    global $meta_box, $post;
    // Use nonce for verification
    echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
    echo '<table class="form-table">';
    foreach ($meta_box['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);
        echo '<tr>',
                '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                '<td>';
        switch ($field['type']) {
            case 'text':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                break;
        }
        echo     '</td><td>',
            '</td></tr>';
    }
    echo '</table>';
}
add_action('save_post', 'mytheme_save_data');
// Save data from meta box
function mytheme_save_data($post_id) {
    global $meta_box;
    // verify nonce
    if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    foreach ($meta_box['fields'] as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post_id;
}

/*Search Sidebar Taxonomy*/
/*For make population*/

add_action( 'wp_ajax_my_make_action', 'make_makes' );
add_action( 'wp_ajax_nopriv_my_make_action', 'make_makes' );

function make_makes(){
//return 1;
//var_dump($taxonomies);
/*New MakeLists*/
//for a given post type, return all
$post_type = 'gtcd';
$tax = 'makemodel';
/*
$args1 = array(
    'orderby'       => 'name', 
    'order'         => 'ASC',
    'hide_empty'    => true, 
    'exclude'       => array(), 
    'exclude_tree'  => array(), 
    'include'       => array(),
    'number'        => '', 
   'class'        => 'make', 
   'name'	  => 'makenox[]',
    'fields'        => 'all', 
    'slug'          => '', 
    'parent'         => 0,
    'hierarchical'  => true, 
    'child_of'      => 0, 
    'get'           => '', 
    'name__like'    => '',

 //'taxonomy'		=> 'makemodel',
	
);*/
$args1 = array(
    'orderby'       => 'name', 
    'order'         => 'ASC',
    'hide_empty'    => true,
     'exclude'       => array(), 
    'exclude_tree'  => array(), 
    'include'       => array(),
    'fields'        => 'all', 
    'hierarchical'  => 0, 
    'child_of'      => 0,
  'get'           => '', 
    'name__like'    => '',
   //'taxonomy'		=> 'makemodel',
	
);
 
$taxonomies=get_terms('makemodel',$args1);
$parents='';
//$allmakes='';
//$mytaxc=count($taxonomies);
  foreach ( $taxonomies as $make1)
  { 
//Sold 

		$term = get_term_by( 'id', $make1->term_id, "makemodel" );
		$object = new stdClass();
		//Special Sold Status
		$pages = get_posts(array( 'post_type' => 'gtcd',  'numberposts' => -1,
		'tax_query' => array(   array(
						'taxonomy' => 'makemodel',
						'field' => 'id',
						'terms' => $make1->term_id, // Where term_id of Term 1 is "1".
						'include_children' => true
							)
						),
		'meta_query' => array(
				array(
					'key'     => '_statustag',
					'value'   => 'Sold',
					'compare' => '!=',
					),
					),


		));

//var_dump($pages);
$count =count($pages);
// End Sold

			if($count>0)
     			{ 
		$parents .=$make1->term_id.',';
if($make1->parent<1)
$allmakes .='<li> <input class="makecheck" type="checkbox"   name="makenox[]" value='.$make1->term_id.' id='.$make1->name.'>'.$make1->name.' ('.$count.')</li>';		
				
		} 


//End of Sold

?><?php
 
   // wp_reset_query();
  }
$allmakes .='<li>  <input type="checkbox"  id="SelectAll" value="Select All" > Select All </li>';	
echo $allmakes;
die();

}
/*End of make*/

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

function my_action_callback() {
	global $wpdb; // this is how you get access to the database
 
	$whatever =  $_POST['whatever'] ;	
//	console.log($whatever);
		$p= array();
	//$whatever = 137;
	if($whatever=='Select All,')
	{
	$whatever='';
	$terms = get_terms( 'makemodel', '&hide_empty=1&hierarchical=0' );
	 foreach ( $terms as $term ) {
	 $whatever .=$term->term_id.',';
	 }
	//array_push($p,$whatever);
	}
$whateverarray= explode(",", $whatever );

  foreach ($whateverarray as $whatever1){
		$whatever2 = intval($whatever1);	
		$termchildren=get_term_children( $whatever2, "makemodel" );
		foreach ( $termchildren as $child ) {
		$term = get_term_by( 'id', $child, "makemodel" );
		$object = new stdClass();
		/*Special Sold Status*/
		$pages = get_posts(array( 'post_type' => 'gtcd',  'numberposts' => -1,
		'tax_query' => array(   array(
						'taxonomy' => 'makemodel',
						'field' => 'id',
						'terms' => $child, // Where term_id of Term 1 is "1".
						'include_children' => true
							)
						),
		'meta_query' => array(
				array(
					'key'     => '_statustag',
					'value'   => 'Sold',
					'compare' => '!=',
					),
					),


		));
$count =count($pages);
/* End Sold*/

			if($count>0)
     			{
			$object->name = $term->name;
			$object->id = $child;
			$object->count= $count;
			array_push($p,$object);
				}
		}
} 
		echo  json_encode($p);
	die(); // this is required to return a proper result
}
// Creating the widget for Quick Car Search 
class wpcarsearch_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpcarsearch_widget', 

// Widget name will appear in UI
__('CarSearch Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Quick Car Search Widget', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
//include('searching.php');

include('widget-search2.php');

echo $args['after_widget'];

}
		
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<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 esc_attr( $title ); ?>" />
</p>
<?php 
}
	
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpcarsearch_widget ends here

// Register and load the widget
function wpb_load_widget() {
	register_widget( 'wpcarsearch_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

add_action('admin_menu', 'sticker_page');

function sticker_page() {
   
add_submenu_page( 
          'tools.php'   //or 'options.php' 
        , 'My Sticker Page' 
        , 'My Sticker Page'
        , 'manage_options'
        , 'generate-sticker'
        , 'sticker_generator'
    );

}
function sticker_generator()
{
include('functions/pdf/Stickerform.php');
}

/*Pages Fix*/

add_action( 'admin_menu', 'register_my_custom_menu_page' );

function register_my_custom_menu_page(){
if ( ! current_user_can( 'administrator' ) ) {
  /* Admin menu Fixes for non-admin users */
add_menu_page( 'My Pages', 'My Pages', 'manage_options', 'edit.php?post_type=page', '', '', 19 ); 
add_menu_page( 'My Options', 'My options', 'manage_options', 'themes.php', '', '',34); 
add_menu_page( 'My Media', 'My Media', 'manage_options', 'upload.php', '', '', 11); 
    //add_menu_page( 'My Settings', 'My settings', 'manage_options', 'options-general.php', '', '',35 ); 
 add_menu_page( 'My Users', 'My Users', 'site_man', 'users.php', '', '',27 ); 
   //add_menu_page( 'My URE', 'URE', 'list_users', 'users.php?page=user-role-editor.php', '', '',28); 
}
}
function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
        
         echo "<div class='pagination'>";
          if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'><</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\"current\">" .$i. "</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">></a>";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last &raquo;</a>";
         echo "</div>\n";
     }
}



/*Inventory Filter*/

add_filter( 'views_edit-gtcd', 'meta_views_wpse_94630', 10, 1 );

function meta_views_wpse_94630( $views ) 
{
    $views['separator'] = '&nbsp;';
    $views['metakey'] = '<a href="edit.php?meta_data=Sold&post_type=gtcd">Sold</a>';
    return $views;
}

add_action( 'load-edit.php', 'load_custom_filter_wpse_94630' );

function load_custom_filter_wpse_94630()
{
    global $typenow;

    // Adjust the Post Type
    if( 'gtcd' != $typenow )
        return;

    add_filter( 'posts_where' , 'posts_where_wpse_94630' );
}

function posts_where_wpse_94630( $where ) 
{
    global $wpdb;       
    if ( isset( $_GET[ 'meta_data' ] ) && !empty( $_GET[ 'meta_data' ] ) ) 
    {
        $meta = esc_sql( $_GET['meta_data'] );
        $where .= " AND ID IN (SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_statustag' AND meta_value LIKE '".$_GET['meta_data']."')";
		
    }
    return $where;
}

/*Car Slider Widget*/

// Creating the widget for Vehicle Slider 
class wpcarslider_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpcarslider_widget', 

// Widget name will appear in UI
__('CarSlider Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Full Width Car Slider Widget', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
//include('searching.php');

echo $args['after_widget'];
}
		
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<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 esc_attr( $title ); ?>" />
</p>
<?php 
}
	
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} 
// Class wpcarslider_widget ends here

/*End of Car Slider Widget*/

/*Pagination Problem Fix for WP v4*/

function workaroundpaginationampersandbug($link) {
return str_replace('#038;', '&', $link);
}
add_filter('paginate_links', 'workaroundpaginationampersandbug');

/* Admin enqueue Script*/

function load_custom_wp_admin_sripts() {
   wp_register_script( 'jquery2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');     
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_sripts' );

add_action('admin_menu', 'view_formdata');
function view_formdata(){

add_submenu_page( 
          'tools.php'     , 'Form Submissions'  , 'Form Submissions'    , 'manage_options' , 'ccn-form-data', 'ccn_forms'
    );
add_submenu_page( 
          'tools.php'     , 'Form View'  , 'Form View'    , 'manage_options' , 'ccn-form-view', 'ccn_form_view'
    );

function ccn_form_view(){

global $wpdb;
 $myid= $_GET['formid'];
 
 ?>
<div class='wrap'><h2>View Form Data</h2>
<?php 

if($myid!=null){
$aformdata= $wpdb->get_row( "SELECT * FROM wp_spform_data WHERE id=".$myid);
?>
<table class="wp-list-table widefat fixed striped posts">
<?php 
$alldata= unserialize($aformdata->othermeta);
foreach($alldata as $key => $value) {
 echo '<tr><td style="text-transform:capitalize;">'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
<tr><td style="text-transform:capitalize;">Download as ADF</td><td><a target="_blank" href="<?php echo site_url();?>/download-xml.php?id=<?php echo $aformdata->id?>"> Download XML</a></td></tr>
</table>
<?php } else {
echo "Please navigate through Form Submissions";
}
?>
</div>

 <?php

}
function ccn_forms(){
global $wpdb;
 $page=$_GET['mypage'];
 
$allcount= $wpdb->get_row("SELECT COUNT(*) as count FROM wp_spform_data");


if($page==null){
	$page=1;

}
$limit= 20; 
$mpage=($page*$limit)-$limit;
$allformdata= $wpdb->get_results( "SELECT * FROM wp_spform_data ORDER BY id DESC LIMIT ".$mpage.",".$limit); //20


?>
<div class='wrap'><h2>View All Forms</h2>
<?php 
$pages= $allcount->count/$limit;
if($allcount->count%$limit!=0){
$pages =$pages+1;
}
echo "<div class='tablenav-pages'><span>";
for($i=1;$i<$pages;$i++){

echo "<a href='http://www.carcreditnation.com/wp-admin/tools.php?page=ccn-form-data&mypage=".$i."'>".$i."</a>";
}
echo "</span></div>";
?>
<table class="wp-list-table widefat fixed striped posts"><thead>
	<tr><th scope="col" id="title" class="manage-column column-title column-primary"><span>Form ID</span></th>
<th scope="col"><span>Type</span></th><th scope="col"><span>Date</span></th><th scope="col"><span>View/ Download</span></th></tr>
	</thead>
<?php 
foreach($allformdata as $aform){
$mydate1= unserialize($aform->othermeta);
$mydate=$mydate1['date'];
if($mydate==null)
$mydate=$mydate1['submitdate'];

echo "<tr><td>". $aform->id."</td><td>". $aform->formtype."</td><td>".$mydate."</td><td><a href='".site_url()."/wp-admin/tools.php?page=ccn-form-view&formid=".$aform->id."' id='view".$aform->id."'>View</a> <a href='".site_url()."/download-xml.php?id=".$aform->id."' id='form".$aform->id."'>Download</a></td></tr>";

}
?>
</table>


</div> 
<?php
}
}
/*AJAX File upload per form*/

add_action( 'wp_ajax_get_uploads', 'mycustomuyploader' );

add_action( 'wp_ajax_nopriv_get_uploads', 'mycustomuyploader' );

function mycustomuyploader(){

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
/*if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
*/
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}


}
/*
add_filter( 'wp_mail_content_type', function( $content_type ) {
	return 'text/xml';
});
*/