<?php
/*
Plugin Name: PledgeDrive
Plugin URI: http://www.havemoneywillvlog.com/
Description: Plugin for Have Money Will Vlog.
Author: Devlon Duthie
Version: 1.1
Author URI: http://www.devlonduthie.com
*/ 

function ispledgeproject($postid)
{
  	global $post, $wpdb;
  	
	//if not, get from db	
	$sql = 'SELECT * 
		 		FROM `pd_projects`
				WHERE `postid` = ' . $post->ID;

   	$project_data = $wpdb->get_row($sql);
   	
   	if ($project_data) 
	{
	  	return true;
	}
	else
	{
	  	return false;
	}	
}

function IsTargetReached($postid)
{
  	global $post, $wpdb;
  	
	//do we have project data?
	$sql = 'SELECT * FROM `pd_pledges` where `projectid` =' . $postid;
	
	$pledge = $wpdb->get_row($sql);
	
   	if ($pledge) 
	{	  	
	  	//the current total
		$current_total = pledgepriveget_amount($postid);	
	  	
	  	//get target total
		$sql2 = 'SELECT required_amount 
			 		FROM `pd_projects`
					WHERE `postid` = ' . $postid;	
		$targettotal = $wpdb->get_row($sql2);
				
	   	if ($targettotal) 
		{	
		  	$the_target = $targettotal->required_amount;
		} 
		else
		{
		  	$the_target = 0;
		}
		
		// = or > than the required amount?
		if ($current_total >= $the_target) 
		{	
		  	return true;
		}
		else
		{
		  	return false;
		} 
		
	}
	return false;
}

function pledgeprivepost($content) 
{
  	global $post, $wpdb;	
	//if not, get from db	
	$sql = 'SELECT * 
		 		FROM `pd_projects`
				WHERE `postid` = ' . $post->ID;

   	$project_data = $wpdb->get_row($sql);
   	if ($project_data) 
	{	
	  	//get total (derived for now...until writing, when total will be calc'd)
	  	$project_total = pledgepriveget_amount($post->ID);
	  		  	
	  	//figure out days left
		$projectdate = strtotime($project_data->target_date);
		$daysleft = getdaysleft($projectdate);
	  	
		$sql = 'SELECT guid 
		 		FROM `wp_posts`
				WHERE `id` = ' . $post->ID;

	   	$permalink_data = $wpdb->get_var($sql);
	   	if ($permalink_data) 
		{	  
		  	$permalink = $permalink_data;
		}
	  	  	
		$pledgemeta = "<div class='postmetadata alt'><table width=\"100%\"><tr valign=\"top\"><td align=\"left\" style=\"background-color:#BDCCAB\">";		
		$pledgemeta .= "<b>Required Amount:</b> " . money_format('$%#4n',$project_data->required_amount) . "<br />";		
		$pledgemeta .= "<b>Total to date:</b> " . money_format('$%#4n',$project_total) . "<br />";
		$pledgemeta .= "<b>Required by:</b> " . date("F j, Y", $projectdate) . " " . $daysleft;
		$pledgemeta .= "</td>";
		$pledgemeta .= "<td align=\"right\">";
		
		if ( IsTargetReached($post->ID) )
		{		  		
			$pledgemeta .= "<font size=3 color='yellow'><b>FUNDED!!</b></font>";
		}
		else
		{
		  	$pledgemeta .= "<a href=\"" . $permalink . "#donate\" title=\"Click here to Donate\"><img src=\"/images/donate3.gif\" alt=\"Click here to Donate\" border=0></a>";
		}
		
		$pledgemeta .= "</td></tr></table></div>";
   	}	
	
	$content = $pledgemeta . $content;
	return $content;
}


function getdaysleft($targetdate)
{  	
	$daysleft = floor(($targetdate - time())/86400);
	if ($daysleft < 0)
	{ 
		$daysleft = "";		
	}
	else
	{
	  	$daysleft++;
	  	
	  	if ($daysleft <= 1)
	  	{
	  	  	$daysleft = "<i><b>(" . $daysleft . " day left!!)</b></i>";
	 	}
		else
		{ 
			$daysleft = "<i><b>(" . $daysleft . " days left!!)</b></i>";
		}
	}
	
	return $daysleft;
}


function isapproved($commentid)
{
  	global $wpdb;
	  	
	$sql = "SELECT wp_comments.comment_approved
			FROM wp_comments 
			WHERE wp_comments.comment_ID = " . $commentid;  	
	
	$approved = $wpdb->get_row($sql);

   	if ($approved) 
	{	
	  	return $approved->comment_approved;
	} 
	else
	{
	  	return 0;
	} 
}

function pledgepriveget_amount($postid) 
{
  	global $wpdb;	
	//$sql = 'SELECT SUM(`amount`) as the_total FROM `pd_pledges` where `projectid` =' . $postid;
	
	$sql = "SELECT SUM( `amount` ) AS the_total
				FROM pd_pledges, wp_comments
				WHERE projectid = " . $postid . "
				AND pd_pledges.commentid = wp_comments.comment_ID
				AND pd_pledges.confirmed = '1'";
	
	$pledgetotal = $wpdb->get_row($sql);

   	if ($pledgetotal) 
	{	
	  	return $pledgetotal->the_total;
	} 
	else
	{
	  	return 0;
	} 	  	  	
}

function DisplayGuage($postid) 
{
	global $wpdb;
	
	$return = '';
	
	$container = 200;
	$level = 0;
	$current_total = 0;
	
	//do we have project data?
	$sql = 'SELECT * FROM `pd_pledges` where `projectid` =' . $postid;
	
	$pledge = $wpdb->get_row($sql);

   	if ($pledge) 
	{	  	
	  	//the current total
		$current_total = pledgepriveget_amount($postid);	
	  	
	  	//get target total
		$sql2 = 'SELECT required_amount 
			 		FROM `pd_projects`
					WHERE `postid` = ' . $postid;	
		$targettotal = $wpdb->get_row($sql2);
		
		
	   	if ($targettotal) 
		{	
		  	$the_target = $targettotal->required_amount;
		} 
		else
		{
		  	$the_target = 0;
		}
		
		// = or > than the required amount?
		if ($current_total >= $the_target) 
		{	
		  	//get total pledged (if zero, need to handle well)
		  	//build guage
		  	$return = '<div class="targetguage" style="margin-bottom:20px;margin-top:10px;"><b>$&nbsp;' . $current_total . '&nbsp;raised<br />to date!!</b></div>';
		  	$return .= '<div class="tgborder" style="height:' . ($container + 1) . 'px;width:73px;border: 2px solid:background-color:#999999;padding:0px;">';
		  	$return .= '<div class="tgshell" style="height:' . $container . 'px;border: 1px solid;background-color:#68896C;padding:0px;">';
		  	//$return .= '<div class="tgfiller" style="height:' . $level. 'px;width:67px;margin-top:' . $topmargin . 'px;margin-bottom:0px;background-color:#68896C">';
		  	$return .= '<h3 style="width:66px;padding-top:10px;margin-top:10px;background-color:#68896C;color:#FFFFCC;font-weight:bold;">';
		  	$return .= "Target<br />reached";
		  	$return .= '</h3></div></div></div></div>';
		} 
		else
		{				  
			//figure out the sizes for the gauge display	  			
		  	$percentcomplete = round(($current_total / $the_target) * 100);					
			$level = $container * ($percentcomplete / 100);	  	
		  	$topmargin = $container - $level;		  		
			
			if ($percentcomplete <= 10)
			{
			  	//build guage
			  	$return = '<div class="targetguage" style="margin-bottom:20px;margin-top:10px;"><b>$&nbsp;' . $current_total . '&nbsp;raised<br />to date!!</b></div>';
			  	$return .= '<div class="tgborder" style="height:' . ($container + 1) . 'px;width:73px;border: 2px solid:background-color:#999999;padding:0px;">';
			  	$return .= '<div class="tgshell" style="height:' . $container . 'px;border: 1px solid;background-color:#FFFFCC;padding:0px;">';			  	
			  	$return .= '<div class="tgfiller" style="height:20px;width:67px;margin-top:180px;margin-bottom:0px;background-color:#68896C">';
			  	$return .= '<h3 style="width:66px;padding-top:2px;margin-top:0px;background-color:#68896C;color:#FFFFCC;font-weight:bold;">';
			  	$return .= $percentcomplete . "%";
			  	$return .= '</h3></div></div></div></div>';
			  	
			  	return $return;			  	
			}
			
		  	//get total pledged (if zero, need to handle well)		  	
			if ($current_total != 0)
			{
			  	//build guage
			  	$return = '<div class="targetguage" style="margin-bottom:20px;margin-top:10px;"><b>$&nbsp;' . $current_total . '&nbsp;raised<br />to date!!</b></div>';
			  	$return .= '<div class="tgborder" style="height:' . ($container + 1) . 'px;width:73px;border: 2px solid:background-color:#999999;padding:0px;">';
			  	$return .= '<div class="tgshell" style="height:' . $container . 'px;border: 1px solid;background-color:#FFFFCC;padding:0px;">';
			  	$return .= '<div class="tgfiller" style="height:' . $level. 'px;width:67px;margin-top:' . $topmargin . 'px;margin-bottom:0px;background-color:#68896C">';
			  	$return .= '<h3 style="width:66px;padding-top:2px;margin-top:0px;background-color:#68896C;color:#FFFFCC;font-weight:bold;">';
			  	$return .= $percentcomplete . "%";
			  	$return .= '</h3></div></div></div></div>';
			}
		}			  	  	
	  	
	}
	else	//no project defined
	{
	  	//do nothing
	  	
		/*
		$level = 20;
		$current_total = 0;
		$topmargin = $container - $level;
		$percentcomplete = 0;
		
	  	//build guage
	  	$return = '<div class="targetguage" style="margin-bottom:20px;margin-top:10px;"><b>$&nbsp;' . $current_total . '&nbsp;raised<br />to date!!</b></div>';
	  	$return .= '<div class="tgborder" style="height:' . ($container + 1) . 'px;width:73px;border: 2px solid:background-color:#999999;padding:0px;">';
	  	$return .= '<div class="tgshell" style="height:' . $container . 'px;border: 1px solid;background-color:#FFFFCC;padding:0px;">';
	  	$return .= '<div class="tgfiller" style="height:' . $level. 'px;width:67px;margin-top:' . $topmargin . 'px;margin-bottom:0px;background-color:#68896C">';
	  	$return .= '<h3 style="width:66px;padding-top:2px;margin-top:0px;background-color:#68896C;color:#FFFFCC;font-weight:bold;">';
	  	$return .= $percentcomplete . "%";
	  	$return .= '</h3></div></div></div></div>';
		*/
	}	
	return $return;  	
}

function pledgepriveget_min($postid) 
{
  	global $wpdb; 		
	
	$sql = 'SELECT mindonation
				FROM pd_projects
				WHERE postid = ' . $postid;	
				
	$result = $wpdb->get_row($sql);
   	if ($result) 
	{	
	  	$mindonation = $result->mindonation;
	} 
	else
	{
	  	$mindonation = 0;
	}
	
	return $mindonation;		  	  	
}

function pledgepriveget_max($postid) 
{
  	global $wpdb; 		
	
	$sql = 'SELECT maxdonation
				FROM pd_projects
				WHERE postid = ' . $postid;	
				
	$result = $wpdb->get_row($sql);
   	if ($result) 
	{	
	  	$maxdonation = $result->maxdonation;
	} 
	else
	{
	  	$maxdonation = 0;
	}
	
	return $maxdonation;
		  	  	
}

function pledgepriveget_percentcomplete($postid) 
{
  	global $wpdb; 		
	//get current total
	$the_total = pledgepriveget_amount($postid);	
	//get target total
	$sql = 'SELECT required_amount 
		 		FROM `pd_projects`
				WHERE `postid` = ' . $postid;	
	$targettotal = $wpdb->get_row($sql);
   	if ($targettotal) 
	{	
	  	$the_target = $targettotal->required_amount;
	} 
	else
	{
	  	$the_target = 0;
	}
	
	$percentage = ($the_total / $the_target) * 100;		
	if ($percentage != 0)
	{
	  	return $percentage;
	}
	else
	{
	  	return 0;
	}		  	  	
}

function pledgepriveget_ppemail($postid) 
{
  	global $wpdb; 		
	
	$sql = 'SELECT ppemail 
		 		FROM `pd_projects`
				WHERE `postid` = ' . $postid;	
	$result = $wpdb->get_row($sql);
   	if ($result) 
	{	
	  	$the_ppemail = $result->ppemail;
	} 
	else
	{
	  	$the_ppemail = 0;
	}
	
	return $the_ppemail;
		
}

function pledgeprive_contriblist($postid) 
{
  	global $wpdb, $post;
  	
  	$return = '';
  	
  	$sql = 'SELECT * 
		 		FROM pd_projects
				WHERE postid = ' . $post->ID;
	
   	$project_data = $wpdb->get_row($sql);
   	if ($project_data) 
	{	
  	
	  	$return .= '<div class="contriblist" style="margin-bottom:20px;margin-top:10px;">';	        
		$return .= '<div class="contribstatus" style="font-weight:bold;margin-bottom:5px;">Contributors:</div>';        		
		$return .= '<div class="contribborder" style="width:180px;">';		
		$return .= '<div class="contribshell" style="text-align:left;border-top: 2px dashed #68896C;padding-top:5px;">';
		$return .= '<small>';
		
		//anon total:
	  	$sql = 'SELECT sum( pd_pledges.amount ) AS the_amount 
			FROM pd_pledges, wp_comments 
			WHERE pd_pledges.anon = "yes" 
			AND pd_pledges.showcontrib = "yes" 
			AND pd_pledges.commentid = wp_comments.comment_ID
			AND pd_pledges.confirmed = "1"
			AND pd_pledges.projectid =  ' . $postid .
			' GROUP BY wp_comments.comment_author ORDER BY wp_comments.comment_date DESC';
		
		$anonamount = $wpdb->get_row($sql);			
		if( $anonamount->the_amount  <> 0 ) 
		{
		  	$return .= '&raquo;&nbsp;anon&nbsp;$&nbsp;' . $anonamount->the_amount . "<br />";		  		
	  	}
	  	
	  	$sql = 'SELECT pd_pledges.anon, pd_pledges.showcontrib, sum( pd_pledges.amount ) AS the_amount, 
		  	wp_comments.comment_author AS the_username, wp_comments.comment_author_url AS the_url 
			FROM pd_pledges, wp_comments
			WHERE pd_pledges.anon = "no" 			
			AND pd_pledges.projectid =  ' . $postid . 
			' AND pd_pledges.commentid = wp_comments.comment_ID  
			AND pd_pledges.confirmed = "1"
			GROUP BY wp_comments.comment_author ORDER BY wp_comments.comment_date DESC';
			
	   	$contriblist = $wpdb->get_results($sql);			
		if( $contriblist ) 
		{									 			
			foreach( $contriblist as $listitem )
			{			
				if ($listitem->the_amount > 0)
				{
				  	if ($listitem->showcontrib <> 'yes')
					{
						$the_amount = 'N/A';
					}else{
						$the_amount = $listitem->the_amount;
					}
					
				  	if ($listitem->the_url != '')
				  	{
				  		$return .= '&raquo;&nbsp;<a href="' . $listitem->the_url . '">' . $listitem->the_username . '</a>  $&nbsp;' . $the_amount . "<br />";	
				 	}
					else
					{
					 	$return .= '&raquo;&nbsp;' . $listitem->the_username . '</a>  $&nbsp;' . $the_amount . "<br />";
					}
				 	
				}			
			}
				
		} 
		else
		{
		  	$return =  'No contributions yet.';
		}
		
		$return .= '</small>';
		$return .= '</div>';
		$return .= '</div>';
		$return .= '</div>';
		$return .= '</div>';	 
	}
	return $return;
}

function pledgeprivecomment_amount($comment_id) 
{
  	global $wpdb;	
  	  	
	$sql = 'SELECT amount, showcontrib, currency, other_amount,  confirmed
				FROM pd_pledges
				WHERE commentid = ' . $comment_id;

//	die( print_r($sql));
	
   	$pledgeamount = $wpdb->get_row($sql);		
	$return = '';		
   	if ($pledgeamount) 
	{		  	
		if ($pledgeamount->amount <> 0)
		{
			$return = '<div class="commentnum" style="margin-left:10px;margin-top:2px;margin-right:2px;color:#68896C;background-color:#FFFFFF;border:1px solid #657E68;padding:5px;float:right;">';
			$return .= '<table><tr><td align="center" valign="middle">';
			  	
			if ($pledgeamount->showcontrib == 'yes')
			{	
			  	$currency = '';
			   	$amount = $pledgeamount->amount;
							
				if ($pledgeamount->confirmed == 1)
				{
				  	$return .= '<h2 style="text-align:right;margin:0px;padding:0px;width:80px;">$&nbsp;' . $amount . $currency. '</b></h2>';
				}			
				else
				{
				  	$return .= '<h2 style="color:#DDDDDD;text-align:center;margin:0px;padding:0px;width:80px;">pending</b></h2>';
				}
							
			}		
			else
			{
			  	$return .= '<h2 style="color:#DDDDDD;text-align:center;margin:0px;padding:0px;width:80px;">not disclosed</b></h2>';				
			} 
			
			$return .= '</td></tr></table>';
			$return .= '</div>';
		}
	} 
		
	return $return;
}

function getnextcommentid()
{
  	global $wpdb;
  	$nextcomment = '';
  	
  	$sql = 'SELECT MAX(`comment_ID`)+1 as commentid FROM `wp_comments`';

   	$nextcommentrow = $wpdb->get_row($sql);

   	if ($nextcommentrow) {
	   	$nextcomment = $nextcommentrow->commentid;
   	}
  	
	return $nextcomment;
}

function isanon($comment_id)
{
  	global $wpdb;
  	$anon = false;
  	
	$sql = 'SELECT `anon`
				FROM `pd_pledges`
				WHERE `commentid` = ' . $comment_id;

   	$anonrow = $wpdb->get_row($sql);		
		
   	if ($anonrow) 
	{	
	  	if ($anonrow->anon == 'yes')
		{	
		  	$anon = true;		  	
		}
		else
		{
		  	$anon = false;
		} 
	} 
	else
	{
	  	$anon = false;
	}  		
  	
	return $anon;
}

function hideamount($comment_id)
{
  	global $wpdb;
  	$hide = false;
  	
	$sql = 'SELECT `showcontrib`
				FROM `pd_pledges`
				WHERE `commentid` = ' . $comment_id;

   	$hiderow = $wpdb->get_row($sql);		
		
   	if ($hiderow) 
	{	
	  	if ($hiderow->showcontrib == 'yes')
		{	
		  	$hide = false;		  	
		}
		else
		{
		  	$hide = true;
		} 
	} 
	else
	{
	  	$hide = true;
	}  		
  	
	return $hide;
}

function pdproject_widget()
{
  	global $post, $wpdb; 
	
	$pd_projtargetdate = "";
	$pd_projtargetamnt = "";
	$ppemail = '';
	$pd_projmin = '';	
	$pd_projmax = '';
	
	//call up existing project info if it exists.
	if ($post->ID){
  	   	$sql = 'SELECT required_amount, target_date, mindonation, maxdonation, ppemail FROM pd_projects WHERE postid=' . $post->ID;
			
	   	$this_project = $wpdb->get_row($sql);

	   	if ($this_project) {
		   	$pd_projtargetdate = $this_project->target_date;
			$pd_projtargetamnt = $this_project->required_amount;
			
			$ppemail = $this_project->ppemail;
			
			$pd_projmin = $this_project->mindonation;
			$pd_projmax = $this_project->maxdonation;
	   	}
	   	else
	   	{
   	  	   	$pd_projtargetdate = '';
			$pd_projtargetamnt = '';	
			
			$ppemail = '';
			
			$pd_projmin = '';	
			$pd_projmax = '';	
		}
	}
	
  	$widget = '';  	
  	$widget .= '<br /><table>';
  	$widget .= '<tr><td width=200 align=right>Project Target Date:</td><td width=400><input type=text name="pd_projtargetdate" value="' . $pd_projtargetdate . '" maxlength="25" size="25">&nbsp<strong>(example: YYYY-MM-DD)</td></tr>';  	
	$widget .= '<tr><td width=200 align=right>Project Target Amount:</td><td width=400><input type=text name="pd_projtargetamnt" value="' . $pd_projtargetamnt . '" size="20"></td></tr>';
	$widget .= '<tr><td width=200 align=right>Paypal Email to send pledges to:</td><td width=400><input type=text name="ppemail" value="' . $ppemail . '" size="40"></td></tr>';	
		
	//min and max donation settings
	$widget .= '<tr><td width=200 align=right>Donation Minimum:</td><td width=400><input type=text name="pd_projmin" value="' . $pd_projmin . '" maxlength="6" size="6"></tr>';
	$widget .= '<tr><td width=200 align=right>Donation Maximum:</td><td width=400><input type=text name="pd_projmax" value="' . $pd_projmax . '" maxlength="6" size="6"></tr>';
	
	$widget .= '</table>';
	$widget .= '<br/><br/>';
	
  	echo '<fieldset id="pd_div" class="dbx-box">' . '<h3 class="dbx-handle">PledgeDrive Plugin - Project Settings/Info for post# ' . $post->ID . '</h3><div class="dbx-content">' . $widget . '</div></fieldset>';
	
	return;
}

function pdproject_save($postID) {
	
	global $wpdb, $table_prefix;
				
	$pd_projtargetdate = trim(strip_tags($_POST['pd_projtargetdate']));
	$pd_projtargetamnt = trim(strip_tags($_POST['pd_projtargetamnt']));
	
	$ppemail = trim(strip_tags($_POST['ppemail']));
	
	$pd_projmin = trim(strip_tags($_POST['pd_projmin']));
	$pd_projmax = trim(strip_tags($_POST['pd_projmax']));	
	
	if (($pd_projtargetdate) and ($pd_projtargetamnt))
	{
	
		$sql = 'SELECT id FROM pd_projects WHERE postid=' . $postID;
		$projectsid = $wpdb->get_var($sql);
		
		if (is_null($projectsid)) {		
			$sql = 'INSERT INTO pd_projects 
				(required_amount, target_date, mindonation, maxdonation, ppemail, postid) VALUES (' . 
					$pd_projtargetamnt . ', "' . 
					$pd_projtargetdate . '", ' . 
					$pd_projmin . ', ' . 
					$pd_projmax . ', "' . 
					$ppemail . '", ' . 
					$postID . ')';
			
			$wpdb->query($sql);								
			
		}else{	  
		  	$sql = 'UPDATE pd_projects 
			  	 SET required_amount=' . $pd_projtargetamnt . 
				  ', target_date= \'' . $pd_projtargetdate . 
				  '\', mindonation= ' . $pd_projmin . 
				  ', maxdonation= ' . $pd_projmax . 
				  ', ppemail= \'' . $ppemail . 
				  '\' WHERE postid=' . $postID;		
		  	
			//die( __($sql)); 
			  		  
			$wpdb->query($sql);			    	  	
		}
	}
}

/*
function pdproject_validatepledge($commentdata)
{
  	global $post;
  	
  	//print_r($commentdata); 
  	
  	//Array ( [comment_post_ID] => 33 [comment_author] => Devlon 
	//[comment_author_email] => duthied@gmail.com [comment_author_url] => http:// [comment_content] => rrr 
  	
	$err_message = '';	  	
  	$the_amount = trim(strip_tags($_REQUEST['amount']));  	
  	$the_ppemail = trim(strip_tags($_REQUEST['pp_email']));  	
	
  	if (($the_ppemail == '') AND ($the_amount == ''))
  	{
  	  	//both are empty, pass through, comment only
  	  	
  	  	return $commentdata;
  	}
  	else
  	{
  		if ((($the_ppemail <> '') AND ($the_amount == '')) OR (($the_ppemail == '') AND ($the_amount <> '')))
  		{
  		  	//missing one or the other
  		  	if ($the_ppemail == '')
		  	{
		  	  	$err_message .= '&raquo;&nbsp;Please enter your Paypal email address<br />';
		  	}
		  	if ($the_amount == '')
		  	{
		  	  	$err_message .= '&raquo;&nbsp;Please enter an amount that you\'d like to donate<br />';
		  	}
		  			  			  	
		  	$donation_min = pledgepriveget_min($post->ID);
		  	$donation_max = pledgepriveget_max($post->ID);
		  			  	
		  	if ( ($the_amount < $donation_min) or ($the_amount > $donation_max) )
		  	{
		  	  	$err_message .= '&raquo;&nbsp;The minimum donation is $' . $donation_min . ' and the maximum is $' . $donation_min . ', please make sure your amount is with the min and max.<br />';
		  	}
		  	
  		}
  	}  	  	
  	//if (!IsNumeric(the_amount))
  	//{
  	//	err_message = "&raquo;&nbsp;Please enter only numbers for the amount that you'd like to donate<br />";
  	//} 	  	
  	
	if ($err_message != '') 
	{
		$err_message = '<h3>Please use your browser\'s back button and correct the following errors:</h3>' . $err_message;
		die( __($err_message));
	}	
 	return $commentdata;
}
*/

/*
preprocess_comment  
    preprocessing a comment, called with the comment passed as an array. 
	Should return a array. 
	The indices of the array are comment, comment_post_ID, user_ID, user_ip, user_domain, user_agent, author, email, url, approved.
*/    
function pdproject_comenttesting($commentid)
{
  	global $wpdb;
  	
	$the_amount = trim(strip_tags($_REQUEST['amount']));  	
	if ($the_amount == '')
  	{
  	  	return;
  	}
  	  	
	$the_ppemail = trim(strip_tags($_REQUEST['pp_email']));  	
	$the_email = trim(strip_tags($_REQUEST['email']));  	
	$the_amount = trim(strip_tags($_REQUEST['amount']));  	
	$thepostid = trim(strip_tags($_REQUEST['comment_post_ID']));
	$username = trim(strip_tags($_REQUEST['author']));
	$paymentcurrency = trim(strip_tags($_REQUEST['paymentcurrency']));
	$hide_pledgeamnt = trim(strip_tags($_REQUEST['hide_pledgeamnt']));
	$anon_donation = trim(strip_tags($_REQUEST['anon_donation']));
	$item_number_1 = trim(strip_tags($_REQUEST['item_number_1']));
	
	//post to db
	//get userid, if none exists, create...
	$sql = "SELECT id FROM `pd_users` WHERE `email` = '" . $the_email . "'";
   	$userid_row = $wpdb->get_row($sql);
   	if ($userid_row) 
	{		  	
	  	$userid =  $userid_row->id;				
  	}
	else	
	{
	   	//no rows returned?  Create a user...
	   	//$commentid = getnextcommentid();  	  	  	
		$sql = 'INSERT INTO `pd_users` (username, email) 
				VALUES("' . $username . '","' . $the_email . '")';
			
		$result = $wpdb->query($sql);	
		
		if (!$result) {	   
		   die( __('Error executing save on pledge info.<br />' . $sql));
		}
		
		//get the id
		$sql = "SELECT id FROM `pd_users` WHERE `email` = '" . $the_email . "'";
	   	$userid_row = $wpdb->get_row($sql);
	   	if ($userid_row) 
		{		  	
		  	$userid =  $userid_row->id;				
	  	}
	}
		
	//save the pledge record!	
	$the_amount = $wpdb->escape($the_amount); 	    	
	$sql = 'INSERT INTO `pd_pledges` (amount, userid, projectid, source, commentid, anon, showcontrib, currency, ppemail, uniqid) 
			VALUES(' . $the_amount . ',' . $userid . ',' . $thepostid . ',"paypal",' . $commentid . ', "' . $anon_donation . '", "' . $hide_pledgeamnt .  '", "USD", "' . $the_email . '", "' . $item_number_1 .  '")';
		
	$result = $wpdb->query($sql);	
	
	if (!$result) {	   
	   die( __('Error executing save on pledge info.'));
	}
			
	return;
}

function pdproject_admin_menu() {
	add_submenu_page('options-general.php', 'PledgeDrive', 'PledgeDrive', 8, 'PledgeDrive', 'pdproject_submenu');
}

//returns an array of the project names and id
function pdproject_getprojectlist()
{
  	$sql = 'SELECT wp_posts.post_title AS thetitle, pd_projects.id AS theid
				FROM pd_projects, wp_posts
				WHERE pd_projects.postid = wp_posts.id';
		
	$projectlist = $wpdb->get_results($sql);										
	if ($projectlist)
	{			
		return $projectlist;			
	}
	
	return '';		
}

// The admin page
function pdproject_submenu() 
{
	global $wpdb;
		
	if ($_REQUEST['save']) 
	{
	  	if ($_REQUEST['sorting'] == "oldfirst")
		{
			$oldfirst = true;
			update_option('sorting', "oldfirst");
			$sorting = "oldfirst";			
		}
		elseif ($_REQUEST['sorting'] == "newfirst")
		{
			$newfirst = true;
			update_option('sorting', "newfirst");
			$sorting = "newfirst";			
		}
		
		update_option('ppemail', trim(strip_tags($_REQUEST['ppemail'])));
		$ppemail = get_option('ppemail'); 
		
	}
	else
	{	  	
	 	$sorting = get_option('sorting');
		$ppemail = get_option('ppemail'); 		
		
		if ($sorting == "oldfirst")
		{
			$oldfirst = true;						
		}
		elseif ($sorting == "newfirst")
		{
			$newfirst = true;						
		}
	}	

?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">

<div class="wrap" id="sociable_options">
<fieldset id="pledgedriver_options">

<h3>PledgeDrive Options</h3>

<table align="left" border=0 width=100%>
<tr valign="top">
	<td align="right" width=250>Sort comments/pledges:</td>
	<td align="left">
	
	<input type="radio" id="sorting" name="sorting" value="oldfirst"<?php echo $oldfirst ? " checked=\"checked\"" : ""; ?> />&nbsp;&nbsp;Oldest First<br />
	<input type="radio" id="sorting" name="sorting" value="newfirst"<?php echo $newfirst ? " checked=\"checked\"" : ""; ?> />&nbsp;&nbsp;Newest First
	
	</td>
	<td></td>
</tr>

<tr valign="top">
	<td align="left" colspan=2>	
	
	<?php 			
		if ($_REQUEST['save'])
		{
			echo "<div id=\"message\" class=\"updated fade\"><h3 id=\"feedback\" name=\"feedback\">Information Saved.</h3></div>"; 			
		}
	?>
	
	</td>
	
	<td><p class="submit"><input name="save" id="save" tabindex="4" value="Save Changes" type="submit" /></p></td>
</tr>

</table>

</fieldset>
</div>
</form>

<div style="clear: left; display: none;"><br/></div>

<div class="wrap">
<p>
Pick a project title and click the button to get the list of Pledges and thier payment status:

<form name="theForm1" id="theForm1">
	<select id="projectselect" name="projectselect" style="width:300px;">		
		
		<?php 	
		$sql = 'SELECT wp_posts.post_title AS thetitle, pd_projects.postid AS theid
					FROM pd_projects, wp_posts
					WHERE pd_projects.postid = wp_posts.id';
		
		$projectlist = $wpdb->get_results($sql);
		foreach ($projectlist as $project) 
		{
			echo "<option value='" . $project->theid . "'>". $project->thetitle ."</option>";
		}		
		?>
	
	</select>&nbsp;&nbsp;&nbsp;
	<input name="save" id="save" tabindex="3" value="Show List" type="button" style="width:100px;" onclick="display_accounting(this.form);" />	
	
</form>

</p>
<br />


<div id="text_accounting" name="text_accounting" style="display:none;padding:5px;border:1px solid #6DA6D1;"></div>
</div>

<div style="clear: left; display: none;"><br/></div>

<div id="text_csv" name="text_csv" style="display:none;padding:5px;border:1px solid #6DA6D1;"></div>
</div>

<div style="clear: left; display: none;"><br/></div>

<div class="wrap">
<p>
<a href="<?php get_settings('siteurl') ?>/wp-content/plugins/PledgeDrive_v1/ipn/logs/debug.txt">debug</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="<?php get_settings('siteurl') ?>/wp-content/plugins/PledgeDrive_v1/ipn/logs/ipn_success.txt">ipn success log</a>
</p>
</div>

<div class="wrap">
<p>
<img src="<?php get_settings('siteurl') ?>/wp-content/plugins/PledgeDrive_v1/pd_med.jpg"><br/>
Contact info, site link, etc.
</p>
</div>


<?php
}

function pdproject_admin_head() 
{
  	//inject js function to list csv in the window...
?>
<SCRIPT LANGUAGE="JavaScript" SRC="<?php echo get_settings('siteurl') ?>/wp-content/plugins/PledgeDrive_v1/js/prototype.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" SRC="<?php echo get_settings('siteurl') ?>/wp-content/plugins/PledgeDrive_v1/js/functions.js"></SCRIPT>

<SCRIPT LANGUAGE="JavaScript">

var url = "http://havemoneywillvlog.com/wp-content/plugins/PledgeDrive_v1/pd_post.php";
var indicator_icon = "http://havemoneywillvlog.com/wp-content/plugins/PledgeDrive_v1/indicator.gif";

function display_accounting(thisform) 
{
  	try
	{ 			
		var projectid = thisform.projectselect.value;		
							
		var pars = 'action=getaccounting&projectid=' + projectid;
						  	
	  	//make a call to get data
	  	var display_accounting_Ajax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onLoading: display_accounting_handleLoading,			
				onComplete: display_accounting_handleResponse
			}
		);
					
	}
	catch (err)
	{
	   alert("display_accounting:"+err);
	}
	
	return;
}

function display_accounting_handleResponse(originalRequest)
{  			
	try
	{						
		$("text_accounting").innerHTML = originalRequest.responseText;			

	}
	catch (err)
	{
	   alert("display_accounting_handleResponse:"+err);
	}

	return;
}

function display_accounting_handleLoading()
{
  	try
	{
	 	$("text_accounting").style.display = '';
		$("text_accounting").style.background = '#FFFFCC';
		
		var thetext = '<img id="indicator" name="indicator" src="' + indicator_icon + '" align="absmiddle">';
		thetext = thetext + '&nbsp;&nbsp;&nbsp;Getting pledge listing...';
		
		$("text_accounting").innerHTML = thetext;
	}
	catch (err)
	{
	   alert("display_accounting_handleLoading:"+err);
	}

	return;		
}

function closeaccounting()
{
  	try
	{
	  	$("text_accounting").style.display = '';
	}
	catch (err)
	{
	   alert("closeaccounting:"+err);
	}

	return;		
}

function removepledge(theID)
{
   	try
	{
		pars = 'action=removepledge&theid=' + theID;
		
		fRet = confirm('Are you sure you want to remove the pledge?  This is no un-doable.');
				
		if (fRet)
		{		
			//comment form post the form via ajax
			//and on the callback, post the paypal form				
		  	var removepledge_accounting_Ajax = new Ajax.Request(
				url, 
				{
					method: 'get', 
					parameters: pars, 
					onLoading: removepledge_handleLoading,			
					onComplete: removepledge_handleResponse
				}
			);  
		}
	}
	catch (err)
	{
	   alert("removepledge: "+err);
	}

	return;		
}

function confirmpledge(theID)
{
   	try
	{
		pars = 'action=confirmpledge&theid=' + theID;
		
		//comment form post the form via ajax
		//and on the callback, post the paypal form				
	  	var removepledge_accounting_Ajax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onLoading: removepledge_handleLoading,			
				onComplete: removepledge_handleResponse
			}
		);  
	}
	catch (err)
	{
	   alert("confirmpledge: "+err);
	}

	return;		
}

function removepledge_handleResponse(originalRequest)
{  			
	try
	{						
		//var thetext = '<h3 style="margin-top:2px;margin-bottom:2px;">Removed</h3>';
		
		$("text_accounting").innerHTML = originalRequest.responseText;
	}
	catch (err)
	{
	   alert("removepledge_handleResponse:"+err);
	}

	return;
}

function removepledge_handleLoading()
{

  	try
	{
	 	$("text_accounting").style.display = '';
		$("text_accounting").style.background = '#FFFFCC';
		
		var thetext = '<img id="indicator" name="indicator" src="' + indicator_icon + '" align="absmiddle">';
		thetext = thetext + '&nbsp;&nbsp;&nbsp;Removing...';
		
		$("text_accounting").innerHTML = thetext;
	}
	catch (err)
	{
	   alert("removepledge_handleLoading:"+err);
	}

	return;		
}
</SCRIPT>
<?php
}

// --- Actions ---

// Admin page header
add_action('admin_head', 'pdproject_admin_head');

add_action('admin_menu', 'pdproject_admin_menu');
add_action('simple_edit_form', 'pdproject_widget');
add_action('edit_form_advanced', 'pdproject_widget');

add_action('publish_post', 'pdproject_save');
add_action('save_post', 'pdproject_save');

//add_action('preprocess_comment', 'pdproject_validatepledge');
add_action('comment_post', 'pdproject_comenttesting');

// --- Filters ---
add_filter('the_content', 'pledgeprivepost');
?>
