<?php

class ShortCodelicAdd{

	/**
	 * @since   0.0.9
	 *
	 * @var     string
	 */
	protected $version = '0.0.9';

	/**
	 * @since   0.0.1
	 *
	 * @var      string
	 */
	protected $plugin_slug = 'shortcodelicadd';

	/**
	 * @since   0.0.1
	 *
	 * @var      string
	 */
	protected $plugin_name = 'ShortCodelicAdd';

	/**
	 * @since   0.0.1
	 *
	 * @var      object
	 */
	protected static $instance = null;

	public function __construct() {
		add_action( 'init', array( &$this, 'load_plugin_textdomain' ) );

		add_action('init', array( &$this, 'register_portfolio' ) );
		add_action('init', array( &$this, 'create_portfolio_taxonomies' ) );

		add_action('tiny_mce_before_init', array( &$this, 'add_tinymce_tags' ) );
		add_action( 'init', array( &$this, 'custom_tinymce_css' ) );

		add_filter( 'tiny_mce_version', array( &$this, 'shortcodelic_refresh_mce' ) );
		add_action( 'init', array( &$this, 'add_shortcodelic_buttons' ), 100 );
		add_action( 'admin_enqueue_scripts', array( &$this, 'admin_styles' ) );
		add_action( 'admin_enqueue_scripts', array( &$this, 'admin_scripts' ) );
		add_action( 'add_meta_boxes', array( &$this, 'add_meta' ) );
		add_action( 'save_post', array( &$this, 'sc_page_template_save' ) );

		add_action( 'wp_enqueue_scripts', array( &$this, 'front_scripts' ) );
		add_action( 'wp_enqueue_scripts', array( &$this, 'front_styles' ) );

		add_shortcode('sc-searchform', array( &$this, 'scadd_search_form_sc') );
		add_shortcode('hr', array( &$this, 'scadd_hr_sc') );
		add_shortcode('hr-circled', array( &$this, 'scadd_hr_circled_sc') );
		add_shortcode('shortcodelic-video', array( &$this, 'shortcodelicVideoSC') );
		add_shortcode('shortcodelic-sidebar', array( &$this, 'shortcodelicSidebarsSC') );
		add_shortcode('shortcodelic-portfolio', array( &$this, 'shortcodelicPortfolioCategorySC') );
		add_shortcode('shortcodelic-posts', array( &$this, 'shortcodelicCategorySC') );
		add_shortcode('shortcodelic-langswitcher', array( &$this, 'shortcodelicWPMLSwitcher') );

		add_filter( 'the_content', array( &$this, 'filter_content' ), 10 );

		remove_shortcode( 'gallery', 'gallery_shortcode' );
		add_shortcode('gallery', array( &$this, 'filter_gallery') );
		add_action( 'wp_enqueue_media', array( $this, 'wp_enqueue_media' ) );
		add_action( 'print_media_templates', array( $this, 'print_media_templates' ) );
		add_action( 'widgets_init', array( $this, 'scadd_remove_gallery_widget' ), 11 );

		add_filter( 'pre_set_site_transient_update_plugins', array( &$this, 'check_for_plugin_update' ));
		add_filter( 'plugins_api', array( &$this, 'plugin_api_call' ), 10, 3);
		add_filter( 'body_class', array( &$this, 'shortcodelic_body_class' ) );
		
    }

	/**
	 * Return an instance of this class.
	 *
	 * @since   0.0.1
	 *
	 * @return    object    A single instance of this class.
	 */
	public static function get_instance() {

		// If the single instance hasn't been set, set it now.
		if ( null == self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

	/**
	 * Fired when the plugin is activated.
	 *
	 * @since   0.0.1
	 *
	 * @param    boolean    $network_wide    True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog.
	 */
	public static function activate( $network_wide ) {
	}

	/**
	 * Load text domain for translation.
	 *
	 * @since   0.0.1
	 */
	public function load_plugin_textdomain() {

		$domain = $this->plugin_slug;
		$locale = apply_filters( 'plugin_locale', get_locale(), $domain );

		load_textdomain( $domain, WP_LANG_DIR . '/' . $domain . '/' . $locale . '.mo' );
		load_plugin_textdomain( $domain, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/lang/' );
	}

	/**
	 * Register and enqueue front-end style sheets.
	 *
	 * @since   0.0.1
	 */
	public function front_styles() {
		global $post;

		//wp_enqueue_style( $this->plugin_slug, SHORTCODELICADD_URL.'css/shortcodelic_compiled.css', array(), $this->version );

	}

	/**
	 * Register and enqueue front-end scripts.
	 *
	 * @since   0.0.1
	 */
	public function front_scripts() {
		global $post;

	    /*if ( !$post )
	    	return;
		$content = $post->post_content;*/

		//wp_enqueue_script( $this->plugin_slug . '-fx', SHORTCODELICADD_URL.'scripts/fx.js', array('jquery'), $this->version );

	}

	/**
	 * Register and enqueue admin-specific style sheet.
	 *
	 * @since   0.0.1
	 */
	public function admin_styles() {
		global $pagenow;
		if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' ) {
			wp_enqueue_style( $this->plugin_slug .'-meta', SHORTCODELICADD_URL.'css/meta.css', array(), $this->version );
		}
	}

	/**
	 * Register and enqueue admin-specific scripts.
	 *
	 * @since   0.0.1
	 */
	public function admin_scripts() {
		global $pagenow;
		if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' ) {
			wp_enqueue_script( $this->plugin_slug . '-meta', SHORTCODELICADD_URL.'scripts/meta.js', array('shortcodelic-meta') );
		}
	}

	/**
	 * Add the metaboxes: the grid builder and its tabs to switch between builder and preview.
	 *
	 * @since   0.0.9
	 */
	public function add_meta() {
		global $post;
		$typenow = get_post_type();

		if ( $typenow == '' )
			return;

        add_meta_box( 'shortcodelic_video', 'ShortCodelic Video', 'shortcodelic_video', $typenow, 'normal', 'low' );
		if (!function_exists('shortcodelic_video')) {
			function shortcodelic_video( $post, $display ) {
			    require_once( SHORTCODELICADD_PATH.'lib/shortcodelic_video.php' );
			}
		}
        add_meta_box( 'shortcodelic_sidebars', 'ShortCodelic Sidebars', 'shortcodelic_sidebars', $typenow, 'normal', 'low' );
		if (!function_exists('shortcodelic_sidebars')) {
			function shortcodelic_sidebars( $post, $display ) {
			    require_once( SHORTCODELICADD_PATH.'lib/shortcodelic_sidebars.php' );
			}
		}
        add_meta_box( 'shortcodelic_posts', 'ShortCodelic Posts', 'shortcodelic_posts', $typenow, 'normal', 'low' );
		if (!function_exists('shortcodelic_posts')) {
			function shortcodelic_posts( $post, $display ) {
			    require_once( SHORTCODELICADD_PATH.'lib/shortcodelic_posts.php' );
			}
		}
        add_meta_box( 'shortcodelic_portfolio', 'ShortCodelic Portfolio', 'shortcodelic_portfolio', $typenow, 'normal', 'low' );
		if (!function_exists('shortcodelic_portfolio')) {
			function shortcodelic_portfolio( $post, $display ) {
			    require_once( SHORTCODELICADD_PATH.'lib/shortcodelic_portfolio.php' );
			}
		}
	}

/*=========================================================================================*/

	/**
	 * Add a stylesheet to tinyMCE editor.
	 *
	 * @since   0.0.1
	 */
	public static function custom_tinymce_css() {
		add_editor_style( SHORTCODELICADD_URL.'css/tinymce.css' );
   	}


	/**
	 * Set the style formats on tinyMCE editor.
	 *
	 * @since   0.0.1
	 */
	public static function add_tinymce_tags($settings) {

		$settings['fontsize_formats'] = "0.725em 0.9em 1.175em 1.5em 1.725em 2em 2.175em 2.5em 2.725em 3em 3.175em 3.5em 3.725em 4em 4.175em 4.5em 4.725em 5em 5.175em 5.5em 5.725em 6em 6.175em 6.5em 6.725em 7em";

		$settings['theme_advanced_more_colors'] = false;

		$settings['style_formats'] = '[
			{title: "Headings", items: [
				{title: ".H1", selector: "*", classes: "h1"},
				{title: ".H1-Font", selector: "*", classes: "h1_font"},
				{title: ".H2",selector: "*", classes: "h2"},
				{title: ".H2-Font", selector: "*", classes: "h2_font"},
				{title: ".H3", selector: "*", classes: "h3"},
				{title: ".H3-Font", selector: "*", classes: "h3_font"},
				{title: ".H4", selector: "*", classes: "h4"},
				{title: ".H4-Font", selector: "*", classes: "h4_font"},
				{title: ".H5", selector: "*", classes: "h5"},
				{title: ".H5-Font", selector: "*", classes: "h5_font"},
				{title: ".H6", selector: "*", classes: "h6"},
				{title: ".H6-Font", selector: "*", classes: "h6_font"}
			]},
			{title: "Styles", items: [
				{title: "Lined title", selector: "*", classes: "title-line"},
				{title: "Text shadow", selector: "*", classes: "text-shadow"},
				{title: "Text shadow 2", selector: "*", classes: "text-shadow-2"},
				{title: "Very big", selector: "*", classes: "very_big"},
				{title: "Alternative font", selector: "*", classes: "alternative_font"},
				{title: "Small underline", selector: "*", classes: "small_underline"},
				{title: "First letter", selector: "*", classes: "first-letter"},
				{title: "First line", selector: "*", classes: "first-line"},
				{title: "Let me be", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "letmebe"},
				{title: "No margin", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "no_margin"},
				{title: "Width 100%", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "width_100"},
				{title: "Fit text", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "fit_text"},
				{title: "Align-left", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "alignleft"},
				{title: "Align-right", selector: "*", selector: "p,div,h1,h2,h3,h4,h5,h6,span,img,a", classes: "alignright"},
			]},
			{title: "Effects", items: [
				{title: "Fade in", selector: "*", classes: "pix-fadeIn"},
				{title: "Fade down", selector: "*", classes: "pix-fadeDown"},
				{title: "Fade up", selector: "*", classes: "pix-fadeUp"},
				{title: "Fade left", selector: "*", classes: "pix-fadeLeft"},
				{title: "Fade right", selector: "*", classes: "pix-fadeRight"},
				{title: "Zoom in", selector: "*", classes: "pix-zoomIn"},
				{title: "Zoom out", selector: "*", classes: "pix-zoomOut"},
				{title: "Rotate in", selector: "*", classes: "pix-rotateIn"},
				{title: "Rotate out", selector: "*", classes: "pix-rotateOut"},
				{title: "Flip clock", selector: "*", classes: "pix-flipClock"},
				{title: "Swing", selector: "*", classes: "pix-swing"},
				{title: "Turn backward", selector: "*", classes: "pix-turnBackward"},
				{title: "Turn forward", selector: "*", classes: "pix-turnForward"}
			]},
			{title: "Line height", items: [
				{title: "Line height 1", selector: "*", classes: "line-height-1"},
				{title: "Line height 1.25", selector: "*", classes: "line-height-125"},
				{title: "Line height 1.5", selector: "*", classes: "line-height-15"},
				{title: "Line height 1.75", selector: "*", classes: "line-height-175"},
				{title: "Line height 2", selector: "*", classes: "line-height-2"},
				{title: "Line height 2.25", selector: "*", classes: "line-height-225"},
				{title: "Line height 2.5", selector: "*", classes: "line-height-25"}
			]}
		]';

	    return $settings;
   	}

	/**
	 * Print search form.
	 *
	 * @since   0.0.1
	 */
	function scadd_search_form_sc() {
		$search_query = isset($_GET['nf']) ? $_GET['nf'] : get_search_query();
	    $form = '<form role="search" method="get" class="search-form cf" action="' . esc_url( home_url( '/' ) ) . '">';
	    if ( is_rtl() ) {
	    	$form .= '<button type="submit" id="searchsubmit"><i class="scicon-awesome-search"></i></button>
	    	<label>
	    	<input type="search" class="search-field" placeholder="' . esc_attr_x( 'Search &hellip;', 'placeholder', 'geode' ) . '" value="' . $search_query . '" name="s" title="' . esc_attr_x( 'Search for:', 'label', 'geode' ) . '">
	    </label>';
	    } else {
	    	$form .= '<label>
	    	<input type="search" class="search-field" placeholder="' . esc_attr_x( 'Search &hellip;', 'placeholder', 'geode' ) . '" value="' . $search_query . '" name="s" title="' . esc_attr_x( 'Search for:', 'label', 'geode' ) . '">
	    </label>
	    <button type="submit" id="searchsubmit"><i class="scicon-awesome-search"></i></button>';
	    }
	    $form .= '</form>';

	    return $form;
	}

	/**
	 * Print hr tag.
	 *
	 * @since   0.0.1
	 */
	function scadd_hr_sc() {
	    return '<hr>';
	}

	/**
	 * Print hr tag.
	 *
	 * @since   0.0.1
	 */
	function scadd_hr_circled_sc() {
	    return '<hr class="circled">';
	}

	/**
	 * Set the button on tinyMCE editor.
	 *
	 * @since   0.0.1
	 */
	function add_shortcodelic_buttons() {

		global $post, $pagenow;
			
		if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') ) {
			if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
				return;
			if ( get_user_option('rich_editing') == 'true' ) {
				add_filter('mce_external_plugins', array( &$this, 'add_shortcodelicadd_js' ) );
				add_filter('mce_buttons', array( &$this, 'register_shortcodelicadd_buttons_page' ) );
				add_filter('mce_buttons_2', array( &$this, 'register_shortcodelicadd_buttons_page_2' ) );
			}

		}
	}

	function add_shortcodelicadd_js($plugin_array) {
		$plugin_array['shortcodelicadd'] = SHORTCODELICADD_URL.'scripts/sc_buttons.js';
		return $plugin_array;
	}

	function register_shortcodelicadd_buttons_page($buttons) {
		array_push(
			$buttons,
			"shortcodelic_video",
			"shortcodelic_sidebars",
			"shortcodelic_extra"
		);

		if (  get_post_type()=='page' ) {
			array_push(
				$buttons,
				"shortcodelic_posts",
				"shortcodelic_portfolio"
			);
		}
		return $buttons;
	}

	function register_shortcodelicadd_buttons_page_2($buttons) {
		array_push(
			$buttons,
			"backcolor",
			"backcolorpicker"
		);
		array_unshift( $buttons, 'fontsizeselect', 'styleselect' );
		return $buttons;
	}

	function shortcodelicadd_refresh_mce($ver) {
		$ver += 3;
		return $ver;
	}


	/**
	 * Display videos from shortcodes.
	 *
	 * @since    0.0.1
	 */
	public function shortcodelicVideoSC($atts, $content = null) {

		global $post;

		extract(shortcode_atts(array(
	        'mp4' => '',
	        'ogg' => '',
	        'webm' => '',
	        'autoplay' => '',
	        'loop' => '',
	        'fullsize' => '',
	        'volume' => '',
	        'poster' => ''
	    ), $atts));

		preg_match("/\<(.*?) class=[\'|\"]scicon-(.*?)<\/(.*?)>/", $content, $icon);
		if ( isset($icon[0]) ) {
			$icon = "<span class='shortcodelic-featured-icon'>$icon[0]</span>";
			$icon = preg_replace('/\<p\>/', '', $icon);
			$icon = preg_replace('/\<\/p\>/', '', $icon);
			$content = preg_replace("/\<(.*?) class=[\'|\"]scicon-(.*?)<\/(.*?)>/", "", $content, 1);
		} else {
			$icon = '';
		}

		$class = $fullsize == 'true' ? ' pix_section_video' : '';

	    $out = "<video class='pix_video$class' style='width: 100%; height: 100%;'";

    	if ( $autoplay!='' ) {
			$out .= " data-autoplay='true'";	
    	}

    	if ( $loop!='' ) {
			$out .= " data-loop='true'";	
    	}

    	if ( $volume!='' ) {
			$out .= " data-volume='$volume'";	
    	}

    	if ( $poster!='' ) {
			$out .= " poster='$poster'";	
    	}

	    $out .= ">";

    	if ( $mp4!='' ) {
			$out .= "<source type='video/mp4' src='$mp4'>";	
    	}
    	if ( $ogg!='' ) {
			$out .= "<source type='video/ogg' src='$ogg'>";	
    	}
    	if ( $webm!='' ) {
			$out .= "<source type='video/webm' src='$webm'>";	
    	}

	    $out .= "</video>";

    	return $out;


	}	

	/**
	 * Display sidebars from shortcodes.
	 *
	 * @since    0.0.8
	 */
	public function shortcodelicSidebarsSC($atts, $content = null) {

		global $post;

		extract(shortcode_atts(array(
	        'sidebar' => ''
	    ), $atts));

		ob_start();
		dynamic_sidebar(strtolower($sidebar));
		$sidebar = ob_get_clean();
		if ($sidebar) {
		    return $sidebar;
		}
	}	

	/**
	 * Display portfolio categories from shortcodes.
	 *
	 * @since    0.0.1
	 */
	public function shortcodelicPortfolioCategorySC($atts, $content = null) {

		global $query_string, 
			$shortcodelic_loop, 
			$columns, 
			$ratio,
			$textpos,
			$linkto,
			$gutter,
			$shortcodelic_widget, 
			$singlefx;

		$shortcodelic_widget = false;

		extract(shortcode_atts(array(
	        'order' => '',
	        'orderby' => '',
	        'ppp' => ''
	    ), $atts));

	    if ( !isset($atts['categories']) || $atts['categories']=='' ) {
	    	$atts['categories'] = '0';
	    }
	    $categories = $atts['categories'];

	    if ( !isset($atts['category_filter']) || $atts['category_filter']=='' ) {
	    	$atts['category_filter'] = false;
	    }
	    $category_filter = $atts['category_filter'];
	    $category_filter = $category_filter == 'false' ? false : $category_filter;
	    $category_filter = $category_filter == 'true' ? true : $category_filter;

	    if ( !isset($atts['tag_filter']) || $atts['tag_filter']=='' ) {
	    	$atts['tag_filter'] = false;
	    }
	    $tag_filter = $atts['tag_filter'];
	    $tag_filter = $tag_filter == 'false' ? false : $tag_filter;
	    $tag_filter = $tag_filter == 'true' ? true : $tag_filter;

	    if ( !isset($atts['columns']) || $atts['columns']=='' ) {
	    	$atts['columns'] = get_option('pix_style_portfolio_list_columns');
	    }
	    $columns = $atts['columns'];

	    if ( !isset($atts['layout']) || $atts['layout']=='' ) {
	    	$atts['layout'] = get_option('pix_style_portfolio_list_layout');
	    }
	    $layout = $atts['layout'];

	    if ( !isset($atts['text_position']) || $atts['text_position']=='' ) {
	    	$atts['text_position'] = get_option('pix_style_portfolio_text_position');
	    }
	    $textpos = $atts['text_position'];

	    if ( !isset($atts['link']) || $atts['link']=='' ) {
	    	$atts['link'] = get_option('pix_style_portfolio_list_link');
	    }
	    $linkto = $atts['link'];

	    if ( !isset($atts['gutter']) || $atts['gutter']=='' ) {
	    	$atts['gutter'] = get_option('pix_style_portfolio_list_gutter');
	    }
	    $gutter = $atts['gutter'];

	    if ( !isset($atts['pagination']) || $atts['pagination']=='' ) {
	    	$atts['pagination'] = get_option('pix_style_portfolio_list_pagination');
	    }
	    $pagination = $atts['pagination'];

	    $filter = false;
	    if ( isset($atts['fx']) && $atts['fx']!='' ) {
		    global $fx;
		    $fx = $atts['fx'];
		    if ( has_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' ) ) {
		    	remove_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' );
		    	$filter = true;
		    }
	    	add_filter( 'geode_fx_onscroll', function(){ global $fx; return $fx; } );
	    }

	    $ratio = $layout;
	    $datagrid = $ratio=='masonry' ? 'data-grid="masonry"' : '';
	    $pagination = $ppp == '' ? $pagination : false;
	    $ppp = $ppp == '' ? get_option( 'posts_per_page' ) : $ppp;

	    $out = '';

		$original = $query_string; 

		if ( is_front_page() ) {
			$paged = (get_query_var('page')) ? get_query_var('page') : 1;	
		} else {
			$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;	
		}

		$args = array(
			'post_type' => 'portfolio',
			'paged'	=> $paged,
			'portfolio_category' => $categories,
			'posts_per_page' => $ppp,
			'order' => $order,
			'orderby' => $orderby
		);

		$query_string = geode_build_query($args);

		$shortcodelic_loop = true;

		query_posts($query_string);

		$query = new WP_Query( $args );

		if ( isset($atts['widget']) && $atts['widget']=='true' ) {

			$shortcodelic_widget = true;

			$out .= '<div class="sc-widget sc-columns-'.$columns.' sc-shortcodelic">';
			$gutter_2 = $gutter/2;
				$out .= "<style scoped>
			.sc-widget .sc-grid {
				margin-left: -{$gutter}%!important;
			}
			.sc-widget .sc-grid article.hentry,
			.sc-widget article.hentry {
				margin: $gutter_2% 0!important;
				padding-left: $gutter%!important;
			}
		</style>";

				if ( $query->have_posts() ) :

					$out .= '<div class="sc-grid cf" '.$datagrid.'>';

					while ( $query->have_posts() ) : $query->the_post();

						ob_start();  
						get_template_part( 'portfolio/content', 'thumb' );
						$out .= ob_get_contents();
						ob_end_clean(); 

					endwhile;

					$out .= '</div><!-- .sc-grid -->';

				endif;

			$out .= '</div><!-- .sc-filter-wrap -->';

		} else {

				$gutter_2 = $gutter/2;
				$padding = $gutter <= 1 ? '1.5rem' : '0';
			$out .= "<style scoped>
				.sc-grid {
					margin-left: -{$gutter}%!important;
					margin-right: 0!important;
				}
				[data-extrachild=\"fullwidth\"] .sc-grid {
					margin-left: 0!important;
					margin-right: $gutter%!important;
				}
				.sc-layout .sc-grid article.hentry,
				.sc-grid article.hentry {
					margin: $gutter_2% 0!important;
					padding-left: $gutter%!important;
				}
				.sc-layout .sc-grid article.post-portfolio-below .entry-title,
				.sc-layout .sc-grid article.hentry .sc-position-below .category-list {
					padding: 0 $padding!important;
				}
			</style>";

			$out .= '<div class="sc-filter-wrap sc-columns-'.$columns.' sc-shortcodelic">';
			
				$out .= geode_portfolio_filter($category_filter, $tag_filter);

					if ( $query->have_posts() ) :

						$out .= '<div class="sc-grid cf" '.$datagrid.'>';

						while ( $query->have_posts() ) : $query->the_post();

							ob_start();  
							get_template_part( 'portfolio/content', get_post_format() );
							$out .= ob_get_contents();
							ob_end_clean(); 

						endwhile;

						$out .= '</div><!-- .sc-grid -->';

					    if ( $filter == true ) {
					    	add_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' );
					    }

						if ( $pagination !== false ) {
							ob_start();
							geode_pagenavi($infinite=$pagination);
							$out .= ob_get_contents();
							ob_end_clean();
						}

				endif;

			$out .= '</div><!-- .sc-filter-wrap -->';

		}

		wp_reset_postdata(); wp_reset_query();

		$shortcodelic_loop = false;
		$shortcodelic_widget = false;

		$query_string = $original; 

		return $out;
	}	

	/**
	 * Add body class if shortcode is used.
	 *
	 * @since    0.0.1
	 */
	public function shortcodelic_body_class( $classes ) {

	    global $post;

	    if( isset($post->post_content) && has_shortcode( $post->post_content, 'shortcodelic-portfolio' ) ) {
	    	$classes[] = 'sc-layout';
	    }

	    return $classes;

	}

	/**
	 * Display blog posts from shortcodes.
	 *
	 * @since    0.0.1
	 */
	public function shortcodelicCategorySC($atts, $content = null) {

		global $query_string, 
			$shortcodelic_blog,
			$shortcodelic_blog_masonry,
			$columns, 
			$ratio,
			$gutter,
			$more,
			$wp_query;

		extract(shortcode_atts(array(
			'order' => '',
			'orderby' => '',
	        'ppp' => ''
	    ), $atts));

	    if ( !isset($atts['categories']) || $atts['categories']=='' ) {
	    	$atts['categories'] = '0';
	    }
	    $categories = $atts['categories'];

	    if ( !isset($atts['layout']) || $atts['layout']=='' ) {
	    	$atts['layout'] = get_option('pix_style_archive_layout');
	    }
	    $layout = $atts['layout'];

	    if ( !isset($atts['columns']) || $atts['columns']=='' ) {
	    	$atts['columns'] = get_option('pix_style_archive_columns');
	    }
	    $columns = $atts['columns'];

	    if ( !isset($atts['gutter']) || $atts['gutter']=='' ) {
	    	$atts['gutter'] = get_option( 'pix_style_archive_gutter' );
	    }
	    $gutter = $atts['gutter'];

	    if ( !isset($atts['pagination']) || $atts['pagination']=='' ) {
	    	$atts['pagination'] = 'numbers';
	    }
	    $pagination = $atts['pagination'];

	    $filter = false;
	    if ( isset($atts['fx']) && $atts['fx']!='' ) {
		    global $fx;
		    $fx = $atts['fx'];
		    if ( has_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' ) ) {
		    	remove_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' );
		    	$filter = true;
		    }
	    	add_filter( 'geode_fx_onscroll', function(){  global $fx; return $fx; } );
	    }

	    $ratio = $layout;
	    $datagrid = $ratio=='masonry' ? 'data-grid="masonry"' : '';
	    $pagination = ($ppp == '' && $pagination!='none') ? $pagination : false;
	    $ppp = $ppp == '' ? get_option( 'posts_per_page' ) : $ppp;

	    $out = '';

		$margin_bottom = $gutter > 0 ? "$gutter%" : "-1px";
		$margin_right = $gutter > 0 ? "-1px" : "-2px";
		$selector = '.grid-blog .blog-isotope-grid';
		$full = '[data-extra="fullwidth"] .grid-blog .blog-isotope-grid';

		if ( isset( $gutter ) && $gutter != '' ) {
$out .= "<style scoped>
	$selector {
		margin-left: -{$gutter}%!important;
		margin-right: 0!important;
	}
	$full {
		margin-left: 0!important;
		margin-right: {$gutter}%!important;
	}
	$selector article.hentry {
		margin: 0 -1px $margin_bottom 0!important;
		padding-left: $gutter%!important;
	}
	$selector article.hentry:first-child {
		margin-right: $margin_right!important;
	}
	/*#main .entry-content > .row {
		padding-top: 0;
	}*/
	@media (max-width: 1024px) {
		$selector article.hentry:first-child {
			margin-right: -1px!important;
		}
	}
</style>";
}

		if ( is_front_page() ) {
			$paged = (get_query_var('page')) ? get_query_var('page') : 1;	
		} else {
			$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;	
		}

		$original = $query_string; 

		$args = array(
			'post_type' => 'post',
			'paged'	=> $paged,
			'cat' => $categories,
			'order' => $order,
			'orderby' => $orderby,
			'posts_per_page' => $ppp
		);

		$query_string = geode_build_query($args);

		$shortcodelic_blog = true;

		query_posts($query_string);

		$query = new WP_Query( $args );

		$more = 0;

			$out .= '<div class="archive-list">';

			if ( $layout == 'masonry' ) {
				$shortcodelic_blog_masonry = true;
				$out .= '<div class="cf grid-blog blog-columns-'.$columns.'">';
			}

				$out .= '<div class="blog-isotope-grid" '.$datagrid.'>';

					if ( $query->have_posts() ) :

						while ( $query->have_posts() ) : $query->the_post();

							ob_start();  
							get_template_part( 'content', get_post_format() );
							$out .= ob_get_contents();
							ob_end_clean(); 

						endwhile;

					endif;


				$out .= '</div><!-- .blog-isotope-grid -->';

			    if ( $filter == true ) {
			    	add_filter( 'geode_fx_onscroll', 'geode_fx_onscroll' );
			    }

				if ( $pagination && function_exists('geode_pagenavi') ) {
					ob_start();
					geode_pagenavi($infinite=$pagination);
					$out .= ob_get_contents();
					ob_end_clean();
				}

			if ( $layout == 'masonry' ) {
				$out .= '</div><!-- .grid-blog -->';
				$shortcodelic_blog_masonry = false;
			}
			
			$out .= '</div><!-- .archive-list -->';

		wp_reset_postdata(); wp_reset_query();

		$shortcodelic_loop = false;

		$query_string = $original; 

		return $out;
	}	

	/**
	 * Display language switcher if activated.
	 *
	 * @since    0.0.3
	 */
	public function shortcodelicWPMLSwitcher($atts, $content = null) {

		include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		if ( is_plugin_active('sitepress-multilingual-cms/sitepress.php') ) {
			ob_start();
			do_action('icl_language_selector');
			$out = ob_get_clean();

			return '<div class="lang_switcher">'.$out.'</div>';
		}

	}	

	/**
	 * Replace the html comments in the post content to create the grid
	 *
	 * @since    0.0.1
	 *
	 */
	public function filter_content($content) {

		$content = preg_replace('/<p>\[shortcodelic-video(.*?)\]<\/p>/', '[shortcodelic-video$1]', $content);
		$content = preg_replace('/<p>\[shortcodelic-sidebar(.*?)\]<\/p>/', '[shortcodelic-sidebar$1]', $content);
		$content = preg_replace('/<p>\[shortcodelic-portfolio(.*?)\]<\/p>/', '[shortcodelic-portfolio$1]', $content);
		$content = preg_replace('/<p>\[shortcodelic-posts(.*?)\]<\/p>/', '[shortcodelic-posts$1]', $content);
		$content = preg_replace('/<p>\[shortcodelic-langswitcher\]<\/p>/', '[shortcodelic-langswitcher]', $content);
		$content = preg_replace('/<p>\[sc-searchform\]<\/p>/', '[sc-searchform]', $content);
		$content = preg_replace('/<p>\[indeed(.*?)\]<\/p>/', '[indeed$1]', $content);
		$content = preg_replace('/<p>\[hr-circled\]<\/p>/', '[hr-circled]', $content);
		$content = preg_replace('/<p>\[hr\]<\/p>/', '[hr]', $content);
		$content = preg_replace('/<p>\[gallery (.*?)\]<\/p>/', '[gallery $1]', $content);

		return $content;
	}

	/**
	 * Filter gallery shortcode.
	 *
	 * @since    0.0.5
	 */
	public function filter_gallery($attr) {
		global $content_width;
		$post = get_post();

		static $instance = 0;
		$instance++;

		$rel_id = time().'-'.mt_rand();

		if ( ! empty( $attr['ids'] ) ) {
			// 'ids' is explicitly ordered, unless you specify otherwise.
			if ( empty( $attr['orderby'] ) )
				$attr['orderby'] = 'post__in';
			$attr['include'] = $attr['ids'];
		}

		// Allow plugins/themes to override the default gallery template.
		$output = apply_filters('post_gallery', '', $attr);
		if ( $output != '' )
			return $output;

		// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
		if ( isset( $attr['orderby'] ) ) {
			$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
			if ( !$attr['orderby'] )
				unset( $attr['orderby'] );
		}

		extract(shortcode_atts(array(
			'order'      => 'ASC',
			'orderby'    => 'menu_order ID',
			'id'         => $post ? $post->ID : 0,
			'columns'    => 3,
			'include'    => '',
			'exclude'    => '',
			'type'		 => ''
		), $attr, 'gallery'));

		$size = 'full';

		$id = intval($id);
		if ( 'RAND' == $order )
			$orderby = 'none';

		if ( !empty($include) ) {
			$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

			$attachments = array();
			foreach ( $_attachments as $key => $val ) {
				$attachments[$val->ID] = $_attachments[$key];
			}
		} elseif ( !empty($exclude) ) {
			$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
		} else {
			$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
		}

		if ( empty($attachments) )
			return '';

		if ( is_feed() ) {
			$output = "\n";
			foreach ( $attachments as $att_id => $attachment )
				$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
			return $output;
		}

		$columns = intval($columns);

		$selector = "gallery-{$instance}";

		$width = isset($content_width) ? $content_width : '940';
		$height = $width/(16/7);
		$layout = 'fixed2';

		if ( function_exists('geode_get_thumb_size') ) {
			$cols = $type=='slideshow' ? null : $columns;
			$geode_embed_size = geode_get_thumb_size($cols);
			$width = $geode_embed_size['width'];
			$height = $geode_embed_size['height']; 
			$size = $geode_embed_size['size'];
		}

		if ( $height == 0 ) {
			$height = $width/(4/3);
		} else {
			$layout = 'fluid';
		}

		$output = '';

		if ( is_archive() || (function_exists('geode_is_related') && geode_is_related()) || is_home() ) {
			$type = 'slideshow';
			$thumbnails = 'false';
		} else {
			$thumbnails = 'true';
		}

		switch ($type) {
			case 'slideshow': 
				$link_arr = array();
				$output .= "<!--[if lte IE 8]><div class='ie8-'><![endif]--><!--[if IE 9]><div class='ie9'><![endif]--><div id='$selector' class='gallery-slideshine pix_slideshine pix_slideshine-$id' data-opts='{\"layout\":\"$layout\",\"height\":\"$height\",\"width\":\"$width\",\"fx\":\"fade\",\"mobfx\":\"\",\"longfx\":\"none\",\"timeout\":\"7000\",\"speed\":\"750\",\"easing\":\"easeOutSine\",\"fxslide\":\"next\",\"autoplay\":\"false\",\"hover\":\"0\",\"thumbnails\":\"$thumbnails\",\"bullets\":\"false\",\"rows\":\"1\",\"cols\":\"1\",\"gridrows\":\"1\",\"gridcols\":\"1\",\"skin\":\"#ffffff\",\"skinrgb\":\"255,255,255\",\"skinbg\":\"#000000\",\"skinbgrgb\":\"0,0,0\",\"skinopacity\":\"0.2\"}'>";

				$i = 0;
				foreach ( $attachments as $id => $attachment ) {	
					$hidden_link = '';
					if ( is_single() || is_page() ) {
						$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_url($id) : get_attachment_link($id);
					} elseif ( function_exists('geode_portfolio_linkto') && (geode_portfolio_linkto()=='image' || geode_portfolio_linkto()=='both') ) {
						$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_url($id) : '';
					} else {
						$link = '';
						$hidden_link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_url($id) : get_attachment_link($id);
					}
					if ($link != '') $link_arr[] = $link;
					$slide_image = wp_get_attachment_image_src($id, $size, false);
					$slide_thumb = wp_get_attachment_image_src($id, 'geode_small', false);

					$output .= "<div><div data-link='$hidden_link' data-opts='{\"src\":\"".$slide_image[0]."\",\"thumb\":\"url(".$slide_thumb[0].")\",\"thumb2\":\"\",\"bg_pos\":\"center\",\"timeout\":\"\",\"speed\":\"\",\"fx\":\"\",\"mobfx\":\"\",\"longfx\":\"\",\"fxslide\":\"\",\"stop\":\"\",\"link\":\"$link\",\"target\":\"\"}'></div>";
					if ( trim($attachment->post_excerpt) && !is_archive() && !is_home() && (function_exists('geode_is_related') && !geode_is_related()) ) {
						$output .= "
							<div class='slideshine_caption slideshine_caption_$i' data-caption='{\"wider\":\"\",\"narrower\":\"\",\"bg\":\"#000000\",\"rgb\":\"rgba(0,0,0,0.8)\",\"entering\":\"upwards\",\"from\":\"100\",\"fromduration\":\"500\",\"fromeasing\":\"easeOutQuad\",\"leaving\":\"downwards\",\"to\":\"\",\"toduration\":\"500\",\"toeasing\":\"linear\"}'>" . wpautop(wptexturize($attachment->post_excerpt)) . "</div>";
					}
					$output .= "</div>";
					$i++;
				}

				$output .= "<div class='slideshine_prev slideshine_fontsized scicon-entypo-left-open-big' style='color: #ffffff; border-color: #ffffff; background: #000000; background: rgba(0,0,0,0.2);'></div><!-- .slideshine_prev -->
<div class='slideshine_next slideshine_fontsized scicon-entypo-right-open-big' style='color: #ffffff; border-color: #ffffff; background: #000000; background: rgba(0,0,0,0.2);'></div><!-- .slideshine_next -->
<div class='slideshine_waiter hiddenspinner'>
	<div class='spinner slideshine_fontsized' style='border-top-color: #ffffff;'></div>
</div>
</div>
<div class='slideshine_margin slideshine_margin-gallery slideshine_margin-gallery-$id'></div>
<!--[if IE 9]></div><![endif]--><!--[if lte IE 8]></div><![endif]-->";
				
				foreach ( $link_arr as $link ) {
					$output .= '<a class="hidden slideshine_hidden_links" data-rel="rel-'.$rel_id.'" href="'.$link.'" '.apply_filters('shortcodelic_slideshine_gallery_atts','') .'></a>';
				}				

				break;
			
			default:
				switch ($type) {
					case 'rectangular': 
						$grid = 'masonry';
						break;
					default:
						$grid = 'fitRows';
						break;
				}
				$output .= "<div class='wrap-sc-gallery'><div id='$selector' class='sc-gallery gallery galleryid-{$id} gallery-columns-{$columns} cf' data-grid='$grid'>";

				$i = 0;
				foreach ( $attachments as $id => $attachment ) {
					$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_url($id) : get_attachment_link($id);
					$rel = isset($attr['link']) && 'file' == $attr['link'] ? ' data-rel="'.$rel_id.'"' : '';
					$image = wp_get_attachment_image( $id, $size );

					$output .= "<span class='gallery-item alignleft'><span>";
					$output .= $link!='' ? '<a href="'.$link.'" '.$rel.'>' : '';
					$output .= $image;
					if ( trim($attachment->post_excerpt) ) {
						$output .= "
							<span class='wp-caption-text gallery-caption sc-bg-hover'>
							" . wptexturize($attachment->post_excerpt) . "
							</span>";
					}
					$output .= $link!='' ? '</a>' : '';
					$output .= "</span></span>";
				}
				$output .= "</div></div>\n";
				break;

		}


		return $output;
	}

	/**
	 * Get the values from additional fields of galleries.
	 *
	 * @since    0.0.1
	 */
	public function wp_enqueue_media() {
		if ( ! wp_script_is( 'scadd-gallery-settings', 'registered' ) )
			wp_register_script( 'scadd-gallery-settings', SHORTCODELICADD_URL.'scripts/galleries.js', array( 'media-views' ), $this->version );

		wp_enqueue_script( 'scadd-gallery-settings' );
	}

	/**
	 * Print the additional fields for galleries.
	 *
	 * @since    0.0.1
	 */
	public function print_media_templates() {
		$gallery_types = array(
			'' => __( 'Thumbnail grid','shortcodelicadd' ),
			'rectangular' => __( 'Tiles','shortcodelicadd' ),
			'slideshow' => __( 'Slideshow','shortcodelicadd' )
		);
		$default_gallery_type = apply_filters( 'jetpack_default_gallery_type', 'default' );
		?>
		<script type="text/html" id="tmpl-scadd-gallery-settings">
			<label class="setting">
				<span><?php _e( 'Type', 'shortcodelicadd' ); ?></span>
				<select class="type" name="type" data-setting="type">
					<?php foreach ( $gallery_types as $value => $caption ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, $default_gallery_type ); ?>><?php echo esc_html( $caption ); ?></option>
					<?php endforeach; ?>
				</select>
			</label>
		</script>
		<?php
	}

	/**
	 * Remve the gallery widget
	 *
	 * @since    0.0.1
	 */
	public function scadd_remove_gallery_widget() {
		unregister_widget( 'Jetpack_Gallery_Widget' );
	}

	/**
	 * Register portfolio post type.
	 *
	 * @since    0.0.1
	 */
	public function register_portfolio() {
	  $args = array(
	    'labels' => array(
	      'name' => __( 'Portfolio' ), 
	      'singular_name' => __( 'Portfolio' ),
	      'add_new' => _x('Add new', 'portfolio'),
	      'add_new_item' => __('Add a new item'), 
	      'edit_item' => __('Edit item'),
	      'new_item' => __('New item'),
	      'view_item' => __('View item'),
	      ),
	    'capability_type' => 'page',
	    'has_archive' => true,
	    'hierarchical' => false,
	    'menu_position' => 20,
	    'public' => true,
	    'rewrite' => true,
	    'singular_label' => __('Portfolio'),
	    'show_ui' => true,
	    'supports' => array(
	      'title',
	      'page-attributes',
	      'thumbnail',
	      'editor',
	      'excerpt',
	      'trackbacks',
	      'custom-fields',
	      'comments',
	      'revisions',
	      'post-formats')
	  );

		register_post_type( 'portfolio' , $args );
		add_post_type_support( 'portfolio', 'post-formats', array( 'gallery', 'video' ) );
	}

	/**
	 * Register portfolio taxonomies.
	 *
	 * @since    0.0.1
	 */
	public function create_portfolio_taxonomies() 
	{
	  // Add new taxonomy, make it hierarchical (like categories)
	  $labels = array(
	    'name' => _x( 'Portfolio categories', 'taxonomy general name' ),
	    'singular_name' => _x( 'Portfolio category', 'taxonomy singular name' ),
	    'search_items' =>  __( 'Search category' ),
	    'all_items' => __( 'All categories' ),
	    'parent_item' => __( 'Parent category' ),
	    'parent_item_colon' => __( 'Parent Category:' ),
	    'edit_item' => __( 'Edit Category' ), 
	    'update_item' => __( 'Update Category' ),
	    'add_new_item' => __( 'Add New Category' ),
	    'new_item_name' => __( 'New Category Name' ),
	    'menu_name' => __( 'Portfolio categories' ),
	  ); 	

	  register_taxonomy('portfolio_category',array('portfolio'), array(
	    'hierarchical' => true,
	    'labels' => $labels,
	    'show_ui' => true,
	    'query_var' => true,
		'rewrite' => array('hierarchical' => true )
	  ));

	  $labels = array(
	    'name' => _x( 'Portfolio tags', 'taxonomy general name' ),
	    'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
	    'search_items' =>  __( 'Search tags' ),
	    'popular_items' => __( 'Popular tags' ),
	    'all_items' => __( 'All tags' ),
	    'parent_item' => null,
	    'parent_item_colon' => null,
	    'edit_item' => __( 'Edit tag' ), 
	    'update_item' => __( 'Update tag' ),
	    'add_new_item' => __( 'Add New tag' ),
	    'new_item_name' => __( 'New tag name' ),
	    'separate_items_with_commas' => __( 'Separate tags with commas. They will be used for filtering portfolio items' ),
	    'add_or_remove_items' => __( 'Add or remove tags' ),
	    'choose_from_most_used' => __( 'Choose from the most used tags' ),
	    'menu_name' => __( 'Portfolio tags' ),
	  ); 

	  register_taxonomy('portfolio_tag','portfolio',array(
	    'hierarchical' => false,
	    'labels' => $labels,
	    'show_ui' => true,
	    'query_var' => true,
	    'rewrite' => array( 'slug' => 'portfolio_tag' ),
	  ));

	  $labels = array(
	    'name' => _x( 'Format', 'taxonomy general name' )
	  ); 

	  register_taxonomy('post_format',array('portfolio','post'),array(
	    'hierarchical' => false,
	    'labels' => $labels,
	    'show_ui' => false,
	    'query_var' => false
	  ));

	}

	/**
	 * Page template metabox.
	 *
	 * @since    0.0.1
	 */
	public function sc_page_template( $post ) {

		$values = get_post_custom( $post->ID );
		$selected = isset( $values['sc_page_template_select'] ) ? esc_attr( $values['sc_page_template_select'][0] ) : '';

		wp_nonce_field( 'sc_page_template_nonce', 'sc_page_template_nonce' );
		?>	
	    <div class="pix_meta_boxes">
	        <label for="sc_page_template_select"><?php _e('Template','shortcodelicadd'); ?></label>
	        <p>
	            <select name="sc_page_template_select" id="sc_page_template_select">
                    <option value='' <?php echo selected( $selected, '' ); ?>><?php _e('Default Template','shortcodelicadd'); ?></option>
                    <option value='single-portfolio-wide.php' <?php echo selected( $selected, 'single-portfolio-wide.php' ); ?>><?php _e('Default wide','shortcodelicadd'); ?></option>
	            </select>
	        </p>
	    </div><!-- .pix_meta_boxes -->
		<?php	
	}

	/**
	 * Save page template metabox values.
	 *
	 * @since    0.0.1
	 */
	public function sc_page_template_save( $post_id ) {
		if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
		if( !isset( $_POST['sc_page_template_select'] ) || !wp_verify_nonce( $_POST['sc_page_template_nonce'], 'sc_page_template_nonce' ) ) return;

		if( !current_user_can( 'edit_post', $post_id ) ) return;
		
		if( isset( $_POST['sc_page_template_select'] ) )
			update_post_meta( $post_id, 'sc_page_template_select', esc_attr( $_POST['sc_page_template_select'] ) );
	}

	/**
	 * Check for update.
	 *
	 * @since    1.2.0
	 */
	public function check_for_plugin_update($checked_data) {
		global $wp_version;

		$api_url = 'http://www.pixedelic.com/api/';

		if (empty($checked_data->checked))
			return $checked_data;
		
		$args = array(
			'dir' => sanitize_title( $this->plugin_name ),
			'slug' => $this->plugin_slug,
			'version' => $checked_data->checked[ SHORTCODELICADD_NAME ],
			'id' => apply_filters('sc_addons_itemID',''),
			'user' => apply_filters('sc_addons_username',''),
			'license' => apply_filters('sc_addons_licensekey','')
		);

		$request_string = array(
				'body' => array(
					'action' => 'basic_check', 
					'request' => serialize($args),
					'api-key' => md5(get_bloginfo('url'))
				),
				'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
			);
		
		$raw_response = wp_remote_post($api_url, $request_string);

		if (!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
			$response = unserialize($raw_response['body']);

		if (is_object($response) && !empty($response)) // Feed the update data into WP updater
			$checked_data->response[ SHORTCODELICADD_NAME ] = $response;
		
		return $checked_data;
	}

	/**
	 * Call for update.
	 *
	 * @since    1.2.0
	 */
	public function plugin_api_call($def, $action, $args) {
		global $wp_version;
		
		$api_url = 'http://www.pixedelic.com/api/';
		
		if (!isset($args->slug) || ($args->slug != $this->plugin_slug))
			return false;
		
		$plugin_info = get_site_transient('update_plugins');
		$current_version = $plugin_info->checked[ SHORTCODELICADD_NAME ];
		$args->version = $current_version;
		
		$request_string = array(
				'body' => array(
					'action' => $action, 
					'request' => serialize($args),
					'api-key' => md5(get_bloginfo('url'))
				),
				'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
			);
		
		$request = wp_remote_post($api_url, $request_string);

		if (is_wp_error($request)) {
			$res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>'), $request->get_error_message());
		} else {
			$res = unserialize($request['body']);

			if ($res === false)
				$res = new WP_Error('plugins_api_failed', __('An unknown error occurred'), $request['body']);
		}
		
		return $res;
	}

}

/**
 * Get template part.
 *
 * @since    0.0.1
 */
function sc_get_template_part( $slug, $name = '' ) {
	$template = locate_template( 'portfolio/'.$slug.'-'.$name.'.php', false );
	if ( !$template && file_exists( SHORTCODELICADD_PATH.'templates/'.$slug.'-'.$name.'.php' ) )
		$template = SHORTCODELICADD_PATH.'templates/'.$slug.'-'.$name.'.php';

	if ( $template )
		load_template( $template, false );
}


/**
 * Gallery widget.
 *
 * @since    0.0.1
 */
class shortcodelicGalleryWidget extends WP_Widget
{
	const THUMB_SIZE = 45;

    function shortcodelicGalleryWidget(){
	    $widget_ops = array('class' => 'sc-gallery-widget', 'description' => __( "Display a gallery", "shortcodelicadd") );
	    $this->WP_Widget('shortcodelicGalleryWidget', __('Gallery widget'), $widget_ops, 200);
    }

    function widget($args, $instance){
		extract($args);
		$title = $instance['title'];
		$ids = $instance['ids'];
		$random = $instance['random'];
		$type = $instance['type'];

		if ( isset($random) && $random==true ) {
			$ids = explode( ',', $instance['ids'] );
			shuffle( $ids );
			$ids = implode( ',', $ids );
		}

		echo $before_widget;

		if ( $title )
			echo $before_title . $title . $after_title .'';

		echo do_shortcode("[gallery type=\"$type\" ids=\"$ids\"]");

		echo $after_widget . '';
	}

    function update($new_instance, $old_instance){
		$instance = $old_instance;
		$instance['title'] = $new_instance['title'];
		$instance['ids'] = $new_instance['ids'];
		$instance['random'] = $new_instance['random'];
		$instance['type'] = $new_instance['type'];

		return $instance;
	}

	public function get_attachments( $instance ){
		$ids = explode( ',', $instance['ids'] );

		$order = ( isset( $instance['random'] ) && $instance['random'] ) ? 'rand' : 'post__in';

		$attachments_query = new WP_Query( array(
			'post__in' 			=> $ids,
			'post_status' 		=> 'inherit',
			'post_type' 		=> 'attachment',
			'post_mime_type' 	=> 'image',
			'posts_per_page'	=> -1,
			'orderby'			=> $order
		) );

		$attachments = $attachments_query->get_posts();

		wp_reset_postdata();

		return $attachments;
	}

    function form($instance){
		$instance = wp_parse_args( (array) $instance, array('title'=>'', 'ids'=>'', 'random'=>false, 'type'=>'') );

		$title = esc_html($instance['title']);
		$ids = $instance['ids'];
		$random = $instance['random'];
		$type = $instance['type'];
		?>

<p>
	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'shortcodelicadd' ); ?>
		<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( $instance['title'] ); ?>" />
	</label>
</p>

<p>
	<label>
		<?php esc_html_e( 'Images:', 'shortcodelicadd' ); ?>
	</label>
</p>

<div class="gallery-widget-thumbs-wrapper">
	<div class="gallery-widget-thumbs">
		<?php

		$gallery_types = array(
			'' => __( 'Thumbnail grid','shortcodelicadd' ),
			'rectangular' => __( 'Tiles','shortcodelicadd' ),
			'slideshow' => __( 'Slideshow','shortcodelicadd' )
		);

		// Add the thumbnails to the widget box
		$attachments = $this->get_attachments( $instance );

		foreach( $attachments as $attachment ){
			$url = esc_url_raw( add_query_arg( array(
				'w' 	=> self::THUMB_SIZE,
				'h' 	=> self::THUMB_SIZE,
				'crop'	=> 'true'
			), wp_get_attachment_url( $attachment->ID ) ) );

			?>

			<img src="<?php echo esc_url( $url ); ?>" title="<?php echo esc_attr( $attachment->post_title ); ?>" alt="<?php echo esc_attr( $attachment->post_title ); ?>"
				width="<?php echo self::THUMB_SIZE; ?>" height="<?php echo self::THUMB_SIZE; ?>" class="thumb" />
		<?php } ?>
	</div>

	<div style="clear: both;"></div>
</div>

<p>
	<a class="button gallery-widget-choose-images" title="<?php _e( 'Choose Images', 'shortcodelicadd' ); ?>"><span class="wp-media-buttons-icon"></span> <?php esc_html_e( 'Choose Images', 'shortcodelicadd' ); ?></a>
</p>

<p>
	<label for="<?php echo $this->get_field_id( 'random' ); ?>"><?php esc_html_e( 'Random Order:', 'shortcodelicadd' ); ?></label>
	<?php $checked = '';

	if ( isset( $instance['random'] ) && $instance['random'] )
		$checked = 'checked="checked"';

	?>
	<input name="<?php echo $this->get_field_name( 'random' ); ?>" id="<?php echo $this->get_field_id( 'random' ); ?>" type="checkbox" <?php echo $checked; ?>>
</p>

<p class="gallery-widget-style-wrapper">
	<label for="<?php echo $this->get_field_id( 'type' ); ?>"><?php esc_html_e( 'Style:', 'shortcodelicadd' ); ?></label>
	<select name="<?php echo $this->get_field_name( 'type' ); ?>" id="<?php echo $this->get_field_id( 'type' ); ?>" class="widefat gallery-widget-style">
		<?php foreach ( $gallery_types as $key => $label ) {
			$selected = '';

			if ( $instance['type'] == $key ) {
				$selected = "selected='selected' ";
			} ?>

			<option value="<?php echo $key; ?>" <?php echo $selected; ?>><?php esc_html_e( $label, 'shortcodelicadd' ); ?></option>
		<?php } ?>
	</select>
</p>

<?php


?>

<?php // Hidden input to hold the selected image ids as a csv list ?>
<input type="hidden" class="gallery-widget-ids" name="<?php echo $this->get_field_name( 'ids' ); ?>" id="<?php echo $this->get_field_id( 'ids' ); ?>" value="<?php echo esc_attr( $instance['ids'] ); ?>" />		

	<?php  }

}

function shortcodelicGalleryWidgetInit() {
	if ( class_exists( 'Jetpack_Tiled_Gallery' ) )
		register_widget('shortcodelicGalleryWidget');
}
add_action('widgets_init', 'shortcodelicGalleryWidgetInit');
