<?php require_once "cmsAdmin/lib/viewer_functions.php"; ?>
<?php

	// load global functions
  require_once "init.php";
  require_once("makeLinkFunctions.php");

  // load listings
  list($listingsRecordRecords, $listingsRecordDetails) = getRecords(array(
    'tableName'   => 'listings',
    'joinTable'   => 'homepages',
    'where'       => "num = '".intval(@$_REQUEST['productNum'])."'",
    'limit'       => '1',
    'allowSearch' => false,
  ));
  $listingsRecord = @$listingsRecordRecords[0];
  if (!$listingsRecord) { print "listingsRecord not found!"; exit; }
  
  
  // load selected categories
  list($categoryRecords) = getRecords(array(
    'tableName' => 'categories',
    'where' 	=> "show_on_homepage = '1'",
    'orderBy'   => 'name',
  ));

  
  //
  list($listingRecords, $listingDetails) = getRecords(array(
    'tableName'   => 'listings',
    'joinTable'   => 'categories',
    'perPage'     => '10',
  ));
    
  //generate maths test
  $mathTest = simpleMathTest();

  // process form
  if (@$_REQUEST['Send']) {

    //remove any potentially bad characters from the POST
    foreach($_POST as $key=>$value){
      $_POST[$key] = htmlspecialchars($value);
    }
    // error checking
    $errorsAndAlerts = "";
    if      (!@$_REQUEST['name'])                               { $errorsAndAlerts .= "Please enter your name<br/>\n"; }
    if      (!@$_REQUEST['email'])                              { $errorsAndAlerts .= "Please enter your email<br/>\n"; }
    else if (!isValidEmail(@$_REQUEST['email']))                { $errorsAndAlerts .= "Please enter a valid email (example: user@example.com)<br/>\n"; }
    if      (!@$_REQUEST['skill'])                              { $errorsAndAlerts .= "Please answer the skill testing question<br>\n";}
    else if (sha1(@$_REQUEST['skill']) != @$_REQUEST['skilla']) { $errorsAndAlerts .= "Your answer was wrong. Please try again<br>\n";}

    if ($_REQUEST['phone'] == '') { $_REQUEST['phone'] = 'not provided'; }
    
    // turn off strict mysql error checking for: STRICT_ALL_TABLES
    mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)

    // add message
    if (!$errorsAndAlerts) {
      mysql_query("INSERT INTO `{$TABLE_PREFIX}contact_seller` SET
                      name			            = '".mysql_escape( $_REQUEST['name'] )."',
                      email			            = '".mysql_escape( $_REQUEST['email'] )."',
                      message			        = '".mysql_escape( $_REQUEST['message'] )."',
                      phone_number		        = '".mysql_escape( $_REQUEST['phone'] )."',
                      listing_id		        = '".mysql_escape( $_REQUEST['listing_id'] )."',
                      seller            	    = '".$listingsRecord['homepages.organisation']."',
                      createdDate               = '".mysql_datetime()."',
                      updatedDate               = '".mysql_datetime()."',
                      createdByUserNum          = '".$listingsRecord['createdByUserNum']."',
                      updatedByUserNum          = '".$listingsRecord['createdByUserNum']."'"
		      )
      or die("MySQL Error Creating Record:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      
      $placeholders = array(
        'from'            => $_REQUEST['email'],
        'to'              => $_REQUEST['to'],
        'buyer_name'      => $_REQUEST['name'],
        'buyer_email'     => $_REQUEST['email'],
        'seller_name'     => $listingsRecord['homepages.contact_name'],
        'phone'           => htmlspecialchars($_REQUEST['phone']),
        'message'         => htmlspecialchars($_REQUEST['message']),
        'subject'         => htmlspecialchars($_REQUEST['subject']),
        'listing_id'      => $_REQUEST['listing_id'],
        'listing_link'    => 'www.mydomain.co.uk/listingDetail.php?',
        'listing_item'    => $listingsRecord['product']
      );
      
      //email admin
      $errors = sendMessage(contact_emailTemplate(array(
        'template_id'      => 'MESSAGE-BUYER-SELLER',
        'placeholders'     => $placeholders,
        'from'             => $_REQUEST['email'],
        'to'               => 'admin@mydomain.co.uk',
        'subject'         => htmlspecialchars($_REQUEST['subject'])        
      )));
      
      // email seller
      $errors = sendMessage(contact_emailTemplate(array(
        'template_id'      => 'MESSAGE-BUYER-SELLER',
        'placeholders'     => $placeholders,
        'from'             => $_REQUEST['email'],
        'to'               => $_REQUEST['to'],
        'subject'         => htmlspecialchars($_REQUEST['subject'])        
      )));
           
      // email buyer
      $placeholders['from'] = 'admin@mydomain.co.uk';
      $placeholders['to']   = $_REQUEST['email'];
      $errors = sendMessage(contact_emailTemplate(array(
        'template_id'      => 'MESSAGE-SELLER-BUYER',
        'placeholders'     => $placeholders,
        'from'             => 'admin@mydomain.co.uk',
        'to'               => $_REQUEST['email'],
        'subject'         => htmlspecialchars($_REQUEST['subject']) 
      )));
      
      
      
      if ($errors) { die("Error sending message: $errors\n\nPlease let us know about this error!"); }
      
      $errorsAndAlerts  = "Thanks, we've emailed the seller with your message.<br/><br/>\n";
      $allGood          = "<font style='color: #32cd32; font-weight: bold; font-size: 10px; font-family: arial;'>";
      
      $_REQUEST        = array(); // clear form values
      $_POST           = array(); // clear post on successful submit

    }
  }
  
  $specificTitle = "<title>" . $listingsRecord['product'] . " - " . $listingsRecord['manufacturer'] . "</title>";


  
?>
<?php include "include_header_new.php"; ?>
		<!-- main -->
		<div id="main">
			<div class="main-c">
				<!-- main-section -->
				<div class="main-section">
					<div class="section-holder">
						<!-- content -->
						<div id="content">
							<div class="topping">
								<!-- Breadcrumbs -->
								<ul class="breadcrumbs">
									<li><a href="/">HOME</a></li>
									<li><a href="<?php echo makeListCategory($listingsRecord);?>" class="secondary"><?php echo $listingsRecord['category:label'] ?></a></li>
									<li>Product Details</li>
								</ul>
								<!-- Back to Previous -->
								<a href="javascript:history.back(1)" class="back-to-prev">Back to Previous</a>
							</div>
							<!-- Page Heading -->
							<div class="page-heading">
								<h1><?php echo $listingsRecord['product'] ?> <?php if(@$listingsRecord['top_deal']) : ?><span class="mark-top">TOP DEAL</span><?php endif ?></h1>

								<div class="links">
									<a href="javascript:window.print()" class="link-print">Print this page</a>
									




  <?php
    $tableOrTag = 'listings';       // Update with your section's table name
    $recordNum  = $listing['num'];  // Update this with current record number
  ?>

  <div class="<?php wsf_cssClassFor($tableOrTag, $listingNum, 'add'); ?>"
       style="<?php wsf_displayStyleFor($tableOrTag, $listingNum, 'add'); ?>">
    <a href="#" class="link-add" onclick="<?php wsf_onClickFor($tableOrTag, $recordNum, 'add'); ?>">Add to Watch list</a>
  </div>

  <div class="<?php wsf_cssClassFor($tableOrTag, $recordNum, 'remove'); ?>"
       style="<?php wsf_displayStyleFor($tableOrTag, $recordNum, 'remove'); ?>">
    <a href="#" class="link-add" onclick="<?php wsf_onClickFor($tableOrTag, $recordNum, 'remove'); ?>">Remove from Watch list</a>
  </div>


								</div>
							</div>
							<div class="main-holder">
								<!-- gallery -->
								<div class="gallery gallery2">
                  
                  

                    <!-- fade-list -->
                    <ul class="fade-list">
                    <?php if (!$listingsRecord['uploads']): /* if no uploads show this: */ ?>
                      <li class="active"><div class="gallery-block"><img src="http://www.mydomain.co.uk/images/comingsoon.jpg" /></div></li>
                    <?php else : // otherwise display the gallery ?>
                    <?php $firstItem = true; ?>
                      <?php foreach ($listingsRecord['uploads'] as $upload): ?>
                        <?php if ($firstItem) { echo "<li class='active'>"; $firstItem = false; } else { echo "<li>"; } ?>
                          <?php if(@$listingsRecord['top_deal']) : ?><span class="ico-top">top deal!</span><?php endif ?>
                          <?php if(@$listingsRecord['sold']) : ?><span class="ico-sold">sold!</span><?php endif ?>
                          <div class="gallery-block">
                            
							<img src="<?php echo $upload['urlPath'] ?>" title="<?php echo $upload['info1'] ?>" alt="<?php echo $upload['info1'] ?>" width="<?php echo $upload['width'] ?>" height="<?php if($upload['height'] < 295) { echo $upload['height']; }else{ echo '295';} ?>" />
                            <div class="click"><a href="<?php echo $upload['urlPath'] ?>" class="open-popup" rel="gall"><span>click to magnify</span></a></div>
                          </div>
                        </li>
                      <?php endforeach ?>
                    
                    </ul>
                  
									<!-- switcher -->
                    <div class="gallery-thumbnail">
                      <a href="#" class="prev">prev</a>
                      <div class="hold">
                      <div class="frame">
                      <ul>
                      <?php $firstItem = true; ?>
                      <?php foreach ($listingsRecord['uploads'] as $upload): ?>
                        <?php if ($firstItem) { echo "<li class='active'>"; $firstItem = false; } else { echo "<li>"; } ?>
                        <a href="#">
                          <img src="<?php echo $upload['thumbUrlPath'] ?>" width="51" height="38" title="<?php echo $upload['info1'] ?>" alt="<?php echo $upload['info1'] ?>" />
                        </a>
                        </li><?php echo "\n"; ?>
                      <?php endforeach ?>
                      </ul>
                      </div>
                      </div>
                      <a href="#" class="next">next</a>
                    </div>
                  <?php endif //and if there are images for this product ?>
								</div>
								<!-- Block Meta date -->
								<div class="meta-block">
									<dl>
										<dt>MANUFACTURER</dt>
										<dd><?php 
if(!$listingsRecord['manufacturer']) { 
echo "<p>No manufacturer specified</p>"; 
} 
else echo $listingsRecord['manufacturer'];
?></dd>
										<dt>MODEL</dt>
										<dd><?php 
if(!$listingsRecord['model']) { 
echo "<p>Contact advertiser for details</p>"; 
} 
else echo $listingsRecord['model'];
?></dd>
										<dt>LIST PRICE</dt>
										<dd>

<?php 
if(!$listingsRecord['list_price']) { 
echo "<p>No price specified</p>"; 
} 
else echo $listingsRecord['currency'].$listingsRecord['list_price'];
?></dd>
										<dt style="color:#E32C3B;">SALE PRICE</dt>
										<dd><?php 
if(!$listingsRecord['sale_price']) { 
echo "<p>Contact advertiser for price</p>"; 
} 
else echo $listingsRecord['currency'].$listingsRecord['sale_price'];
?></dd>
										<dt>AGE</dt>
										<dd><?php 
if(!$listingsRecord['age']) { 
echo "<p>Contact advertiser for details</p>"; 
} 
else echo $listingsRecord['age'];
?></dd>
										<dt>CONDITION</dt>
										<dd><?php 
if(!$listingsRecord['condition']) { 
echo "<p>Contact advertiser for details</p>"; 
} 
else echo $listingsRecord['condition'];
?></dd>
										<dt>WARRANTY</dt>
										<dd><?php 
if(!$listingsRecord['warranty']) { 
echo "<p>No warranty specified</p>"; 
} 
else echo $listingsRecord['warranty'];
?></dd>
									</dl>
									<div class="social-holder">
										<ul>
											<li>
                        <div id="fb-root"></div>
                        <script>(function(d, s, id) {
                          var js, fjs = d.getElementsByTagName(s)[0];
                          if (d.getElementById(id)) {return;}
                          js = d.createElement(s); js.id = id;
                          js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
                          fjs.parentNode.insertBefore(js, fjs);
                        }(document, 'script', 'facebook-jssdk'));</script>
                        
                        <div class="fb-like" data-send="false" data-action="like" data-layout="button_count" data-show-faces="false"></div>
                      </li>
											<li style="margin-right: 2px;">
                        <a href="https://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
                      </li>
											<li style="margin-left: 8px;">
                        <!-- Place this tag where you want the +1 button to render -->
                        <g:plusone size="medium" annotation="none"></g:plusone>
                        
                        <!-- Place this render call where appropriate -->
                        <script type="text/javascript">
                          (function() {
                            var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                            po.src = 'https://apis.google.com/js/plusone.js';
                            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                          })();
                        </script>  
                      </li>
										</ul>
									</div>
									<div class="link-holder">
										<a href="#contactForm" class="btn-contact">contact advertiser</a>
									</div>
								</div>
							</div>
							<!-- Product Description -->
							<div class="product-description">
								<h2>PRODUCT DESCRIPTION</h2>
								<div class="text-holder">
                  <?php 
if(!$listingsRecord['description']) { 
echo "This product currently has no description. For further details please contact the advertiser using the contact form below."; 
} 
else echo $listingsRecord['description'];
?>

                  <?php 
if($listingsRecord['document_uploads']) { 
echo "<h2>Download Product Files</h2>"; 
} 
?>

      <!-- STEP 2a: Display Uploads for field 'document_uploads' (Paste this anywhere inside STEP2 to display uploads) -->
        <!-- Upload Fields: num, createdTime, tableName, fieldName, recordNum, preSaveTempId, filePath, filename, extension, thumbFilePath, isImage, hasThumbnail, urlPath, width, height, thumbUrlPath, thumbWidth, thumbHeight, info1, info2, info3, info4, info5 -->
        <?php foreach ($listingsRecord['document_uploads'] as $upload): ?>
          <?php if ($upload['hasThumbnail']): ?>
            <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br/>

          <?php elseif ($upload['isImage']): ?>
            <img src="<?php echo $upload['urlPath'] ?>" width="<?php echo $upload['width'] ?>" height="<?php echo $upload['height'] ?>" alt="" /><br/>

          <?php else: ?>
            <a href="<?php echo $upload['urlPath'] ?>">Download <?php echo $upload['filename'] ?></a><br/>

          <?php endif ?>
        <?php endforeach ?>
      <!-- STEP2a: /Display Uploads -->
									
								</div>
							</div>
							<!-- ADVERTISER DETAILS -->
							<div class="details-box">
								<div class="details vcard">
									<h3>ADVERTISER DETAILS</h3>
									<ul>
										<li>
											<h4>Organisation</h4>
											<span class="org"><?php echo $listingsRecord['homepages.organisation'] ?></span>
										</li>
										<li>
											<h4>Contact name</h4>
											<span class="fn"><?php echo $listingsRecord['homepages.contact_name'] ?></span>
										</li>
										<li>
											<h4>Member since</h4>
											<span><?php echo date("jS M Y ", strtotime ($listingsRecord['homepages.createdDate'])) ?></span>
										</li>
									</ul>
									<ul>
										<li>
											<h4>Phone</h4>
											<span class="tel"><span class="type hidden">work</span><?php echo $listingsRecord['homepages.phone'] ?></span>
										</li>
										<li>
											<h4>Email</h4>
											<span class="email"><?php echo $listingsRecord['homepages.email'] ?></span>
										</li>
										<?php 
												if ($listingsRecord['homepages.research_areas'])
												echo "<li><h4>Research Areas</h4><span>" . $listingsRecord['homepages.research_areas'] . "</span></li>";
											?>
										<li><?php 
												if ($listingsRecord['homepages.background'])
												echo "<h4>Background</h4>" . $listingsRecord['homepages.background']
										?>
										</li>
									</ul>
								</div>
								<div id='contactForm' class="contacts">
									<h3>CONTACT ADVERTISER</h3>
										<p style="font-weight: bold; color: #333">Fill out the form below to contact the advertiser.</p>
									<!-- Form CONTACT ADVERTISER -->
                    <form method="post" action="?<?php echo $listingsRecord['num']."-".$listingsRecord['num']; ?>#contactForm" class="form-contact"/>
                      <input type="hidden" name="subject" value="Listing Enquiry: <?php echo $listingsRecord['product']; ?>"/>
                      <input type="hidden" name="to" value="<?php echo $listingsRecord['homepages.email'] ?>"/>
                      <input type="hidden" name="listing_id" value="<?php echo $listingsRecord['num']; ?>"/>
                      <input type="hidden" name="skilla" value="<?php echo $skillA?>"/>
                      <fieldset>
                        
                      <?php if (@$errorsAndAlerts): ?>
                      <div class="row">
                        <?php if(@$allGood): ?>
                          <?php echo $allGood; ?>
                        <?php else: ?>
                          <font style="color: #C00; font-weight: bold; font-size: 12px; font-family: arial;">
                        <?php endif ?>
                          <?php echo $errorsAndAlerts; ?><br/>
                          </font>
                      </div>
                      <?php endif ?>
										
											<div class="row">
												<label for="name-field" class="required">Name</label>
												<div class="text"><input id='name-field' type="text" name="name" value="<?php echo @$_POST['name']?>"/></div>
											</div>
											<div class="row">
												<label for="company-field">Company</label>
												<div class="text"><input id='company-field' type="text" value="<?php echo @$_POST['company']?>" name="company" /></div>
											</div>
                      <div class="row">
												<label for="phone-field" class="required">Phone</label>
												<div class="text"><input id='phone-field' type="text" name="phone" value="<?php echo @$_POST['phone']?>"/></div>
											</div>
											<div class="row">
												<label for="email-field" class="required">Email Address</label>
												<div class="text"><input id='email-field' type="text" name="email" value="<?php echo @$_POST['email']?>" /></div>
											</div>
                      <div class="row">
												<label for="skill-field" class="required">What is <?php echo $skillQ; ?>?</label>
												<div class="text"><input id='skill-field' type="text" name="skill" value=""/></div>
											</div>
											<div class="row">
												<label for="message-field">Message</label>
												<div class="textarea">
													<textarea id='message-field' name="message" rows="5" cols="34"><?php echo @$_POST['message']; ?></textarea>
												</div>
											</div>
											<div class="link-holder">
												<input class="btn-send" name='Send' type="submit" value="SEND" />
											</div>
										</fieldset>
									</form>
								</div>
							</div>
							<!-- Back to top -->
							<div class="link-holder">
								<a href="#main" class="back-to-top">Back to top</a>
							</div>
						</div>
						<!-- sidebar -->
						<div id="sidebar">
							<!-- heading -->
							<div class="heading">
								<h2>CATEGORIES</h2>
								<a href="http://www.mydomain.co.uk/allCats_notempty.php">VIEW ALL</a>
							</div>
							<!-- side-menu -->
							<ul class="side-menu">
								<!-- category list starts here -->
								<?php foreach ($categoryRecords as $category): ?>
								<li>
									<a href="<?php echo makeLinkCategory($category);?>">
										<?php echo $category['name']; ?>
									</a>
								</li>
								<?php endforeach ?>
								<!-- category list ends here -->
							</ul>
              <a href="#" class="see-more">SEE MORE</a>
              
							
							<!-- side-box -->
							<div class="side-box">
								<p></p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
<?php incrementCounterField('listings', 'hits', $listingsRecord['num']); ?>
<?php include "include_footer_new.php"; ?>