<?php
global $theme_options;


/**
 * Retrieve option value based on name of option.
 * 
 * If the option does not exist or does not have a value, then the return value will be false.
 * 
 * @param string $page page name
 * @param string $name option name
 */
function theme_get_option($page, $name = NULL) {
	global $theme_options;
	if ($name == NULL) {
		if (isset($theme_options[$page])) {
			return $theme_options[$page];
		} else {
			return false;
		}
	} else {
		if (isset($theme_options[$page][$name])) {
			return $theme_options[$page][$name];
		} else {
			return false;
		}
	}
}

function theme_set_option($page, $name, $value) {
	global $theme_options;
	$theme_options[$page][$name] = $value;

	update_option(THEME_SLUG . '_' . $page, $theme_options[$page]);
}
function theme_get_sidebar_default(){
	if(theme_is_post_type('post')){
		return theme_get_option('sidebar','single_post');
	}
	if(theme_is_post_type('portfolio')){
		return theme_get_option('sidebar','single_portfolio');
	}
	if(theme_is_post_type('page')){
		return theme_get_option('sidebar','single_page');
	}
	if(theme_is_post_type('product')){
		return theme_get_option('sidebar','single_product');
	}
	return '';
}

function theme_get_sidebar_options(){
	$sidebars = theme_get_option('sidebar','sidebars');
	if(!empty($sidebars)){
		$sidebars_array = explode(',',$sidebars);
		
		$options = array();
		foreach ($sidebars_array as $sidebar){
			$options[$sidebar] = $sidebar;
		}
		return $options;
	}else{
		return array();
	}
}

/**
 * It will return a boolean value.
 * If the value to be checked is empty, it will use default value instead of.
 * 
 * @param mixed $value
 * @param mixed $default
 */
function theme_is_enabled($value, $default = false) {
	if(is_bool($value)){
		return $value;
	}
	switch($value){
	case '1'://for theme compatibility
	case 'true':
		return true;
	case '-1'://for theme compatibility
	case 'false':
		return false;
	case '0':
	case '':
	default:
		return $default;
	}
}

function theme_get_excluded_pages(){
	$excluded_pages = theme_get_option('general', 'excluded_pages');
	$excluded_pages_with_childs = '';
	if (! empty($excluded_pages)) {
		//Exclude a parent and all of that parent's child Pages
		foreach($excluded_pages as $parent_page_to_exclude) {
			if ($excluded_pages_with_childs) {
				$excluded_pages_with_childs .= ',' . $parent_page_to_exclude;
			} else {
				$excluded_pages_with_childs = $parent_page_to_exclude;
			}
			$descendants = get_pages('child_of=' . $parent_page_to_exclude);
			if ($descendants) {
				foreach($descendants as $descendant) {
					$excluded_pages_with_childs .= ',' . $descendant->ID;
				}
			}
		}
		if('page' == get_option('show_on_front') ){
			$home = get_option('page_on_front');
			$loop = get_option('page_for_posts');
			if($home)
				$excluded_pages_with_childs .= ',' .$home;
			else
				$excluded_pages_with_childs .= ',' .$loop;
		}
	} else {
		if('page' == get_option('show_on_front') ){
			$home = get_option('page_on_front');
			$loop = get_option('page_for_posts');
			if($home)
				$excluded_pages_with_childs = $home;
			else
				$excluded_pages_with_childs = $loop;
		}
	}
	return $excluded_pages_with_childs;
}

if(!function_exists("get_queried_object_id")){
	/**
	 * Retrieve ID of the current queried object.
	 */
	function get_queried_object_id(){
		global $wp_query;
		return $wp_query->get_queried_object_id();
	}
}

function is_shortcode_preview() {
	if(defined('DOING_AJAX') && isset($_GET['action']) && $_GET['action']=='theme-shortcode-preview'){
		return true;
	}else{
		return false;
	}
}
if(!function_exists("wp_basename")){
	function wp_basename( $path, $suffix = '' ) {
		return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
	}
}

function theme_add_cufon_code(){
	$code = stripslashes(theme_get_option('cufon','code'));
	$fonts = theme_get_option('cufon','fonts');
	if(!empty($fonts['include'])){
		echo "<script type='text/javascript'>";
		foreach($fonts['include'] as $font=>$items){
			if(!empty($items)){
				echo 'Cufon.replace("'.$items.'",{hover:true,fontFamily:"'.$font.'"});';
			}
		}
		echo "</script>";
	}
	echo <<<HTML
<script type='text/javascript'>
{$code}
</script>
HTML;
}

function theme_add_cufon_code_footer(){
	echo <<<HTML
<script type='text/javascript'>

HTML;
	if(theme_get_option('font','font_advance') == 'cufon'){
		echo <<<HTML
Cufon.now();

HTML;
	}
	echo <<<HTML
if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10)==8){
	jQuery(".jqueryslidemenu ul li ul").css({display:'block', visibility:'hidden'});
}
</script>
HTML;
}

function theme_add_fontface_code(){
	$code = stripslashes(theme_get_option('fontface','code'));
	$fonts = theme_get_option('fontface','fonts');
	if(!empty($fonts['include'])){
		echo "<style type='text/css'>";
		foreach($fonts['include'] as $font=>$items){
			if(!empty($items)){
				echo $items.'{font-family:'.$font.';}';
			}
		}
		echo "</style>";
	}
	echo <<<HTML
<style type='text/css'>
{$code}
</style>
HTML;
}

function theme_add_gfont_code(){
	$code = stripslashes(theme_get_option('gfont','code'));
	$fonts = theme_get_option('gfont','fonts');
	if(!empty($fonts['include'])){
		echo "<style type='text/css'>";
		foreach($fonts['include'] as $font=>$items){
			if(!empty($items)){
				echo $items.'{font-family:'.$font.';}';
			}
		}
		echo "</style>";
	}
	echo <<<HTML
<style type='text/css'>
{$code}
</style>
HTML;
}




function theme_get_superlink($link, $default=false){
	if(!empty($link)){
		$link_array = explode('||',$link);
		switch($link_array[0]){
		case 'page':
			return get_page_link($link_array[1]);
		case 'cat':
			return get_category_link($link_array[1]);
		case 'post':
			return get_permalink($link_array[1]);
		case 'portfolio':
			return get_permalink($link_array[1]);
		case 'product':
			return get_permalink($link_array[1]);
		case 'manually':
			return $link_array[1];
		}
	}
	return $default;
}
function change_rgba($color=null, $transparent=1)
{
	if($color!=null)
	{
		$red=substr($color,1,2);
		$green=substr($color,3,2);
		$blue=substr($color,5,2);
		return 'rgba('.hexdec($red).','.hexdec($green).','.hexdec($blue).','.$transparent.')';
	}
	return 'rgba(255,255,255,1)';
}
function theme_image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h){
	if ($orig_w <= 0 || $orig_h <= 0)
		return false;
	// at least one of dest_w or dest_h must be specific
	if ($dest_w <= 0 && $dest_h <= 0)
		return false;
	$src_x=0;
	$src_y=0;
	$src_w = $orig_w;
	$src_h = $orig_h;

	$cmp_x = $orig_w / $dest_w;
	$cmp_y = $orig_h / $dest_h;
	if ($cmp_x > $cmp_y) {

		$src_w = round ($orig_w / $cmp_x * $cmp_y);
		$src_x = round (($orig_w - ($orig_w / $cmp_x * $cmp_y)) / 2);

	} else if ($cmp_y > $cmp_x) {

		$src_h = round ($orig_h / $cmp_y * $cmp_x);
		$src_y = round (($orig_h - ($orig_h / $cmp_y * $cmp_x)) / 2);

	}
	return array( 0, 0, $src_x,  $src_y, $dest_w,  $dest_h,  $src_w,  $src_h );
}

function theme_image_resize( $file, $orig_type,$orig_w,$orig_h,$max_w, $max_h,$suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
	global $wp_version;
	if(version_compare($wp_version, "3.5", '<')){
		$image = wp_load_image( $file );
	}else {
		@ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
		$image = imagecreatefromstring( file_get_contents( $file ) );
	}
	
	if ( !is_resource( $image ) )
		return new WP_Error( 'error_loading_image', $image, $file );

	$newimage = imagecreatetruecolor( $max_w, $max_h );

	if ( IMAGETYPE_PNG == $orig_type || IMAGETYPE_GIF == $orig_type ){
		imagealphablending($newimage, false);
		$color = imagecolorallocatealpha ($newimage, 255, 255, 255, 127);
		imagefill ($newimage, 0, 0, $color);
		imagesavealpha($newimage, true);
	}


	$dims = theme_image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h);
	if ( !$dims )
		return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
	list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
	imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
	// convert from full colors to index colors, like original PNG.
	if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
		imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );

	// we don't need the original in memory anymore
	imagedestroy( $image );

	// $suffix will be appended to the destination filename, just before the extension
	if ( !$suffix )
		$suffix = "{$max_w}x{$max_h}";

	$info = pathinfo($file);
	$dir = $info['dirname'];
	$ext = $info['extension'];
	$name = wp_basename($file, ".$ext");

	if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
		$dir = $_dest_path;
	$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";

	if ( IMAGETYPE_GIF == $orig_type ) {
		if ( !imagegif( $newimage, $destfilename ) )
			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
	} elseif ( IMAGETYPE_PNG == $orig_type ) {
		if ( !imagepng( $newimage, $destfilename ) )
			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
	} else {
		// all other formats are converted to jpg
		$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
		if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
	}

	imagedestroy( $newimage );

	// Set correct file permissions
	$stat = stat( dirname( $destfilename ));
	$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
	@ chmod( $destfilename, $perms );

	return $destfilename;
}
function theme_get_resizeimage($img_path,$type,$orig_width,$orig_height,$width,$height,$msg = null){
	$dst_path = THEME_CACHE_IMAGES_DIR;
	$file_info = pathinfo($img_path);
	$extension = '.'. $file_info['extension'];
	//the image path without the extension
	$no_ext_path = $dst_path.'/'.$file_info['filename'];

	if(empty($height)){
		$height = (int)$width/$orig_width*$orig_height;
	}
	if(empty($width)){
		$width = (int)$height/$orig_height*$orig_width;
	}
	$resized_img_url = $no_ext_path.'-'.$width.'x'.$height.$extension;
	if (is_file($resized_img_url)) {
		$resized_img_url = THEME_CACHE_IMAGES_URI.'/'.basename($resized_img_url);
	}else{
		$new_img_path = theme_image_resize($img_path,$type,$orig_width,$orig_height,$width,$height,null,$dst_path);
		if(!is_string($new_img_path) && is_object($new_img_path) && get_class($new_img_path) =='WP_Error'){
			return array(
				'url'=>$img_path,
				'width'=>$width,
				'height'=>$height,
				'msg'=>'error'
			);
		}
		$new_img_size = getimagesize($new_img_path);
		$width = $new_img_size[0];
		$height = $new_img_size[1];
		$resized_img_url = THEME_CACHE_IMAGES_URI.'/'.basename($new_img_path);
	}
	return array(
		'url'=>$resized_img_url,
		'width'=>$width,
		'height'=>$height,
		'msg'=>$msg
	);
}
function theme_resize($img = null,$width='',$height='',$source_type) {
	
	if(empty($height) && empty($width)){
		$width = 100;
		$height =100;
	}
	
	if($source_type == 'form'){
		$img_id = $img;
		if(stripos($img,'ngg-') !== false && class_exists('nggdb')) {
			$nggMeta = new nggMeta(str_replace('ngg-','',$img));
			$img = $nggMeta->image->imagePath;
		}else{
			$img_id = $img;
			$img = get_attached_file($img);
		}
	}
	$error_path = THEME_IMAGES_DIR.'/image-error.png';
	$error_width = 1500;
	$error_height = 1000;

	if(! $img || !is_string($img) || (is_object($img) && get_class($img) =='WP_Error')){
		return theme_get_resizeimage($error_path,IMAGETYPE_PNG,$error_width,$error_height,$width,$height,'your image url is error');
	}

	$file_path = parse_url($img);
	if(! $file_path ){
		return theme_get_resizeimage($error_path,IMAGETYPE_PNG,$error_width,$error_height,$width,$height,'your image url is error');
	}
	
	$image_info = @getimagesize($img);
	if(! $image_info && $source_type !='url'){
		return theme_get_resizeimage($error_path,IMAGETYPE_PNG,$error_width,$error_height,$width,$height,'your image can not be load');
	}
	if(empty($height)){
		if(! $image_info)
			$height = $width;
		else
			$height = (int)$width/$image_info[0]*$image_info[1];
	}
	if(empty($width)){
		if(! $image_info)
			$width = $height;
		else
			$width = (int)$height/$image_info[1]*$image_info[0];
	}
	if($source_type == 'url'){
		return array(
			'url' => $img,
			'width' => $width,
			'height' => $height,
			'msg' => 'success-url',
		);
	}
	
	if($width == $image_info[0] && $height == $image_info[1]){
		if($source_type == 'form'){
			if(stripos($img_id,'ngg-') !== false && class_exists('nggdb')) {
				$nggMeta = new nggMeta(str_replace('ngg-','',$img_id));
				$img= $nggMeta->image->imageURL;
			}else{	
				$img = @wp_get_attachment_image_src($img_id,'full',true);
				$img = $img[0];
			}
		}
		elseif($source_type == 'dir'){
			$img = basename($img);
			$img = THEME_IMAGES.'/'.$img;
		}

		return array(
			'url' => $img,
			'width' => $width,
			'height' => $height,
			'msg' => 'success-no',
		);
	}
	$res = theme_get_resizeimage($img,$image_info[2],$image_info[0],$image_info[1],$width,$height,'success');
	if($res['msg'] == 'error')
		return theme_get_resizeimage($error_path,IMAGETYPE_PNG,$error_width,$error_height,$width,$height,'your image can not be load');
	else
		return $res;
	
}
function portfolio_sortable_ajax_init(){
	if ( 'POST' != $_SERVER['REQUEST_METHOD'] || ! isset( $_POST['portfolioAction'] ) )
		return;
	if($_POST['portfolioAction'] != 'sortable')
		return;
	$params = array();
	if(isset($_POST['portfolioParams']))
		$params =  htmlspecialchars_decode($_POST['portfolioParams']);
	$params = str_replace('\\"','"',$params);
	$params = unserialize($params);
	if(isset($_POST['category']) && $_POST['category']!='all')
		$params['cat'] = $_POST['category'];
	if(isset($_POST['portfoliopage']))
		$params['paged'] = intval($_POST['portfoliopage']);
	if ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {
		@header( 'Content-Type: application/html; charset=' . get_option( 'blog_charset' ) );
		echo apply_filters('the_content',theme_generator('portfolio_list',$params));
	}
	exit();
}
add_action('init', 'portfolio_sortable_ajax_init');
function clean_wp(){
	remove_action( 'wp_head', 'rsd_link' );   
	remove_action( 'wp_head', 'wlwmanifest_link' );         
	remove_action( 'wp_head', 'index_rel_link' );   
	remove_action( 'wp_head', 'wp_generator' );  
	remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );        
	remove_action( 'wp_head', 'start_post_rel_link', 10, 0 ); 
}
add_action('init','clean_wp');

function theme_parse_image($param,$default,$tourl){
	$image_url = array();
	if(!is_null($default)){
		if($tourl){
			$image_url['media']=THEME_IMAGES.'/'.$default;
			$image_url['method'] = 'url';
		}else{
			$image_url['media']=THEME_IMAGES_DIR.'/'.$default;
			$image_url['method']='dir';
		}
	}
	if(empty($param))
		return $image_url;
	$image_json = (array)json_decode(stripslashes($param),true);
	if(empty($image_json)){
		$image_url['media'] = $param;
		$image_url['method'] = 'url';
	}elseif(is_array($image_json)){
		$image_url = $image_json;
		if($image_json['method']=='form' && $tourl){
			$image_src = @wp_get_attachment_image_src($image_json['media'],'full', true);
			$image_url['media'] = $image_src[0];
			$image_url['method'] = 'url';
		}
	}
	return $image_url;
}
function theme_get_all_category($separator = '' , $post_id){
	global $wp_rewrite;
	$categories = get_the_category($post_id);
	$i = 0;
	$thelist = '';
	$rel = ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) ? 'rel="category tag"' : 'rel="category"';
	foreach ( $categories as $category ) {
		if ( 0 < $i )
			$thelist .= $separator;
		$thelist .= '<a href="' . get_category_link( $category->term_id ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>' . $category->name.'</a>';
		++$i;
	}
	return $thelist;
}
function theme_maybe_process_contact_form(){
	$submit_contact_form = isset($_POST["theme_contact_form_submit"]) ? $_POST["theme_contact_form_submit"] : 0;
	if($submit_contact_form){
		require_once(THEME_FUNCTIONS.'/email.php');
		exit;
	}
}
add_action('wp', 'theme_maybe_process_contact_form', 9);

add_action('init', 'theme_exclude_from_search');
function theme_exclude_from_search(){
	global $wp_post_types;
	$post_types = theme_get_option('advance','exclude_from_search');
	if(!empty($post_types)){
		foreach($post_types as $post_type){
			$wp_post_types[$post_type]->exclude_from_search = true;
		}
	}
}


class Theme_Walker_Nav_Menu extends Walker_Nav_Menu {
	function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

		if ( !$element )
			return;

		$id_field = $this->db_fields['id'];

		if ( is_object( $args[0] ) ) {
			$args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
		}
		return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
	}
}

class Theme_The_Excerpt_Length_Constructor {
	var $length;
	function __construct($length) {
		$this->length = $length;
	}
	function get_length(){
		return $this->length;
	}
}


add_action( 'wp_head', 'theme_wpmu_signup_stylesheet',1 );
function theme_wpmu_signup_stylesheet() {
	remove_action( 'wp_head', 'wpmu_signup_stylesheet');
	?>
	<style type="text/css">
		.mu_register { margin:0 auto; }
		.mu_register form { margin-top: 2em; }
		.mu_register .error,.mu_register .mu_alert { 
			-webkit-border-radius: 1px;
			-moz-border-radius: 1px;
			border-radius: 1px;
			border: 1px solid #bbb;
			padding:10px;
			margin-bottom: 20px;
		}
		.mu_register .error {
			background: #FDE9EA;
			color: #A14A40;
			border-color: #FDCED0;
		}
		.mu_register input[type="submit"],
			.mu_register #blog_title,
			.mu_register #user_email,
			.mu_register #blogname,
			.mu_register #user_name { width:100%; font-size: 24px; margin:5px 0; }
		.mu_register .prefix_address,
			.mu_register .suffix_address {font-size: 18px;display:inline; }
		.mu_register label { font-weight:700; font-size:15px; display:block; margin:10px 0; }
		.mu_register label.checkbox { display:inline; }
		.mu_register .mu_alert { 
			background: #FFF9CC;
			color: #736B4C;
			border-color: #FFDB4F;
		}
	</style>
	<?php
}


// before wp-signup.php and before get_header()
add_action('before_signup_form', 'theme_before_signup_form');
function theme_before_signup_form () {

	$output = '<div id="feature">';
	$output .= '<div class="top_shadow"></div>';
	$output .= '<div class="inner">';
	$output .= '<h1>Sign Up Now</h1>';
	$output .= '</div>';
	$output .= '<div class="bottom_shadow"></div>';
	$output .= '</div>';
	
	$output .= '<div id="page">';
	$output .= '<div class="inner">';
	echo $output;
}

// after wp-signup.php and before get_footer()
add_action('after_signup_form', 'theme_after_signup_form');
function theme_after_signup_form () {
	echo '</div>';
	echo '<div id="page_bottom"></div>';
	echo '</div>';
}

if(!function_exists("get_the_author_posts_link")){
	function get_the_author_posts_link(){
		return '<a href="' . get_author_posts_url(get_the_author_meta( 'ID' )) . '" title="' . esc_attr( sprintf(__("Visit %s&#8217;s all posts"), get_the_author()) ) . '" rel="author">' . get_the_author() . '</a>';
	}
}
function is_shortcode_dialog() {
	if(isset($_GET['action']) && $_GET['action']=='theme-shortcode-dialog'){
		return true;
	}else{
		return false;
	}
}

