<?php

/*

# CloudFW Main FrameWork Functions
# Author: Orkun Gürsel - contact@orkungursel.com - support@cloudfw.net

*/

if (file_exists( TEMPLATEPATH . '/cloudfw/inc/core/core.skin_engine.php' )
&&	file_exists( TEMPLATEPATH . '/cloudfw/inc/core/core.only_admin.php' )
&&	file_exists( TEMPLATEPATH . '/cloudfw/inc/core/core.content_maps.php' )
&&	file_exists( TEMPLATEPATH . '/cloudfw/inc/core/core.translate.php' )
){
	require(TEMPLATEPATH . '/cloudfw/inc/core/core.translate.php');
	require(TEMPLATEPATH . '/cloudfw/inc/core/core.skin_engine.php');
	require(TEMPLATEPATH . '/cloudfw/inc/core/core.content_schemes.php');
	require(TEMPLATEPATH . '/cloudfw/inc/core/core.content_maps.php');
	
	/*Only Admin Area*/
	if (is_admin())
		require(TEMPLATEPATH . '/cloudfw/inc/core/core.only_admin.php');
		
	/*---------------*/
}
else{
	_e('CloudFw core files cannot found','cloudfw');
	exit;
};

/**
 *	Get CloudFw Options
 *
 *	@since 1.0
**/
function getCO($section = 'theme', $additional = TRUE, $force = FALSE) {
    
	if (!$additional)
		static $config;
		
	if (empty($section))
		$section = 'theme';
    
    if (empty($config) || $force) {
		
		$config = array();
		
		# Get Options Of The Modules
		$additional_options = array( PFIX.'_skin_ids', PFIX.'_slider_ids', PFIX.'_custom_sidebars', PFIX.'_page_ids', PFIX.'_last_checked_version' );
		
		if ($additional):
		
			if (is_array($additional))
				$additional_options = array_merge($additional_options, $additional);
			elseif (is_string($additional))
				$additional_options[] = $additional;
			
			foreach( $additional_options as $additional_option )
				$config[$additional_option] = get_option($additional_option);
		
		endif;
		
		# Theme Options		
    	$map = apply_filters("cloudfw_options", cloudfw_get_content_maps($section));
		$options = get_option(PFIX.'_options');
		
		

        foreach ((array) $map as $option => $default) {
            if (empty($options[$option])):
                $config[$option] = $default;
            else:
                $config[$option] = loop_get_defaults($map[$option], $options[$option]);
            endif;
        }

    } 
		
return $config;
    
}

/**
 *	Get A CloudFw Option
 *
 *	@since 1.0
**/
function get_cOption($option = NULL, $sub_option = NULL, $pfix = TRUE) {
    global $_opt;
	if (!$_opt)
		$_opt = getCO();
	
	if ($sub_option)
		 return $_opt[$pfix ? PFIX.'_'.$option:$option][$sub_option];
		
    return $_opt[$pfix ? PFIX.'_'.$option:$option];
}

/**
 *	Loops Data
 *
 *	@since 1.0
**/
function loop_get_defaults($default, $data, $level = 0, $current_level = 0){
	$current_level++;
	
    if (is_array($default)) {
        foreach ($default as $def_arr_key => $def_arr_val) {
            if (!isset($data[$def_arr_key]))
                $data[$def_arr_key] = $def_arr_val;
            
			if (@$data[$def_arr_key][0])
				$data[$def_arr_key] = $data[$def_arr_key];
			else
				$data[$def_arr_key] = loop_get_defaults($default[$def_arr_key], $data[$def_arr_key], $level, $current_level);
            
        }
        
    } 
    return $data;
}

/**
 *	CloudFw Save All Options
 *
 *	@since 1.0
**/
function cloudfw_save_options( $section = NULL ){
	
	if (empty($section))
		$section = 'theme';

    $map = cloudfw_get_content_maps($section);

	$options = array();
	if ($section !== 'setup'):
    foreach ((array) $map as $main_option => $default) {
		
		if ( is_array( $default ) &&  !empty( $default ) ) {
			
			foreach ( $default as $sub_option => $sub_default ) {
				
				
				$var = ( $_REQUEST[ cloudfw_PV_make_form_name($main_option, $sub_option) ] );
				$is_defined = ( $_REQUEST[ cloudfw_PV_make_form_name('is_defined_'.$main_option, $sub_option) ] );
				if (!isset($var) &&  !isset($is_defined) )
					continue;
					
				if ($is_defined == 'onoff' && empty($var))
					$var = 'FALSE';
				
				if (!is_array($var)) $var = stripslashes($var);					
				$out_attr[$sub_option] = !empty($var) ? $var : $sub_default;
				
			}
			
			if (isset($out_attr)) $options[$main_option] = $out_attr;
			$out_attr = NULL;
			
		}else{
			
			$var = ( $_REQUEST[ cloudfw_PV_make_form_name($main_option) ] );
			$is_defined = ( $_REQUEST[ cloudfw_PV_make_form_name('is_defined_'.$main_option) ] );
			if (!isset($var) && !isset($is_defined) )
				continue;
			
			if ($is_defined == 'onoff' && empty($var))
				$var = 'FALSE';
			
			if (!is_array($var)) $var = stripslashes($var);
			$options[$main_option] = ! empty($var) ? $var : $default;
			
		}
		
		
    } // foreach
	
	else:
	
		$options = $map;
	
	endif;
		
		$old_options = getCO($section, FALSE, TRUE);
		$options = cloudfw_array_merge($old_options, $options);
	
	update_option(PFIX.'_options', $options);
    cloudfw_get_ahook("cloudfw_hook_save_options");
	
	return $options;
}

/**
 *	CloudFw Update An Option
 *
 *	@since 1.0
**/
function cloudfw_update_option( $option, $value = NULL, $section = 'theme' ) {

	if (!is_array($option))
		$options[$option] = $value;
	else
		$options = $option;

	$old_options = getCO($section, FALSE, TRUE);
	$options = cloudfw_array_merge($old_options, $options);	

	update_option(PFIX.'_options', $options);
	return $options;
}


/**
 *	CloudFw Reset Options To Defaults
 *
 *	@since 1.0
**/
function cloudfw_reset_options(){
	return cloudfw_save_options('setup');	
}

/**
 *	Prepares Variables For Extracting
 *
 *	@since 1.0
**/
function cloudfw_make_var($pairs, $atts){
  $atts = (array)$atts;
  $out = array();
  foreach($pairs as $name => $default) {
		   if ( array_key_exists($name, $atts) )
				$out[$name] = $atts[$name];
		 else
				$out[$name] = $default;
	}
	return $out;
}

/**
 *	Merge Array With Multi Level
 *
 *	@since 1.0
**/
function cloudfw_array_merge($arr1 = array(), $arr2 = array()) {
	
	foreach((array) $arr1 as $option => $old) {
		if ( (!isset($arr2[$option])) ) {
			# No New Option
			$arr2[$option] = $old;	
			
		}
					
		# New Option
		if ($arr1[$option][0] || $arr2[$option][0])
			$arr2[$option] = $arr2[$option];
		else
			$arr2[$option] = loop_get_defaults($arr1[$option],$arr2[$option]);
			
	}

    return $arr2;
	
}

/**
 *	Inline Conditional
 *
 *	@since 1.0
**/
function _isso($cond = NULL , $is_true = NULL, $is_false = NULL, $echo = FALSE){
	$out = ($cond) ? $is_true : $is_false;
	if ($echo) echo $out; else; return $out;
}

/**
 *	Check is On or Off
 *
 *	@since 1.0
**/
function _isOnOff($val = NULL){
	return ($val !== "FALSE") ? TRUE: FALSE;
}

function cloudfw_get_ahook($hook, $var_1 = NULL, $var_2 = NULL){
	if(function_exists($hook)) return $hook($var_1, $var_2);
	return false;
}

/**
 *	Check is need for update
 *
 *	@since 1.0
**/
function is_need_update() {
	static $cache_theme_version;
	
	if ($cache_theme_version) 
		return $cache_theme_version;
	
	global $_opt;

	if (!_isOnOff($_opt[PFIX."_cloudfw_actives"]["autocheck"]) || (!function_exists("is_multisite")) || ( !is_super_admin() && is_multisite() ) )
		return false;
	
	if ( ( $the_version = get_option(PFIX.'_version') ) ) {
		
		$_last_checked_version = get_option(PFIX.'_last_checked_version');

		if (version_compare(CLOUD_THEMEVERSION /*Now*/, $the_version/*Last Version*/, '<') && $_last_checked_version !== $the_version) {
			$cache_theme_version = $the_version;
			return $the_version;
		}
	}	
	
	return false;
}

/**
 *	Check whether the folder is writable
 *
 *	@since 1.0
**/
function is__writable($path) {

	if ($path{strlen($path)-1}=='/')
		return is__writable($path.uniqid(mt_rand()).'.tmp');
	
	if (file_exists($path)) {
		if (!($f = @fopen($path, 'r+')))
			return false;
		fclose($f);
		return true;
	}
	
	if (!($f = @fopen($path, 'w')))
		return false;
	fclose($f);
	unlink($path);
	return true;
}


/**
 *	CloudFw Get Home URL
 *
 *	@since 1.0
**/
function cloudfw_home_url(){
	
	if ( (defined('MULTISITE')) && (MULTISITE == true) )
		return get_blogaddress_by_id(1);
	else
		return get_bloginfo('url');
	
}

/**
 *	CloudFw Get Ajax URL
 *
 *	@since 1.0
**/
function cloudfw_ajax_url(){

	$url = 'admin-ajax.php';

	if ( defined('ICL_LANGUAGE_CODE') )
		$url .= '?lang='.ICL_LANGUAGE_CODE;
	elseif (isset($GLOBALS['q_config']['language']))
		$url .= '?lang='.$GLOBALS['q_config']['language'];

	return admin_url($url);
}

/**
 *	CloudFw Thumbnails
 *
 *	@since 1.0
**/
function cloudfw_thumbnail($data){
	
	extract(cloudfw_make_var(array(
		'src'	=> NULL,
		'w'		=> NULL,
		'h'		=> NULL,
		'r'		=> NULL,
		'q'		=> NULL,
		'cache'	=> 1,		
	), $data));	
	
	if (!is_array($data)) return $data;

	if ( (defined('MULTISITE')) && (MULTISITE == true) ) {
		global $blog_id;
	
		
		$image_path = explode($_SERVER['SERVER_NAME'], $src);	
		$image_path = $_SERVER['DOCUMENT_ROOT'] . $image_path[1];
			
			$the_image_src = $src;
			if (isset($blog_id) && $blog_id > 0) {
				$image_parts = explode('/files/', $the_image_src);

				if (isset($image_parts[1])) {
					$the_image_src = '/blogs.dir/' . $blog_id . '/files/' . $image_parts[1];
					$src = get_blogaddress_by_id(1).'/wp-content' .$the_image_src;
				}
			}
		
		}
	
	$url = NULL;$url .= TMP_URL."/image.php?";
	if($w) 		$url .= "w=$w&amp;";
	if($h) 		$url .= "h=$h&amp;";
	if($r) 		$url .= "zc=$r&amp;";
	if($q) 		$url .= "q=$q&amp;";
				$url .= "src=$src";
	if(!$cache)	$url .= "&amp;";

	
	return $url;
	
}

/**
 *	Check if the cURL PHP extension is loaded
 *
 *	@since 1.0
**/
function is_support_curl() {
	return in_array('curl', get_loaded_extensions());
}

define('MFUN', 'Y19zX2Y=');

/**
 *	CloudFw Get Admin Panel URL
 *
 *	@since 1.0
**/
function cloudfw_admin_url($tab = NULL, $jump = NULL){
	global $theme_setting_slug;
	$url  = 'admin.php?page='.$theme_setting_slug;
	if ($tab) $url .= '&tab='.$tab;
	if ($jump) $url .= '&jump='.$jump;
		
	return admin_url($url);
}

/**
 *	CloudFw Fatal Error Messages
 *
 *	@since 1.0
**/
function cloudfw_fatalError($message){
	return "<div class=\"cloudfw-fatal-error\"><strong>".__('Error','cloudfw')."</strong>: {$message}</div>";
}

/**
 *	CloudFw File Cache
 *
 *	@since 1.0
**/
function cloud_cache_write(
	   $data,
	   $file,
	   $cfile,
	   $cache = true
	   ){
	
		if ($cache && !@fopen($cfile, 'w+')) {return $data;}
	
		$fp = fopen($cfile, 'w+');
		@fwrite($fp, $data);
		@fclose($fp);
		
		if (file_exists($file)):	
			@copy($cfile,$file);
			@unlink($cfile);
		else:
			@rename($cfile,$file);
		endif;
		
		return $file;	
};

/**
 *	CloudFw Delete File Cache
 *
 *	@since 1.0
**/
function cloud_cache_delete( $file ){
	
	$upload_dir = wp_upload_dir();
	$upload_dir = $upload_dir["basedir"]."/";
	$file = "".$upload_dir."".$file;

	if (!@fopen($file, 'w+')) {return false;}

	@unlink($file);
	
};
			
		
/**
 *	CloudFw File Cache Init
 *
 *	@since 1.0
**/		
function cloud_cache(
		 $function=NULL,
		 $file=NULL,
		 $thetime=10800,
		 $force = FALSE
				 ){
	
$upload_dir = CLOUD_UPLOAD_DIR;
($thetime)? NULL : $thetime = 3600;


$cachefile = "".$upload_dir."".$file;
$copy_cachefile = "".$upload_dir."copy_".$file;


if (file_exists($cachefile) && !$force){
	
	if (time() - $thetime < filemtime($cachefile)){
		
		//if read from the cache file
		//echo "there is the file and is read from the cache<br/>";
		
		return file_get_contents($cachefile);
		}
	else
	{	
		//if need to write cache file
		//echo "there is the file but its time is over<br/>";
		
		if (is_array($function)){
			
			$func = $function[0];
			$args = $function[1];
			
			$data = $func($args);
			}
		else{
			$data = $function();
		}
		
		if (empty($data) || $data == '%nocache%') {
			return 'No Data';
			}
		
		cloud_cache_write($data, $cachefile, $copy_cachefile);
		return $data;
		
	};
}
else
{
		//if need to write cache file
		//echo "there is no the file<br/>";
		
		if (is_array($function)){
			
			$func = $function[0];
			$args = $function[1];
			
			$data = $func($args);
			}
		else{
			$data = $function();
		}
		
		if (empty($data) || $data == '%nocache%') {
			return 'No Data';
			}
		
		cloud_cache_write($data, $cachefile, $copy_cachefile);
		return $data;
	};
							
};


function cloudfw_get_page_link($data){
	if (empty($data)) return false;
	
	if(strstr($data,"||")){
		$data = explode('||', $data);
		return esc_attr($data[1]);
		}
		else{
		return esc_attr($data);
		}
	
}
	
function cloudfw_get_page_id($data){
	if (empty($data) || !strstr($data,"||")) return false;
	
	$data = explode('||', $data);
	return (int) $data[2];
}
	
function cloudfw_excluding_page($out = array()){
	global $_opt;
	$out = (array) $out;
	$out[] = get_option("cloud_created_att_page");
	return $out;
}

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

	
function make_blurb (){
		global $wp_query;
		
		
		if (!$wp_query) return false;
			
		$metas = get_post_meta($wp_query->queried_object->ID, false);			
		$blurb = isset($metas[PFIX.'_blurb'][0]) ? $metas[PFIX.'_blurb'][0] : NULL;
		$blurb_title = isset($metas[PFIX.'_blurb_title'][0]) ? $metas[PFIX.'_blurb_title'][0] : NULL;
		$blurb_text = isset($metas[PFIX.'_blurb_text'][0]) ? $metas[PFIX.'_blurb_text'][0] : NULL;
		$blurb_alignment = isset($metas[PFIX.'_blurb_alignment'][0]) ? $metas[PFIX.'_blurb_alignment'][0] : NULL;
		
		if (($blurb !== "FALSE")) {
			$breadcrumble = '';
			$blurb_text =	$blurb_text ? '<span class="sub-text">'.$blurb_text.'</span>':NULL ;
			
			if (function_exists('bcn_display')) {
				if (!is_front_page())
					$breadcrumble = bcn_display(true);
			}
			
			return '
				<div id="blurb">
				
					'._isso( !empty($blurb_title), 
							 '<h1>'.$blurb_title.'</h1>',
							 '<h1>'.$breadcrumble.'</h1>' 
						   ).'
					
				</div>
				<!-- / .blurb -->
			';

		}
}

	
function cloudfw_bookmark_it($dim = NULL, $services = NULL, $link = NULL, $title = NULL){
	global $_opt;
	$social_services = cloudfw_social_services();
	
	if (empty($dim)) $dim = $_opt[PFIX."_blog_social_icon_size"];
	
	switch ($dim){
		case 'small':
		default:
			$size = "-16x16";
		break;
		case 'big':
			$size = "-24x24";
		break;
		}
	
	if (!$link) $link = __url( get_permalink(FALSE) );
	if (!$title) $title = __translate( get_the_title() );
	
	if (!is_array($services)) $intended_social_services = $_opt[PFIX."_blog_social_services"]; else $intended_social_services = $services;
	$social_services_icons_dir = TMP_ADMIN_SRC. "/social_icon";
                        
	if (is_array($intended_social_services)){
		
		foreach ($intended_social_services as $service){
	
			if (!empty($social_services[$service])){
		
				$out .= sprintf (
					"<a href=\"%s\" rel=\"nofollow\" target=\"_blank\" class=\"tooltip\" title=\"".sprintf(__('Share On %s','cloudfw'), $social_services[$service]["item_name"])."\" ><img src=\"$social_services_icons_dir/".$service."$size.png\"/></a>",
					sprintf (
							$social_services[$service]["item_regex"], //	format
							urlencode($link),
							urlencode($title)
						)
				);
				
			} // is_empty
			
		} // foreach
		
		return $out;
		
	} //is_array

} // cloudfw_bookmark_it




function cloudfw_find_gridclass($loop,$current){
	
	if ($current == $loop) {
		
		return ' cl_'.$loop.' last';
		
		}else{
			
		return ' cl_'.$loop;
		
	}
	
}

function cloudfw_randomizer($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}



function cloudfw_sc99($d){
	return @base64_decode($d);
}

function cloudfw__sc99($d){
	return @base64_encode($d);
}

function cloudfw_sc95($d){
	return @md5($d);
}

	
	
function facebook_like_button($url = NULL){
	if (!$url) $url = __url( get_permalink() );
	return '
	<iframe src="http://www.facebook.com/plugins/like.php?href='.urlencode($url).'&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe>
	';
	
	}
	
	

function remove_old_cache_files() {
	
	if ($handle = @opendir(CLOUD_UPLOAD_DIR)) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && 
				
				(
				 strpos($file, 'twitter_cache_') !== false ||
				 strpos($file, 'ga_cache_') !== false
						)
			) {
				@unlink(CLOUD_UPLOAD_DIR."/$file");
			}
		}
		closedir($handle);
	}
	
}

function cloudfw_get_icon_folders($icon_folder) {
	if (!$icon_folder) return false;
	
	if ($handle = @opendir($icon_folder)) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && 
				(
				 is_dir($icon_folder.$file)
				)
			) {
				$out[] = $file;
			}
		}
		closedir($handle);
	}
	
	return $out;
	
}

function cloudfw_make_icon_url($url) {
	static $icon_folder;
	if (!isset($icon_folder)) $icon_folder = TMP_URL.'/lib/icons/';
	return $icon_folder.$url;
}

function cloudfw_get_icon_files() {
	
	$icon_folder = TEMPLATEPATH.'/lib/icons/';
	$path = TMP_URL;
	$folders = cloudfw_get_icon_folders($icon_folder);

	if (is_array($folders)):

	foreach((array) $folders as $folder):
		//if (!is_dir($folder)) continue;
		
		if ($handle = @opendir($icon_folder.$folder)) {
			while (false !== ($file = readdir($handle))) {
				if ($file != "." && $file != ".." && 
					(
					 strpos($file, '.png') !== false ||
					 strpos($file, '.gif') !== false ||
					 strpos($file, '.jpg') !== false
					)
				) {
					$file_name = explode('.',$file);
					$out[$folder][$folder.'/'.$file] = $file_name[0];
				}
			}
			closedir($handle);
		}
	
	endforeach;
	
	endif;
	
	return $out;
	
}


function cloudfw_get_icons() {
	//delete_transient('cloudfw_icons');
	if (false === ( $icons = get_transient('cloudfw_icons') ) ) {
		 $icons = cloudfw_get_icon_files();
		 set_transient('cloudfw_icons', $icons, 2592000);
	}
	return $icons;
	
}




/**
 * @author Eric Martin <eric@ericmmartin.com>
 * @copyright Copyright (c) 2009, Eric Martin
 * @version 1.0
 */
function cloudfw_paginate($args = NULL) {
	$defaults = array(
		'page' => NULL, 'pages' => NULL, 
		'range' => 2, 'gap' => 1, 'anchor' => 1,
		'before' => '<ul class="blog-pagination">', 'after' => '</ul>',
		'title' => '',
		'nextpage' => __('Next','cloudfw'), 'previouspage' => __('Previous','cloudfw'),
		'echo' => 1
	);

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

	if (!$page && !$pages) {
		global $wp_query;

		$page = get_query_var('paged');
		$page = !empty($page) ? intval($page) : 1;

		$posts_per_page = intval(get_query_var('posts_per_page'));
		$pages = intval(ceil($wp_query->found_posts / $posts_per_page));
	}
	
	
	$output = "";
		
		if ($page > 1 && !empty($previouspage)) {
			$output .= "<div class='blog-pagination-previous-link'><a href='" . get_pagenum_link($page - 1) . "' class='sprite previous-link' title='".__('Newer Posts','cloudfw')."'>$previouspage</a></div>";
		}else {
			$output .= "<div class='blog-pagination-previous-link inactive'><span class='sprite previous-link'>$previouspage</span></div>";
		}
		
		$output .= "<div class='blog-pagination-center'>";
		
		$output .= "<div class='blog-pagination-summary'><h2><a href='javascript:void(0);' id='blog-pagination'>$page/$pages<span class='blog-pagination-arrow-container'><span class='blog-pagination-arrow'></span></span></h2></a></div>";
		
		$output .= $before;
		if($title) $output .= "<li><span class='blog-pagination-title'>$title</span></li>";
		$ellipsis = "<li class='blabla'>...</li>";
		
		$min_links = $range * 2 + 1;
		$block_min = min($page - $range, $pages - $min_links);
		$block_high = max($page + $range, $min_links);
		$left_gap = (($block_min - $anchor - $gap) > 0) ? true : false;
		$right_gap = (($block_high + $anchor + $gap) < $pages) ? true : false;

		if ($left_gap && !$right_gap) {
			$output .= sprintf('%s%s%s', 
				cloudfw_paginate_loop(1, $anchor), 
				$ellipsis, 
				cloudfw_paginate_loop($block_min, $pages, $page)
			);
		}
		else if ($left_gap && $right_gap) {
			$output .= sprintf('%s%s%s%s%s', 
				cloudfw_paginate_loop(1, $anchor), 
				$ellipsis, 
				cloudfw_paginate_loop($block_min, $block_high, $page), 
				$ellipsis, 
				cloudfw_paginate_loop(($pages - $anchor + 1), $pages)
			);
		}
		else if ($right_gap && !$left_gap) {
			$output .= sprintf('%s%s%s', 
				cloudfw_paginate_loop(1, $block_high, $page),
				$ellipsis,
				cloudfw_paginate_loop(($pages - $anchor + 1), $pages)
			);
		}
		else {
			$output .= cloudfw_paginate_loop(1, $pages, $page);
		}

		$output .= $after;
		
		$output .= "</div>";		
		
		if ($page < $pages && !empty($nextpage)) {
			$output .= "<div class='blog-pagination-next-link'><a href='" . get_pagenum_link($page + 1) . "' class='sprite next-link' title='".__('Older Posts','cloudfw')."'>$nextpage</a></div>";
		}else {
			$output .= "<div class='blog-pagination-next-link inactive'><span class='sprite next-link'>$nextpage</span></div>";
		}
		
		$output .= "<div class='cf'></div>";
		

	if ($echo) {
		echo $output;
	}

	return $output;
}

/**
 * @author Eric Martin <eric@ericmmartin.com>
 * @copyright Copyright (c) 2009, Eric Martin
 * @version 1.0
 */
function cloudfw_paginate_loop($start, $max, $page = 0) {
	$output = "";
	for ($i = $start; $i <= $max; $i++) {
		$output .= ($page === intval($i)) 
			? "<li class='current'><span>$i</span></li>" 
			: "<li><a href='" . get_pagenum_link($i) . "' class='emm-page'>$i</a></li>";
	}
	return $output;
}




function cloudfw_font_engine( $id = NULL ) {
	echo get_cloudfw_font_engine($id);
}

function cloudfw_get_font_data( $force = FALSE ) {
	static $font_data;
	if (empty($font_data) || $force):
		$font_data = cloudfw_prepare_skin_data( cloudfw_get_content_maps("font_map"), get_option(PFIX.'_font_engine') );
	endif;
	return $font_data;
}

function cloudfw_get_fonts( $force = FALSE ) {
	static $fonts;
	if (empty($fonts) || $force):
		$fonts = get_option(PFIX.'_fonts');
		if (empty($fonts) || !is_array($fonts))
			$fonts = array('BebasNeueRegular');
	endif;
	return $fonts;
}

function get_cloudfw_font_engine( $id = NULL ) {
	global $_opt, $custom_fonts, $google_fonts;
	$fonts = cloudfw_get_fonts();
	$load_google_fonts = $load_custom_fonts = '';
	
	if (is_array($fonts)){
	
		foreach ($fonts as $font_id) {
			 if (in_array($font_id, $google_fonts)) {
				//Google Font	 
				$load_google_fonts[] = $font_id;
			}elseif (isset($custom_fonts[$font_id])) {
				//Custom Font	 
				$load_custom_fonts[] = $font_id;
			}
			
		} // foreach: fonts
		
	}else {return false;}
	

	if ( is_array($load_google_fonts) ) {
		
		foreach ($load_google_fonts as $load_google_fonts => $g_font) {
			
			$out_google_fonts .= '"'.$g_font.'",';
		
		} // foreach: load_google_fonts
			
		$out_google_fonts = '
		google: {
		  families: [ '.substr($out_google_fonts,0,-1) .' ]
		},
		';
	}
	
	$out_custom_fonts = $out_google_fonts = '';
	if (is_array($load_custom_fonts)) {
		$out_custom_font_families = $out_custom_font_csses = '';

		foreach ($load_custom_fonts as $load_custom_fonts => $c_font) {
			
			$out_custom_font_families .= '"'.$c_font.'",';
			$out_custom_font_csses .= '"'.FONTS_DIR.$custom_fonts[$c_font]["css"].'",';
			
		} // foreach: load_google_fonts
			
		$out_custom_fonts = '
		custom: {
			families: [ '.substr($out_custom_font_families,0,-1).' ],
			urls : [ '.substr($out_custom_font_csses,0,-1).' ]
		 },
		';
	}
		

$out = '
	
    <!-- Load Fonts -->
	<script type="text/javascript">
		WebFont.load({
		  '.$out_custom_fonts.''.$out_google_fonts.'
		  fontinactive: function(fontFamily, fontDescription) {
			//alert("Font Cannot Loaded: "+ fontFamily);
		  }

		});		
    </script>';

	return $out;
}

function cloudfw_comments_open(){
	global $_opt;
	return _isOnOff($_opt[PFIX.'_blog_actives']['comments']);
}


function cloudfw_make_slider_for_blog($id, $url, $class = NULL){
	
	$gallery = $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order') );
	
	if (is_array($attachments)):
	
	if (is_single()) $class = 'next';
	
	foreach ($gallery as $gal_id => $gal) {
		
		 $title	= 	$gal -> post_title;
		 $desc	= 	$gal -> post_content;
		
		 $thumbnail = wp_get_attachment_image_src($gal_id, 'post-thumbnail', TRUE );
		 $thumbnail_src = $thumbnail[0];
		 $width = $thumbnail[1];
		 $height = $thumbnail[2];

		 if ($width < 640) {
		 	$ratio = (640 / $width);
		 	$width = 640;
			$height = floor($height * $ratio);
		 }
		 		 
		 $out .= "				  
		   <a href=\"$url\" class=\"$class\"> <img title=\"$title\" alt=\"$desc\" src=\"$thumbnail_src\" width=\"$width\" height=\"$height\"></a>
		 ";
		 
		}
	
	endif;
	
	return "<div class=\"slides_container\">$out</div>";
}




function archive_titles(){
	global $post;

	if (is_single()) {
		return array(
			'blog_layout' 	=> false,
			'title' 		=> false,
			'text'		 	=> false
		);
		
	}elseif (is_category()) {
		return array(
			'blog_layout' 	=> false,
			'title' 		=> __('Category','cloudfw').':',
			'text'		 	=> single_cat_title('', false)
		);
	}elseif (is_author()) {
		return array(
			'blog_layout' 	=> 'minimal',
			'title' 		=> __('Author','cloudfw').':',
			'text'		 	=> get_the_author()
		);
	}elseif (is_tag()) {
		return array(
			'blog_layout' 	=> 'minimal',
			'title' 		=> __('Tag','cloudfw').':',
			'text'		 	=> single_tag_title( '', false )
		);
	}elseif (is_search()) {
		return array(
			'blog_layout' 	=> 'minimal',
			'title' 		=> __('Search Results For','cloudfw').':',
			'text'		 	=> '"'.get_search_query().'"'
		);
	}elseif (is_archive()) {		
					
			if ( is_day() ) $text = get_the_date();
			elseif ( is_month() ) $text = get_the_date('F / Y');
			elseif ( is_year() ) $text = get_the_date('Y');
		
		return array(
			'blog_layout' 	=> 'minimal',
			'title' 		=> __('Archives','cloudfw'),
			'text'		 	=> $text
		);
			

	}	


}


function cloudfw_get_image_width($column) {
	$portfolio_image_defaults[1] = 410;
	$portfolio_image_defaults[2] = 410;
	$portfolio_image_defaults[3] = 260;
	$portfolio_image_defaults[4] = 185;	
	$portfolio_image_defaults[5] = 140;	
	$portfolio_image_defaults[6] = 110;	
	
	return $portfolio_image_defaults[$column];
}


function get_sidebar_defaults($sidebar){
	
	$def = array('before_title' => '<h3 class="sidebar-widget-title">','after_title' => '</h3>');
	
	switch($sidebar){
		default:
		case 'primary-widget-area':

						 the_widget('WP_Widget_Meta', NULL, $def);
						 the_widget('WP_Widget_Calendar', array('title' => 'Calender'), $def);
					
		break;
		case 'archive-widget-area':
		
			if ( ! dynamic_sidebar( 'primary-widget-area' ) ) {
			
			 			 the_widget('WP_Widget_Search', NULL, $def);
						 the_widget('WP_Widget_Calendar', array('title' => 'Calender'), $def);
			}
			
		break;	
		case 'searchpage-widget-area':
			
			 			 the_widget('WP_Widget_Search', NULL, $def);
						 the_widget('WP_Widget_Calendar', array('title' => 'Calender'), $def);
						 
		break;	
		
	}
	
}

function cloudfw_less_text($text = NULL, $count = 50, $after = '..') {
	if(empty($text)) return false;
	$text_length = strlen($text);
	return ($text_length > $count) ? mb_substr($text,0,$count).$after:$text;
}


/*********************************
*
*	@ Orkun Gursel
*	Slider Functions
*	Since 1.0
*
**********************************/

// Call Slider Function
function cloudfw_get_slider($id) {

	$slider = get_option($id);
	return $slider;

}

// Call Slider Options Function
function cloudfw_get_slider_options($id = NULL) {
	if (!isset($id)) return false;
	
	global $_opt;
	$slider_ids = $_opt[PFIX.'_slider_ids'];
	
	$options = isset($slider_ids[$id]) ? $slider_ids[$id] : NULL;
	return $options;
}

// Call Slider Type Function
function cloudfw_get_slider_type($id = NULL) {
	if (!isset($id)) return false;
	
	global $_opt;
	$slider_ids = $_opt[PFIX.'_slider_ids'];
	$type = isset($slider_ids[$id]["type"]) ? $slider_ids[$id]["type"] : NULL;
	return $type;
}

// Create Function
function cloudfw_create_slider($atts = array(), $reg_a_page = NULL) {
	$_opt = getCO('theme', TRUE, TRUE);
	
	$slider_types = cloudfw_sliders();
	
	extract(cloudfw_make_var(array(
		'id'				=> NULL,
		'title'				=> NULL,
		'type'				=> NULL,
		'default_height'	=> 400,
	), $atts));	
	
	$random_id = cloudfw_randomizer(20);
	
	if (empty($title))
		$atts["title"] = __('(Untitled) '.$slider_types[$type]["name"].'','cloudfw');
		
	if (empty($id))
		$id = $random_id;
	
	if (!$type) $atts["type"] = cloudfw_get_slider_type($id);
	
	$new_slider[$id] = $atts;
	
	$slider_ids = $_opt[PFIX.'_slider_ids'];
	if (empty($id)) 
		is_array($slider_ids) ? $slider_ids += $new_slider: $slider_ids = $new_slider;
	else
		$slider_ids[$id] = $new_slider[$id];
	
	update_option(PFIX.'_slider_ids', $slider_ids);
	
	
	if ($reg_a_page) {
		$old_val = get_post_meta($reg_a_page, PFIX.'_slider_id', TRUE);
		if (empty($old_val)) add_post_meta($reg_a_page, PFIX.'_slider_id', $id); else; update_post_meta($reg_a_page, PFIX.'_slider_id', $id, $old_val);	
	
	}
	
	delete_transient('cloudfw_slider_'.$id);
	return $id;
}

// Delete Function
function cloudfw_delete_slider($id = NULL) {
	if (!isset($id)) return false;
	
	global $_opt;
	$slider_ids = $_opt[PFIX.'_slider_ids'];
	unset($slider_ids[$id]);
	
	update_option(PFIX.'_slider_ids', $slider_ids);
	delete_option($id);
	return $slider_ids;
}

// Call Slider Into Header
function get_the_slider($id = NULL) {
	global $post, $wp_query;

	if (empty($id) && $wp_query->queried_object->ID) {$id = get_post_meta( $wp_query->queried_object->ID , PFIX.'_slider_id', TRUE);}
	
	$type = cloudfw_get_slider_type($id);
	$slider_options = cloudfw_get_slider_options($id);
	$slider_data = cloudfw_get_slider($id);
		
	/* Get Sliders Options */
	if (is_array($slider_data)) {
		echo '<div id="slider">';
			if (file_exists(TMP_INCLUDES."/sliders/$type.php")) {
				 include(TMP_INCLUDES."/sliders/$type.php");
				}
		echo '</div><!-- /#slider -->';
		return true;
	}
	else return false;
	
}


// Call Slider Into Pages
function cloudfw_get_the_slider($atts = array()) {
	/* Get Sliders Options */
	
	$id = $atts["id"];
	$type = cloudfw_get_slider_type($id);
	
	if (empty($id)) 
		return cloudfw_fatalError(__('The Slider Cannot Found','cloudfw'));
	
	if (file_exists(TMP_INCLUDES."/sliders/{$type}.php")) include_once(TMP_INCLUDES."/sliders/{$type}.php"); else return '<br/><br/>'.cloudfw_fatalError(__('The Slider Cannot Found','cloudfw')).'<br/><br/>';
	$function = "get_{$type}_results";
	
	//if ($_GET["cache"] = "FALSE")
	 return $function($atts);
	
	/*if (false === ( $out = get_transient('cloudfw_slider_'.$id) ) ) {
		 $out = $function($atts);
		 set_transient('cloudfw_slider_'.$id, $out, 2592000);
	}*/
		
	return $out;
}


// Call Slider Source From A Post Gallery
function cloudfw_get_post_gallery_source($post_id = NULL){
	
	if (empty( $post_id ))
		return false;
	
	$gallery = $attachments = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order') );
	
	if (is_array($attachments)):
	
	foreach ($gallery as $gal_id => $gal) {
		
		$image = wp_get_attachment_image_src($gal_id, 'full', TRUE );
		$image_src = $image[0];			
		$out[] = array(
			'slider_image' =>  $image_src,
			'slider_title' =>  $gal -> post_title,
			'slider_caption' => $gal -> post_content
		);
		
	}
	
	endif;
	
	return $out;
	
}


/*********************************
*
*	@ Orkun Gursel
*	Skin Functions
*	Since 1.0
*
**********************************/

// Get All Skins Function
function cloudfw_get_all_skins() {
	return get_option(PFIX.'_skin_ids');
}

// Get Current Skin Function
function cloudfw_get_current_skin() {
	return get_option(PFIX.'_skin_engine');
}

// Get Current Skin Function
function cloudfw_get_current_skin_ID() {
	$current_skin = cloudfw_get_current_skin();
	return $current_skin['id'];
}

// Get A Skin Function
function cloudfw_get_a_skin($id = NULL) {
	if (!$id) return false;
	$skin = get_option($id);
	
	return (!empty($skin)) ? $skin: false;
}

// Creating/Deleting Function
function cloudfw_manage_skin_ID($id = NULL, $op = 'add', $data = array()) {
	$skin_ids = cloudfw_get_all_skins();
							
	switch ($op) {
	case 'add': default:
		$random_id = 'skin_'.cloudfw_randomizer(20);
		if (empty($id)) $id = $random_id;
		
		if (!in_array($id, (array)$skin_ids)){	
			$skin_ids[] = $id;

			update_option(PFIX.'_skin_ids', $skin_ids);
			
			if (!empty($data)) {
				$data["id"] = $id;
				update_option($id, $data);
			}
			
			return $id;
		}
		return false;
		
	break;
	case 'update':
		if (empty($id) || !in_array($id, (array)$skin_ids) ) 
			return;

		if (!empty($data)) {
			update_option($id, $data);
			return $id;
		}
	
		return false;
		
	break;
	case 'delete':

		$key = array_search($id,(array) $skin_ids);	

		if (isset($key)) {
			unset($skin_ids[$key]);
			$skin_ids = array_unique($skin_ids);

			update_option(PFIX.'_skin_ids', $skin_ids);
			delete_option($id);
			
			$currrent_skin_id = cloudfw_get_current_skin();
			if ($currrent_skin_id["id"] == $id)
				cloudfw_set_default_skins();
				
			return $id;

		}
		delete_transient(PFIX.'_cloudfw_skin');
		
		
		return false;
		
	break;
	case 'duplicate':
			
		$key = array_search($id,(array) $skin_ids);	
		
		if ($key) {
			
			$new_id = cloudfw_manage_skin_ID();
			$the_new_skin = cloudfw_get_a_skin($id);
			
			$the_new_skin["id"] = $new_id;
			$the_new_skin["name"] = __('Copy_','cloudfw').$the_new_skin["name"];
			
			update_option($new_id, $the_new_skin);
			return $id;
		}
		
		return false;
	
	break;
	}
	
}
// Skin Sync
function cloudfw_sync_skins($id = NULL, $force = FALSE){
	
	$currren_skin_id = cloudfw_get_current_skin();
	if ($currren_skin_id["id"] == $id || $force)
		update_option(PFIX.'_skin_engine' , get_option($id));
	delete_transient(PFIX.'_cloudfw_skin');
		
}

// Make Default
function cloudfw_set_default_skins(){
	$out = array(
		'mode' 		=> 'default', //custom
		'name' 		=> '',
		'css' 		=> '',
		'version' 	=> 0,
		'id'		=> 'default',
		'data'		=> cloudfw_get_content_maps("skin_map")
	);
	
	update_option(PFIX.'_skin_engine' , $out);
	delete_transient(PFIX.'_cloudfw_skin');
}

// Skin Changer
function cloudfw_change_skin($id = NULL) {
	$the_skin = get_option($id);
	$skin_ids = get_option(PFIX.'_skin_ids');
	
	if (in_array($id, (array)$skin_ids)) {
	
		cloudfw_sync_skins($id, TRUE);
		
	} else {
		
		$the_skin = array(
			'mode'	=>  'defined',
			'id'	=>	$id
		);
		update_option(PFIX.'_skin_engine' , $the_skin);
	
	}
	
	delete_transient(PFIX.'_cloudfw_skin');
	
	return $id;
	
}

// Get Custom Skin Logo
function cloudfw_get_custom_skin_logo($id = NULL) {
	if ($id)
		$data = cloudfw_get_a_skin($id);
	else{
		$data = get_option(PFIX.'_skin_engine');
	}
	
	return isset($data["data"]["custom"]["custom-logo"]) ? $data["data"]["custom"]["custom-logo"] : NULL;
}


// Get Custom Skin Logo
function cloudfw_get_custom_skin_css_code($id = NULL) {
	if ($id)
		$data = cloudfw_get_a_skin($id);
	else{
		$data = get_option(PFIX.'_skin_engine');
	}
	
	return $data["data"]["custom"]["custom-css"];
}

// Get Custom Skin Logo
function cloudfw_get_custom_skin_attr($id = NULL, $attr = NULL) {
	if ($id)
		$data = cloudfw_get_a_skin($id);
	else{
		$data = get_option(PFIX.'_skin_engine');
	}
	
	return isset($data["data"]["custom"][$attr]) ? $data["data"]["custom"][$attr] : NULL;
}

// Get Custom Skin Logo
function cloudfw_get_skin_data_instant( $id = NULL ) {
	//global $current_skin_id;
	$current_skin_id = cloudfw_get_the_skin_id();
	static $current_skin_data;

	if ($current_skin_id)
		$id = $current_skin_id;
	
	if(!empty($current_skin_data))
		return $current_skin_data;
	
	if ($id)
		$current_skin_data = cloudfw_get_a_skin($id);
	else{
		$current_skin_data = cloudfw_get_current_skin();
	}
	
	$current_skin_data['data'] = cloudfw_prepare_skin_data(cloudfw_get_content_maps("skin_map"), $current_skin_data['data']);
	return $current_skin_data;
}


function cloudfw_get_font_type($id){
	global $custom_fonts, $google_fonts, $default_fonts;

	if (in_array($id, $google_fonts)) {
		//Google Font	 
		return 'google';
	}elseif (isset($custom_fonts[$id])) {
		//Custom Font	 
		return 'custom';
	}elseif (in_array($id, $default_fonts)) {
		//Default Font	 
		return 'default';
	}
		
}





function wp_the_excerpt_reloaded($args='') {
	parse_str($args);
	if(!isset($excerpt_length)) $excerpt_length = 10; // length of excerpt in words. -1 to display all excerpt/content
	if(!isset($allowedtags)) $allowedtags = '<a>'; // HTML tags allowed in excerpt, 'all' to allow all tags.
	if(!isset($filter_type)) $filter_type = 'none'; // format filter used => 'content', 'excerpt', 'content_rss', 'excerpt_rss', 'none'
	if(!isset($use_more_link)) $use_more_link = 1; // display
	if(!isset($more_link_text)) $more_link_text = __('(more...)','cloudfw');
	if(!isset($force_more)) $force_more = 0;
	if(!isset($fakeit)) $fakeit = 1;
	if(!isset($fix_tags)) $fix_tags = 1;
	if(!isset($no_more)) $no_more = 1;
	if(!isset($more_tag)) $more_tag = 'div';
	if(!isset($more_link_title)) $more_link_title = __('Continue reading this entry','cloudfw');
	if(!isset($showdots)) $showdots = 1;
	if(!isset($strip_shortcodes)) $strip_shortcodes = 1;

	return the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $fix_tags, $no_more, $more_tag, $more_link_title, $showdots, $strip_shortcodes);
}

function the_excerpt_reloaded($excerpt_length=120, $allowedtags='<a>', $filter_type='none', $use_more_link=true, $more_link_text="(more...)", $force_more=true, $fakeit=1, $fix_tags=true, $no_more=false, $more_tag='div', $more_link_title='Continue reading this entry', $showdots=true, $strip_shortcodes = 1) {
	if(preg_match('%^content($|_rss)|^excerpt($|_rss)%', $filter_type)) {
		$filter_type = 'the_' . $filter_type;
	}
	return get_the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $no_more, $more_tag, $more_link_title, $showdots, $strip_shortcodes);
}

function get_the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $no_more, $more_tag, $more_link_title, $showdots, $strip_shortcodes) {
	global $post;

	if (!empty($post->post_password)) { // if there's a password
		if ($_COOKIE['wp-postpass_'.COOKIEHASH] != $post->post_password) { // and it doesn't match cookie
			if(is_feed()) { // if this runs in a feed
				$output = 'There is no excerpt because this is a protected post.';
			} else {
	            $output = get_the_password_form();
			}
		}
		return $output;
	}

	if($fakeit == 2) { // force content as excerpt
		$text = $post->post_content;
	} elseif($fakeit == 1) { // content as excerpt, if no excerpt
		$text = (empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { // excerpt no matter what
		$text = $post->post_excerpt;
	}

	if($strip_shortcodes) $text = strip_shortcodes($text);

	if($excerpt_length < 0) {
		$output = $text;
	} else {
		if(!$no_more && strpos($text, '<!--more-->')) {
		    $text = explode('<!--more-->', $text, 2);
			$l = count($text[0]);
			$more_link = 1;
		} else {
			$text = explode(' ', $text);
			if(count($text) > $excerpt_length) {
				$l = $excerpt_length;
				$ellipsis = 1;
			} else {
				$l = count($text);
				$more_link_text = '';
				$ellipsis = 0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . ' ';
	}

	if('all' != $allowed_tags) {
		$output = strip_tags($output, $allowedtags);
	}

//	$output = str_replace(array("\r\n", "\r", "\n", "  "), " ", $output);

	$output = rtrim($output, "\s\n\t\r\0\x0B");
	$output = ($fix_tags) ? $output : balanceTags($output);
	$output .= ($showdots && $ellipsis) ? '...' : '';

	switch($more_tag) {
		case('div') :
			$tag = 'div';
		break;
		case('span') :
			$tag = 'span';
		break;
		case('p') :
			$tag = 'p';
		break;
		default :
			$tag = 'span';
	}

	if ($use_more_link && $more_link_text) {
		if($force_more) {
			$output .= ' <' . $tag . ' class="more-link"><a href="'. __url( get_permalink($post->ID ) ) . '#more-' . $post->ID .'" title="' . $more_link_title . '">' . $more_link_text . '</a></' . $tag . '>' . "\n";
		} else {
			$output .= ' <' . $tag . ' class="more-link"><a href="'. __url( get_permalink($post->ID ) ) . '" title="' . $more_link_title . '">' . $more_link_text . '</a></' . $tag . '>' . "\n";
		}
	}

	$output = apply_filters($filter_type, $output);

	return $output;
}

function cloudfw_google_analytics_tracking($tracking_id){
	if (empty($tracking_id)) return false;
	echo '<script type="text/javascript">
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
	</script>
	<script type="text/javascript">
	try{
	var pageTracker = _gat._getTracker("'.$tracking_id.'");
	pageTracker._trackPageview();
	} catch(err) {}
	</script>';
};



	
function cloudfw_register_font($type = 'custom', $id = NULL, $name = NULL, $css = NULL) {
	
	if ($type == 'google') {
		global $google_fonts;
		
		if (is_array($id)):
			foreach((array) $id as $font):
			$google_fonts[] = $font;
			endforeach;
		else:
			$google_fonts[] = $id;
		endif;
	
	} elseif ($type == 'custom') { 
		global $custom_fonts;
		
		$custom_fonts[$id] = array('name' => $name, 'css' => $css);
	
	}elseif ($type == 'default') { 
		global $default_fonts;
		
		$default_fonts[$id] = array('name' => $name);
	
	}
	
}

function cloudfw_register_pattern($id = NULL, $name = NULL, $code = NULL, $group = NULL) {
	global $patterns;
	$patterns[$id] = array('name' => $name, 'code' => $code, 'group' => $group);
}

function cloudfw_deregister_pattern($id = NULL) {
	global $patterns;
	if(!empty($id)) 
		unset($patterns[$id]);
}



/**
 *	Loop Of Social Bookmarking Services For Select Modules
 *
 *	@since 1.0
**/	
function cloudfw_loop_social_services() {
	$social_services = cloudfw_social_services();
	
	foreach ($social_services as $social_service_item => $item){
		$loop_social_services[] = array(
			 "item_value"	=> $social_service_item,
			 "item_html" 	=> '<span class="contrainer"><img src="'.TMP_ADMIN_SRC.'/social_icon/'.$social_service_item.'-16x16.png" /><br/>'.$item["item_name"].'</span>'
		 );
	}
	return $loop_social_services;
}

/**
 *	Convert toBytes
 *
 *	@since 1.0
**/	
function cloudfw_toBytes($str) {
    $val = trim($str);
    $last = strtolower($str[strlen($str)-1]);
    switch($last) {
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;        
    }
    return $val;
}

/**
 *	Check Upload Folders
 *
 *	@since 1.0
**/	
function cloudfw_check_upload_folders(){

	if ( ! is__writable(CLOUD_UPLOAD_DIR) === true ) {
		add_action( 'network_admin_notices', 'cloudfw_check_upload_folder_message', 4 );
		add_action( 'admin_notices', 'cloudfw_check_upload_folder_message', 1 );
	}

	if ( ! is__writable(TEMPLATEPATH . '/cache/') === true ) {
	    // Create Directory If There Is No
	    if ( ! file_exists(TEMPLATEPATH . '/cache/')) {
	        @mkdir(TEMPLATEPATH . '/cache/');
	        @chmod(TEMPLATEPATH . '/cache/', 0777);
	    } 
	    // Check Again
	    if ( ! is__writable(TEMPLATEPATH . '/cache/') === true ) {
    		add_action( 'network_admin_notices', 'cloudfw_check_cache_folder_message', 4 );
			add_action( 'admin_notices', 'cloudfw_check_cache_folder_message', 1 );
	    } 
	}
}


/**
 *	CloudFw Error Messages
 *
 *	@since 1.0
**/	
function cloudfw_check_upload_folder_message() {
  
      printf ("<div class='cloudfw-update-messages error'>%s</div>",
      sprintf ("<div style='padding:15px;'>%s</div>", 
		sprintf ( __('Error: %s folder is not writable. Please adjust the chmod permissions to allow it to be written to. (CHMOD to 777)','cloudfw') , '<strong>'. CLOUD_UPLOAD_DIR . '</strong>' )       
      )
    
    );
}

function cloudfw_check_cache_folder_message() {
  
      printf ("<div class='cloudfw-update-messages error'>%s</div>",
      sprintf ("<div style='padding:15px;'>%s</div>", 
		sprintf ( __('Error: %s folder is not writable. Please adjust the chmod permissions to allow it to be written to. (CHMOD to 777)','cloudfw') , '<strong>'. TEMPLATEPATH . '/cache/</strong>')       
      )
    
    );
}


/**
 *	CloudFw Create Sample Pages
 *
 *	@since 1.0
 */	
function cloudfw_create_a_page($args = array(), $opt = array()){
    if (empty($args) || !is_array($args))
        return false;
    
    // Insert the post into the database
    if (!$opt["update"])
        $out["id"] = wp_insert_post($args);
    else
        $out["id"] = wp_update_post($args);
    
    foreach ((array) get_pages('sort_column=post_date&sort_order=desc&post_type=' . $args["post_type"] . '') as $page) {
        $lastID       = $page->ID;
        //$out["id"]    = $lastID;
        $out["title"] = get_the_title($page->ID);
        $out["url"]   = get_permalink($page->ID);
        
        break;
    }
    
    $template = $opt["template"];
    
    if (!update_post_meta($lastID, '_wp_page_template', $template) && isset($template))
        add_post_meta($lastID, '_wp_page_template', $template, true);
    
    return $out;
}

/**
 *	CloudFw Get Theme Item Page URL
 *
 *	@since 1.0
 */
function get_template_item_page_url(){
	return 'http://themeforest.net/item/positive-premium-multipurpose-wordpress-theme/560405';
}