<?php
define('THEME_NAME', "Designer theme");
global $wp_version;
define('WP_VERSION', $wp_version);
define('THEME_NS', 'twentyten');
define('THEME_LANGS_FOLDER', '/languages');

load_theme_textdomain(THEME_NS, TEMPLATEPATH . THEME_LANGS_FOLDER);


if (function_exists('mb_internal_encoding')) {
	mb_internal_encoding(get_bloginfo('charset'));
}
if (function_exists('mb_regex_encoding')) {
	mb_regex_encoding(get_bloginfo('charset'));
}

theme_include_lib('defaults.php');
theme_include_lib('misc.php');
theme_include_lib('wrappers.php');
theme_include_lib('sidebars.php');
theme_include_lib('navigation.php');
theme_include_lib('shortcodes.php');
theme_include_lib('widgets.php');
theme_include_lib('text_404.php');
theme_include_lib('rating.php');
theme_include_lib('post_templates.php');

function theme_woocommerce_enabled() {
    global $woocommerce;
    return $woocommerce != null;
}

if (get_option('theme_show_comments_anywhere')) {
    global $withcomments;
    $withcomments = true;
}

add_action( 'wp_enqueue_scripts', 'theme_manage_woocommerce_styles', 99 );
function theme_manage_woocommerce_styles() {
	remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
    wp_dequeue_script( 'wc-single-product' );
}
add_action('wp_enqueue_scripts', 'theme_update_scripts_and_styles', 1000);
add_action('wp_print_scripts', 'theme_update_jquery_scripts', 1000);
add_action('wp_head', 'theme_update_posts_styles', 1000);
add_action('wp_head', 'theme_header_image_script');
add_action('media_upload_image_header', 'wp_media_upload_handler');

function theme_header_rel_link() {
	if (theme_get_option('theme_header_clickable')):
		?><link rel='header_link' href='<?php echo esc_url(theme_get_option('theme_header_link')); ?>' /><?php
	endif;
}
add_action('wp_head', 'theme_header_rel_link');
add_action('login_head', 'theme_header_rel_link');

add_action('init', 'theme_editor_auto_login');
add_action('init', 'theme_editor_domain');
add_action('wp',   'theme_change_cart_page_template');

add_filter('locale', 'set_new_locale');

add_theme_support('post-thumbnails');
add_theme_support('nav-menus');
add_theme_support('automatic-feed-links');
add_theme_support('post-formats', array('aside', 'gallery'));
add_theme_support( 'woocommerce' );

function theme_wp_title( $title, $sep ) {
    global $paged, $page;
    if ( is_feed() ) {
        return $title;
    }
    $title .= get_bloginfo( 'name' );
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) ) {
        $title = "$title $sep $site_description";
    }
    if ( $paged >= 2 || $page >= 2 ) {
        $title = "$title $sep " . sprintf( __( 'Page %s', THEME_NS ), max( $paged, $page ) );
    }
    return $title;
}
add_filter( 'wp_title', 'theme_wp_title', 10, 2 );

function theme_autoinclude($folder){
    $path = STYLESHEETPATH . '/' . $folder;

    if (!is_dir($path)) {
        return ;
    }

    if ($handle = opendir($path)) {
        while (($name = readdir($handle)) !== false) {
            if (!preg_match("#.php$#", $name)) {
                continue;
            }
            locate_template(array($folder . '/' . $name), true);
        }
        closedir($handle);
    }
}

theme_autoinclude('includes');

function theme_activation_function(){
    $base_template_dir = get_template_directory();
    $path = $base_template_dir . '/preview';
    if (!is_dir($path)) {
        return ;
    }

    $template = get_template();
    $theme_root = get_theme_root( $template );

    FilesHelper::copy_recursive($path, $theme_root);
}
add_action('after_switch_theme', 'theme_activation_function');


function theme_deactivation_function(){
    $theme_root = get_theme_root();
    $template = get_option('theme_switched');

    $base_template_dir = $theme_root . '/' . $template;
    $preview_template_dir = FilesHelper::normalize_path($base_template_dir . '_preview');

    if (!is_dir($base_template_dir) || !is_dir($preview_template_dir)) {
        return ;
    }

    $path = $base_template_dir . '/preview';

    $path = $path . '/' . $template . '_preview';

    if (is_dir($path)) {
        FilesHelper::empty_dir($path, true);
    }

    FilesHelper::copy_recursive($preview_template_dir, $path);
    FilesHelper::empty_dir($preview_template_dir, true);
}
add_action('switch_theme', 'theme_deactivation_function');

function theme_header_image_script() {
	$theme_header_image = theme_get_meta_option(get_queried_object_id(), 'theme_header_image');
	if ($theme_header_image) {
		?>
		<style>
			.bd-header {
				background-image : url(<?php echo $theme_header_image; ?>) !important;
				background-position : center center !important;
			}
		</style>
		<?php
	}
}

function theme_has_header_image() {
	return (bool) theme_get_meta_option(get_queried_object_id(), 'theme_header_image');
}
function theme_show_flash() {
	return (bool) theme_get_meta_option(get_queried_object_id(), 'theme_header_image_with_flash');
}

if (is_admin()) {
	theme_include_lib('options.php');
	theme_include_lib('admins.php');
    theme_include_lib('export.php', 'export');
	function theme_add_option_page() {
		add_theme_page(__('Theme Options', THEME_NS), __('Theme Options', THEME_NS), 'edit_themes', basename(__FILE__), 'theme_print_options');
	}

	add_action('admin_menu', 'theme_add_option_page');
	add_action('sidebar_admin_setup', 'theme_widget_process_control');
	add_filter('widget_update_callback', 'theme_update_widget_additional');
	add_action('add_meta_boxes', 'theme_add_meta_boxes');
	add_action('save_post', 'theme_save_post');
	add_filter('admin_footer', 'theme_page_templates');
	add_filter('wp_prepare_themes_for_js', 'theme_remove_customize_link');
	return;
}

add_filter('wp_redirect', 'theme_fix_woocommerce_redirect', 100);
function theme_fix_woocommerce_redirect($location){

	if (!isset($_GET)
		|| !isset($_GET['preview'])
		|| !isset($_GET['preview_iframe'])
		|| !isset($_GET['template'])
		|| !isset($_GET['stylesheet']))
	{
		return $location;
	}

	$parse_location = parse_url($location);
	$is_preview_url = false;
	$add_to_url = '?';
	if (isset($parse_location['query'])){
		$add_to_url = '&';
		$query = explode('&' , $parse_location['query']);
		foreach ($query as $pair){
			$query_pair = explode('=' , $pair);
			if (isset($query_pair[0]) && (
				strtolower($query_pair[0]) == 'preview'
					|| strtolower($query_pair[0]) == 'preview_iframe'
					|| strtolower($query_pair[0]) == 'template'
					|| strtolower($query_pair[0]) == 'stylesheet'))
			{
				$is_preview_url = true;
			}
		}

	}

	if (!$is_preview_url){
		$location .= $add_to_url . 'preview=1&template=' . $_GET['template'] . '&stylesheet=' . $_GET['stylesheet'] . '&preview_iframe=1';
	}

	return $location;
}

function theme_update_jquery_scripts() {
	if(is_admin()) {
		return;
	}
	wp_deregister_script('jquery');
	if (theme_get_option('theme_include_scripts_from_cdn')) {
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
	} else {
		wp_register_script('jquery', get_bloginfo('template_url', 'display') . '/jquery.js');
	}
}

function theme_update_posts_styles() {
	global $wp_query;
	$res = '';
	if(!is_singular()) {
		$post_id = get_queried_object_id();
		if ($post_id == 0 && theme_is_home()) {
            $post_id = get_option('page_for_posts');
        }
		$res .= get_post_meta($post_id, 'theme_head', true);
	}
	while ($wp_query->have_posts()) {
		the_post();
		$post_id = theme_get_the_ID();
		$res .= get_post_meta($post_id, 'theme_head', true);
	}
	if (!empty($res)) {
		echo $res;
	}
	wp_reset_postdata();
}

function theme_get_option($name) {
	global $theme_default_options;
	$result = get_option($name);
	if ($result === false) {
		$result = theme_get_array_value($theme_default_options, $name);
	}
	return $result;
}

function theme_get_widget_meta_option($widget_id, $name) {
	global $theme_default_meta_options;
	if (!preg_match('/^(.*[^-])-([0-9]+)$/', $widget_id, $matches) || !isset($matches[1]) || !isset($matches[2])) {
		return theme_get_array_value($theme_default_meta_options, $name);
	}
	$type = $matches[1];
	$id = $matches[2];
	$wp_widget = get_option('widget_' . $type);
	if (!$wp_widget || !isset($wp_widget[$id])) {
		return theme_get_array_value($theme_default_meta_options, $name);
	}
	if (!isset($wp_widget[$id][$name])) {
		$wp_widget[$id][$name] = theme_get_array_value(get_option($name), $widget_id, theme_get_array_value($theme_default_meta_options, $name));
	}
	return $wp_widget[$id][$name];
}

function theme_set_widget_meta_option($widget_id, $name, $value) {
	if (!preg_match('/^(.*[^-])-([0-9]+)$/', $widget_id, $matches) || !isset($matches[1]) || !isset($matches[2])) {
		return;
	}
	$type = $matches[1];
	$id = $matches[2];
	$wp_widget = get_option('widget_' . $type);
	if (!$wp_widget || !isset($wp_widget[$id])) {
		return;
	}
	$wp_widget[$id][$name] = $value;
	update_option('widget_' . $type, $wp_widget);
}

function theme_get_meta_option($id, $name) {
	global $theme_default_meta_options;
	if (!is_numeric($id)) {
        return theme_get_array_value($theme_default_meta_options, $name);
    }
	$value = get_post_meta($id, '_' . $name, true);
	if ('' === $value) {
		$value = theme_get_array_value(get_option($name), $id, theme_get_array_value($theme_default_meta_options, $name));
		theme_set_meta_option($id, $name, $value);
	}
	return $value;
}

function theme_set_meta_option($id, $name, $value) {
	update_post_meta($id, '_' . $name, $value);
}

function theme_get_post_id() {
	$post_id = theme_get_the_ID();
	if ($post_id != '') {
		$post_id = 'post-' . $post_id;
	}
	return $post_id;
}

function theme_get_the_ID() {
	global $post;
	return $post->ID;
}

function theme_get_post_class() {
	return implode(' ', get_post_class());
}

function theme_include_lib($name, $dir = 'library') {
	locate_template(array($dir . '/' . $name), true);
}

function theme_get_post_thumbnail($args = array()) {
	global $post;

	$size = theme_get_array_value($args, 'size', array(theme_get_option('theme_metadata_thumbnail_width'), theme_get_option('theme_metadata_thumbnail_height')));
	$auto = theme_get_array_value($args, 'auto', theme_get_option('theme_metadata_thumbnail_auto'));
	$featured = theme_get_array_value($args, 'featured', theme_get_option('theme_metadata_use_featured_image_as_thumbnail'));
	$title = theme_get_array_value($args, 'title', get_the_title());

	$result = '';

	if ($featured && (has_post_thumbnail())) {
		theme_ob_start();
		the_post_thumbnail($size, array('alt' => '', 'title' => $title));
		$result = theme_ob_get_clean();
	} elseif ($auto) {
		$attachments = get_children(array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID'));
		if ($attachments) {
			$attachment = array_shift($attachments);
			$img = wp_get_attachment_image_src($attachment->ID, $size);
			if (isset($img[0])) {
				$result = '<img src="' . $img[0] . '" alt="" width="' . $img[1] . '" height="' . $img[2] . '" title="' . $title . '" class="wp-post-image" />';
			}
		}
	}
	if ($result !== '') {
		$result = '<a href="' . get_permalink($post->ID) . '" title="' . $title . '">' . $result . '</a>';
	}
	return $result;
}

function theme_get_content($args = array()) {
	$more_tag = theme_get_array_value($args, 'more_tag', __('Continue reading <span class="meta-nav">&rarr;</span>', THEME_NS));
	theme_ob_start();
	the_content($more_tag);
	$content = theme_ob_get_clean();
	return $content . wp_link_pages(array(
				'before' => '<p><span class="page-navi-outer page-navi-caption"><span class="page-navi-inner">' . __('Pages', THEME_NS) . ': </span></span>',
				'after' => '</p>',
				'link_before' => '<span class="page-navi-outer"><span class="page-navi-inner">',
				'link_after' => '</span></span>',
				'echo' => 0
			));
}

function theme_get_excerpt($args = array()) {
	global $post;
	$more_tag = theme_get_array_value($args, 'more_tag', __('Continue reading <span class="meta-nav">&rarr;</span>', THEME_NS));
	$auto = theme_get_array_value($args, 'auto', 1);
	$all_words = theme_get_array_value($args, 'all_words', theme_get_option('theme_metadata_excerpt_words'));
	$min_remainder = theme_get_array_value($args, 'min_remainder', theme_get_option('theme_metadata_excerpt_min_remainder'));
	$allowed_tags = theme_get_array_value($args, 'allowed_tags',
		(theme_get_option('theme_metadata_excerpt_use_tag_filter')
			? explode(',',str_replace(' ', '', theme_get_option('theme_metadata_excerpt_allowed_tags')))
			: null));
	$perma_link = get_permalink($post->ID);
	$more_token = '%%theme_more%%';
	$show_more_tag = false;
	$tag_disbalance = false;
	if (post_password_required($post)) {
		return get_the_excerpt();
	}
	if ($auto && has_excerpt($post->ID)) {
		$excerpt = get_the_excerpt();
		$show_more_tag = theme_strlen($post->post_content) > 0;
	} else {
		$excerpt = get_the_content($more_token);
		// hack for badly written plugins
		theme_ob_start();
		echo apply_filters('the_content', $excerpt);
		$excerpt = theme_ob_get_clean();
		global $multipage;
		if ($multipage && theme_strpos($excerpt, $more_token) === false) {
			$show_more_tag = true;
		}
		if (theme_is_empty_html($excerpt))
			return $excerpt;
		if ($allowed_tags !== null) {
			$allowed_tags = '<' . implode('><', $allowed_tags) . '>';
			$excerpt = strip_tags($excerpt, $allowed_tags);
		}
		if (theme_strpos($excerpt, $more_token) !== false) {
			$excerpt = str_replace($more_token, $more_tag, $excerpt);
		} elseif ($auto && is_numeric($all_words)) {
			$token = "%theme_tag_token%";
			$content_parts = explode($token, str_replace(array('<', '>'), array($token . '<', '>' . $token), $excerpt));
			$content = array();
			$word_count = 0;
			foreach ($content_parts as $part) {
				if (theme_strpos($part, '<') !== false || theme_strpos($part, '>') !== false) {
					$content[] = array('type' => 'tag', 'content' => $part);
				} else {
					$all_chunks = preg_split('/([\s])/u', $part, -1, PREG_SPLIT_DELIM_CAPTURE);
					foreach ($all_chunks as $chunk) {
						if ('' != trim($chunk)) {
							$content[] = array('type' => 'word', 'content' => $chunk);
							$word_count += 1;
						} elseif ($chunk != '') {
							$content[] = array('type' => 'space', 'content' => $chunk);
						}
					}
				}
			}

			if (($all_words < $word_count) && ($all_words + $min_remainder) <= $word_count) {
				$show_more_tag = true;
				$tag_disbalance = true;
				$current_count = 0;
				$excerpt = '';
				foreach ($content as $node) {
					if ($node['type'] == 'word') {
						$current_count++;
					}
					$excerpt .= $node['content'];
					if ($current_count == $all_words) {
						break;
					}
				}
				$excerpt .= '&hellip;'; // ...
			}
		}
	}
	if ($show_more_tag) {
		$excerpt = $excerpt . ' <a class="more-link" href="' . $perma_link . '">' . $more_tag . '</a>';
	}
	if ($tag_disbalance) {
		$excerpt = force_balance_tags($excerpt);
	}
	return $excerpt;
}

function theme_get_search() {
	theme_ob_start();
	get_search_form();
	return theme_ob_get_clean();
}

function theme_is_home() {
	return (is_home() && !is_paged());
}

function theme_get_previous_post_link($format = '&laquo; %link', $link = '%title', $in_same_cat = false, $excluded_categories = '') {
	return theme_get_adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true);
}

function theme_get_next_post_link($format = '%link &raquo;', $link = '%title', $in_same_cat = false, $excluded_categories = '') {
	return theme_get_adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);
}

function theme_get_adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
	global $post;
	$post = get_post($post);
	$attachments = array_values(get_children(array('post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID')));

	foreach ($attachments as $k => $attachment)
		if ($attachment->ID == $post->ID)
			break;

	$k = $prev ? $k - 1 : $k + 1;

	if (isset($attachments[$k]))
		return wp_get_attachment_link($attachments[$k]->ID, $size, true, false, $text);
}

function theme_get_previous_image_link($size = 'thumbnail', $text = false) {
	$result = theme_get_adjacent_image_link(true, $size, $text);
	if ($result)
		$result = '&laquo; ' . $result;
	return $result;
}

function theme_get_next_image_link($size = 'thumbnail', $text = false) {
	$result = theme_get_adjacent_image_link(false, $size, $text);
	if ($result)
		$result .= ' &raquo;';
	return $result;
}

function theme_get_adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
	if ($previous && is_attachment())
		$post = & get_post($GLOBALS['post']->post_parent);
	else
		$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);

	if (!$post)
		return;

	$title = strip_tags($post->post_title);

	if (empty($post->post_title))
		$title = $previous ? __('Previous Post', THEME_NS) : __('Next Post', THEME_NS);

	$title = apply_filters('the_title', $title, $post->ID);
	$short_title = $title;
	if (theme_get_option('theme_single_navigation_trim_title')) {
		$short_title = theme_trim_long_str($title, theme_get_option('theme_single_navigation_trim_len'));
	}
	$date = mysql2date(get_option('date_format'), $post->post_date);
	$rel = $previous ? 'prev' : 'next';

	$string = '<a href="' . get_permalink($post) . '" title="' . esc_attr($title) . '" rel="' . $rel . '">';
	$link = str_replace('%title', $short_title, $link);
	$link = str_replace('%date', $date, $link);
	$link = $string . $link . '</a>';

	$format = str_replace('%link', $link, $format);

	$adjacent = $previous ? 'previous' : 'next';
	return apply_filters("{$adjacent}_post_link", $format, $link);
}

function theme_rating($rating, $args = array()) {
?>
    <div class="<?php echo $args['classNames']; ?>">
    <?php
        for ($i = 1; $i <= 5; $i++) {
            echo '<span class="' . $args['icon'] . ($i <= $rating ? ' active' : '') . '" data-control-id="' . $args['icon_dataId'] . '"></span>';
        }
    ?>
    </div>
<?php
}

function theme_comment($comment, $args, $depth) {
    $GLOBALS['comment'] = $comment;

    switch ($comment->comment_type) {

    case '' :
?>
        <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
            <?php theme_ob_start(); ?>
            <div class="comment-author vcard">
                <?php echo theme_get_avatar(array('id' => $comment, 'size' => 48)); ?>
                <?php printf(__('%s <span class="says">says:</span>', THEME_NS), sprintf('<cite class="fn">%s</cite>', get_comment_author_link())); ?>
            </div>
            <?php if ($comment->comment_approved == '0') : ?>
            <em><?php _e('Your comment is awaiting moderation.', THEME_NS); ?></em>
            <br />
            <?php endif; ?>

            <div class="comment-meta commentmetadata"><a href="<?php echo esc_url(get_comment_link($comment->comment_ID)); ?>">
                <?php printf(__('%1$s at %2$s', THEME_NS), get_comment_date(), get_comment_time()); ?></a><?php edit_comment_link(__('(Edit)', THEME_NS), ' '); ?>
            </div>

            <div class="comment-body"><?php comment_text(); ?></div>

            <div class="reply">
                <?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth']))); ?>
            </div>
            <?php echo '<div id="comment-'.get_comment_ID().'">' . theme_ob_get_clean() . '</div>'; ?>
<?php
        break;
    case 'pingback' :
    case 'trackback' :
?>
        <li class="post pingback">
            <?php theme_ob_start(); ?>
            <p><?php _e('Pingback:', THEME_NS); ?> <?php comment_author_link(); ?><?php edit_comment_link(__('(Edit)', THEME_NS), ' '); ?></p>
<?php
            echo '<div class="' . $comment->comment_type . '">' . theme_ob_get_clean() . '</div>';
        break;
    }
}


function theme_get_avatar($args = '') {
	$args = wp_parse_args($args, array('id' => false, 'size' => 96, 'default' => '', 'alt' => false, 'url' => false));
	extract($args);
	$result = get_avatar($id, $size, $default, $alt);
	if ($result) {
		if ($url) {
			$result = '<a href="' . esc_url($url) . '">' . $result . '</a>';
		}
		$result = '<div class="avatar">' . $result . '</div>';
	}
	return $result;
}

function theme_get_next_post() {
	static $ended = false;
	if (!$ended) {
		if (have_posts()) {
			the_post();
			get_template_part('content', get_post_format());
		} else {
			$ended = true;
		}
	}
}

function theme_ob_start() {
	ob_start();
}

function theme_ob_get_clean() {
	return ob_get_clean();
}

function theme_update_scripts_and_styles() {
    wp_register_script("script.js", get_bloginfo('template_url', 'display') . '/script.js', array('jquery'));
    wp_enqueue_script("script.js");
    wp_register_script("bootstrap.min.js", get_bloginfo('template_url', 'display') . '/bootstrap.min.js', array('jquery'));
    wp_enqueue_script("bootstrap.min.js");

    wp_register_style("bootstrap.css", get_bloginfo('template_url', 'display') . '/bootstrap.css', array(), false, "all");
    wp_enqueue_style("bootstrap.css");

    if (isset($_GET['preview'])){
        wp_register_script("script.preview.js", get_bloginfo('template_url', 'display') . '/script.preview.js', array('jquery'));
        wp_enqueue_script("script.preview.js");
    }

    if (theme_woocommerce_enabled() && is_checkout()) {
        wp_dequeue_script('wc-checkout');
        wp_enqueue_script('wc-checkout', get_bloginfo('template_url', 'display'). '/checkout.min.js', array('jquery'), false, true);
    }
}

function theme_editor_auto_login() {
    if(isset($_GET['editor_auto_login'])) {
        $_POST['log'] = $_GET['log'];
        $_POST['pwd'] = $_GET['pwd'];
    }
}

function theme_editor_domain() {
    if(isset($_GET['domain'])) {
        $template_dir = get_template_directory();
        $project_file = $template_dir . '/export/project.json';
        $project = file_exists($project_file) ? json_decode(file_get_contents($project_file), true) : array();
        $domain = $_GET['domain'];
        $project['domain'] = $domain;
        file_put_contents($project_file, json_encode($project));
    }
}

global $wp_locale;
if (isset($wp_locale)) {
    $wp_locale->text_direction = '@direction';
}

function theme_price_html($price, $old_price_start = '', $old_price_end = '', $regular_price_start = '', $regular_price_end = ''){
    $price = str_replace('<del>', $old_price_start, $price);
    $price = str_replace('</del>', $old_price_end, $price);

    $price = str_replace('<ins>', $regular_price_start, $price);
    $price = str_replace('</ins>', $regular_price_end, $price);

    return $price;
}

function theme_shop_products_per_page() {
    $items = theme_get_option( 'theme_shop_products_per_page' );
    return $items == 0 ? -1 : $items;
}
add_filter('loop_shop_per_page', 'theme_shop_products_per_page');

//Diasable Core Updates wp-3+
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_version_check' );

//Disable Plugin Updates wp-3+
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_plugins' );

//Disable Theme Updates wp-3+
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_themes' );

function set_new_locale( $lang ) {
    if (isset($_COOKIE['language'])) {
        return $_COOKIE['language'];
    }
    // return original language
    return $lang;
}

if (!function_exists('get_woocommerce_currencies')) {
    function get_woocommerce_currencies() {
        return array_unique(
            apply_filters( 'woocommerce_currencies',
                array(
                    'AUD' => __( 'Australian Dollars', 'woocommerce' ),
                    'BRL' => __( 'Brazilian Real', 'woocommerce' ),
                    'CAD' => __( 'Canadian Dollars', 'woocommerce' ),
                    'RMB' => __( 'Chinese Yuan', 'woocommerce' ),
                    'CZK' => __( 'Czech Koruna', 'woocommerce' ),
                    'DKK' => __( 'Danish Krone', 'woocommerce' ),
                    'EUR' => __( 'Euros', 'woocommerce' ),
                    'HKD' => __( 'Hong Kong Dollar', 'woocommerce' ),
                    'HUF' => __( 'Hungarian Forint', 'woocommerce' ),
                    'IDR' => __( 'Indonesia Rupiah', 'woocommerce' ),
                    'INR' => __( 'Indian Rupee', 'woocommerce' ),
                    'ILS' => __( 'Israeli Shekel', 'woocommerce' ),
                    'JPY' => __( 'Japanese Yen', 'woocommerce' ),
                    'KRW' => __( 'South Korean Won', 'woocommerce' ),
                    'MYR' => __( 'Malaysian Ringgits', 'woocommerce' ),
                    'MXN' => __( 'Mexican Peso', 'woocommerce' ),
                    'NOK' => __( 'Norwegian Krone', 'woocommerce' ),
                    'NZD' => __( 'New Zealand Dollar', 'woocommerce' ),
                    'PHP' => __( 'Philippine Pesos', 'woocommerce' ),
                    'PLN' => __( 'Polish Zloty', 'woocommerce' ),
                    'GBP' => __( 'Pounds Sterling', 'woocommerce' ),
                    'RON' => __( 'Romanian Leu', 'woocommerce' ),
                    'RUB' => __( 'Russian Ruble', 'woocommerce' ),
                    'SGD' => __( 'Singapore Dollar', 'woocommerce' ),
                    'ZAR' => __( 'South African rand', 'woocommerce' ),
                    'SEK' => __( 'Swedish Krona', 'woocommerce' ),
                    'CHF' => __( 'Swiss Franc', 'woocommerce' ),
                    'TWD' => __( 'Taiwan New Dollars', 'woocommerce' ),
                    'THB' => __( 'Thai Baht', 'woocommerce' ),
                    'TRY' => __( 'Turkish Lira', 'woocommerce' ),
                    'USD' => __( 'US Dollars', 'woocommerce' ),
                )
            )
        );
    }
}

function theme_get_languages() {
    return array('en_US' => __('English', THEME_NS),
                 'fr_FR' => __('French', THEME_NS),
                 'de_DE' => __('German', THEME_NS)
    );
}

function theme_get_woocommerce_currency_full_name($currency) {
    $currencies = get_woocommerce_currencies();
    return $currencies[$currency];
}

function theme_get_language_full_name($language) {
    $languages = theme_get_languages();
    return $languages[$language];
}

add_filter('woocommerce_currency', 'set_new_currency');

function set_new_currency( $currency ) {
    if (isset($_COOKIE['currency'])) {
        $new_currency = $_COOKIE['currency'];
        $currencies = get_woocommerce_currencies();
        if (isset($currencies[$new_currency]))
            $currency = $new_currency;
    }
    return $currency;
}

function theme_get_currency_title($textType, $showLabel, $showArrow) {
    $label = $showLabel ? __('Currency', THEME_NS) : '';
    $currency = get_woocommerce_currency();
    $symbol = get_woocommerce_currency_symbol($currency);

    if ($textType === 'noText')
        $value = $symbol;
    elseif ($textType === 'short')
        $value = $currency;
    elseif ($textType === 'full')
        $value = $symbol . ' ' . theme_get_woocommerce_currency_full_name($currency);

    if ($value && $label)
        $label .= ': ';
    $title = $label . $value;

    if ($showArrow)
        $title .= ' <span class="caret"></span>';
    return $title;
}

function theme_get_language_title($textType, $showLabel, $showArrow) {
    $label = $showLabel ? __('Language', THEME_NS) : '';
    $language = get_locale();

    if ($textType === 'short')
        $value = preg_replace('/.+_(.+)/', '$1', $language);
    elseif ($textType === 'noText')
        $value = '';
    elseif ($textType === 'full')
        $value = theme_get_language_full_name($language);

    if ($value && $label)
        $label .= ': ';
    $title = $label . $value;
    if ($showArrow)
        $title .= ' <span class="caret"></span>';
    return $title;
}

function theme_get_page_title() {
    $title = trim(wp_title('', false));
    if (!$title)
        $title = get_bloginfo('name');
    else if (theme_woocommerce_enabled() && is_shop()) {
        $shop_page = get_post( woocommerce_get_page_id( 'shop' ) );
        $title = apply_filters( 'the_title', ( $shop_page_title = get_option( 'woocommerce_shop_page_title' ) ) ? $shop_page_title : $shop_page->post_title );
    }
    return $title;
}

function theme_change_cart_page_template(){
    if (is_page()){
        global $post;
        if (function_exists('woocommerce_get_page_id') && woocommerce_get_page_id('cart') == $post->ID){
            if ( !is_page_template('cart.php') ) {
                update_post_meta($post->ID, '_wp_page_template', 'cart.php');
            }
        }
    }
}

function theme_woocommerce_in_cart_product_thumbnail($image){
    global $woocommerce;
    $img = $image;
    if ($woocommerce != null){
        $width  = $woocommerce->get_image_size( 'shop_thumbnail_image_width' );
        $height = $woocommerce->get_image_size( 'shop_thumbnail_image_height' );

        $img = str_replace('>', ' style="' . ($width !== '' ? 'width:'.$width.'px;' : '')
                                           . ($height !== '' ? 'height:'.$height.'px;' : '')
                                           . 'max-width:none;">', $img);
    }

    return $img;
}
add_filter('woocommerce_in_cart_product_thumbnail', 'theme_woocommerce_in_cart_product_thumbnail');

function theme_page_templates(){
    if(isset($_GET['post'])){
        echo '<script type="text/javascript">
                    if (jQuery(\'select#page_template\').val() === \'default\'){
                        jQuery(\'select#page_template\').val(\'page.php\');
                    }
                    jQuery(\'select#page_template option[value="default"]\').remove();
              </script>';
    }
}

function theme_remove_customize_link($prepared_themes){
    $current_theme = get_stylesheet();
    if ( isset( $prepared_themes[ $current_theme ] ) ) {
			$theme_data = &$prepared_themes[ $current_theme ];
			$theme_data['actions']['customize'] = str_replace('customize.php?theme=', 'themes.php?page=theme_editor&theme=', $theme_data['actions']['customize']);
			$theme_data['actions']['customize'] = str_replace('customize.php', 'themes.php?page=theme_editor', $theme_data['actions']['customize']);
			$preview_theme = $current_theme . '_preview';
			if ( isset( $prepared_themes[ $preview_theme ] ) ) {
                unset($prepared_themes[ $preview_theme ]);
			}
    }
    
    return $prepared_themes;
}

function theme_customize_preview_js() {
    wp_enqueue_script( 'theme-customizer-js', get_template_directory_uri() . '/theme-customizer.js', array(), '', true );
    wp_enqueue_style( 'theme-customizer-css', get_template_directory_uri() . '/theme-customizer.css');
}
add_action( 'customize_preview_init', 'theme_customize_preview_js' );
remove_action('woocommerce_before_shop_loop', 'woocommerce_catalog_ordering',30);
remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );

function theme_woocommerce_params($woocommerce_params) {
    $woocommerce_params['ajax_url'] .= '?preview=' . $_GET['preview'] . '&template=' . $_GET['template'] . '&stylesheet=' . $_GET['stylesheet'] . '&preview_iframe=' . $_GET['preview_iframe'];
    return $woocommerce_params;
}

if (isset($_GET['template']) && isset($_GET['preview']) && isset( $_GET['preview_iframe'] ) && current_user_can( 'switch_themes' )) {
    add_filter('woocommerce_params', 'theme_woocommerce_params');
    add_filter('wc_checkout_params', 'theme_woocommerce_params');
    add_filter('wc_cart_params', 'theme_woocommerce_params');
    add_filter('wc_cart_fragments_params', 'theme_woocommerce_params');
    add_filter('wc_add_to_cart_params', 'theme_woocommerce_params');
}

function theme_add_to_cart_fragments($fragments) {
    $new_fragments = array();
    foreach($fragments as $key => $content) {
        if ($key !== 'div.widget_shopping_cart_content') {
            $new_fragments[$key] = preview_theme_ob_filter($content);
        }
    }
    return $new_fragments;
}

?>