<?php

/* include ad code - functions here are required throughout the template */
require_once(dirname(__FILE__) . "/ads.php");

/* these functions allow this template to work properly in all scenarios */

function _tdie($s) {
		global $wp; global $wp_query;
		header("Content-Type: text/plain; charset=utf-8");
		die("\n".$s."\n");
}

/* title functions */

function revvedup_title_portion() {
	if (revvedup_get_http_error_code()) echo " " . revvedup_get_http_error_title() . " &raquo;  ";
	elseif (is_archives_page()) { ?> Complete archives &raquo; <?php }
	elseif (is_directory_index()) { ?> Folder contents &raquo; <?php }
	elseif (is_search()) { ?> Search results &raquo; <?php }
	elseif (is_single()) { /* do not put anything, leave empty to increase SEO relevance  */  }
}

function revvedup_title() {
	if (is_home()) {
		bloginfo('name'); echo ' &raquo; '; bloginfo('description');
	} else {
		if (function_exists("optimal_title")) { optimal_title(); revvedup_title_portion(); bloginfo('name'); }
		else { bloginfo('name'); revvedup_title_portion(); wp_title(); }
	}
}

/* overriding classes */

class RevvedUp_WP extends WP {

	function parse_request($extra_query_vars = '') {
		$this->public_query_vars[] = "template_page";
		parent::parse_request($extra_query_vars);

		if ($this->query_vars["template_page"]) {
			$tentative_file_name = TEMPLATEPATH . "/" . $this->query_vars["template_page"] . ".php";
			if (is_readable($tentative_file_name)) {
				global $wp_query;
				$wp_query->is_template_page = true;
				$wp_query->requested_template_page = $this->query_vars["template_page"];
			} else {
				// aca hay que simular un 404 porque no hubo el template solicitado
				$this->query_vars['error'] = 404;
			}
		}
	}

	function query_posts() {
		parent::query_posts();
		if (is_template_page()) {
			global $wp_query;
			$wp_query->is_single = null;
			$wp_query->is_preview  = null;
			$wp_query->is_page  = null;
			$wp_query->is_archive  = null;
			$wp_query->is_date  = null;
			$wp_query->is_year  = null;
			$wp_query->is_month  = null;
			$wp_query->is_day  = null;
			$wp_query->is_time  = null;
			$wp_query->is_author  = null;
			$wp_query->is_category  = null;
			$wp_query->is_search  = null;
			$wp_query->is_feed  = null;
			$wp_query->is_trackback  = null;
			$wp_query->is_home  = null;
			$wp_query->is_404  = null;
			$wp_query->is_comments_popup  = null;
			$wp_query->is_admin  = null;
			$wp_query->is_attachment  = null;
			$wp_query->is_paged  = null;
		}
	}

	function handle_404() {
		/* forces showing of 404 page if a redirect status error is present */
		/* 404.php will handle special cases */

		parent::handle_404();
		
		global $wp_query;
		$rstatus = $_SERVER["REDIRECT_STATUS"];
		if ($rstatus && $rstatus != 200 && $rstatus != 304) {
			$wp_query->set_404();
			$wp_query->redirect_status = intval($rstatus);
			global $known_http_errors;
			$errarray = $known_http_errors[intval($rstatus)];
			$errtitle = $errarray[0];
			$header = "$rstatus ".$errtitle;
			status_header( $header );
		} elseif (is_404()) {
			$wp_query->redirect_status = 404;
		}

	}

}

class RevvedUp_WP_Query extends WP_Query {
	var $is_template_page = false;
	var $requested_template_page = null;
	var $redirect_status = null;
}

function init_revvedup() {
	global $wp; $wp = new RevvedUp_WP();
	global $wp_query; $wp_query = new RevvedUp_WP_Query();
}

function add_revvedup_rewrite_rules($arr) {
	$arr["([a-z]+)$"] = 'index.php?template_page=$matches[1]';
	$arr["([a-z]+)/$"] = 'index.php?template_page=$matches[1]';
	return $arr;
}

function override_template_redirect_with_revvedup() {
	if (is_template_page()) {
			require(TEMPLATEPATH . "/" . get_template_page_name() . ".php");
			die;
	}
}

function generate_mod_rewrite_rules_for_revvedup($rules) {
	$site_root = parse_url(get_settings('siteurl'));
	$site_root = trailingslashit($site_root['path']);
	$baseindexphp = $site_root . "index.php";
	$rules .= "DirectoryIndex index.php index.html $baseindexphp?template_page=directoryindex
ErrorDocument 400 $baseindexphp
ErrorDocument 401 $baseindexphp
ErrorDocument 403 $baseindexphp
ErrorDocument 404 $baseindexphp
ErrorDocument 405 $baseindexphp
ErrorDocument 408 $baseindexphp
ErrorDocument 410 $baseindexphp
ErrorDocument 411 $baseindexphp
ErrorDocument 412 $baseindexphp
ErrorDocument 413 $baseindexphp
ErrorDocument 414 $baseindexphp
ErrorDocument 415 $baseindexphp
ErrorDocument 500 $baseindexphp
ErrorDocument 501 $baseindexphp
ErrorDocument 502 $baseindexphp
ErrorDocument 503 $baseindexphp
ErrorDocument 506 $baseindexphp
";

	if ($site_root == "/") {
		$pathtorevvedup = get_template_directory_uri();
		$rules = "<IfModule mod_rewrite.c>
RewriteRule ^favicon.ico$ $pathtorevvedup/images/favicon.ico [QSA,L]
</IfModule>
" . $rules;
	}

	return $rules;
}

add_action("init","init_revvedup");
add_filter('rewrite_rules_array','add_revvedup_rewrite_rules');
add_action("template_redirect","override_template_redirect_with_revvedup");
add_filter("mod_rewrite_rules","generate_mod_rewrite_rules_for_revvedup");



/* HTTP error handling */

$known_http_errors = array(
	400 => array("Bad request",
	"Your web browser performed a request this server could not understand.  There is also the possibility that you are a (sadly unsuccessful) hacker, trying to do nasty things."),
	401 => array("Unauthorized",
	"The page you were trying to load requires authorization."),
	403 => array("Forbidden",
	"The file you were trying to access is off-limits for this server."),
	404 => array("Resource not found",
	"The page you were trying to access cannot be found."),
	405 => array("Method not allowed",
	"The HTTP method you requested is not allowed for this resource"),
	408 => array("Request timed out",
	"The server closed the network connection because the browser didn't finish the request within the specified time."),
	410 => array("No longer at this address",
	"The requested URL is no longer available on this server and there is no forwarding address."),
	411 => array("Bad Content-Length",
	"The issued request requires a valid Content-Length header."),
	412 => array("Precondition failed",
	"The precondition on the request for the URL failed positive evaluation."),
	413 => array("Request entity too large",
	"The requested method does not allow the data transmitted, or the data volume exceeds the capacity limit."),
	414 => array("Submitted URI too large",
	"The length of the requested URL exceeds the capacity limit for this server. The request cannot be processed."),
	415 => array("Unsupported media type",
	"The server does not support the media type transmitted in the request."),
	500 => array("Internal server error",
	"An unknown error took place while generating the page you requested."),
	501 => array("Cannot process request",
	" The server does not support the action requested by the browser."),
	502 => array("Bad gateway",
	"The proxy server received an invalid response from an upstream server."),
	503 => array("Service unavailable",
	"This service is temporarily disabled due to technical difficulties."),
	506 => array("Variant also varies",
	"A variant for the requested entity is itself a negotiable resource.  Access not possible.")
);

function revvedup_get_http_error_code() {
	global $wp_query;
	return $wp_query->redirect_status;
}

function revvedup_get_http_error_title() {
	$code = revvedup_get_http_error_code();
	global $known_http_errors;
	$errarray = $known_http_errors[$code];
	return $errarray[0];
}

function revvedup_get_http_error_description() {
	$code = revvedup_get_http_error_code();
	global $known_http_errors;
	$errarray = $known_http_errors[$code];
	return $errarray[1];
}

/* template page functions */

function is_template_page() {
	/* return true if this is a template page, false if it isn't */
	global $wp_query; return $wp_query->is_template_page;
}

function get_template_page_name() {
/* return the requested template page file name, null if none */
	global $wp_query; return $wp_query->requested_template_page;
}

function is_archives_page() { return get_template_page_name() == "archives"; }
function is_directory_index() { return get_template_page_name() == "directoryindex"; }

function get_the_archives_permalink() {
	global $wp_rewrite;
	$rewrite = $wp_rewrite->wp_rewrite_rules();
	if ($rewrite) {
		return get_settings('siteurl') . "/archives/";
	} else {
		return get_settings('siteurl') . "/index.php?template_page=archives";
	}
}
function the_archives_permalink() { print get_the_archives_permalink(); }


/* integration of useronline */
function is_useronline() { global $bots; global $usersonline; return isset($bots) && isset($usersonline); }
/* fixme a better integration would be to put it right into the template as a special page, and that's it */


/* theme toolkit integration */

require_once(dirname(__FILE__).'/themetoolkit.php');

/************************************************************************************
 * THEME AUTHOR : edit the following function call :
 ************************************************************************************/

themetoolkit(
	'revvedup', /* Make yourself at home :
			* Name of the variable that will contain all the options of
			* your theme admin menu (in the form of an array)
			* Name it according to PHP naming rules (http://php.net/variables) */

	array(     /* Variables used by your theme features (i.e. things the end user will
			* want to customize through the admin menu)
 			* Syntax :
			* 'option_variable' => 'Option Title ## optionnal explanations',
			* 'option_variable' => 'Option Title {radio|value1|Text1|value2|Text2} ## optionnal explanations',
			* 'option_variable' => 'Option Title {textarea|rows|cols} ## optionnal explanations',
			* 'option_variable' => 'Option Title {checkbox|option_varname1|value1|Text1|option_varname2|value2|Text2} ## optionnal explanations',
			* Examples :
			* 'your_age' => 'Your Age',
			* 'cc_number' => 'Credit Card Number ## I can swear I will not misuse it :P',
			* 'gender' => 'Gender {radio|girl|You are a female|boy|You are a male} ## What is your gender ?'
			* Dont forget the comma at the end of each line ! */
	'revvedup_meta_code' => 'Extra elements to show under "About": {textarea|4|60} ## Shows up in the sidebar, under the "About this site" heading.  It\'s the ideal spot for badges like Technorati and Popdex.  This code needs to start with <code>&lt;li&gt;</code> and end with <code>&lt;/li&gt;</code> because it appears under an <code>&lt;/ul&gt; element.</code>.',
	'ad_after_content_code' => 'Code for ads after content: {textarea|4|60} ## Shows up only in single posts and pages',
	//'Stuff {textarea|6|50} ## Enter some text',
	'ad_after_title_code' => 'Code for ads after story titles: {textarea|4|60} ## Shows up only in single posts and pages',
	'ad_header_code' => 'Code for ads in header: {textarea|4|60} ## Shows up at the top of each page',
	'ad_intermixed_code' => 'Code for ads between excerpts: {textarea|4|60} ## Shows up between posts in the main page and any of the archive pages',
	'ad_intermixed_max' => 'Maximum ads between excerpts: ## Use it to place a limit on how how many ads between excerpts get displayed (leave empty for no limit)',
	'ad_left_of_content_code' => 'Code for ads floating left of content: {textarea|4|60} ## Shows up only in single posts and pages with a 50% chance of being replaced by the code for ads floating right of content',
	'ad_right_of_content_code' => 'Code for ads floating right of content: {textarea|4|60} ## Shows up only in single posts and pages with a 50% chance of being replaced by the code for ads floating left of content',
	'ad_referral_code' => 'Code for referral ads: {textarea|4|60} ## Shows up in the sidebar',
	'ad_sidebar_code' => 'Code for sidebar ads: {textarea|4|60} ## Shows up in the sidebar, along with the referral code (if any)',
	'ad_tip_block_code' => 'Code for donation requests: {textarea|4|60} ## Shows up below each post, page and directory index'
//	'setting3' => 'Choice {radio|choice1|Choice One|choice2|Choice Two} ## Chose one.',
//	'setting4' => 'Multiple choice {checkbox|mc1|happy|Are you Happy ?|mc2|human|Are you Human ?} ## Chose any',

//	'debug' => 'debug', 	/* this is a fake entry that will activate the "Programmer's Corner"
//			 * showing you vars and values while you build your theme. Remove it
//			 * when your theme is ready for shipping */
	),
	__FILE__	 /* Parent. DO NOT MODIFY THIS LINE !
			  * This is used to check which file (and thus theme) is calling
			  * the function (useful when another theme with a Theme Toolkit
			  * was installed before */
);
	
/************************************************************************************
 * THEME AUTHOR : Congratulations ! The hard work is all done now :)
 *
 * From now on, you can create functions for your theme that will use the array
 * of variables $mytheme->option. For example there will be now a variable
 * $mytheme->option['your_age'] with value as set by theme end-user in the admin menu.
 ************************************************************************************/

/***************************************
 * Additionnal Features and Functions
 *
 * Create your own functions using the array
 * of user defined variables $mytheme->option.
 *
 **************************************/

/*function creditcard() {
	global $mytheme;
	print "My Credit Card Number is : ";
	print $mytheme->option['creditcard'];
}*/


function revvedup_meta() {
	global $revvedup;
	if ($revvedup->option["revvedup_meta_code"]) {
		print $revvedup->option["revvedup_meta_code"];
	}
}


?>