<?php
/**
 * FunGames functions and definitions
 * 
 * @author Daniel Bakovic
 * @uri http://myarcadeplugin.com   
 * 
 * @package WordPress
 * @subpackage FunGames
 */

define ( 'MYAPB_THEMEVERSION', '4.62');
define ( 'MYAPB_THEMENAME', 'Fungames');

/** Include MyArcadePlugin Theme API **/
include_once('inc/myabp_api.php');
/** Include MyArcadePlugin Theme Options **/
include_once('inc/myabp_themeoptions.php');
/** Include MyArcadePlugin Theme Default Settings **/
include_once('inc/myabp_settings.php');

/** Include custom widgets **/
include_once('inc/myabp_widgets.php');

/** Include theme actions API **/
include_once('inc/actions.php');

/** Include buddypress integration file **/
include_once('inc/buddypress.php');

add_action('widgets_init', 'fungames_widgets_init');
add_action('wp_head', 'fungames_custom_style');

if ( !is_admin() ) {
  add_action('wp_print_scripts', 'funames_scripts_init');
  add_action('wp_print_styles',  'fungames_stylesheet_init');
}

/** Add filter for blog template **/
add_filter('single_template', 'fungames_blog_template');
// Add action to handle fullscreen 
add_filter('template_include', 'fungames_fullscreen');

function fungames_fullscreen( $template ) {
  
  //echo "full"; die();
  
  if ( isset($_GET['gid']) && isset($_GET['play']) && ($_GET['play'] == 'fullscreen') ) {
   $template = locate_template('template-fullscreen.php');
  }
  
  return $template;
}


function funames_scripts_init() {
  $path_to_theme = get_bloginfo('template_url');
  
  if ( !is_admin() ) {
  
    // load the jquery script
    if ( get_option('fungames_jquery_cdn') == 'enable' ) {
      wp_deregister_script('jquery');
      wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
    }
    
    wp_enqueue_script('jquery');
    
    // Do this only on the front page
    if ( is_front_page() ) {
      // Which slider should be displayed..
      switch ( get_option('fungames_slider_type') ) {
        case 'nivoSlider': {
          // load the nivoslider script
          wp_enqueue_script('fungames_nivoslider', 
              $path_to_theme.'/js/jquery.nivo.slider.pack.js', 
              '', 
              '',
              false);
        } break;

        case 'Default':
        default: {
          // load default slider script
          wp_enqueue_script('fungames_top_slider', 
              $path_to_theme.'/js/scroll.js', 
              '', 
              '',
              false 
          );          
        } break;
      }
    }
    
    // Include featured scoller code only when the widget is displayed
    //if ( is_active_widget(false, false, 'MABP_Random_Games') ) {
      // load the featured scroller script
      wp_enqueue_script('fungames_featured_scroller', 
                $path_to_theme.'/js/spy.js',
                '', 
                '',
                false );
    //}
    
    if ( is_singular() ) {
      // include mochi leaderboard bridge to be able to handle score submissions
      wp_enqueue_script('leaderboard', 
                'http://xs.mochiads.com/static/pub/swf/leaderboard.js', 
                '', 
                '',
                false );
                
      wp_enqueue_script('fungames_lights', 
                $path_to_theme.'/js/lights.js', 
                '', 
                '',
                false );                
    }
  }  
}

function fungames_stylesheet_init() {
  $path_to_theme_css = get_bloginfo('template_url').'/css';
  $color_scheme = get_option('fungames_color_scheme');
  wp_register_style('FunGamesStyle', $path_to_theme_css.'/color-'.$color_scheme.'.css');
  wp_enqueue_style( 'FunGamesStyle');  
  
  $box_design = get_option('fungames_box_design');
  if ( empty($box_design) ) $box_design = 'Vertical';
  
  wp_register_style('FunGamesBoxDesign', $path_to_theme_css.'/box-'.$box_design.'.css');
  wp_enqueue_style( 'FunGamesBoxDesign');  
  
  // Include Accordion css
  if ( get_option('fungames_slider_type') == 'Accordion' ) {
    wp_register_style('AccordionStyle', $path_to_theme_css.'/accordion.css');
    wp_enqueue_style( 'AccordionStyle');  
  } else if ( get_option('fungames_slider_type') == 'nivoSlider' ) {
    wp_register_style('nivoSliderStyle', $path_to_theme_css.'/nivoslider.css');
    wp_enqueue_style( 'nivoSliderStyle');
    wp_register_style('nivoSliderOrman', $path_to_theme_css.'/orman/orman.css');
    wp_enqueue_style( 'nivoSliderOrman');    
  }
  
  //Should we include Buddypress adminbar css?
  if ( defined( 'BP_VERSION' ) ) {
    $bpcss = WP_PLUGIN_URL . '/buddypress/bp-themes/bp-default/_inc/css/adminbar.css';
    wp_register_style('FunGamesBuddyPress', $bpcss);
    wp_enqueue_style( 'FunGamesBuddyPress'); 
    wp_register_style('FunGamesBuddyPressIntegration', $path_to_theme_css.'/buddypress.css');
    wp_enqueue_style( 'FunGamesBuddyPressIntegration');
  }
}

function fungames_widgets_init() {
  register_sidebar(
    array('name'          =>'Home Sidebar',
          'id'            =>'home-sidebar',
          'description'   => 'This is the sidebar that gets shown on the home page.',
          'before_widget' => '',
          'after_widget'  => '',
          'before_title'  => '<h2>',
          'after_title'   => '</h2>',
    )
  );
  
  register_sidebar(
    array('name'          =>'Single Sidebar',
          'id'            =>'single-sidebar',
          'description'   => 'This is your sidebar that gets shown on the game or blog pages.',
          'before_widget' => '',
          'after_widget'  => '',
          'before_title'  => '<h2>',
          'after_title'   => '</h2>',
    )
  );
  
  register_sidebar(
    array('name'          =>'Page Sidebar',
          'id'            =>'page-sidebar',
          'description'   => 'This is your sidebar that gets shown on most of your pages.',
          'before_widget' => '',
          'after_widget'  => '',
          'before_title'  => '<h2>',
          'after_title'   => '</h2>',
    )
  );  
  
  register_sidebar(
    array('name'          =>'Category Sidebar',
          'id'            =>'category-sidebar',
          'description'   => 'This is your sidebar that gets shown on the category pages.',
          'before_widget' => '',
          'after_widget'  => '',
          'before_title'  => '<h2>',
          'after_title'   => '</h2>',
    )
  );   
    
  // Area 1, located in the footer. Empty by default.
  register_sidebar( array(
    'name' => __( 'First Footer Widget Area', 'fungames' ),
    'id' => 'first-footer-widget-area',
    'description' => __( 'The first footer widget area', 'fungames' ),
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
  ) );

  // Area 2, located in the footer. Empty by default.
  register_sidebar( array(
    'name' => __( 'Second Footer Widget Area', 'fungames' ),
    'id' => 'second-footer-widget-area',
    'description' => __( 'The second footer widget area', 'fungames' ),
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
  ) );

  // Area 3, located in the footer. Empty by default.
  register_sidebar( array(
    'name' => __( 'Third Footer Widget Area', 'fungames' ),
    'id' => 'third-footer-widget-area',
    'description' => __( 'The third footer widget area', 'fungames' ),
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
  ) );

  // Area 4, located in the footer. Empty by default.
  register_sidebar( array(
    'name' => __( 'Fourth Footer Widget Area', 'fungames' ),
    'id' => 'fourth-footer-widget-area',
    'description' => __( 'The fourth footer widget area', 'fungames' ),
    'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    'after_widget' => '</li>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
  ) );   
}


function fungames_calculate_height($fungames_box_count) {
  
  switch ( get_option('fungames_box_design') ) {
    case 'Vertical': {
      $count = round(intval($fungames_box_count) / 2);
      $height = 60 + 110 * $count;
      return 'style="height:'.$height.'px;"';
    } break;
  
    case 'Half': {
      $count = round(intval($fungames_box_count) );
      $height = 65 + 110 * $count;
      return 'style="height:'.$height.'px;"';      
    } break;
  
    case 'Miniclip': {
      $count = round(intval($fungames_box_count) );
      $height = 155 + 20 * $count;
      return 'style="height:'.$height.'px;"';      
    } break;  
  
    default: {
      return false;
    }
  }
 
 return '';
}


function fungames_default_header_menu() {
    wp_list_categories('sort_column=name&title_li=&depth=1'); 
}


function fungames_default_footer_menu() {
  ?>
  <li class="page_item <?php if ( is_home() ) { ?>current_page_item<?php } ?>">
    <a href="<?php echo get_option('url'); ?>/" title="<?php _e("Home", "fungames"); ?>"><?php _e("Home", "fungames"); ?></a>
  </li>
  <?php
  wp_list_pages('sort_column=menu_order&depth=1&title_li=');  
}


if ( !function_exists('fungames_favorite_link') ) {
  function myabp_favorite_link($post_id, $opt, $action) {
    $img = get_bloginfo('template_directory').'/images/'.$action.'.png';
    $link = "<a href='?wpfpaction=".$action."&amp;postid=". $post_id . "' title='". $opt ."' rel='nofollow'><img src='".$img."' title='".$opt."' alt='".$opt."' class=".favoritos." /></a>";
    $link = apply_filters( 'wpfp_link_html', $link );
    return $link; 
  }
}


if ( !function_exists('fungames_favorite') ) {
  function fungames_favorite() {
    global $post, $action;  
    // Works only when WP Favorite Post is active
    if (function_exists('wpfp_link')) {
      if ($action == "remove") {
        $str .= myabp_favorite_link($post->ID, wpfp_get_option('remove_favorite'), "remove");
       } elseif ($action == "add") {
        $str .= myabp_favorite_link($post->ID, wpfp_get_option('add_favorite'), "add");
       } elseif (wpfp_check_favorited($post->ID)) {
        $str .= myabp_favorite_link($post->ID, wpfp_get_option('remove_favorite'), "remove");
       } else {
        $str .= myabp_favorite_link($post->ID, wpfp_get_option('add_favorite'), "add");
       }   
       echo $str;
    }
  }
}


function myabp_get_nivoslider( $query ) {
  
  $games = new WP_Query($query);  
  
  if ( $games->have_posts() ) {  
    ?>
   
    <div class="contentbox customslider">
      <div class="slider-wrapper theme-orman">
        <div class="ribbon"></div>
        <div id="slider" class="nivoSlider">
        <?php  
        while ($games->have_posts()) {
          $games->the_post();     
          
          $screen = base64_encode(myabp_print_screenshot_url(1, false));
          $img = get_bloginfo('template_directory').'/timthumb.php?src='.$screen.'&w=587&h=218&zc=1&q=100';
          
          ?>
          <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
            <img src="<?php echo $img; ?>" alt="<?php the_title_attribute(); ?>" title="<?php echo wp_strip_all_tags(fungames_get_excerpt(200, false)); ?>" width="587" heigh="218" />
          </a>
          <?php
        }
        ?>
        </div>
      </div>
    </div>
    <script type="text/javascript">
    jQuery(window).load(function() {
        jQuery('#slider').nivoSlider({
          animSpeed: 600,
          pauseTime: 4000,
          <?php 
          if ( get_option('fungames_topslider_auto') == 'disable') {
            echo 'manualAdvance:true';
          }
          ?>
        });
    });
    </script>  
    <?php  
  }
}

/*
function myabp_get_accordion( $query ) {
  global $wpdb;  
 
  $games = new WP_Query($query);
  
  if ( !empty($games) ) {  
    ?>
    <script type="text/javascript">
    jQuery().ready(function() {
      var $sacc = jQuery.noConflict();
      $sacc("#accordion-slider").kwicks({
        max : '600',
        spacing : 1
      });
    });
    </script>    
    <div class="custom-slider">
      <ul id="accordion-slider">
        <?php
        while ($games->have_posts()) {
          $games->the_post();     
          
          $screen = myabp_print_screenshot_url(1, false);
          $img = get_bloginfo('template_directory').'/timthumb.php?src='.$screen.'&w=587&h=218&zc=1&q=100';
          
          ?>
          <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute('', '', true); ?>">
            <img src="<?php echo $img; ?>" alt="" title="<?php myabp_get_description(200); ?>" width="587" heigh="218" />
          </a></li>
          <?php
        }
        ?>
      </ul>
    </div>
    <?php  
  }
}
 */

if ( !function_exists('fungames_blog_template') ) {
  /**
  * Blog template redirection
  */
  function fungames_blog_template($template) {  
    global $post;
        
    // Get the blog category
    $blog_cat = get_option('fungames_blog_category');
    
    if ($blog_cat == '-- none --') return $template;
    
    $blog_category = get_cat_ID( $blog_cat );
    $post_cat = get_the_category();
    
       
    if ( is_singular() && !empty($post_cat) && ( in_category($blog_category) || ($blog_category == $post_cat[0]->category_parent) ) ) {
      // overwrite the template file if exist
      if ( file_exists(TEMPLATEPATH . '/template-blog-post.php' ) ) {
        $template = TEMPLATEPATH . '/template-blog-post.php';
      }
    }

    return $template;
  }
}


function fungames_get_excluded_categories() {
  $result = 'exclude=';
  $blog = get_cat_ID( get_option('fungames_blog_category') );  
  if ( $blog ) {
    $result = 'exclude='.$blog.',';
  }
  
  $result .= get_option('fungames_exclude_front_cat');
  
  return $result;
}


/*function fungames_excerpt_more($excerpt) {
	return str_replace(' [...]', '...', $excerpt);
}*/
//add_filter('excerpt_more', 'fungames_excerpt_more');


/*function fungames_excerpt_length($length) {
	$limit = 100;	
	return $limit;
}*/
//add_filter('excerpt_length', 'fungames_excerpt_length');


function fungames_get_excerpt($excerpt_length = false, $echo = true) {
  global $post;
  
  // Get post excerpt
  $text = strip_shortcodes( $post->post_content );
  $text = apply_filters('the_content', $text);
  $text = str_replace(']]>', ']]&gt;', $text);
  $text = wp_trim_words( $text, 100, '' );  

  if ( $excerpt_length ) {
    if ( strlen($text) > $excerpt_length ) {
      $text = mb_substr($text, 0, $excerpt_length).' [...]';
    }
  }
  
  if ($echo) 
    echo $text;
  else 
    return $text;
} 


/*** REDIRECT MODIFICATION BEGIN ***/
function fungames_login_redirect() {
  global $mngl_options, $pagenow;
  
  // Check if mingle is instaleld
  if ( defined('MNGL_PLUGIN_NAME') ) {
   
    if( isset($_GET['action']) ) $theaction = $_GET['action']; else $theaction ='';
    
    if ($pagenow == 'wp-login.php' && $theaction != 'logout') {
      if ($theaction == 'register') {
        // Redirect to the sign up page
       wp_redirect( get_permalink($mngl_options->signup_page_id) ); 
      }
      else {
        // Redirect to the login page
        wp_redirect( get_permalink($mngl_options->login_page_id) );  
      }
    }   
  }
}
//add_action('init', 'fungames_login_redirect');
/*** REDIRECT MODIFICATION END ***/
?>