<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set(@date_default_timezone_get());
class venteflash extends Module
{
    private $_html = '';
    private $_postErrors = array();

    public function __construct()
    {
        $this->name    = 'venteflash';
        $this->tab     = 'Tools';
        $this->version = '2.2e';
        $this->path    = $this->_path;
        $this->effect  = Configuration::get('VF_EFFECT');
        $this->offset  = Configuration::get('VF_OFFSET');
        $this->banner  = Configuration::get('VF_BANNER');
        $this->transition = Configuration::get('VF_TRANSITION');

       	parent::__construct();

        $this->displayName = $this->l('Vente Flash');
        $this->description = $this->l('This module creates a Vente Flash.');
        $this->confirmUninstall = $this->l('Are you sure you want to delete all ventes flash?');

    }

    public function install()
    {
        if (!parent::install()
          OR !Configuration::updateValue('VF_EFFECT','1')
          OR !Configuration::updateValue('VF_OFFSET','0')
          OR !Configuration::updateValue('VF_BANNER','no')
          OR !Configuration::updateValue('VF_TRANSITION','5')
          OR !$this->registerHook('rightColumn')
          OR !$this->registerHook('extraRight')
          OR !$this->registerHook('header')
          OR !$this->installDB())
          return false;
          return true;
    }
    
    public function uninstall()
    {
        $this->uninstallVenteFlash();
		if (!parent::uninstall()
            OR !Configuration::deleteByName('VF_EFFECT')
            OR !Configuration::deleteByName('VF_OFFSET')
            OR !Configuration::deleteByName('VF_BANNER')
            OR !Configuration::deleteByName('VF_TRANSITION')
            OR !$this->uninstallDB())
            return false;
            return true;
	}

    function installDB()
    {
        Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'venteflash`;');
        Db::getInstance()->Execute('
        CREATE TABLE `'._DB_PREFIX_.'venteflash` (
        `id` int(11) NOT NULL auto_increment,
        `id_venteflash` int(11) NOT NULL,
        `datedebut` DATETIME,
        `datefin` DATETIME,
        `vfreduction` int(11) NOT NULL,
        `oldreduction` int(11),
        PRIMARY KEY  (`id`)
        ) ENGINE = MyISAM;');
       return true;
	}

    function uninstallDB()
    {
        Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'venteflash`;');
        return true;
	}

    function hookRightColumn($params)
    {
        if (!$this->active)
			return ;
        if ($this->thereisVenteFlash() == FALSE AND $this->commingSVF() == FALSE)
        return "";
        if ($this->thereisVenteFlash() == FALSE AND $this->commingSVF() == TRUE):
            global $smarty; $cookie;
            $smarty->assign(array(
            'csproducts' => $this->commingSoonVF(intval($params['cookie']->id_lang)),
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'slider'     => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/slider.js"></script>',
            'mediumSize' => Image::getSize('medium'),
            'commingsoon' => $this->commingSVF(),
            'vfday'      => $this->l('d'),
            'vfhour'     => $this->l('h'),
            'vfminute'   => $this->l('m'),
            'vfsecond'   => $this->l('s'),
            'effect'     => $this->effect*1000,
            'transition' => $this->transition*1000
            ));
            return $this->display(__FILE__,'commingsoonblock.tpl');
          else:
            global $smarty; $cookie;
            $smarty->assign(array(
            'vfproducts'   => $this->getVFPricesDrop(intval($params['cookie']->id_lang)),
            'csaproducts' => $this->commingSoonVF(intval($params['cookie']->id_lang)),
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'slider'     => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/slider.js"></script>',
            'mediumSize' => Image::getSize('medium'),
            'commingsoon'=> $this->commingSVF(),
            'vfday'      => $this->l('d'),
            'vfhour'     => $this->l('h'),
            'vfminute'   => $this->l('m'),
            'vfsecond'   => $this->l('s'),
            'effect'     => $this->effect*1000,
            'transition' => $this->transition*1000
            ));
            return $this->display(__FILE__,'venteflash.tpl');
         endif;
	}
 
    function hookHeader($params)
    {
        $this->startVenteFlash();
        $this->checkVF();
        if ($this->banner == 'yes' AND ($this->thereisVenteFlash() == TRUE OR $this->commingSVF() == TRUE))
        $this->floatingBanner();
        global $smarty; $cookie;
        $smarty->assign('vfproducts', $this->getVFPricesDrop(intval($params['cookie']->id_lang)));
        $smarty->assign('csproducts', $this->commingSoonVF(intval($params['cookie']->id_lang)));
        $smarty->assign('csbproducts',$this->commingSoonVF(intval($params['cookie']->id_lang)));
    }
    
	function hookLeftColumn($params)
	{
		return $this->hookRightColumn($params);
	}

    function hookHome($params)
    {
         return $this->hookRightColumn($params);
    }
    
    function hookFooter($params)
    {
        $this->hookRightColumn($params);
    }
    
    function hookExtraRight($params)
    {
        if (!$this->active)
			return ;
        $product = new Product(intval($_GET['id_product']), true, intval($params['cookie']->id_lang));
        if ($this->checkVFProductId(intval($product->id)) == '0' AND $this->commingSoonVenteFlash(intval($product->id)) == FALSE):
        return ;
        endif;
        if ($this->commingSoonVenteFlash(intval($product->id)) == TRUE):
            global $smarty; $cookie;
            $smarty->assign(array(
            'datetime'   => date("r",strtotime($this->getCSTime(intval($product->id)))),
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'red'        => $this->getOldreductionVF(intval($product->id)),
            'vfday'      => $this->l('d'),
            'vfhour'     => $this->l('h'),
            'vfminute'   => $this->l('m'),
            'vfsecond'   => $this->l('s'),
             ));

            return $this->display(__FILE__,'csproduct.tpl');
        else:
            global $smarty; $cookie;
            $smarty->assign(array(
            'datetime'   => date("r",strtotime($this->getTime(intval($product->id)))),
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'vfday'      => $this->l('d'),
            'vfhour'     => $this->l('h'),
            'vfminute'   => $this->l('m'),
            'vfsecond'   => $this->l('s'),
             ));

            return $this->display(__FILE__,'product.tpl');
       endif;

    }
    
   //To stop it at the whem timer reaches zero
     function checkVF()
     {
         $active = Configuration::get('VF_ACTIVE');
         $query = Db::getInstance()->Execute('
         SELECT vf.`id_venteflash`,vf.`datefin`
         FROM   `'._DB_PREFIX_.'venteflash` as vf, `'._DB_PREFIX_.'product` as p
         WHERE  p.`id_product` =  vf.`id_venteflash`
         AND    p.`reduction_percent` =  vf.`vfreduction`
         ');
         $nb_reg = mysql_num_rows($query);
         if ($nb_reg > '0')
         {
             while($sql = mysql_fetch_row($query))
             {
                 if(strtotime($sql[1]) <= time())
                 {
                     if(Configuration::get('VF_KEEPREDUCTION') == '1')
                     {
                         $result=Db::getInstance()->Execute('
                         UPDATE `'._DB_PREFIX_.'product`
                         SET reduction_percent="'.($this->getOldreductionVF($sql[0])).'", reduction_from="'.(date("Y-m-d H:i:s")).'", reduction_to="'.(date("Y-m-d H:i:s")).'",active="'.($active).'", date_upd=NOW()
                         WHERE id_product="'.($sql[0]).'"
                         ');
                     }
                     else
                     {
                         $result=Db::getInstance()->Execute('
                         UPDATE `'._DB_PREFIX_.'product`
                         SET reduction_percent=0, reduction_from=0, reduction_to=0,active="'.($active).'", date_upd=NOW()
                         WHERE id_product="'.($sql[0]).'"
                         ');
                     }
                 }
             }
            $free = mysql_free_result($query);
         }
      }
    //Get reduction  product table
    function getOldreduction($id)
    {
        $query = Db::getInstance()->Execute('
        SELECT *
        FROM   `'._DB_PREFIX_.'product`
        WHERE `id_product` = "'.(trim($id)).'"
        ');
        while($sql = mysql_fetch_row($query))
        {
            $reduction_percent = $sql[13];
        }
        return $reduction_percent;
        $free = mysql_free_result($query);
    }
    
    //Get reduction venteflash table
    function getOldreductionVF($id)
    {
        $query = Db::getInstance()->Execute('
        SELECT *
        FROM   `'._DB_PREFIX_.'venteflash`
        WHERE `id_venteflash` = "'.(trim($id)).'"
        ');
        while($sql = mysql_fetch_row($query))
        {
            $reduction_percent = $sql[5];
        }
        return $reduction_percent;
        $free = mysql_free_result($query);
    }

    //To  start a vente flash automatically.
     function startVenteFlash()
     {
         $offset = time()+Configuration::get('VF_OFFSET');
         $start = Db::getInstance()->Execute('
         SELECT *
         FROM `'._DB_PREFIX_.'venteflash` as vf
         WHERE vf.datedebut < vf.datefin
         ');
         $nb_reg = mysql_num_rows($start);
         if ($nb_reg > '0')
         {
            while ($list = mysql_fetch_row($start))
            {
                if(strtotime($list[2]) < $offset AND strtotime($list[3]) > $offset)
                {
                    $sql=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent='.($list[4]).', reduction_from=CURDATE(), reduction_to=CURDATE(), date_upd=NOW()
                    WHERE id_product="'.($list[1]).'"
                    ');
                }
            }
            $free = mysql_free_result($start);
         }
     }
     
     //Verify if there is a Comming soon vente flash.
     function commingSVF()
     {
         $query = Db::getInstance()->Execute('
         SELECT *
         FROM `'._DB_PREFIX_.'venteflash` as vf
         WHERE vf.datedebut < vf.datefin
         AND   vf.datedebut > "'.(date("Y-m-d H:i:s")).'"
         ');
         $nb_reg = mysql_num_rows($query);
         if ($nb_reg > '0')
         return TRUE;
         else
         return FALSE;
         $free = mysql_free_result($query);
     }
     
     //Verify if a product id is a Comming soon vente flash.
     function commingSoonVenteFlash($id)
     {
         $query = Db::getInstance()->Execute('
         SELECT *
         FROM `'._DB_PREFIX_.'venteflash` as vf
         WHERE vf.datedebut < vf.datefin
         AND   vf.datedebut > "'.(date("Y-m-d H:i:s")).'"
         AND   vf.id_venteflash = "'.($id).'"
         ');
         $nb_reg = mysql_num_rows($query);
         if ($nb_reg > '0')
         return TRUE;
         else
         return FALSE;
         $free = mysql_free_result($query);
     }
      
    private function _displayVenteflash()
	{
         $this->_html .= '<img src="../modules/venteflash/venteflash.jpg"  style="float:left; margin-right:15px;"></a>  <b>'.$this->l('- This module creates a vente flash:').'</b><br />
        '.$this->l('- Fill in a reduction percent.').'
        '.$this->l('- Choose start and end date/time.').'<br />
        '.$this->l('- Start date is important only if you choose a date in the future.').'<br />
        '.$this->l('- Fill in a product id (not a reference number).').'<br />
        '.$this->l('- Once the start button is submited, the choosed vente flash(es) will begin.').'<br />
        '.$this->l('- To stop a vente flash, press stop button.').'
        '.$this->l('- To delete a vente flash, press delete button.').'<br /> <br />
        ';
    }
    
    private function _displayForm()
    {
        $this->_html .= '
        <style type="text/css">
        	.asholder
            {
                position: relative;
            }
       </style>
       <fieldset><legend><img src="../img/admin/contact.gif" />'.$this->l('Complementary Actions').'</legend>
        <table class="table" border="0" width="860" cellpadding="0" cellspacing="2" id="form10">
        <form action="'.$_SERVER['REQUEST_URI'].'" method="post" name="Form10">
        <tr>
           <td colspan="2" style="color:blue; vertical-align: top;font-weight:bold;">'.$this->l('Deactivate the product when venteflash be finished:').'</td>
           <td style="color: black;text-align: left;font-weight:bold"><input type="checkbox" name="active" value="0"  '.htmlentities(Configuration::get('VF_ACTIVE') == '0' ? 'checked="checked" ' : '').' >&nbsp;&nbsp;&nbsp;'.$this->l('Deactivate').' </td>
         </tr>
         <tr>
            <td colspan="2" style="color:blue;  vertical-align: top;"><b>'.$this->l('When finished venteflash or pressed Delete button, return to the original percentage reduction.').'</b></td>
            <td style="color: black;text-align: left;font-weight:bold"><input type="checkbox" name="keepreduction" value="1"  '.htmlentities(Configuration::get('VF_KEEPREDUCTION') == '1' ? 'checked="checked" ' : '').' >&nbsp;&nbsp;&nbsp;'.$this->l('Keep Reduction').' </td>
          </tr>
          <tr>
            <td colspan="2" style="color:blue;  vertical-align: top;"><b>'.$this->l('Show banner on home page:').'</b></td>
            <td style="color: black;text-align: left;font-weight:bold"><input type="checkbox" name="banner" value="yes"  '.htmlentities(Configuration::get('VF_BANNER') == 'yes' ? 'checked="checked" ' : '').' >&nbsp;&nbsp;&nbsp;'.$this->l('Show banner').' </td>
          </tr>
          <tr>
            <td colspan="2" style="color:blue;  vertical-align: top;"><b>'.$this->l('Offset in order to syncronize start and end of venteflash:').'</b></td>
            <td style="vertical-align: top;text-align: left"><input maxlength="4" type="text" name="offset" value="'.Tools::getValue('offset', $this->offset).'" style="width: 70px"/>
          </tr>
          <tr>
            <td colspan="3" style="vertical-align: top;text-align: right"><input class="button" name="compactions" value="'.$this->l('Update settings').'" type="submit" style="color:blue;font-weight:bold;width: 180px;font-weight:bold"/></td>
         </tr>

        </form>
        </table>
        </fieldset>  <br />
        <fieldset><legend><img src="../img/admin/contact.gif" />'.$this->l('Setting the slider').'</legend>
        <table class="table" border="0" width="860" cellpadding="0" cellspacing="2" id="form">
        <form action="'.$_SERVER['REQUEST_URI'].'" method="post" name="FormVF class="asholder">
        <tr>
           <td width="200" style="color:blue; vertical-align: top;font-weight:bold;">'.$this->l('Local Time:').'</td>
           <td width="120" style="color:green; vertical-align: top;font-weight:bold;" id="clock">
           <SCRIPT LANGUAGE="JavaScript">
           <!-- Begin
           function getthedate(){
               var mydate=new Date();
               var hours=mydate.getHours();
               var minutes=mydate.getMinutes();
               var seconds=mydate.getSeconds();
               var dn="AM";
               if (hours>=12) dn="PM";
               if (hours>12) hours=hours-12;
               if (hours==0) hours=12;
               if (minutes<=9) minutes="0"+minutes;
               if (seconds<=9)    seconds="0"+seconds;
               var cdate=""+hours+":"+minutes+":"+seconds+" "+dn+"";
               if (document.all)
               document.all.clock.innerHTML=cdate;
               else if (document.getElementById)
               document.getElementById("clock").innerHTML=cdate;
               else
               document.write(cdate);
               }
               if (!document.all&&!document.getElementById) getthedate();
               
               function goforit(){
                   if (document.all||document.getElementById) setInterval("getthedate()",1000);
                   }
                   window.onload=goforit;
                   // End -->
                   </SCRIPT>
            </td>
            <td width="200" style="color:blue; vertical-align: top;font-weight:bold;">'.$this->l('Server Time:').'</td>
            <td style="color:green; vertical-align: top;font-weight:bold;"><iframe height="20" frameborder="0" vspace="0" hspace="0" marginwidth="0" marginheight="0 width="700" src="../modules/venteflash/clock.php" ></iframe></td>
         </tr>
         <tr>
            <td colspan="2" style="color:blue;  vertical-align: top;"><b>'.$this->l('Shop TimeZone:').'</b></td>
            <td colspan="2" style="color:red;   vertical-align: top;"><b>'.$this->timeZone().'</b></td>
        </tr>
        </table><br />
        <table class="table" border="0" width="860" cellpadding="0" cellspacing="2" id="form2">
        <tr>
           <td colspan="5" style="color:blue; vertical-align: top;text-align: left;font-weight:bold">'.$this->l('Setting the duration of effect and time before the exchange of promotion (Seconds).').'</td>
        </tr>
        <tr>
           <td style="color:black; vertical-align: top;text-align: left;font-weight:bold">'.$this->l('Time during sliding:').'</td>
           <td style="vertical-align: top;text-align: left"><input maxlength="1" type="text" name="effect" value="'.Tools::getValue('effect', $this->effect).'" style="width: 70px;" /></td>
           <td style="color:black; vertical-align: top;text-align: left;font-weight:bold">'.$this->l('Time out to start new sliding:').'</td>
           <td style="vertical-align: top;text-align: left"><input maxlength="2" type="text" name="transition" value="'.Tools::getValue('transition', $this->transition).'" style="width: 70px"/>
           <td style="vertical-align: top;text-align: right"><input class="button" name="vfEffect" value="'.$this->l('Set effect times').'" type="submit" style="color:blue;font-weight:bold;width: 180px;font-weight:bold"/></td>
        </tr>
        </form>
        </table>
        </fieldset>
        ';
     }
     
    public function getContent()
    {
        echo '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/datetimepicker_css.js"></script>';
        echo '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/bsn.AutoSuggest_2.1.3.js" charset="utf-8"></script>';
        echo '<link rel="stylesheet" href="'.__PS_BASE_URI__.'modules/venteflash/css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />';
        $this->startVenteFlash();
        $this->checkVF();
        $this->_html = '<h2>'.$this->displayName.'</h2><br>';
        if ($_POST)
        {
            $this->_postValidation();
			if (!sizeof($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors AS $err)
					$this->_html .= '<div class="alert error">'. $err .'</div>';
 	    }
		else
          $this->_displayVenteflash();
          $this->getVentesFlash();
          $this->showCategories();
          $this->_displayForm();
          return $this->_html;
	}
 
    private function _postValidation()
	{
       	if (Tools::isSubmit('addSubmit') AND !isset($_POST['vf']))
        {
            if (Tools::isEmpty($_POST['vf_reduction']))
            $this->_postErrors[] = $this->l('Reduction is required.');
            if (!is_numeric($_POST['vf_reduction']))
            $this->_postErrors[] = $this->l('Reduction must be numeric.');
            if (Tools::isEmpty($_POST['vf_from']))
            $this->_postErrors[] = $this->l('Begin date is required.');
            if (Tools::isEmpty($_POST['vf_to']))
            $this->_postErrors[] = $this->l('End date is required.');
            if (strtotime($_POST['vf_to']) < strtotime($_POST['vf_from']))
            $this->_postErrors[] = $this->l('Date from is greater than date to.');
            if (strtotime($_POST['vf_to']) == strtotime($_POST['vf_from']))
            $this->_postErrors[] = $this->l('Date from is equal to date to.');
            if (Tools::isEmpty($_POST['vf_product']))
            $this->_postErrors[] = $this->l('A product id is required.');
            if (!is_numeric($_POST['vf_product']))
            $this->_postErrors[] = $this->l('Product id must be numeric.');
            if ($this->checkProductId($_POST['vf_product']) == FALSE)
            {
                $this->_postErrors[] = $this->l('Product Id does not exists.');
            }
            else
            {
                if ($this->isActiveProduct($_POST['vf_product']) == FALSE)
                $this->_postErrors[] = $this->l('This product is not active product.');
                if ($this->reductionPrice($_POST['vf_product']) == FALSE)
                $this->_postErrors[] = $this->l('This product has a reduction by price.');
            }
        }
        if (Tools::isSubmit('addSubmit') AND Tools::isSubmit('vf'))
        {
            if (!empty($_POST['vf_reduction']) AND !is_numeric($_POST['vf_reduction']))
            $this->_postErrors[] = $this->l('Reduction must be numeric.');
            if(is_array($_POST['vf']) == TRUE)
            {
                foreach($_POST['vf'] as $chave => $id)
                {
                    if (strtotime($_POST['vf_to']) == strtotime($_POST['vf_from']))
                    $this->_postErrors[] = $this->l('Product ID')." ".$id." : ".$this->l('Date from is equal to date to.');
                    if (strtotime($_POST['vf_to']) < strtotime($_POST['vf_from']))
                    $this->_postErrors[] = $this->l('Product ID')." ".$id." : ".$this->l('Date from is greater than date to.');
                }
            }
            else
            {
                if (strtotime($_POST['vf_to']) < strtotime($_POST['vf_from']))
                $this->_postErrors[] = $this->l('Date from is greater than date to.');
            }
        }
        if (Tools::isSubmit('startVF'))
        {
            if (Tools::isEmpty($_POST['vf']))
            $this->_postErrors[] = $this->l('Please select a product.');
            else
            {
                if(is_array($_POST['vf']) == TRUE)
                {
                    foreach($_POST['vf'] as $chave => $id)
                    {
                         if($this->from_to_Compare($id) == FALSE)
                         $this->_postErrors[] = $this->l('Product ID')." ".$id." : ".$this->l('Select a date/time to greater than now.');
                     }
                 }
                 else
                 {
                     if($this->from_to_Compare($_POST['vf']) == FALSE)
                     $this->_postErrors[] = $this->l('Product ID')." ".$_POST['vf']." : ".$this->l('Select a date/time to greater than now.');
                 }
            }

        }
        if (Tools::isSubmit('stopVF'))
        {
            if (Tools::isEmpty($_POST['vf']))
            $this->_postErrors[] = $this->l('Please select a product to stop it.');
        }
        if (Tools::isSubmit('delVF'))
        {
            if (Tools::isEmpty($_POST['vf']))
            $this->_postErrors[] = $this->l('Please select a product to delete it.');
        }
        if (Tools::isSubmit('vfEffect'))
        {
            if (Tools::isEmpty($_POST['effect']))
            $this->_postErrors[] = $this->l('Effect time is required.');
            if (!is_numeric($_POST['effect']))
            $this->_postErrors[] = $this->l('Effect time must be numeric.');
            if (Tools::isEmpty($_POST['transition']))
            $this->_postErrors[] = $this->l('Transition time is required.');
            if (!is_numeric($_POST['transition']))
            $this->_postErrors[] = $this->l('Transition time must be numeric.');
        }
        if (Tools::isSubmit('addCat'))
        {
            if (Tools::isEmpty($_POST['cat']))
            $this->_postErrors[] = $this->l('Please select a category.');
            if (Tools::isEmpty($_POST['cat_reduction']))
            $this->_postErrors[] = $this->l('Reduction field is empty.');
        }
        if (Tools::isSubmit('compactions'))
        {
            if (!is_numeric($_POST['offset']))
            $this->_postErrors[] = $this->l('Offset must be numeric.');
        }
    }
    
    private function _postProcess()
	{
        if (Tools::isSubmit('addSubmit') AND Tools::isSubmit('vf') == FALSE)
        {
            $this->addVenteFlash($_POST['vf_product'],$_POST['vf_from'],$_POST['vf_to'],$_POST['vf_reduction'], $this->getOldreduction($_POST['vf_product']));
        }
        if (Tools::isSubmit('addSubmit') AND Tools::isSubmit('vf'))
        {
            if(isset($_POST['vf_from']))
            $vf_from = $_POST['vf_from'];
            if(isset($_POST['vf_to']))
            $vf_to = $_POST['vf_to'];
            if(empty($_POST['vf_reduction']))
            $vf_reduction = "";
            elseif(isset($_POST['vf_reduction']))
            $vf_reduction = ',`reduction` ="'.($_POST['vf_reduction']).'"';

            foreach($_POST['vf'] as $chave => $value)
            {
                $venteflash = Db::getInstance()->Execute('
                UPDATE `'._DB_PREFIX_.'venteflash`
                SET `datedebut` ="'.($vf_from).'",`datefin` ="'.($vf_to).'" '.($vf_reduction).'
                WHERE `id_venteflash` = "'.($value).'"
                ');
                if(strtotime($vf_from) > strtotime(date("Y-m-d H:i:s")))
                {
                    $sql=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent=0, reduction_from=0, reduction_to=0, date_upd=NOW()
                    WHERE id_product="'.($value).'"
                    ');
                }
            }
        }

        if (Tools::isSubmit('delVF'))
        {
            foreach($_POST['vf'] as $chave => $value)
            {
                if(Configuration::get('VF_KEEPREDUCTION') == '1')
                {
                    $deleted=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent="'.($this->getOldreductionVF($value)).'", reduction_from="'.(date("Y-m-d H:i:s")).'", reduction_to="'.(date("Y-m-d H:i:s")).'", date_upd=NOW()
                    WHERE id_product="'.($value).'"
                    ');
                }
                else
                {
                    $deleted2=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent=0, reduction_from=0, reduction_to=0, date_upd=NOW()
                    WHERE id_product="'.($value).'"
                    ');
                }
                $deleted3=Db::getInstance()->Execute('
                DELETE FROM `'._DB_PREFIX_.'venteflash`
                WHERE `id_venteflash` =  "'.(trim($value)).'"
                ');
            }
        }
        if (Tools::isSubmit('startVF'))
        {
            foreach($_POST['vf'] as $chave => $value)
            {
                $sql = Db::getInstance()->Execute('
                SELECT * FROM `'._DB_PREFIX_.'venteflash`
                WHERE `id_venteflash` = "'.(trim($value)).'"
                ');
                while ($aux = mysql_fetch_row($sql))
                {
                    $sql2=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent='.(trim($aux[4])).', reduction_from=CURDATE(), reduction_to=CURDATE(), date_upd=NOW()
                    WHERE id_product="'.(trim($value)).'"
                    ');
                }
            }
        }
        if (Tools::isSubmit('stopVF'))
        {
            foreach($_POST['vf'] as $chave => $value)
            {
                $sql = Db::getInstance()->Execute('
                SELECT * FROM `'._DB_PREFIX_.'venteflash`
                WHERE `id_venteflash` = "'.(trim($value)).'"
                ');
                while ($aux = mysql_fetch_row($sql))
                {
                    $sql2=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'product`
                    SET reduction_percent=0, reduction_from=0, reduction_to=0, date_upd=NOW()
                    WHERE id_product="'.(trim($value)).'"
                    ');
                    $sql3=Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'venteflash`
                    SET datedebut="'.(date("Y-m-d H:i:s")).'", datefin="'.(date("Y-m-d H:i:s")).'"
                    WHERE id_venteflash="'.(trim($value)).'"
                    ');
                }
            }
        }
        if (Tools::isSubmit('compactions'))
        {
           $banner = 'no';
           $active = '1';
           if(isset($_POST['banner']))
           $banner =  $_POST['banner'];
           Configuration::updateValue('VF_BANNER', $banner);
           if(isset($_POST['active']))
           $active =  $_POST['active'];
           Configuration::updateValue('VF_ACTIVE', $active);
           $keepreduction = '0';
           if(isset($_POST['keepreduction']))
           $keepreduction = $_POST['keepreduction'];
           Configuration::updateValue('VF_KEEPREDUCTION',  $keepreduction);
           $offset = $_POST['offset'];
           if (Tools::isEmpty($offset))
           $offset = '0';
           Configuration::updateValue('VF_OFFSET', $offset);
        }
        if (Tools::isSubmit('vfEffect'))
        {
            Configuration::updateValue('VF_EFFECT', $_POST['effect']);
            Configuration::updateValue('VF_TRANSITION', $_POST['transition']);
        }
        if (Tools::isSubmit('addCat'))
        {
            foreach($_POST['cat'] as $chave => $value)
            {
                $this->addCatVenteFlash($value, date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), $_POST['cat_reduction']);
            }
        }
        
        $this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('ok').'" /> '.$this->l('Settings updated').'</div>';

     }
     
     //Verify if exists a product added, if no, insert it, if yes, update it.
     public function addCatVenteFlash($id, $debut, $fin, $reduction)
     {
         $check  = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'product`
         WHERE  `id_category_default` = "'.($id).'"
         AND    `active` = 1
         AND    `reduction_price` = 0.00
         AND  id_product NOT IN (SELECT id_venteflash FROM `'._DB_PREFIX_.'venteflash`)
         ');
         $nb_reg = mysql_num_rows($check);
         if ($nb_reg > '0')
         {
             while($list = mysql_fetch_row($check))
             {
                 $query =  Db::getInstance()->Execute('
                 INSERT INTO  `'._DB_PREFIX_.'venteflash`
                 (`id_venteflash`, `datedebut`,`datefin`,`vfreduction`, `oldreduction`)
                 VALUES ("'.($list[0]).'","'.($debut).'","'.($fin).'","'.($reduction).'", "'.($list[13]).'")
                 ');
             }
         }
     }
     
     function checkrandomSpecial($id)
     {
         if(mysql_num_rows(Db::getInstance()->Execute('SHOW TABLES LIKE `'._DB_PREFIX_.'venteflash`')))
         {
             $sql = Db::getInstance()->Execute('
             SELECT * FROM `'._DB_PREFIX_.'`
             WHERE `id_timezone` = "'.($tz).'"
             ');
             while ($aux = mysql_fetch_row($sql))
             {
                 $return = $aux[1];
             }
             return $return;
         }
     }
     
     //Verify which timezone your shop is set.
     function timeZone()
     {
         $tz = Configuration::get('PS_TIMEZONE');
         $sql = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'timezone`
         WHERE `id_timezone` = "'.($tz).'"
         ');
         while ($aux = mysql_fetch_row($sql))
         {
             $return = $aux[1];
         }
         return $return;
      }
     
     //Verify if datetime to is greater of datetime from.
     function from_to_Compare($id)
     {
         $sql = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'venteflash`
         WHERE `id_venteflash` = "'.($id).'"
         ');
         while ($aux = mysql_fetch_row($sql))
         {
             if(strtotime($aux[3]) < strtotime(date("r")))
             return FALSE;
             else
             return TRUE;
         }
      }
     
     //Verify if a venteflash is active in order to display a flag.
     public function statusVenteFlash($id,$reduction)
     {
         $sql = Db::getInstance()->Execute('
         SELECT vf.`id_venteflash`, p.`id_product`
         FROM   `'._DB_PREFIX_.'venteflash` as vf, `'._DB_PREFIX_.'product` as p
         WHERE  p.`id_product` =  "'.($id).'"
         AND    p.`reduction_percent` =  "'.($reduction).'"
         LIMIT  0,1
         ');
         $nb_reg  = mysql_num_rows($sql);
         if ($nb_reg == '0')
         {
             $sql2 = Db::getInstance()->Execute('
             SELECT *
             FROM `'._DB_PREFIX_.'venteflash`
             WHERE `id_venteflash` =  "'.($id).'"
             LIMIT  0,1
             ');
             while($aux = mysql_fetch_row($sql2))
             {
                 if (strtotime($aux[2]) > time())
                 return '<img src="../modules/venteflash/images/date-icon.png" />';
                 elseif (strtotime($aux[2]) < time() AND strtotime($aux[3]) > time())
                 return '<img src="../modules/venteflash/images/wait.png" />';
                 else
                 return '<img src="../img/admin/disabled.gif" />';
             }
         }
         else
         return '<img src="../img/admin/enabled.gif" />';
     }
     
     //Verify if there is a venteflash active to display on home page.
     public function thereisVenteFlash()
     {
         $sql = Db::getInstance()->Execute('
         SELECT vf.*
         FROM   `'._DB_PREFIX_.'venteflash` as vf, `'._DB_PREFIX_.'product` as p
         WHERE  p.`id_product` =  vf.`id_venteflash`
         AND    p.`reduction_percent` =  vf.`vfreduction`
         ');
         $nb_reg = mysql_num_rows($sql);
         if ($nb_reg == '0')
         {
             return FALSE;
         }
         else
         return TRUE;
     }
     
      //Retrieve product categories
     function showCategories()
     {
         global $cookie;
         $id_lang = $cookie->id_lang;
         $query  = Db::getInstance()->Execute('
         SELECT  * FROM `'._DB_PREFIX_.'category_lang`
         WHERE  `id_lang` = "'.($id_lang).'"
         ');
         $nb_reg = mysql_num_rows($query);
          $this->_html .='
         <script language = "javascript">
         function CheckCatID()
         {
             for (var i=0;i<document.formcat.elements.length;i++)
             {
                 var x = document.formcat.elements[i];
                 if (x.name == "cat[]")
                 {
                     x.checked = document.formcat.selall.checked;
                 }
             }
         }
         </script>';
         $this->_html .= ' <br />
         <form action="'.$_SERVER['REQUEST_URI'].'" method="post" id="formcat" name="formcat">
              <fieldset>
                   <legend><img src="../modules/venteflash/logo.gif" />'.$this->l('Current Categories').'</legend>';
         if ($nb_reg == '0')
         {
             $this->_html .= '<div style="font-size:15px;color: red;text-align: left">'.$this->l('There is not a single categorie yet.').'</div>';
         }
         else
         {
              $this->_html .= '
             <table  class="table" border="0" width="900" cellpadding="0" cellspacing="2" id="formcat">
             <tr>
                 <td width="10" align="left" style="vertical-align: top;"><input type=checkbox name="selall" onClick="CheckCatID()"></td>
                 <td colspan="3" style="color: blue;"><b>'.$this->l('Select/Deselect all').'</b></td>
             </tr>
             <tr>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">---</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('ID').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('Categorie Name').'</td>
            </tr>
             ';
             while ($aux = mysql_fetch_row($query))
             {
                 $this->_html .='
             <tr>
             <td style="vertical-align: top;text-align: left"><INPUT TYPE=checkbox VALUE="'.$aux[0].'" NAME="cat[]"></td>
             <td style="color:#8B0000;font-weight:bold;vertical-align: top;text-align: left">'.$aux[0].'</a></td>
             <td style="color:#191970;font-weight:bold;vertical-align: top;text-align: left">'.$aux[2].'</td>
             </tr>
             ';
             }
             $this->_html .='
             <tr>
             <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('Reduction').'</td>
             <td style="color:blue; vertical-align: top;" ><input type="text" MAXLENGTH="2" name="cat_reduction" value="" style="width: 100px;"/></td>
             <td style="text-align: right"><input class="button" name="addCat" value= "'.$this->l('Add').'" type="submit" style="color:green;font-weight:bold;width: 180px;"/></td>
              </tr>
          </table></fieldset> </form><br />
          ';
          }
     }
     
     // Get category ID
     function getCategoryID($id)
     {
         $sql = Db::getInstance()->Execute('
         SELECT *
         FROM `'._DB_PREFIX_.'product`
         WHERE id_product = "'.($id).'"
         LIMIT 0,1
         ');
         while($list = mysql_fetch_row($sql))
         {
             return $list[4];
         }
     }

     // Called within getcontent
     function getVentesFlash()
     {
         global $cookie;
         $id_lang = $cookie->id_lang;
         $sql = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'venteflash`
         ORDER BY datefin DESC
         ');

         $nb_comments = mysql_num_rows($sql);
         $this->_html .='
         <script language = "javascript">
         function CheckAllID()
         {
             for (var i=0;i<document.formvf.elements.length;i++)
             {
                 var x = document.formvf.elements[i];
                 if (x.name == "vf[]")
                 {
                     x.checked = document.formvf.selall.checked;
                 }
             }
         }
         </script>';
         $this->_html .= ' <br />
         <form action="'.$_SERVER['REQUEST_URI'].'" method="post" id="formvf" name="formvf">
              <fieldset>
                   <legend><img src="../modules/venteflash/logo.gif" />'.$this->l('Current added products').'</legend>';
         if ($nb_comments == '0')
         {
             $this->_html .= '<div style="font-size:15px;color: red;text-align: left">'.$this->l('There are not added products yet.').'</div>';
         }
         else
         {
              $this->_html .= '
             <table  class="table" border="0" width="900" cellpadding="0" cellspacing="2" id="formvf">
             <tr>
                 <td width="10" align="left" style="vertical-align: top;"><input type=checkbox name="selall" onClick="CheckAllID()"></td>
                 <td colspan="7" style="color: blue;"><b>'.$this->l('Select/Deselect all').'</b></td>
             </tr>
             <tr>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">---</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('ID').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: center">'.$this->l('Cat.').'</td>
                 <td width="280" style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('Product Name').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('Date/Time From').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: left">'.$this->l('Date/Time To').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: center;">'.$this->l('Reduction').'</td>
                 <td style="color:green;vertical-align: top;font-weight:bold;text-align: center;">'.$this->l('Status').'</td>
             </tr>
             ';
             while ($aux = mysql_fetch_row($sql))
             {
                 $this->_html .='
             <tr>
             <td style="vertical-align: top;text-align: left"><INPUT TYPE=checkbox VALUE="'.$aux[1].'" NAME="vf[]"></td>
             <td style="color:#8B0000;font-weight:bold;vertical-align: top;text-align: left"><a href="#" title="'.$this->l('Click!').'" onclick="document.getElementById(\'vfproduct\').value=\''.$aux[1].'\'">'.$aux[1].'</a></td>
             <td style="color:#8B0A50;font-weight:bold;vertical-align: top;text-align: center">'.$this->getCategoryID($aux[1]).'</td>
             <td width="280" style="color:#191970;font-weight:bold;vertical-align: top;text-align: left">'.$this->showproductname($aux[1],$id_lang).'</td>
             <td style="color:#8B0A50;font-weight:bold;vertical-align: top;text-align: left">'.$aux[2].'</td>
             <td style="color:#000000;font-weight:bold;vertical-align: top;text-align: left">'.$aux[3].'</td>
             <td style="color:#8B008B;font-weight:bold;vertical-align: top;text-align: center">'.$aux[4].'%</td>
             <td style="vertical-align: top;text-align: center">'.$this->statusVenteFlash($aux[1],$aux[4]).'</td>
             </tr>
             ';
             }
             $this->_html .='
             <tr>
                <td style="text-align: right" colspan="5"><input class="button" name="startVF" value= "'.$this->l('Start').'" type="submit" style="color:green;font-weight:bold;width: 165px;"/></td>
                <td style="text-align: right" ><input class="button" name="stopVF" value= "'.$this->l('Stop').'" type="submit" style="color:orange;font-weight:bold;width: 165px;"/></td>
                <td style="text-align: right" colspan="2"><input class="button" name="delVF" value= "'.$this->l('Delete').'" type="submit" style="color:red;font-weight:bold;width: 165px;"/></td>
            </tr>
          </table> <br />';}
           $this->_html .='
             <table class="table" border="0" width="900" cellpadding="0" cellspacing="2" id="form">
        <tr>
           <td style="color:blue; vertical-align: top;"><b>'.$this->l('Product').'</b></td>
           <td style="color:blue; vertical-align: top;"><b>'.$this->l('Id').'</b></td>
           <td style="color:blue; vertical-align: top;"><b>'.$this->l('Date/Time From').'</b></td>
           <td style="color:blue; vertical-align: top;"><b>'.$this->l('Date/Time To').'</b></td>
           <td style="color:blue; vertical-align: top;"><b>'.$this->l('Reduction (%)').'</b></td>
        </tr>
        <tr>
           <td style="color:blue; vertical-align: top;"><input style="width: 200px" type="text" id="productinput" value="" /></td>
           <td style="color:blue; vertical-align: top;"><input type="text" name="vf_product" id="vfproduct" value="" style="font-size: 10px; width: 20px;" /></td>
           <td style="color:blue; vertical-align: top;"><input type="text" id="vf_from" name="vf_from" value="'.(date('Y-m-d H:i:s')).'" style="width: 150px;"/>
             <a href="javascript:NewCssCal(\'vf_from\',\'yyyymmdd\',\'arrow\',true,24,false)"><img src="'.__PS_BASE_URI__.'modules/venteflash/images/cal.gif" width="16" height="16" alt="'.$this->l('Pick a date').'"></a></td>
           <td style="color:blue; vertical-align: top;"><input type="text" id="vf_to" name="vf_to"   value="'.(date('Y-m-d H:i:s')).'" style="width: 150px;"/>
             <a href="javascript:NewCssCal(\'vf_to\',\'yyyymmdd\',\'arrow\',true,24,false)"><img src="'.__PS_BASE_URI__.'modules/venteflash/images/cal.gif" width="16" height="16" alt="'.$this->l('Pick a date').'"></a></td>
           <td style="color:blue; vertical-align: top;"><input type="text" MAXLENGTH="2" name="vf_reduction" value="" style="width: 100px;"/></td>
        </tr>
        <tr>
           <td align="right" colspan="5"><input class="button" name="addSubmit" value= "'.$this->l('Add').'" type="submit" style="color:blue;font-weight:bold;width: 180px;" onClick="javascript: submitform()"/></td></tr>
        </table>
              <script language="JavaScript">
              var options = {
		      script:"'.__PS_BASE_URI__.'modules/venteflash/productsuggest.php?json=true&limit=6&",
		      varname:"input",
		      json:true,
		      shownoresults:true,
		      maxresults:15,
		      callback: function (obj) { document.getElementById(\'vfproduct\').value = obj.id; }
	        };
	          var as_json = new bsn.AutoSuggest(\'productinput\', options);
             </script>
              </fieldset></form>
             ';

     }
     
     //Get date/time for the comming soon countdown
     function getCSTime($id)
     {
         $sql = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'venteflash`
         WHERE `id_venteflash` = "'.(trim($id)).'"
         ');
         while ($aux = mysql_fetch_row($sql))
         {
             $return = $aux[2];
         }
         return $return;
     }
     
     //Get date/time for the countdown
     function getTime($id)
     {
         $sql = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'venteflash`
         WHERE `id_venteflash` = "'.(trim($id)).'"
         ');
         while ($aux = mysql_fetch_row($sql))
         {
             $return = $aux[3];
         }
         return $return;
     }

      //Checks if a product id in order to timer appear on product.tpl
     function checkVFProductId($id)
     {
         $query = Db::getInstance()->Execute('
         SELECT vf.*
         FROM   `'._DB_PREFIX_.'venteflash` as vf, `'._DB_PREFIX_.'product` as p
         WHERE  p.`id_product` =  vf.`id_venteflash`
         AND  p.`reduction_percent` =  vf.`vfreduction`
         AND  vf.`id_venteflash` = "'.($id).'"
         ');
         $nb_reg = mysql_num_rows($query);
         if ($nb_reg  == '0')
         {
             $return = '0';
         }
         else
         $return = '1';

         return $return;
     }

     //Verify if exists a product added, if no, insert it, if yes, update it.
     public function addVenteFlash($id, $debut, $fin, $reduction, $oldreduction)
     {
         $check  = Db::getInstance()->Execute('
         SELECT * FROM `'._DB_PREFIX_.'venteflash`
         WHERE  `id_venteflash` = "'.($id).'"
         ');
         $nb_reg = mysql_num_rows($check);
         if ($nb_reg == '0')
         {
             $query =  Db::getInstance()->Execute('
             INSERT INTO  `'._DB_PREFIX_.'venteflash`
             (`id_venteflash`, `datedebut`,`datefin`,`vfreduction`,`oldreduction`)
             VALUES ("'.($id).'","'.($debut).'","'.($fin).'","'.($reduction).'","'.($oldreduction).'")
             ');
         }
         else
         {
             $venteflash = Db::getInstance()->Execute('
             UPDATE `'._DB_PREFIX_.'venteflash`
             SET `datedebut` ="'.($debut).'",`datefin` ="'.($fin).'",`vfreduction` ="'.($reduction).'"
             WHERE `id_venteflash` = "'.($id).'"
             ');
         }
     }

     //Called on uninstall module event
     function uninstallVenteFlash()
     {
         $query = Db::getInstance()->Execute('
         SELECT *
         FROM  `'._DB_PREFIX_.'venteflash`
         ');
         $nb_reg = mysql_num_rows($query);
         if ($nb_reg > '0')
         {
             while($aux = mysql_fetch_row($query))
             {
                 $sql=Db::getInstance()->Execute('
                 UPDATE `'._DB_PREFIX_.'product`
                 SET reduction_percent=0, reduction_from=0, reduction_to=0, date_upd=NOW()
                 WHERE id_product="'.($aux[1]).'"
                 ');
              }
          }
      }

     //Retrieve product name in getVentesFlash
     function showproductname($id,$id_lang)
     {
         $show  = Db::getInstance()->Execute('
         SELECT  * FROM `'._DB_PREFIX_.'product_lang`
         WHERE  `id_product` = "'.($id).'"
         AND    `id_lang` = "'.($id_lang).'"
         ');
         $nb_reg = mysql_num_rows( $show);
         if ($nb_reg  == '0')
         {
              $result = $this->l('Failed to retrieve product name');
         }
         else
         {
             while ($line = mysql_fetch_row($show))
             {
                 $result = $line[8];
             }
         }
         
         return  $result;
     }

     //Checks if a product id exists
     function checkProductId($id)
     {
         $get_id  = Db::getInstance()->Execute('
         SELECT  * FROM `'._DB_PREFIX_.'product`
         WHERE  `id_product` = "'.($id).'"
         ');
         $nb_reg = mysql_num_rows($get_id);
         if ($nb_reg  == '0')
         {
             return FALSE;
         }
         else
         return TRUE;
     }
     //Checks if is a active product
     function isActiveProduct($id)
     {
         $active  = Db::getInstance()->Execute('
         SELECT  * FROM `'._DB_PREFIX_.'product`
         WHERE `id_product` = "'.($id).'"
         AND `active` =1
         ');
         $nb_reg = mysql_num_rows($active);
         if ($nb_reg  == '0')
         {
             return FALSE;
         }
         else
         return TRUE;
     }
     //Checks if there is a reduction by price for a product
     function reductionPrice($id)
     {
         $reduction = Db::getInstance()->Execute('
         SELECT  * FROM `'._DB_PREFIX_.'product`
         WHERE `id_product` = "'.($id).'"
         AND `reduction_price` =0
         ');
         $nb_reg = mysql_num_rows($reduction);
         if ($nb_reg  == '0')
         {
             return FALSE;
         }
         else
         return TRUE;
     }

    public function getVFPricesDrop($id_lang, $pageNumber = 0, $nbProducts = 10, $count = false, $orderBy = NULL, $orderWay = NULL, $beginning = false, $ending = false)
	{
        global $link, $cookie;
		if (!Validate::isBool($count))
			die(Tools::displayError());

		if ($pageNumber < 0) $pageNumber = 0;
		if ($nbProducts < 1) $nbProducts = 10;
		if (empty($orderBy) || $orderBy == 'position') $orderBy = 'myprice';
		if (empty($orderWay)) $orderWay = 'DESC';
		if ($orderBy == 'id_product' OR $orderBy == 'price' OR $orderBy == 'date_add')
			$orderByPrefix = 'p';
		elseif ($orderBy == 'name')
            $orderByPrefix = 'pl';
		if (!Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay))
			die (Tools::displayError());

		if ($count)
		{
			$sql = '
			SELECT COUNT(DISTINCT p.`id_product`) AS nb
			FROM `'._DB_PREFIX_.'product` p
			WHERE p.`active` = 1
			AND p.`id_product` IN (
				SELECT cp.`id_product`
				FROM `'._DB_PREFIX_.'category_group` cg
				LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
				WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
			)';
			$result = Db::getInstance()->getRow($sql);
			return intval($result['nb']);
		}
		$currentDate = date('Y-m-d');
		$sql = '
		SELECT vf.*, p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`, i.`id_image`, il.`legend`, t.`rate`, (p.`reduction_price` + (p.`reduction_percent` * p.`price`)) AS myprice, m.`name` AS manufacturer_name
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = p.`id_tax`)
		LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
        LEFT JOIN `'._DB_PREFIX_.'venteflash` vf ON vf.`id_venteflash` = p.`id_product`
		WHERE p.`id_product` = vf.`id_venteflash` AND  p.`reduction_percent` = vf.`vfreduction`
		AND p.`active` = 1
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
		)
		ORDER BY '.(isset($orderByPrefix) ? pSQL($orderByPrefix).'.' : '').'`'.pSQL($orderBy).'`'.' '.pSQL($orderWay).'
		LIMIT '.intval($pageNumber * $nbProducts).', '.intval($nbProducts);
		$result = Db::getInstance()->ExecuteS($sql);
		if($orderBy == 'price')
		{
			Tools::orderbyPrice($result,$orderWay);
		}
		if (!$result)
			return false;
		return Product::getProductsProperties($id_lang, $result);
	}
 
     public function commingSoonVF($id_lang, $pageNumber = 0, $nbProducts = 10, $count = false, $orderBy = NULL, $orderWay = NULL, $beginning = false, $ending = false)
	{
        global $link, $cookie;
		if (!Validate::isBool($count))
			die(Tools::displayError());

		if ($pageNumber < 0) $pageNumber = 0;
		if ($nbProducts < 1) $nbProducts = 10;
		if (empty($orderBy) || $orderBy == 'position') $orderBy = 'myprice';
		if (empty($orderWay)) $orderWay = 'DESC';
		if ($orderBy == 'id_product' OR $orderBy == 'price' OR $orderBy == 'date_add')
			$orderByPrefix = 'p';
		elseif ($orderBy == 'name')
            $orderByPrefix = 'pl';
		if (!Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay))
			die (Tools::displayError());

		if ($count)
		{
			$sql = '
			SELECT COUNT(DISTINCT p.`id_product`) AS nb
			FROM `'._DB_PREFIX_.'product` p
			WHERE p.`active` = 1
			AND p.`id_product` IN (
				SELECT cp.`id_product`
				FROM `'._DB_PREFIX_.'category_group` cg
				LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
				WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
			)';
			$result = Db::getInstance()->getRow($sql);
			return intval($result['nb']);
		}
		$currentDate = date('Y-m-d H:i:s');
		$sql = '
		SELECT vf.*, p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`, i.`id_image`, il.`legend`, t.`rate`, (p.`reduction_price` + (p.`reduction_percent` * p.`price`)) AS myprice, m.`name` AS manufacturer_name
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = p.`id_tax`)
		LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
        LEFT JOIN `'._DB_PREFIX_.'venteflash` vf ON vf.`id_venteflash` = p.`id_product`
		WHERE vf.`datedebut` > "'.pSQL($currentDate).'" AND vf.`datefin` > vf.`datedebut` AND vf.`datedebut` > "'.pSQL($currentDate).'"
		AND p.`active` = 1
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
		)
		ORDER BY '.(isset($orderByPrefix) ? pSQL($orderByPrefix).'.' : '').'`'.pSQL($orderBy).'`'.' '.pSQL($orderWay).'
		LIMIT '.intval($pageNumber * $nbProducts).', '.intval($nbProducts);
		$result = Db::getInstance()->ExecuteS($sql);
        if($orderBy == 'price')
		{
			Tools::orderbyPrice($result,$orderWay);
		}
		if (!$result)
			return false;
		return Product::getProductsProperties($id_lang, $result);
	}

    public function showVentesFlash()
    {
        global $cookie;
        $id_lang = $cookie->id_lang;
        $nbProducts = $this->getVFPricesDrop(intval($id_lang), NULL, NULL, true);
        $nArray = intval(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array(intval(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50);
        $n = abs(intval(Tools::getValue('n', intval(Configuration::get('PS_PRODUCTS_PER_PAGE')))));
        $p = abs(intval(Tools::getValue('p', 1)));
        $range = 2; /* how many pages around page selected */
        if (!$n)
        $n = $nArray[0];
        if ($p < 0)
        $p = 0;
        if ($p > ($nbProducts / $n))
        $p = ceil($nbProducts / $n);
        $pages_nb = ceil($nbProducts / intval($n));
        $start = intval($p - $range);
        if ($start < 1)
        $start = 1;
        $stop = intval($p + $range);
        if ($stop > $pages_nb)
        $stop = intval($pages_nb);
        $pagination_infos = array('pages_nb' => intval($pages_nb), 'p' => intval($p), 'n' => intval($n), 'nArray' => $nArray, 'range' => intval($range), 'start' => intval($start),	'stop' => intval($stop));
        global $smarty;
        $smarty->assign($pagination_infos);
        $products = $this->getVFPricesDrop(intval($id_lang), intval($p) - 1, intval($n), false,NULL,NULL);
        $smarty->assign(array(
        	'products'   => $this->getVFPricesDrop(intval($id_lang), intval($p) - 1, intval($n), false,NULL,NULL),
	        'nbProducts' => $nbProducts,
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'vfstatus'   => $this->thereisVenteFlash(),
            'vfd'        => $this->l('d'),
            'vfh'        => $this->l('h'),
            'vfm'        => $this->l('m'),
            'vfs'        => $this->l('s'),
             ));

            return $this->display(__FILE__,'flash-sales.tpl');
    }
    
    public function showCommingSoonVentesFlash()
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        global $cookie;
        $id_lang = $cookie->id_lang;
        $nbProducts = $this->getVFPricesDrop(intval($id_lang), NULL, NULL, true);
        $nArray = intval(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array(intval(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50);
        $n = abs(intval(Tools::getValue('n', intval(Configuration::get('PS_PRODUCTS_PER_PAGE')))));
        $p = abs(intval(Tools::getValue('p', 1)));
        $range = 2; /* how many pages around page selected */
        if (!$n)
        $n = $nArray[0];
        if ($p < 0)
        $p = 0;
        if ($p > ($nbProducts / $n))
        $p = ceil($nbProducts / $n);
        $pages_nb = ceil($nbProducts / intval($n));
        $start = intval($p - $range);
        if ($start < 1)
        $start = 1;
        $stop = intval($p + $range);
        if ($stop > $pages_nb)
        $stop = intval($pages_nb);
        $pagination_infos = array('pages_nb' => intval($pages_nb), 'p' => intval($p), 'n' => intval($n), 'nArray' => $nArray, 'range' => intval($range), 'start' => intval($start),	'stop' => intval($stop));
        global $smarty;
        $smarty->assign($pagination_infos);
        $smarty->assign(array(
        	'csproducts' => $this->commingSoonVF(intval($id_lang), intval($p) - 1, intval($n), false,NULL,NULL),
	        'nbProducts' => $nbProducts,
            'timer'      => '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/venteflash/js/countdown.js"></script>',
            'vfstatus'   => $this->thereisVenteFlash(),
            'vfd'        => $this->l('d'),
            'vfh'        => $this->l('h'),
            'vfm'        => $this->l('m'),
            'vfs'        => $this->l('s'),
             ));

            return $this->display(__FILE__,'commingsoon.tpl');
    }
    
    function floatingBanner()
    {
        global $cookie;
        $id_lang = $cookie->id_lang;
        $special = $this->getVFSpecial(intval($id_lang));
        if (!$special)
        $special = $this->getCSSpecial(intval($id_lang));
         echo '
         <!-- CSS with support for IE -->
         <style type="text/css">
         <!--
         #fixme {
             /* IE 5.0/Win and other lesser browsers will use this */
             position: absolute; right: 0px; bottom: 0px;
             }
             body > div#fixme {
             /* used by Netscape6+/Mozilla, Opera 5+, Konqueror, Safari, OmniWeb 4.5+, ICEbrowser */
             position: fixed;
             }
             --></style>
             <!--[if gte IE 5.5]>
             <![if lt IE 7]>
             <style type="text/css">
             div#fixme {
                 /* IE5.5+/Win - this is more specific than the IE 5.0 version */
                 right: auto; bottom: auto;
                 left: expression( ( -0 - fixme.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + \'px\' );
                 top: expression( ( +0 - fixme.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + \'px\' );
                 }
                 </style>
                 <![endif]>
                 <![endif]-->
            <div id="fixme" style="color:red; height: 120px; width: 100%;">
                <!-- EDIT BANNER CONTENTS BELOW -->
             <div id="banner" style="z-index: 5; background: url('._MODULE_DIR_.'venteflash/images/banner.gif); width: 100%; height: 120px;">
             <div id="clock"  style="float: left; position: relative; left: 0; top: 0;"><img src="'._MODULE_DIR_.'venteflash/images/clock.jpg" height="120" border="0"/></div>
             <div id="closeme" style="float: right; position: relative; text-align: right; top: 75px; font-size: 10px; font-weight: bold;"><a onclick="javascript:document.getElementById(\'fixme\').style.display=\'none\';return true;" style="cursor: pointer;">'.$this->l('Close Me').'</a></div>
             <span id="text1" style="color:red; float: left; position: relative; top: 80px; text-align: left; font-size: 12px; font-weight: bold; text-decoration: blink;"><a href="'.$special['link'].'">'.$this->l('Take a look at our Flash Sales!').'</a></span>
             <span id="text2" style="color:green; float: left; position: relative; top: 80px; text-align: center; font-size: 12px; font-weight: bold; font-style: italic;"><a href="'.$special['link'].'">'.$special['name'].'<br />'. Tools::displayPrice($special['price_without_reduction']).' -  '.$special['reduction_percent'].'</a></span>
             <div id="productimg" style="float: center; position: relative; center: 1; top: 0;"><a href="'.$special['link'].'"><img src="'._THEME_PROD_DIR_.$special['id_image'].'-small.jpg" alt="'.$special['legend'].'" title="'.$special['name'].'" border="0"/></a></div>
             </div>
             </div> ';
    }
    
    public function getCSSpecial($id_lang, $beginning = false, $ending = false)
    {
        global	$link, $cookie;
        $currentDate = date('Y-m-d H:i:s');
		$row = Db::getInstance()->getRow('
		SELECT  vf.*, p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`,
			i.`id_image`, il.`legend`, t.`rate`
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = p.`id_tax`
		LEFT JOIN `'._DB_PREFIX_.'venteflash` vf ON vf.`id_venteflash` = p.`id_product`
	    WHERE vf.`datedebut` > "'.pSQL($currentDate).'" AND vf.`datefin` > vf.`datedebut` AND vf.`datedebut` > "'.pSQL($currentDate).'"
     	AND p.`active` = 1
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
		)
		ORDER BY RAND()');

		if ($row)
			return Product::getProductProperties($id_lang, $row);

		return $row;
	}
    
    public function getVFSpecial($id_lang, $beginning = false, $ending = false)
    {
        global	$link, $cookie;
		$row = Db::getInstance()->getRow('
		SELECT  vf.*, p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`,
			i.`id_image`, il.`legend`, t.`rate`
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.intval($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = p.`id_tax`
		LEFT JOIN `'._DB_PREFIX_.'venteflash` vf ON vf.`id_venteflash` = p.`id_product`
        WHERE p.`id_product` = vf.`id_venteflash` AND  p.`reduction_percent` = vf.`vfreduction`
     	AND p.`active` = 1
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.(!$cookie->id_customer ?  '= 1' : 'IN (SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.intval($cookie->id_customer).')').'
		)
		ORDER BY RAND()');

		if ($row)
			return Product::getProductProperties($id_lang, $row);

		return $row;
	}
}
?>
