<?php
//////////////////////////////////////////////////////////
/*
  $email="john@zend.com";

  if( !eregi( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email )
  {
    echo "The e-mail was not valid";
  }
  else
  {
    echo "The e-mail was valid";
  }
*/


/*
Find records that need to be reviewed:

SELECT * FROM `kp_bestof_other` WHERE review_status=0 order by other_text


update `kp_bestof_other` set review_status=1 where id <= ???
update `kp_bestof_other` set review_status=1 where id <= 346

*/



// banned list
// Email
// ==================================
// anjent@comcast.net
// christine@anjphotography.com
// ken@anjentertainment.com

// $Id: pnuser.php,v 1.1.1.1 2002/09/15 22:26:15 root Exp $
// ----------------------------------------------------------------------
// POST-NUKE Content Management System
// Copyright (C) 2002 by the PostNuke Development Team.
// http://www.postnuke.com/
// ----------------------------------------------------------------------
// Based on:
// PHP-NUKE Web Portal System - http://phpnuke.org/
// Thatware - http://thatware.org/
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WIthOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Original Author of file: Jim McDonald
// Purpose of file:  BestOf user display functions
// ----------------------------------------------------------------------


// db.php remote //
define("SUBMIT_HOST", "localhost");
// remote
define("SUBMIT_DB",   "kp_phoenix");
define("SUBMIT_USER", "kp_pnmonkey");
define("SUBMIT_PASS", "buster");
// db.php //
//////////////////////////////////////////////////////////////////////////

/*
// db.php local //
define("SUBMIT_HOST", "localhost");
// local
define("SUBMIT_DB", "phoenix");
define("SUBMIT_USER", "root");
define("SUBMIT_PASS", "");
// db.php local //
*/


global $pnuser_googleAd;

$pnuser_googleAd = "";


// todo:
// function pnVarCleanFromInput()
// and add this to <form so admin user and enter stuff
// also add votes string to spreadsheet and e-mail

global $show_numbers;

$show_numbers = false;
list( $show_numbers_var ) = pnVarCleanFromInput('show_numbers_3094893430' );
if ( !empty( $show_numbers_var ) )
{
  $show_numbers = true;
}

/*
global $pnuser_googleAd;

$pnuser_googleAd = <<<EOT
<div style="padding:40px;">
<br />

<script type="text/javascript"><!--
google_ad_client = "pub-2513317495040443";
google_alternate_ad_url = "http://kidspages.org/google_adsense_script.html";
google_ad_width = 300;
google_ad_height = 250;
google_ad_format = "300x250_as";
google_ad_type = "text_image";
google_ad_channel ="";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

</div>

EOT;

*/

// This function converts any series of english words to Proper Casing.
// It also accounts for words such as 'a' and 'the'. To change what
// words are ignored, just change the $noUp array.
function strProperCase( $str )
{
  $size = 0;
  $noUp = array('a','an','of','the','are','at','in');
  $str = trim($str);
  $str = strtoupper($str[0]) . strtolower(substr($str, 1));
  for ( $i=1; $i<strlen($str)-1; ++$i )
  {
    if ( $str[$i] == ' ' )
    {
      for ( $j = $i + 1; $j < strlen( $str ) && $str[$j] != ' '; ++$j ); // find next space
      $size = $j-$i-1;
      $shortWord = false;
      if ( $size <= 3 )
      {
        $theWord = substr( $str, $i + 1, $size );
        for ( $j=0; $j < count( $noUp ) && !$shortWord; ++$j )
          if ( $theWord == $noUp[$j] )
            $shortWord = true;
      }
      if( !$shortWord )
        $str = substr( $str, 0, $i + 1 ) . strtoupper( $str[$i + 1] ) . substr( $str, $i + 2 );
    }
    $i += $size;
  }
  return $str;
}

/**
 * the main user function
 * This function is the default function, and is called whenever the module is
 * initiated without defining arguments.  As such it can be used for a number
 * of things, but most commonly it either just shows the module menu and
 * returns or calls whatever the module designer feels should be the default
 * function (often this is the view() function)
 */
function bestof_user_main()
{
  $baseurl = pnGetBaseURL();
  Header("Location: $baseurl");
  return true;

  // Create output object - this object will store all of our output so that
  // we can return it easily when required
  $output = new pnHTML();

  // Security check - important to do this as early as possible to avoid
  // potential security holes or just too much wasted processing.  For the
  // main function we want to check that the user has at least overview
  // privilege for some item within this component, or else they won't be
  // able to see anything and so we refuse access altogether.  The lowest
  // level of access for administration depends on the particular module, but
  // it is generally either 'overview' or 'read'
  if (!pnSecAuthAction(0, 'BestOf::', '::', ACCESS_READ))
  {
      $output->Text(_BESTOFNOAUTH);
      return $output->GetOutput();
  }

  // Add menu to output - it helps if all of the module pages have a standard
  // menu at their head to aid in navigation
  $output->SetInputMode(_PNH_VERBATIMINPUT);
  $output->Text(bestof_usermenu());
  $output->SetInputMode(_PNH_PARSEINPUT);

  // Return the output that has been generated by this function
  return $output->GetOutput();
}

/**
 * display item
 * This is a standard function to provide detailed informtion on a single item
 * available from the module.
 */
function bestof_user_display($args)
{
  // Get parameters from whatever input we need.  All arguments to this
  // function should be obtained from pnVarCleanFromInput(), getting them
  // from other places such as the environment is not allowed, as that makes
  // assumptions that will not hold in future versions of PostNuke.
  list($tid,
       $objectid) = pnVarCleanFromInput('tid',
                                        'objectid');

  // User functions of this type can be called by other modules.  If this
  // happens then the calling module will be able to pass in arguments to
  // this function through the $args parameter.  Hence we extract these
  // arguments *after* we have obtained any form-based input through
  // pnVarCleanFromInput().
  extract($args);

  // At this stage we check to see if we have been passed $objectid, the
  // generic item identifier.  This could have been passed in by a hook or
  // through some other function calling this as part of a larger module, but
  // if it exists it overrides $tid
  //
  // Note that this module couuld just use $objectid everywhere to avoid all
  // of this munging of variables, but then the resultant code is less
  // descriptive, especially where multiple objects are being used.  The
  // decision of which of these ways to go is up to the module developer
  if (!empty($objectid))
  {
    $tid = $objectid;
  }

  // Create output object - this object will store all of our output so that
  // we can return it easily when required
  $output = new pnHTML();

  // Add menu to output - it helps if all of the module pages have a standard
  // menu at their head to aid in navigation
  $output->SetInputMode(_PNH_VERBATIMINPUT);
  $output->Text(bestof_usermenu());
  $output->SetInputMode(_PNH_PARSEINPUT);

  // Load API.  All of the actual work for obtaining information on the items
  // is done within the API, so we need to load that in before we can do
  // anything.  If the API fails to load an appropriate error message is
  // posted and the function returns
  if (!pnModAPILoad('BestOf', 'user'))
  {
    $output->Text(_LOADFAILED);
    return $output->GetOutput();
  }

  // The API function is called.  The arguments to the function are passed in
  // as their own arguments array
  $item = pnModAPIFunc('BestOf',
                       'user',
                       'get',
                       array('tid' => $tid));

  // The return value of the function is checked here, and if the function
  // suceeded then an appropriate message is posted.  Note that if the
  // function did not succeed then the API function should have already
  // posted a failure message so no action is required
  if ($item == false)
  {
    $output->Text(_BESTOFITEMFAILED);
    return $output->GetOutput();
  }

  // Display details of the item.  Note the use of pnVarCensor() to remove
  // any words from the name that the administrator has deemed unsuitable for
  // the site.  Also note that a module variable is used here to determine
  // whether not not parts of the item information should be displayed in
  // bold type or not
  $output->Text(_BESTOFNAME . ': ');
  if (pnModGetVar('BestOf', 'bold'))
  {
    $output->BoldText(pnVarCensor($item['name']));
  }
  else
  {
    $output->Text(pnVarCensor($item['name']));
  }
  $output->Linebreak(2);
  $output->Text(_BESTOFNUMBER . ': ');
  $output->Text($item['number']);
  $output->Linebreak(2);

  // Let any hooks know that we are displaying an item.  As this is a display
  // hook we're passing a URL as the extra info, which is the URL that any
  // hooks will show after they have finished their own work.  It is normal
  // for that URL to bring the user back to this function
  $output->SetInputMode(_PNH_VERBATIMINPUT);
  $output->Text(pnModCallHooks('item',
                               'display',
                               $tid,
                               pnModURL('BestOf',
                                        'user',
                                        'display',
                                        array('tid' => $tid))));
  $output->SetInputMode(_PNH_PARSEINPUT);

  // Return the output that has been generated by this function
  return $output->GetOutput();
}

/**
 * generate menu fragment
 */
function bestof_usermenu()
{
  // Create output object - this object will store all of our output so that
  // we can return it easily when required
  $output = new pnHTML();

  // Display status message if any.  Note that in future this functionality
  // will probably be in the theme rather than in this menu, but this is the
  // best place to keep it for now

  // Start options menu
  $output->Text(pnGetStatusMsg());
  $output->Linebreak(2);

  // Menu options.  These options are all added in a single row, to add
  // multiple rows of options the code below would just be repeated
  $output->TableStart(_BESTOF);
  $output->SetOutputMode(_PNH_RETURNOUTPUT);
  $columns = array();
  $columns[] = $output->URL(pnModURL('BestOf',
                                     'user',
                                     'view'),
                            _BESTOFVIEW);
  $output->SetOutputMode(_PNH_KEEPOUTPUT);
  $output->SetInputMode(_PNH_VERBATIMINPUT);
  $output->TableAddRow($columns);
  $output->SetInputMode(_PNH_PARSEINPUT);
  $output->TableEnd();

  // Return the output that has been generated by this function
  return $output->GetOutput();
}


///////////////////////////////////////////
// NOVEMBER 2006 CONTESTS   //////////////
///////////////////////////////////////////

////////////////////////////
// Best Of Poll
function bestof_user_bestofpoll()
{
  $contestid = 73;
  $email_subject = "Best Places for Families 2007 Submission";
  $thankyou_title = "Best Places for Families 2007";

  global $page_title;
  $page_title = "Best Places for Families 2007";

  list( $_submit_check,
        $entryname,
        $entryage,
        $entrygrade,
        $entryschool,
        $entryaddress,
        $entrycity,
        $entrystate,
        $entryzip,
        $entryphone,
        $entryemail ) = pnVarCleanFromInput( '_submit_check',
                                             'entryname',
                                             'entryage',
                                             'entrygrade',
                                             'entryschool',
                                             'entryaddress',
                                             'entrycity',
                                             'entrystate',
                                             'entryzip',
                                             'entryphone',
                                             'entryemail');

  // Create output object - this object will store all of our output so that
  // we can return it easily when required
  $output = new pnHTML();
  $output->SetInputMode(_PNH_VERBATIMINPUT);


//  global $show_numbers;
//  if ( !$show_numbers )
//  {
//    $output->Text( outputHeader() );
//    $output->Text( outputIntro() );
//    $output->Text( '<br /><br />' );
//    $output->Text( '<font class="header">Down for maintenance.</font><br /><br />' );
//    $output->Text( '<span style="font-size:18px">Please come back and vote for your favorites soon!</span><br /><br />' );
//    $output->Text( '<a href="/index.php">Back to the home page</a>' );
//    return $output->GetOutput();
//  }


  list($dbconn) = pnDBGetConn();

  if ( $_submit_check == '1' )
  {
    // Check earlier date
    $can_vote = true;

    global $show_numbers;

    if ( !$show_numbers )
    {
      $voted_date = @$_COOKIE['voted'];
      if ( !empty( $voted_date ) )
      {
        $date=strtotime( @$_COOKIE['voted'] );
        $today=strtotime( date("m/d/Y") );
        $can_vote = ( $date < $today );
      }
      else
      {
        $can_vote = true;
      }
    }

    if ( $can_vote )
    {
       // Update Cookie
      setcookie( "voted", date("m/d/Y"), time()+24*60*60 );

      $votestr = handleInput( $output, $dbconn );


      $subject = $email_subject;

      $submitdate = date("F j, Y, g:i a");
      $submitip = getenv("REMOTE_ADDR");

      $message = "";
      $message .= $submitdate . "\n";
      $message .= $submitip . "\n";
      $message .= $votestr . "\n";
      $message .= "\n\n";

      $message .= "entryname: " . $entryname . "\n\n";
      $message .= "entryage: " . $entryage . "\n\n";
      $message .= "entrygrade: " . $entrygrade . "\n\n";
      $message .= "entryschool: " . $entryschool . "\n\n";
      $message .= "entryaddress: " . $entryaddress . "\n\n";
      $message .= "entrycity: " . $entrycity . "\n\n";
      $message .= "entrystate: " . $entrystate . "\n\n";
      $message .= "entryzip: " . $entryzip . "\n\n";
      $message .= "entryphone: " . $entryphone . "\n\n";
      $message .= "entryemail: " . $entryemail . "\n\n";
      $message .= "votestr: " . $votestr . "\n\n";

      $message .= "--- copy/paste ---\n";
      $message .= $entryname . "\n";
      $message .= $entryage . "\n";
      $message .= $entrygrade . "\n";
      $message .= $entryschool . "\n";
      $message .= $entryaddress . "\n";
      $message .= $entrycity . "\n";
      $message .= $entrystate . "\n";
      $message .= $entryzip . "\n";
      $message .= $entryphone . "\n";
      $message .= $entryemail . "\n";
      $message .= $votestr . "\n";

      // To send HTML mail, you can set the Content-type header.
      $headers  = "MIME-Version: 1.0\r\n";
      $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
      $headers .= "From: Contest Submit <contest@kidspages.org>\r\n";

      // and now mail it
      @mail('contest@kidspages.org', $subject, $message, $headers);

      // begin database
      $entryquestion  = $votestr;

      // insert into database
      $strsql = "INSERT INTO `kp_contest` (";
      $strsql .= "contestid"  . ", ";
      $strsql .= "submitdate" . ", ";
      $strsql .= "ipaddress"  . ", ";
      $strsql .= "name"       . ", ";
      $strsql .= "address"    . ", ";
      $strsql .= "city"       . ", ";
      $strsql .= "state"      . ", ";
      $strsql .= "zip"        . ", ";
      $strsql .= "phone"      . ", ";
      $strsql .= "email"      . ", ";
      $strsql .= "age"      . ", ";
      $strsql .= "grade"      . ", ";
      $strsql .= "school"      . ", ";
      $strsql .= "question";
      $strsql .= ") VALUES (";

      $strsql .= "$contestid, ";
      $strsql .= "'" . addslashes( $submitdate     ) . "', ";
      $strsql .= "'" . addslashes( $submitip       ) . "', ";
      $strsql .= "'" . addslashes( $entryname      ) . "', ";
      $strsql .= "'" . addslashes( $entryaddress   ) . "', ";
      $strsql .= "'" . addslashes( $entrycity      ) . "', ";
      $strsql .= "'" . addslashes( $entrystate     ) . "', ";
      $strsql .= "'" . addslashes( $entryzip       ) . "', ";
      $strsql .= "'" . addslashes( $entryphone     ) . "', ";
      $strsql .= "'" . addslashes( $entryemail     ) . "', ";
      $strsql .= "'" . addslashes( $entryage       ) . "', ";
      $strsql .= "'" . addslashes( $entrygrade     ) . "', ";
      $strsql .= "'" . addslashes( $entryschool    ) . "', ";
      $strsql .= "'" . addslashes( $entryquestion  ) . "'";
      $strsql .= ")";

      $dbconn->Execute( $strsql );
      // end database

      $output->Text( '<font class="header">' . $thankyou_title . '</font><br /><br />' );
      $output->Text( '<span style="font-size:18px">Thank you for your submission!</span><br /><br />' );

      $output->Text( '<a href="/index.php">Back to the home page</a>' );
    }
    else
    {
      $output->Text( '<font class="header">' . $thankyou_title . '</font><br /><br />' );
      $output->Text( '<span style="font-size:18px">We\'re sorry. You can only vote once a day. Come back tomorrow!</span><br /><br />' );

      $output->Text( '<a href="/index.php">Back to the home page</a>' );
    }

    return $output->GetOutput();
  }

  $entryname    = htmlentities( $entryname );
  $entryage     = htmlentities( $entryage );
  $entrygrade   = htmlentities( $entrygrade );
  $entryschool  = htmlentities( $entryschool );
  $entryaddress = htmlentities( $entryaddress );
  $entrycity    = htmlentities( $entrycity );
  $entrystate   = htmlentities( $entrystate );
  $entryzip     = htmlentities( $entryzip );
  $entryphone   = htmlentities( $entryphone );
  $entryemail   = htmlentities( $entryemail );

  generatePoll( $output, $dbconn );

// Contest Form
$output->Text(
<<<EOT
<style>
div.class-container {
  border: 2px dashed #fff;
  background-color: #fff;
  padding-left:15px;
  padding-right:15px;
  padding-top:15px;
  padding-bottom:0px;
  font-family: geneva, verdana, trebuchet MS, trebuchet, verdana, arial, sans-serif;
  font-size: 15px;
  font-weight:bold;
  }

div.class-container table {
  font-size: 15px
}
</style>

<br style="clear:both;" />

<div style="width:785px;">
  <div style="float: right;text-align:left;font-size:18px;font-weight:900;color:#264ba0;width:300px;">
  </div>

  <div style="text-align:center;font-size:14px;font-weight:900;width:480px;">
    Fill out this entry form and enter to win<br />
    a family four-pack of unrestricted admission tickets<br />
    to a local movie theatre and a restaurant gift certificate.
  </div>

  <div class="class-container">
    <span style="font-size:20px">Enter to win now!<br /></span>
    For entry to be valid, fill out form completely.
    <br />
      <table border="0">
        <tr><td>Name:</td><td><input name="entryname" size="50" maxlength="50" value="$entryname"></td></tr>
        <tr><td>Age:</td><td><input name="entryage" size="2" maxlength="2" value="$entryage"></td></tr>
        <tr><td>Grade:</td><td><input name="entrygrade" size="2" maxlength="2" value="$entrygrade"></td></tr>
        <tr><td>School:</td><td><input name="entryschool" size="50" maxlength="50" value="$entryschool"></td></tr>
        <tr><td>Address:</td><td><input name="entryaddress" size="50" maxlength="50" value="$entryaddress"></td></tr>
        <tr><td>City:</td><td><input name="entrycity" size="50" maxlength="50" value="$entrycity"></td></tr>
        <tr><td>State:</td><td><input name="entrystate" size="2" maxlength="2" value="$entrystate"></td></tr>
        <tr><td>Zip:</td><td><input name="entryzip" size="10" maxlength="10" value="$entryzip"></td></tr>
        <tr><td>Phone:</td><td><input name="entryphone" size="15" maxlength="15" value="$entryphone"></td></tr>
        <tr><td>E-Mail:</td><td><input name="entryemail" size="50" maxlength="50" value="$entryemail"></td></tr>
      </table>
  </div>
</div>

EOT
);


// Input Button
$output->Text(
<<<EOD
<br style="clear:both;" />
<br style="clear:both;" />

<div class="bestof-poll" style="padding:0px;margin:0px;">
  <input style="width:460px;height:40px;font-size:15px;font-weight:bold;" value="Vote and Enter to WIN!" type="submit">
</div>
</form>

<br style="clear:both;" />
EOD
);

$output->Text( '</form>' );

  $output->Text( outputSmallPrint() );

  $output->Text( outputFooter() );


  global $pnuser_googleAd;
  $output->Text( $pnuser_googleAd );

  return $output->GetOutput();
}

// new stuff



$eol = "\n";

function outputHeader()
{

$str = <<<EOD

<style>
.bestof-poll {
  width:500px;
  font: small/18px "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif;
  text-align: left;
  color: #000;
  background-color: #fff;
}

.bestof-poll-old {
  width:500px;
  font: small/18px "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif;
  font-family: Verdana;
  font-size: 1em;
  line-height: 1.2em;
  letter-spacing: 0;
  text-align: left;
  word-spacing: normal;
  text-decoration: none;
  color: #444;
  background-color: #fff;
}

.bestof-poll-submit {
  background-color: #ccccff;
  width: 220px;
  padding:10px;
  float: left;
}

.bestof-poll-results {
  background-color: #ffffff;
  width: 220px;
  padding:10px;
  float: left;
  margin-left: 20px;
}

table.bestof-poll-form {
  margin-left: 0px;
  width: 100%;
}

table.bestof-poll-form td {
  vertical-align: top;
  padding: 2px 3px;
  font-size: 90%;
}

.bestof-section-head {
  padding:10px;
  margin: 10px 0px 10px 0px;
  width: 500px;
  font: 18px "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif;
  text-align: left;
  color: #000;
  background-color: #ffff99;
}

.image-right {
  float:right;
  padding:10px;
}

.image-left {
  float:left;
  padding-right:10px;
  padding-top:10px;
  padding-bottom:10px;
}

div.othertext {
  width: 200px;
  border: 1px solid #ccc;
  background: #f2f2f2;
  padding: 5px;
  margin-top: 5px;
}

</style>

EOD;

  return $str;
}


function outputIntro()
{

$str = <<<EOD


<div style="text-align:left;font-size:12px;font-weight:normal;width:500px;">

<div style="text-align:center;font-size:18px;font-weight:bold;">
Who knows the BEST PLACES FOR FAMILIES?<br />
You do!<br />
</div>

<div class="image-left">
  <img src="/images/bestof2007/bestof-megagirl.jpg"  width="121" height="250" border="0">
</div>

<div class="image-right">
  <img src="/images/bestof2007/BestPlaces-2007-FirstPlace.jpg" width="150" height="113" border="0">
</div>

  <p>We value our readers opinions!</p>

  <p>Vote for your favorites below and win a night out on the town for your family!</p>

  <p>Tell us where you get the yummiest ice cream, the cutest hair-do and your family's favorite restaurant!</p>

  <p>Voting will take place online March 1-April 6, 2007.</p>

  <p>Winners will be chosen by YOU, our readers, real families voting for the places they love.</p>

  <p>Winners will be determined by the highest number of votes. Voting will end at midnight April 6, 2007. Winners will be announced in the May Issue of Kids' Pages Family Magazine and on KidsPages.org.</p>

  <p>Good Luck to all of these great family-friendly businesses! Be sure to vote often for your favorites!</p>

<div style="text-align:center;font-size:15px;font-weight:bold;">
  10 Lucky Families will win a night out on the town!<br />
  Movie Tickets and Dinner Gift Certificates<br />
  will be mailed to 10 randomly chosen entries!
</div>

</div>

EOD;

  return $str;
}

function outputSmallPrint()
{

$str = <<<EOD

<div style="text-align:left;font-size:10px;font-weight:normal;width:430px;">
The small print:<br />
Winners will receive a family four-pack of unrestricted admission tickets to a local movie theatre and a restaurant gift certificate. No purchase necessary to enter. Legal residents of the 50 United States may enter. Entrants under age 18 must have a parent or legal guardian’s permission to enter. Limit one online entry per person or email address per day per internet location. Contest Sponsors and their dependants are not eligible to win. Winner will be drawn at random and mailed their prize. For complete Official Rules for Online Contests please click on contest rules.<br />
<br />
To request a paper ballot, please send a self-addressed stamped envelope to Kids' Pages Best Of Poll, PO Box 745219, Arvada, CO  80006. Requests must be made no later than March 25, 2007. Paper ballots will also be available at Kids' Pages Family Festivals.<br />
<br />
<br />
</div>

EOD;

  return $str;
}

function outputFooter()
{

$str = <<<EOD

EOD;

  return $str;
}

function OutputImage( $image, $website_address )
{
  global $eol;
  $retStr = "";
  if ( !empty( $image ) )
  {
    if ( empty( $website_address ) )
    {
      $retStr = '<div style="float:right;margin:10px;"><img src="/images/kplinks/' . $image . '" border="0"></div>' . $eol;
    }
    else
    {
      $strImgage = '<img src="/images/kplinks/' . $image . '" border="0">';
      $strAnchor = '<a href="http://' . $website_address . '" target="_blank">' . $strImgage . '</a>';
      $retStr = '<div style="float:right;margin:10px;">' . $strAnchor . '</div>' . $eol;
    }
  }
  return $retStr;
}

function OutputSponsorImage( $sponsor )
{
  global $eol;
  $retStr = "";
  if ( $sponsor == 'Y' )
  {
    $retStr = '<div style="float:left"><img src="/images/kplinks/hilitesponsor.gif" border="0"></div>' . $eol;
  }
  return $retStr;
}

function OutputHeaderTitle( $title, $value )
{
  global $eol;
  $retStr = "";
  if ( !empty( $value ) )
  {
    $retStr = '<span class="header-title">' . $title . ':</span> ' . $value . '<br>' . $eol;
  }
  return $retStr;
}

function OutputWebsite( $title, $value )
{
  global $eol;
  $retStr = "";
  if ( !empty( $value ) )
  {
    $retStr = '<span class="header-title">' . $title . ':</span> <a href="http://' . $value . '" target="_blank">' . $value . '</a><br>' . $eol;
  }
  return $retStr;
}

function OutputEmail( $title, $value )
{
  global $eol;
  $retStr = "";
  if ( !empty( $value ) )
  {
//    $retStr = '<span class="header-title">' . $title . ':</span> <a href="mailto:' . $value . '" target="_blank">' . $value . '</a><br>' . $eol;
    $retStr = '<span class="header-title">' . $title . ':</span> <a href="mailto:' . $value . '">' . $value . '</a><br>' . $eol;
  }
  return $retStr;
}

function getCategoryListing( $key, &$dbconn, &$vote_totals )
{
  global $eol;

  $retStr = "";

  // Pages
  $strsql = "select contact_id, cat_id, votes, company_name, image, sponsor, contact_name, location_name,
             address1, address2, city, state, zip, phone, hours, ages, cost,
             website_address, email_address, directions, description,
             loc2_location_name, loc2_address, loc2_city, loc2_phone, loc2_email_address,
             loc3_location_name, loc3_address, loc3_city, loc3_phone, loc3_email_address,
             loc4_location_name, loc4_address, loc4_city, loc4_phone, loc4_email_address
             from kp_bestof_entry
             where (cat_id IN ($key) OR cat_id LIKE '%,$key,%') and link_type_id = 0
             order by company_name";

  $result = $dbconn->Execute( $strsql );
  $entry_count = 0;
  while ( !$result->EOF )
  {
    $entry_count++;
    // load key for record
    $row = $result->GetRowAssoc(0);

    $x_contact_id          = $row["contact_id"];
    $x_cat_id              = $row["cat_id"];
    $x_votes               = $row["votes"];
    $x_company_name        = $row["company_name"];
    $x_image               = $row["image"];
    $x_sponsor             = $row["sponsor"];
    $x_contact_name        = $row["contact_name"];
    $x_location_name       = $row["location_name"];
    $x_address1            = $row["address1"];
    $x_address2            = $row["address2"];
    $x_city                = $row["city"];
    $x_state               = $row["state"];
    $x_zip                 = $row["zip"];
    $x_phone               = $row["phone"];
    $x_hours               = $row["hours"];
    $x_ages                = $row["ages"];
    $x_cost                = $row["cost"];
    $x_website_address     = $row["website_address"];
    $x_email_address       = $row["email_address"];
    $x_directions          = $row["directions"];
    $x_description         = $row["description"];
    $x_loc2_location_name  = $row["loc2_location_name"];
    $x_loc2_address        = $row["loc2_address"];
    $x_loc2_city           = $row["loc2_city"];
    $x_loc2_phone          = $row["loc2_phone"];
    $x_loc2_email_address  = $row["loc2_email_address"];
    $x_loc3_location_name  = $row["loc3_location_name"];
    $x_loc3_address        = $row["loc3_address"];
    $x_loc3_city           = $row["loc3_city"];
    $x_loc3_phone          = $row["loc3_phone"];
    $x_loc3_email_address  = $row["loc3_email_address"];
    $x_loc4_location_name  = $row["loc4_location_name"];
    $x_loc4_address        = $row["loc4_address"];
    $x_loc4_city           = $row["loc4_city"];
    $x_loc4_phone          = $row["loc4_phone"];
    $x_loc4_email_address  = $row["loc4_email_address"];
    $result->MoveNext();

    $vote_totals[$x_company_name] = $x_votes;

$retStr .= <<<EOD

    <tr>
      <td style="white-space: nowrap;" valign="top" align="center" width="1%">
        <input name="cat_$key" value="$x_contact_id" id="entry_$x_contact_id" type="radio">
      </td>
      <td>
        <label for="entry_$x_contact_id">$x_company_name</label>
      </td>
    </tr>
EOD;

//    $retStr .= "<h2>x_contact_id: " . $x_contact_id . "</h2>";

//    $retStr .= $eol;
//    $retStr .= '<div class="header">' . $eol;
//    $retStr .= OutputImage( $x_image, $x_website_address );
//    $retStr .= OutputSponsorImage( $x_sponsor );

//    $retStr .=  "<strong>$x_company_name</strong><br>" . $eol;

//    $retStr .= OutputHeaderTitle( "Address", $x_address1 . ( empty( $x_address2 ) ? "" : "<br>$x_address2" ) );
//    $retStr .= OutputHeaderTitle( "City", $x_city );
//    $retStr .= OutputHeaderTitle( "Phone", $x_phone );
//    $retStr .= OutputHeaderTitle( "Hours", $x_hours );
//    $retStr .= OutputHeaderTitle( "Ages", $x_ages );
//    $retStr .= OutputHeaderTitle( "Cost", $x_cost );
//    $retStr .= OutputWebsite( "Website", $x_website_address );
//    $retStr .= OutputEmail( "E-Mail", $x_email_address );
//    $retStr .= OutputHeaderTitle( "Directions", $x_directions );

//    if ( !empty ( $x_loc2_location_name ) ||
//         !empty ( $x_loc2_address ) ||
//         !empty ( $x_loc2_city ) ||
//         !empty ( $x_loc2_phone ) ||
//         !empty ( $x_loc2_email_address ) ||
//         !empty ( $x_loc3_location_name ) ||
//         !empty ( $x_loc3_address ) ||
//         !empty ( $x_loc3_city ) ||
//         !empty ( $x_loc3_phone ) ||
//         !empty ( $x_loc3_email_address ) ||
//         !empty ( $x_loc4_location_name ) ||
//         !empty ( $x_loc4_address ) ||
//         !empty ( $x_loc4_city ) ||
//         !empty ( $x_loc4_phone ) ||
//         !empty ( $x_loc4_email_address ) )
//    {
//      $retStr .= '<div style="color: #6A5ACD; margin-top: 10px; font-size: bigger; font-weight: bold;">Other Locations</div>';
//
//      if ( !empty ( $x_loc2_location_name ) ||
//           !empty ( $x_loc2_address ) ||
//           !empty ( $x_loc2_city ) ||
//           !empty ( $x_loc2_phone ) ||
//           !empty ( $x_loc2_email_address ) )
//      {
//        $retStr .= OutputHeaderTitle( "Location", $x_loc2_location_name );
//        $retStr .= OutputHeaderTitle( "Address", $x_loc2_address );
//        $retStr .= OutputHeaderTitle( "City", $x_loc2_city );
//        $retStr .= OutputHeaderTitle( "Phone", $x_loc2_phone );
//        $retStr .= OutputEmail( "E-Mail", $x_loc2_email_address );
//      }
//
//      if ( !empty ( $x_loc3_location_name ) ||
//           !empty ( $x_loc3_address ) ||
//           !empty ( $x_loc3_city ) ||
//           !empty ( $x_loc3_phone ) ||
//           !empty ( $x_loc3_email_address ) )
//      {
//        $retStr .= '<br>';
//        $retStr .= OutputHeaderTitle( "Location", $x_loc3_location_name );
//        $retStr .= OutputHeaderTitle( "Address", $x_loc3_address );
//        $retStr .= OutputHeaderTitle( "City", $x_loc3_city );
//        $retStr .= OutputHeaderTitle( "Phone", $x_loc3_phone );
//        $retStr .= OutputEmail( "E-Mail", $x_loc3_email_address );
//      }
//
//      if ( !empty ( $x_loc4_location_name ) ||
//           !empty ( $x_loc4_address ) ||
//           !empty ( $x_loc4_city ) ||
//           !empty ( $x_loc4_phone ) ||
//           !empty ( $x_loc4_email_address ) )
//      {
//        $retStr .= '<br>';
//        $retStr .= OutputHeaderTitle( "Location", $x_loc4_location_name );
//        $retStr .= OutputHeaderTitle( "Address", $x_loc4_address );
//        $retStr .= OutputHeaderTitle( "City", $x_loc4_city );
//        $retStr .= OutputHeaderTitle( "Phone", $x_loc4_phone );
//        $retStr .= OutputEmail( "E-Mail", $x_loc4_email_address );
//      }
//    }

//    $retStr .= '</div>' . $eol;
//    $retStr .= "<p>$x_description</p>";
//    $retStr .= '<br>';
    $retStr .= $eol;
  }
  $result->Close();

// todo: debug 'other'

$retStr .= <<<EOD
    <tr>
      <td style="white-space: nowrap;" valign="top" align="center" width="1%">
        <input name="cat_$key" value="other" id="entry_{$key}_other" type="radio">
      </td>
      <td>
        <label for="entry_{$key}_other">Other: </label> <input name="othertext_$key" size="17" maxlength="100" onchange="document.bestofpoll.cat_{$key}[{$entry_count}].checked = (document.bestofpoll.othertext_$key.value.length>0)" type="text">
      </td>
    </tr>
EOD;

//  @mysql_free_result($rs);
  return $retStr;
}

function generatePoll( &$output, &$dbconn )
{
  global $eol;

  $grand_total_votes = 0;

  global $show_numbers;

/*
  $show_numbers = false;
  $show_numbers_var = @$_GET['show_numbers_3094893430'];

  if ( !empty( $show_numbers_var ) )
  {
    $show_numbers = true;
  }
*/
  $output->Text( outputHeader() );
  $output->Text( outputIntro() );

  $output->Text( '<form name="bestofpoll" action="/index.php" method="post">' );
  $output->Text( '<input type="hidden" name="_submit_check" value="1"/>' );
  $output->Text( '<input type="hidden" name="module" value="BestOf">' );
  $output->Text( '<input type="hidden" name="func" value="bestofpoll">' );

  if ( $show_numbers )
  {
    $output->Text( '<input type="hidden" name="show_numbers_3094893430" value="1">' );
  }

  $strsql = 'select section_id, section_desc from kp_bestof_section where section_id > 1';

  $result = $dbconn->Execute( $strsql );

  $sectionArr = array();
  while( list( $section_id, $section_desc ) = $result->fields )
  {
    $result->MoveNext();
    $sectionArr[$section_id] = $section_desc;
  }
  $result->Close();

  reset($sectionArr);

  $allCatsArr = array();
  while (list($key, $val) = each($sectionArr))
  {
    $categoryArr = array();
    $strsql = 'select category_id, category_desc from kp_bestof_category where section_id=' . $key . ' and parent_id = 1';
    $result = $dbconn->Execute( $strsql );

    while( list( $category_id, $category_desc ) = $result->fields )
    {
      $result->MoveNext();
      $categoryArr[$category_id] = $category_desc;
    }
    $result->Close();
    $allCatsArr[$key] = array( "sectiondesc" => $val, "cats" => $categoryArr );
  }


/////////////////////////////////////////////////

  $strsql = 'SELECT category_id, count(*) as other_count FROM kp_bestof_other where review_status = 1 and length( other_text ) > 0 GROUP BY category_id';
  $result = $dbconn->Execute( $strsql );

  $otherArr = array();
  while( list( $category_id, $other_count ) = $result->fields )
  {
    $result->MoveNext();
    $otherArr["".$category_id] = $other_count;

//    $output->Text( '$category_id: ' . $category_id . '    $other_count: ' . $other_count . '<br />' );  // todo: debug
  }
  $result->Close();
/////////////////////////////////////////////////





  reset( $allCatsArr );
  while (list($sectkey, $allcat) = each($allCatsArr) )
  {

    $sectionDesc = $allcat["sectiondesc"];
    $cats = $allcat["cats"];

    $output->Text( "<div class=\"bestof-section-head\">$sectionDesc</div>" );

    while (list($key, $catDesc) = each($cats) )
    {
      $outputStr = "";

$outputStr .= <<<EOD

<div class="bestof-poll" style="padding:0px;margin:0px;">

  <div class="bestof-poll-submit">
    <table class="bestof-poll-form">
    <tr>
    <td colspan="2">
      <b style="font-size: 130%;">$catDesc</b>
    </td>
    </tr>
EOD;

      $vote_totals = array();
      $outputStr .= getCategoryListing( $key, $dbconn, $vote_totals );

$outputStr .= <<<EOD
    </table>
  </div>

  <div class="bestof-poll-results">
EOD;


//  $output->Text( '$key: ' . $key . '<br />' );  // todo: debug

  $otherCount = array_key_exists( $key, $otherArr ) ? $otherArr[$key] : 0;

  $vote_totals['Other'] = $otherCount;


  reset($vote_totals);
  $vote_sum = 0;
  while (list($vote_name, $vote_number) = each($vote_totals))
  {
    $vote_sum += $vote_number;
  }

/*
<div style="clear:both;" >
  <div>Bo Peep Books, 0 </div>
  <div>
    <div style="float: left;background-color:red;height:18px;width:10px;margin-bottom:8px"></div>
    <div>&nbsp;&nbsp;&nbsp;abc0ddd%</div>
  </div>
</div>
*/

  $outputStr .= "<div style=\"font-size: 130%;\" >The results so far:</div>";
  reset($vote_totals);
  while (list($vote_name, $vote_number) = each($vote_totals))
  {
    $outputStr .= "<div style=\"clear:both;\" >";
//    $outputStr .= "<div>$vote_name, $vote_number </div>";
    if ( $show_numbers )
    {
      $outputStr .= "<div>$vote_name: $vote_number</div>";
    }
    else
    {
      $outputStr .= "<div>$vote_name</div>";
    }
    if ( $vote_sum > 0 )
    {
      $column_width = 200;  // pixel width

      $vote_percent = intval( round( 100 * ( $vote_number / $vote_sum ) ) );
      $div_width = intval( $column_width * ( $vote_percent / 100 ) );
      if ( $div_width == 0 )
      {
        $div_width = 1;
      }

      $outputStr .= "<div><div style=\"float: left;background-color:red;height:15px;width:{$div_width}px;margin-bottom:8px\"></div><div>&nbsp;&nbsp;{$vote_percent}%</div></div>";
    }
    $outputStr .= "</div>";
  }


/////////////////////////////////////////////////
  if ( $otherCount > 0 )
  {
    $strsql = "SELECT distinct other_text FROM kp_bestof_other where category_id = $key and review_status = 1 and length( other_text ) > 0 order by other_text";
    $overflow_style = "overflow: auto;";


    if ( $show_numbers )
    {
      $strsql = "SELECT other_text FROM kp_bestof_other where category_id = $key and length( other_text ) > 0 order by other_text";
      $overflow_style = "";
    }

    $result = $dbconn->Execute( $strsql );

    $box_height = "";
    if ( !$show_numbers && $otherCount > 3 )
    {
      $box_height = "height: 55px;";
    }

    $outputStr .= "<div class=\"othertext\" style=\"{$box_height}{$overflow_style}\">";
    while( list( $other_text ) = $result->fields )
    {
      $result->MoveNext();
      $outputStr .= $other_text . '<br />';
    }
    $result->Close();
    $outputStr .= '</div>';
  }
/////////////////////////////////////////////////

  $grand_total_votes += $vote_sum;

  if ( $show_numbers )
  {
    $outputStr .= "<br />";
    $outputStr .= "TOTAL VOTES: $vote_sum <br />";
  }


$outputStr .= <<<EOD
  </div>
</div>

<br style="clear:both;" />
<br style="clear:both;" />
EOD;

      $output->Text( $outputStr );

    }
  }

  if ( $show_numbers )
  {
    $output->Text( "<b>GRAND TOTAL VOTES:</b> $grand_total_votes <br />" );
  }
}

function handleInput( &$output, &$dbconn )
{
  global $eol;

  $votestr = "";

  $debug_output = false;

  $submitdate = date("F j, Y, g:i a");
  $submitip = getenv("REMOTE_ADDR");

  $strsql = 'SELECT category_id, category_desc FROM kp_bestof_category where category_id > 1';
  $result = $dbconn->Execute( $strsql );

  $categoryArr = array();
  while( list( $category_id, $category_desc ) = $result->fields )
  {
    $result->MoveNext();
    $categoryArr[$category_id] = $category_desc;

    if ( $debug_output ) $output->Text( '$categoryArr[$category_id] = ' . $categoryArr[$category_id] . ' $category_desc = ' .  $category_desc . "<br />" );
  }
  $result->Close();

  if ( $debug_output ) $output->Text( "showcategorys<br />" );

  reset($categoryArr);
  while (list($key, $val) = each($categoryArr))
  {
    $category_key = 'cat_' . $key;
    $entry_key = @$_POST[ $category_key ];

    if ( !empty( $entry_key ) )
    {
      if ( $debug_output ) $output->Text( "key: $key, val: $val <br />" );
      if ( $debug_output ) $output->Text( "entry_key: $entry_key <br />" );
      if ( $entry_key == 'other' ) // todo: debug
      {
        $other_key = 'othertext_' . $key;
        $other_text = @$_POST[ $other_key ];

        if ( $debug_output ) $output->Text( "<b>OTHER TEXT</b> $other_key: $other_text <br /><br />" );
        if ( $debug_output ) $output->Text( '$other_text = ' . $other_text . "<br />" );

        if ( !empty( $other_text ) )
        {
          $other_text = strProperCase( $other_text );

          if ( $debug_output ) $output->Text( 'proper cased = ' . $other_text . "<br />" );

          $other_text = (!get_magic_quotes_gpc()) ? addslashes($other_text) : $other_text;
          $strsql = "INSERT INTO kp_bestof_other ( category_id, other_text ) VALUES ( $key, '$other_text' )";

          if ( $debug_output ) $output->Text( $strsql . "<br />" );
          if ( $debug_output ) $output->Text( "strsql: $strsql <br />" );

          $votestr .= "Other($key): " . $other_text . "; ";
          $dbconn->Execute( $strsql );
        }
      }
      else
      {
        $votestr .= $entry_key . "; ";
        $strsql = "UPDATE kp_bestof_entry SET votes = votes + 1 where contact_id = $entry_key";

        if ( $debug_output ) $output->Text( $strsql . "<br />" );

        $dbconn->Execute( $strsql );
      }
    }
    if ( $debug_output ) $output->Text( "<br />" );
  }
  if ( $debug_output ) $output->Text( "<b>votestr:</b> $votestr<br />" );

  return $votestr;
}




/*
$_submit_check = @$_GET[ '_submit_check' ];

if ( $_submit_check == '1' )
{
  handleInput();
}
else
{
  outputSpreadSheet();
}
*/


?>
