<?php
// +---------------------------------------------+
// |     Copyright  2008 - 2018 weenCompany      |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('IN_WEENCOMPANY'))
  die('File not found!');


function m17_DisplayHeader($sectionid)
{
  global $DB, $categoryid, $userinfo, $m17_language, $m17_settings;

  if($m17_settings['顯示跳轉'])
  {
    echo '<div align="right" style="padding-top: 3px;">
          <form style="margin: 0px;" method="post" name="FormMenu" action="' . RewriteLink('index.php?categoryid=' . $categoryid) . '">';

    m17_PrintSectionMenu($sectionid, "FormMenu");

    echo '</form></div><hr size="1" noshade="noshade"  />';
  }

  echo '<table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td>';

  if($m17_settings['顯示導航'])
  {
	  m17_PrintSectionHierarchy($sectionid);
	  
	  if(isset($_GET['m17_imageid']) AND preg_match("/^[0-9]+$/", $_GET['m17_imageid']))
	  {
		$m17_imageid = $_GET['m17_imageid'];

		if($getimagename = $DB->query_first("SELECT title FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$m17_imageid' AND activated = '1'"))
		{
		  echo '&nbsp;&raquo;&nbsp;' . $getimagename['title'];

		}
	  }

  }
	  
  echo '  </td>';

  if(@in_array(17, $userinfo['modulesubmitids']))
  {
    echo '<td width="35%"><div align="right"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_action=submitimage') . '">' . $m17_language['submit_an_image'] . '</a></div></td>';
  }

  echo '</tr>
        </table>';

  if(@in_array(17, $userinfo['modulesubmitids']) || $m17_settings['顯示導航'])
  {
    echo '<hr size="1" noshade="noshade"  /><br />';
  }

}



// ############################ GET SECTION SORT ORDER ##########################

function m17_GetSectionSort()
{
        global $m17_settings;

        switch($m17_settings['類別排序'])
        {
                case '1': //'Oldest First':
                $order = 'datecreated ASC';
                break;

                case '2': //'Alphabetically A-Z'
                $order = 'ordernum DESC';
                break;

                case '3': //'Alphabetically Z-A':
                $order = 'ordernum ASC';
                break;

                default:
                $order = 'datecreated DESC';
                break;
        }

        return $order;
}



function m17_PrintSectionHierarchy($sectionid)
{
        global $DB, $categoryid;

        $section = $DB->query_first("SELECT parentid, name FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid' ORDER BY " . m17_GetSectionSort());

        if($section['parentid'] > 0)
        {
                m17_PrintSectionHierarchy($section['parentid']);
                echo '&nbsp;&raquo;&nbsp;';
        }

        echo '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid) . '">' . $section['name'] . '</a>';
}

function m17_PrintSectionItems($parentid, $sectionid, $parentname)
{
        global $DB, $categoryid;

        $getsection = $DB->query("SELECT sectionid, name FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = '$parentid' AND activated = '1' ORDER BY " . m17_GetSectionSort());

        while($section = $DB->fetch_array($getsection))
        {
                echo '<option value="' . $section['sectionid'] . '"';

                if($sectionid == $section['sectionid'])
                  echo ' selected="selected" ';

                if(strlen($parentname) > 0)
                {
                        $sectionname = $parentname . ' &raquo; ' . $section['name'];
                }
                else
                {
                        $sectionname = $section['name'];
                }

                echo '>' . $sectionname . '</option>';

                m17_PrintSectionItems($section['sectionid'], $sectionid, $sectionname);
        }
}

function m17_PrintSectionMenu($sectionid, $formName)
{
        // get language
        global $m17_language;

        echo '<select name="m17_sectionid" onchange="if(this.value != -1){document.' . $formName . '.submit();}">
        <option value="-1">' . $m17_language['jump_to'] . '</option>';

        m17_PrintSectionItems(0, $sectionid, null);

        echo '</select>';
}


// ############################### INSERT IMAGE ################################

function m17_InsertImage($sectionid)
{
        global $DB, $m17_settings, $m17_language, $sdlanguage, $mainsettings, $rootpath;
		if($m17_settings['驗證碼'] == 1)
		{
				$vvcid     = $_POST['m17_vvcid'];
				$code      = $_POST['m17_verifycode'];

				if(!ValidVisualVerifyCode($vvcid, $code))
				{
                        $errors[] = $sdlanguage['incorrect_vvc_code'];
				}
		}

        // get post variables
        $image         = $_FILES['m17_image'];
        $thumbnail     = $_FILES['m17_thumbnail'];
        $activated     = $m17_settings['自動發佈'];
        $allowsmilies  = 1;
        $allowcomments = 1;
        $showauthor    = 0;
        $author        = $_POST['m17_author'];
        $title         = $_POST['m17_title'];
        $description   = $_POST['m17_description'];
        $specification   = $_POST['m17_specification'];
        $priceship   = $_POST['m17_priceship'];

        // initialization
        $imagedir  = dirname(__FILE__) . '/images';

        // List of our known photo types
        $known_photo_types = array(
        'image/pjpeg' => 'jpg',
        'image/jpeg'  => 'jpg',
        'image/gif'   => 'gif',
        'image/bmp'   => 'bmp',
        'image/x-png' => 'png',
        'image/png'   => 'png'
        );

        $valid_image_types = array('image/pjpeg',
        'image/jpeg',
        'image/gif',
        'image/bmp',
        'image/x-png',
        'image/png');

        $valid_image_extensions = array(
        'gif',
        'jpg',
        'bmp',
        'png');

        if(!in_array($image['type'], $valid_image_types))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        else if(isset($_FILES['m17_thumbnail']) AND !in_array($thumbnail['type'], $valid_image_types))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        // lets make sure the extension is correct
        else if(!in_array(substr($_FILES['m17_image']['name'], -3), $valid_image_extensions))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        // lets make sure the extension is correct
        else if(isset($_FILES['m17_thumbnail']) AND !in_array(substr($_FILES['m17_thumbnail']['name'], -3), $valid_image_extensions))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        // final attempt to make sure it's a real image:
        else if(!getimagesize($_FILES['m17_image']['tmp_name']))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        // final attempt to make sure it's a real image:
        else if(isset($_FILES['m17_thumbnail']) AND !getimagesize($_FILES['m17_thumbnail']['tmp_name']))
        {
                $errors[] = $m17_language['invalid_image_type'];
        }

        else if(!strlen($title))
        {
                $errors[] = $m17_language['enter_title'];
        }

        else if(!strlen($author))
        {
                $errors[] = $m17_language['enter_author'];
        }

        else if($image['size'] == 0)
        {
                $errors[] = $m17_language['select_image'];
        }

        else if($m17_settings['自動縮圖'] == 0 AND $thumbnail['size'] == 0)
        {
                $errors[] = $m17_language['select_thumbnail'];
        }

        else if(($m17_settings['自動縮圖'] == 1 || $m17_settings['自動中圖'] == 1) AND ($image['type'] == 'image/gif' OR $image['type'] == 'image/bmp'))
        {
                $errors[] = $m17_language['no_gif_support'];
        }

        else if(!strlen($description))
        {
                $errors[] = $m17_language['enter_description'];
        }

		if($sameproduct = $DB->query_first("SELECT imageid FROM " . TABLE_PREFIX . "m17_products WHERE author = '$author'
						   AND title = '$title' AND description = '$description'") )

		{
                $errors[] = '<font color=red><b>Sorry! this is a same product.</b></font>' . '<br />';
		}

        if($errors)
        {
                foreach($errors as $key => $value)
                {
                        echo $value . '<br /><br />';
                }

                m17_SubmitImage($sectionid);
                return;
        }

        $DB->query("INSERT INTO " . TABLE_PREFIX . "m17_products(sectionid, activated, filename, thumbname, isautothumb, allowsmilies, allowcomments, showauthor, author, title, description, specification, priceship, datecreated)
              VALUES($sectionid, $activated, '', '', '1', '$allowsmilies', '$allowcomments', '$showauthor', '$author', '$title', '$description', '$specification', '$priceship', " . time() . ") ");

        $imageid   = $DB->insert_id();
        $filetype  = $image['type'];
        $extention = $known_photo_types[$filetype];
        $filename  = $imageid . '.' . $extention;

        $DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET ordernum = '$imageid', filename  = '$filename', thumbname  = '$filename' WHERE imageid = '$imageid' ");

        // Store the orignal file
        copy($image['tmp_name'], $imagedir."/".$filename);

        if($m17_settings['自動縮圖'])
        {
                CreateThumbnail($imagedir."/".$filename, $imagedir."/tb_".$filename, $m17_settings['縮圖最大寬度'], $m17_settings['縮圖最大高度'], $m17_settings['方形縮圖']);

                if($m17_settings['自動中圖'])
                {
                        CreateThumbnail($imagedir."/".$filename, $imagedir."/md_".$filename, $m17_settings['中圖最大寬度'], $m17_settings['中圖最大高度'], $m17_settings['方型中圖']);

                        if(!$m17_settings['大圖保持原始'])
                        {
                                @unlink($imagedir."/".$filename);
                                // Here we would usually clear the 'filename' column in the DB but unfortunately
                            // the thumbnail/midsize code needs it so we'll use file_exists instead
                        }
                }
        }
        else
        {
                // user submitted thumbnail
                $thumbtype = $thumbnail['type'];
                $extention = $known_photo_types[$thumbtype];
                $thumbname = $imageid . '.' . $extention;
				
				$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET thumbname  = '$thumbname', isautothumb='0' WHERE imageid = '$imageid' ");

                copy($thumbnail['tmp_name'], $imagedir . '/' . 'tb_' . $thumbname);
        }

        $email    = $m17_settings['郵件通知'];

        if(strlen($email) > 0)
        {
                // obtain emails
                $getemails = str_replace(',', ' ', $email);                    // get rid of commas
                $getemails = preg_replace("/[[:space:]]+/", " ", $getemails);   // get rid of extra spaces
                $getemails = trim($getemails);                                 // then trim
                $emails    = explode(" ", $getemails);

				require_once($rootpath . 'includes/mail/class.phpmailer.php');

				$mail = new PHPMailer();

				if($mainsettings['email_use_smtp'] == '1')
					$mail->IsSMTP();
				else
					$mail->IsMail();


				$mail->Host = $mainsettings['email_smtp_host'];
				$mail->Port = $mainsettings['email_smtp_port'];

				if( $mainsettings['email_smtp_require_auth'] == "1" ) {
					$mail->SMTPAuth = true;
					$mail->Username = $mainsettings['email_smtp_user'];
					$mail->Password = $mainsettings['email_smtp_pass'];
				}

				$mail->From      =  $mainsettings['technicalemail'];
				$mail->FromName      =  $mainsettings['copyrighttext'];
				$mail->AddReplyTo($mainsettings['technicalemail'], $mainsettings['copyrighttext']);   
				$mail->Sender      =  $mainsettings['email_smtp_from'];

				for($i = 0; $i < count($emails); $i++)
				{
					$mail->AddAddress($emails[$i]);
				}
				
				$mail->Subject   = '有新產品及圖片提交到您的網站!';
				$mail->Body      = '有新產品及圖片提交到您的網站.';

				$mail->Send();

        }

        echo $m17_language['image_submitted'] . '<br /><br />';
        m17_DisplayImages($sectionid, 0);
}



// ############################### SUBMIT IMAGE ################################

function m17_SubmitImage($sectionid)
{
  global $DB, $categoryid, $userinfo, $inputsize, $m17_settings, $m17_language, $sdlanguage;

  m17_DisplayHeader($sectionid);

  echo $m17_language['submitting_image'] . '<br /><br />';

        echo '<form method="post" enctype="multipart/form-data" action="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_action=insertimage') . '">
        <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
        <input type="hidden" name="m17_sectionid" value="' . $sectionid . '" />

        <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td valign="top" width="100">' . $m17_language['image_title'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input size="'.$inputsize.'" type="text" name="m17_title" value="'.$_POST['m17_title'].'" /></td>
        </tr>';

        if($userinfo['loggedin'])
        {
                echo '<input type="hidden" name="m17_author" value="' . $userinfo['username'] . '" />';
        }
        else
        {
                echo '<tr>
            <td valign="top" width="100">' . $m17_language['your_name'] . '</td>
            <td style="padding-left: 8px; padding-bottom: 8px;"><input size="'.$inputsize.'" type="text" name="m17_author" value="'.$_POST['m17_author'].'" /></td>
          </tr>';
        }

        echo '<tr>
          <td valign="top" width="100">' . $m17_language['image'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input name="m17_image" type="file" size="'.$inputsize.'" /></td>
        </tr>';

        // does user needs to upload thumbnail?
        if($m17_settings['自動縮圖'] == 0)
        {
                echo '<tr>
            <td valign="top" width="100">' . $m17_language['thumbnail'] . '</td>
            <td style="padding-left: 8px; padding-bottom: 8px;"><input name="m17_thumbnail" type="file" size="'.$inputsize.'" /></td>
          </tr>';
        }

        echo '<tr>
          <td valign="top" width="100">' . $m17_language['description'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><textarea name="m17_description" rows="5" cols="'.$inputsize.'">'.$_POST['m17_description'].'</textarea></td>
        </tr>';
        echo '<tr>
          <td valign="top" width="100">' . $m17_language['specification'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><textarea name="m17_specification" rows="5" cols="'.$inputsize.'">'.$_POST['m17_specification'].'</textarea></td>
        </tr>';
        echo '<tr>
          <td valign="top" width="100">' . $m17_language['priceship'] . '</td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><textarea name="m17_priceship" rows="5" cols="'.$inputsize.'">'.$_POST['m17_priceship'].'</textarea></td>
        </tr>';

  if($m17_settings['驗證碼'])
  {
    $vvcid = CreateVisualVerifyCode();

    echo '<tr>
    <td valign="top" width="100"></td>
    <td style="padding-left: 8px; padding-bottom: 8px;"><input type="hidden" name="m17_vvcid" value="' . $vvcid . '"/>
        <img src="includes/vvc.php?vvcid=' . $vvcid . '"/></td>
    </tr>
    <tr>
    <td style="padding-left: 8px; padding-bottom: 8px;" colspan="2">' . $sdlanguage['enter_verify_code'] . '</td>
    </tr>
    <tr>
    <td valign="top" width="100"></td>
    <td style="padding-left: 8px; padding-bottom: 8px;"><input type="text" size="'.$inputsize.'" name="m17_verifycode"/></td>
    </tr>';
  }

  echo '<tr>
          <td></td>
          <td style="padding-left: 8px; padding-bottom: 8px;"><input type="submit" name="m17_Submit" value="' . strip_tags($m17_language['submit_image']) . '" /></td>
        </tr>
        </table>

        </form>';
}



// ########################## GET SECTION IMAGE COUNT ##########################

function m17_GetSectionImageCount($sectionid, $imagecount)
{
        global $DB;

        // get total images of the section
        $getimagecount = $DB->query_first("SELECT COUNT(*) AS imagecount FROM " . TABLE_PREFIX . "m17_products
                                     WHERE sectionid = '$sectionid' AND activated = '1'");

        $imagecount += $getimagecount['imagecount'];

        // are there any subsections?
        $getsubsections = $DB->query("SELECT sectionid FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = '$sectionid' ORDER BY " . m17_GetSectionSort());

        while($subsection = $DB->fetch_array($getsubsections))
        {
                $imagecount = m17_GetSectionImageCount($subsection['sectionid'], $imagecount);
        }

        return $imagecount;

}



// ############################## DISPLAY IMAGES ###############################

function m17_DisplayImages($sectionid, $start)
{
  global $DB, $categoryid, $weenurl, $userinfo, $rootpath, $m17_settings, $m17_language;

  if(isset($_GET['m17_imageid']) AND preg_match("/^[0-9]+$/", $_GET['m17_imageid']))
  {
    $m17_imageid = $_GET['m17_imageid'];

    // lets try and get the image
    if($image = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$m17_imageid' AND activated = '1'"))
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET viewcount = viewcount + 1 WHERE imageid = '$m17_imageid'");
    }
  }

  if(empty($image))
  {
     $m17_imageid = 0;
  }

  if($offline = $DB->query_first("SELECT sectionid FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid' AND activated = '0'"))
  {
    $sectionid = 1;
  }

  // module settings
  $limit  = $m17_settings['每頁產品數'];

  m17_DisplayHeader($sectionid);

  // get subsections of sectionid
  
  if($m17_settings['顯示類別']){
  
  if($m17_settings['每行類別數'] <= 0 OR $m17_settings['每行類別數'] == '' OR !is_string($m17_settings['每行類別數'])){
	$m17_settings['每行類別數'] = 4;
  }
  
  $getsubsections = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = '$sectionid' AND activated = '1' ORDER BY " . m17_GetSectionSort());
  $sectionrows = $DB->get_num_rows($getsubsections);

  if($sectionrows > 0)
  {
	  if($m17_language['sections']){
			echo $m17_language['sections'] . '<br/><br />';
	  }

    if($m17_settings['圖片邊框'])
    {
      $section_startdiv = '<div id="m17_imagelinkborder">';
      $section_enddiv = '</div>';
      $section_img_class = 'class="m17_imageborder"';
    }

    // initialize a few variables
    $section_table_opened = false;
    $curr_section_table_column = 0;
    $section_columnwidth = floor(100 / $m17_settings['每行類別數']) . '%';

    // display subsections
    while($subsection = $DB->fetch_array($getsubsections))
    {
      if($m17_settings['分類統計'])
      {
        $numsectionimages = m17_GetSectionImageCount($subsection['sectionid'], 0);
        $numsectionimages_phrase = '<br />(' . $numsectionimages . ' ' . iif($numsectionimages == 1, $m17_language['image2'], $m17_language['images']) . ')';
      }
      else
      {
        $numsectionimages_phrase = '';
      }

        $curr_section_table_column++;

        // open the table for the sections
        if(!$section_table_opened)
        {
          echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
          $section_table_opened = true;
        }

        if($curr_section_table_column == 1)
        {
          echo '<tr>';
        }

        echo '<td valign="top" width="' . $section_columnwidth . '" style="padding-bottom: 7px;">' . iif($m17_settings['居中顯示'], '<center>') . $section_startdiv . '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $subsection['sectionid']) . '">';

		if($m17_settings['顯示方式'])
		{
			if($subsection['imageid'] > 0)
			{
			  $image88 = $DB->query_first("SELECT imageid, thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = " . $subsection['imageid']);
			  echo '<img ' . $section_img_class . ' src="' . $weenurl . 'modules/m17_products/images/tb_'.$image88['thumbname'].'" alt="'.$subsection['name'].'" title="'.$subsection['name'].'" />';
			}
			else
			{
			  echo '<img ' . $section_img_class . ' alt="'.$subsection['name'].'" title="'.$subsection['name'].'" src="' . $weenurl . 'modules/m17_products/defaultfolder.gif" />';
			}
		}

        echo '</a>' . $section_enddiv . '<br /><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $subsection['sectionid']) . '">' . $subsection['name'] .'</a>'. $numsectionimages_phrase . '<br />' . nl2br($subsection['description']) . iif($m17_settings['居中顯示'], '</center>') . '</td>';

        if($curr_section_table_column == $m17_settings['每行類別數'])
        {
          echo '</tr>';
          $curr_section_table_column = 0;
        }

    } // end sections loop

    if($section_table_opened)
    {
      if($curr_section_table_column != 0)
      {
        // close the section's table
        while($curr_section_table_column != $m17_settings['每行類別數'])
        {
          echo '<td valign="top" width="' . $section_columnwidth . '" style="padding-bottom: 7px;">&nbsp;</td>';
          $curr_section_table_column++;
        }

        echo '</tr>';
      }

      echo '</table>';
    }

  } 
  } // end if sections


  // get sort type of current section
  $getsorttype = $DB->query_first("SELECT sorting FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid'");
  $sorttype    = $getsorttype['sorting'];

  // get sorting for images
  switch($sorttype)
  {
    case '編號(升序)':
    $order = 'ordernum ASC';
    break;

    case '編號(降序)':
    $order = 'ordernum DESC';
    break;

    case '時間(升序)':
    $order = 'datecreated ASC';
    break;

    default:
    $order = 'datecreated DESC';
    break;
  }


  // get image if we are viewing an image
  if($m17_imageid)
  {
    $imagelist = array();

    // fetch list of all images in this list
    $getimagelist = $DB->query("SELECT imageid FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = $sectionid AND activated = 1 ORDER BY " . $order);

    while($img = $DB->fetch_array($getimagelist))
    {
      $imagelist[] = $img[0];
    }

    // Find where the current image is in the list
    $currentID = array_search($image['imageid'], $imagelist);

    if($currentID > 0)
    {
      $previousimagelink = '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_imageid=' . $imagelist[$currentID - 1]) . '">' . $m17_language['previous_image'] . '</a>';
    }

    if($currentID < count($imagelist)-1)
    {
            $nextimagelink = '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_imageid=' . $imagelist[$currentID + 1]) . '">' . $m17_language['next_image'] . '</a>';
    }

    if($sectionrows)
    {
      echo '<hr size="1" noshade="noshade"  /><br />';
    }

    // display image here
    echo '<table cellpadding="0" cellspacing="0" width="100%">
          <tr>
            <td colspan="2">' . iif($m17_settings['居中顯示'], '<center>');

    

    if(file_exists($rootpath . 'modules/m17_products/images/md_' . $image['filename']))
    {
      list($width, $height, $type, $attr) = getimagesize($rootpath . 'modules/m17_products/images/md_' . $image['filename']);

      if($m17_settings['中圖邊框'])
      {
        $midsize_startdiv = '<div id="m17_imagelinkborder">';
        $midsize_enddiv = '</div>';
        $midsize_img_class = 'class="m17_imageborder"';
      }
      else
      {
        $midsize_startdiv = '';
        $midsize_enddiv = '';
        $midsize_img_class = '';
      }

      echo $midsize_startdiv;

      if(file_exists($rootpath . 'modules/m17_products/images/' . $image['filename']))
      {
        echo '
				<script type="text/javascript" src="includes/javascript/image/highslide-with-gallery.js"></script>
				<link rel="stylesheet" type="text/css" href="includes/javascript/image/highslide.css" />
			
				<script type="text/javascript">
					hs.graphicsDir = \'includes/javascript/image/\';
					hs.align = \'center\';
					hs.transitions = [\'expand\', \'crossfade\'];
					hs.outlineType = \'rounded-white\';
					hs.wrapperClassName = \'controls-in-heading\';
					hs.fadeInOut = true;
					hs.dimmingOpacity = 0.75;
				
					if (hs.addSlideshow) hs.addSlideshow({
						interval: 800,
						repeat: false,
						useControls: true,
						fixedControls: false,
						overlayOptions: {
							opacity: 1,
							position: \'top right\',
							hideOnMouseOut: false
						}
					});
				</script>
				
			
			    <div class="highslide-gallery"><a href="' . $weenurl . "modules/m17_products/images/" . $image['filename'] . '" class="highslide" onclick="return hs.expand(this)">
				<img ' . $midsize_img_class . ' title="' . $image['title'] . '" alt="' . $image['title'] . '" src="' . $weenurl . "modules/m17_products/images/md_" . $image['filename'] . '" width="' . $width . '" height="' . $height . '" /></a>
		
				<div class="highslide-heading">' . $image['title'] . '</div>
				</div>';
	  
      }
      else
      {
        echo '<img title="' . $image['title'] . '" alt="' . $image['title'] . '" src="' . $weenurl . 'modules/m17_products/images/md_' . $image['filename'] . '" width="' . $width . '" height="' . $height . '" />';
      }

      echo $midsize_enddiv;
    }
    else
    {
      list($width, $height, $type, $attr) = getimagesize($rootpath . 'modules/m17_products/images/' . $image['filename']);
      echo '<img title="' . $image['title'] . '" alt="' . $image['title'] . '" src="' . $weenurl . 'modules/m17_products/images/' . $image['filename'] . '"  width="' . $width . '" height="' . $height . '" />';
    }

    echo '<br><b>' . $image['title'] . '</b>';
	
    echo iif($m17_settings['居中顯示'], '</center>') . '</td>
          </tr>
          <tr>
            <td style="padding-bottom: 5px; padding-top: 7px; padding-right: 20px;" align="left">'  . iif(isset($previousimagelink), $previousimagelink) . '</td>
            <td style="padding-bottom: 5px; padding-top: 7px;"><div align="right">' . iif(isset($nextimagelink),     $nextimagelink)     . '</div></td>
          </tr>
          </table>';

    if(strlen($image['description']))
    {
      if($image['allowsmilies'])
      {
        $image['description'] = AddSmilies($image['description']);
      }

      echo '<style type="text/css">
		ul.m17_idTabs {
			list-style-type:none;
			border-bottom:solid 1px #76839b;
			height:23px;
			margin-top:1em;
			margin:0;
			padding-top:16px;
			padding-left:0px;
		}
		ul.m17_idTabs li {
			float:left;
			margin-right:3px;
		}
		ul.m17_idTabs li a {
			background: url("includes/javascript/image/tab_bg.jpg") no-repeat 0 0;
			display:block;
			width:148px;
			height:18px;
			text-align:center;
			text-decoration:none;
			font-weight:normal;
			padding-top:5px;
			color:#374853;
		}
		ul.m17_idTabs li.on a{
			background: url("includes/javascript/image/tab_bg_selected.jpg") no-repeat 0 0;
			font-weight:bold;
			color:white;
		}
		
		.m17_products_info_sheets {
			padding-top:6px;
		}</style>
		
		<script type="text/javascript">
		function m17_gopage(n) 
		{
		  var tag = document.getElementById("m17_products_info_block").getElementsByTagName("li");
		  var taglength = tag.length;
		
		  for (i=1;i<=taglength;i++)
		  {
			document.getElementById("m"+i).className="";
			document.getElementById("c"+i).style.display="none";
		  }
			document.getElementById("m"+n).className="on";
			document.getElementById("c"+n).style.display="";
		}
		</script>';
			  
			  
		$lasttagid = 2;
		
		echo '<div id="m17_products_info_block">
			<ul id="m17_more_info_tabs" class="m17_idTabs">
				<li id="m1" class="on"><a onclick="javascript:m17_gopage(1)" style="cursor: pointer">'.$m17_language['descriptiontitle']. '</a></li>';
		 if(strlen($image['specification'])){
			 echo '<li id="m2"><a onclick="javascript:m17_gopage(2)" style="cursor: pointer">'.$m17_language['specificationtitle']. '</a></li>';
			$lasttagid += 1;
		 }
		 if(strlen($image['priceship'])){
			 echo '<li id="m' . $lasttagid . '"><a onclick="javascript:m17_gopage(' . $lasttagid . ')" style="cursor: pointer">'.$m17_language['priceshiptitle']. '</a></li>';
		 }
				
		echo '</ul></div>
			<div class="m17_products_info_sheets">
			<div id="c1">'.$image['description']. '</div>';

		 if(strlen($image['specification'])){
			 echo '<div id="c2" style="display:none">'.$image['specification']. '</div>';
		 }
		 if(strlen($image['priceship'])){
			 echo '<div id="c' . $lasttagid . '" style="display:none">'.$image['priceship']. '</div>';
		 }

		 echo '</div><br /><br />';
    }

    if($image['showauthor'])
    {
      echo $m17_language['submitted_by'] . ' ' . $image['author'] . '<br /><br />';
    }

    if($m17_settings['顯示點擊率'])
    {
      echo $m17_language['views'] . ' ' . $image['viewcount'] . '<br /><br />';
    }

    if($image['allowcomments'])
    {
      Comments(17, $image['imageid'], 'index.php?categoryid='.$categoryid.'&m17_sectionid='.$sectionid.'&m17_imageid='.$image['imageid'], false);
    }
  }
  else
  {
  
	if($m17_settings['根類別顯示所有產品'] && $sectionid == 1){
		$showallimages = ''; 
	}else{
		$showallimages = 'sectionid = '.$sectionid.' AND '; 
	}
	  
    // get images
    $getimages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE " . $showallimages . " activated = '1'
                             ORDER BY " . $order . " LIMIT $start, " . ($limit + 1) . "");

    $rows = $DB->get_num_rows($getimages);
     // get all section images number
    $getsectionimages = $DB->query("SELECT imageid FROM " . TABLE_PREFIX . "m17_products WHERE " . $showallimages . " activated = '1' ");

    $sectionimagesnum = $DB->get_num_rows($getsectionimages);

    if($sectionrows)
    {
      if($rows)
      {
        echo '<hr size="1" noshade="noshade"  /><br />';
      }
    }

    if($rows > 0)
    {
 	  if($m17_language['images2']){
			echo $m17_language['images2'] . '<br/><br />';
	  }
      if($m17_settings['縮圖邊框'])
      {
        $thumbnail_startdiv = '<div id="m17_imagelinkborder">';
        $thumbnail_enddiv = '</div>';
        $thumbnail_img_class = 'class="m17_imageborder"';
      }

      // initialize a few variables
      $thumbnail_columnwidth = floor(100 / $m17_settings['每行產品數']) . '%';

      echo '<table width="100%" cellpadding="0" cellspacing="0" border="0">';

      $curcol = 0; // current column

      // display images
      for($i = 0; $i < $rows AND $i < $limit; $i++)
      {
        $image = $DB->fetch_array($getimages);

        if($curcol == 0)
        {
          echo '<tr>';
        }

        echo '<td valign="top" width="' . $thumbnail_columnwidth . '" style="padding-bottom: 26px;">' . iif($m17_settings['居中顯示'], '<center>');
        echo $thumbnail_startdiv;

        if($m17_settings['彈出方式'])
        {
          echo '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $image['sectionid'] . '&m17_imageid=' . $image['imageid']) . '" target="_blank"><img ' . $thumbnail_img_class . ' title="' . $image['title'] . '" alt="' . $image['title'] . '" src="' . $weenurl . 'modules/m17_products/images/tb_'.$image['thumbname'].'" /></a>';
        }
        else
        {
          echo '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $image['sectionid'] . '&m17_imageid=' . $image['imageid']) . '"><img ' . $thumbnail_img_class . ' title="' . $image['title'] . '" alt="' . $image['title'] . '" src="' . $weenurl . 'modules/m17_products/images/tb_'.$image['thumbname'].'" /></a>';
        }

        echo $thumbnail_enddiv;
		
		if(strlen($image['title']) > 0)
		{
			echo '<br />' . $image['title'];
		}

        if($m17_settings['顯示評論數'])
        {
          $commentcount = GetCommentsCount(substr("m17_", 1, -1), $image['imageid']);

          echo '<br />(' . $commentcount . ' ' . iif($commentcount == 1, $m17_language['comment'], $m17_language['comments']) . ')';
        }

        echo iif($m17_settings['居中顯示'], '</center>') . '</td>';

        $curcol++;

        if($curcol == $m17_settings['每行產品數'])
        {
          echo '</tr>';
          $curcol = 0;
        }

      }

      if($curcol != 0)
      {
        while($curcol != $m17_settings['每行產品數'])
        {
          echo '<td valign="top" width="' . $thumbnail_columnwidth . '" style="padding-bottom: 26px;">&nbsp;</td>';
          $curcol++;
        }

        echo '</tr>';
      }

      echo '</table>';

      // multiple pages
      if(($start > 0) || ($rows > $limit))
      {
        echo '<br /><hr size="1" noshade="noshade"  />
				<style type="text/css">
				<!--
				.pages_nav a {BACKGROUND: #cad9ea; PADDING-TOP: 5px; PADDING-BOTTOM: 5px; PADDING-RIGHT: 7px; PADDING-LEFT: 7px;  LINE-HEIGHT: 24px;}
				.pages_nav STRONG{FONT-WEIGHT: bold; BACKGROUND: #BBBBBB; COLOR: #CC0000;PADDING-TOP: 5px; PADDING-BOTTOM: 5px; PADDING-RIGHT: 7px; PADDING-LEFT: 7px;LINE-HEIGHT: 24px;}
				-->
				</style>
              <table width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>';

        if($start > 0)
        {
          echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' . ($start - $limit)) . '">' . $m17_language['previous_images'] . '</a></td>';
        }else{
          echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}

		$page_num = ceil($sectionimagesnum / $limit);
		$page_group = floor($start/$limit/8)*8+1;
		$now_page_num = $start/$limit+1;

		if($page_num - $now_page_num < 10){
			$start_page = $page_num - 9;
			if($start_page<1){
				$start_page = 1;
			}
			$end_page = $page_num + 1;
		}else{
			$start_page = $page_group;
			$end_page = $start_page + 8;
		}

		if($start_page > 1){
			$direct_bar = '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=0') . '">1</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' . ($start_page-2)*$limit) . '">&lsaquo;&lsaquo;...</a>';
		}
		
		for ($p=$start_page; $p < $end_page; $p++ ) 
		{	
			if (($start/$limit+1) == $p){
			 	$direct_bar .= '<STRONG>'.$p.'</STRONG>';
			}else{
			 	$direct_bar .= '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' . ($p-1)*$limit) . '">'.$p.'</a>';
			}
			if($p >= $page_num){
				break;
			}
		}

		if($page_num - $now_page_num >= 10){
			$direct_bar .= '<a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' . (($page_group + 7)*$limit)) . '">...&rsaquo;&rsaquo;</a><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' .($page_num-1)*$limit) . '">'.$page_num.'</a>';
		}

        echo '<td width="80%" style="text-align:center; vertical-align:middle;" class="pages_nav">'.$direct_bar.'</td>';
		
        if($rows > $limit)
        {
          $start += $limit;
          echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><div align="right"><a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&m17_sectionid=' . $sectionid . '&m17_start=' . $start) . '">' . $m17_language['more_images'] . '</a></div></td>';
        }else{
          echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}

        echo '</tr></table>';
      }

    } // if rows

  } // else if displaying all images
}



// get module settings
$getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
while($setting = $DB->fetch_array($getsettings))
{
        $m17_settings[$setting['title']] = $setting['value'];
}

// ########################### MODULE STYLESHEET ################################

echo '<style type="text/css">
      .m17_imageborder
      {
        border-style: solid;
        border-color: ' . $m17_settings['邊框顏色'] . ';
        border-width: 1px;
        padding: ' . $m17_settings['邊框間隙'] . 'px;
        margin: 1px;
      }

      #m17_imagelinkborder a:hover img
      {
        border-width: 2px;
        border-color: ' . $m17_settings['邊框顏色'] . ';
        margin: 0px;
      }
      </style>';

// get language
$m17_language = GetLanguage(17);

// ######################### START CALLING FUNCTIONS  ##########################

$m17_action    = isset($_GET['m17_action']) ? $_GET['m17_action'] : ( isset($_POST['m17_action']) ? $_POST['m17_action'] : NULL);
$m17_sectionid = (isset($_GET['m17_sectionid']) AND preg_match("/^[0-9]+$/", $_GET['m17_sectionid'])) ? $_GET['m17_sectionid'] : ( (isset($_POST['m17_sectionid']) AND preg_match("/^[0-9]+$/", $_POST['m17_sectionid'])) ? $_POST['m17_sectionid'] : 1);
$m17_start     = (isset($_GET['m17_start'])     AND preg_match("/^[0-9]+$/", $_GET['m17_start']))     ? $_GET['m17_start']     : ( (isset($_POST['m17_start'])     AND preg_match("/^[0-9]+$/", $_POST['m17_start']))     ? $_POST['m17_start']     : 0);

if($m17_action == 'insertimage' AND @in_array(17, $userinfo['modulesubmitids']))
{
        m17_InsertImage($m17_sectionid);
}
else if($m17_action == 'submitimage' AND @in_array(17, $userinfo['modulesubmitids']))
{
        m17_SubmitImage($m17_sectionid);
}
else
{
        m17_DisplayImages($m17_sectionid, $m17_start);
}

unset($m17_settings, $m17_language, $m17_action, $m17_sectionid, $m17_start);
?>
