<?
        function CalculatePrice($params) {
            global $smarty;
            $hotel     = isset($params["Hotel"]) ? $params["Hotel"] : $params["Resort"];
            $room_type = $params["Room_Type"];
            $nights    = $params["Nights"];
            $adults    = isset($params["Adults"]) ?  $params["Adults"] : 0;
            $children  = isset($params["Children"]) ?  $params["Children"] : 0;
            $juniors   = isset($params["Juniors"]) ?  $params["Juniors"] : 0;
            $form_type = isset($params["form_type"]) ?  $params["form_type"] : "";

            $section   = $hotel.":".$room_type;
//            dump($section);

            $mode = 1;
            $smarty->config_load('calculation_high_season.conf',$section);
            $configs = $smarty->get_config_vars();

        if ($configs["BaseNights"]) {
            $season_dates = array();
            calculate_season_price("High",$configs,$params,$season_dates);
            calculate_season_price("Holiday",$configs,$params,$season_dates);
            $season_days  = array_count_values($season_dates);
        }
        else {
            $mode = 0;
            $smarty->config_load('calculation.conf',$section);
            $configs = $smarty->get_config_vars();
        }

            $Currency     = $configs["Currency"];
            $BaseNights   = $configs["BaseNights"];
            $AddPrice     = $configs["AddPrice"];
            $MaxNights    = $configs["MaxNights"];

            $HighPrice    = $configs["HighSeasonPrice"];
            $HighAddPrice = $configs["HighAddPrice"];
            $HolidayPrice = $configs["HolidaySeasonPrice"];
            $BasePrice    = $configs["BasePrice"];


            if ($BaseNights==0) {
                $price = 0;
            }
            elseif ($nights <= $BaseNights) {
                if ($mode) {
                    $price = ($season_days['High']*$HighPrice + $season_days['Holiday']*$HolidayPrice + ($nights-$season_days['High']-$season_days['Holiday'])*$BasePrice)/$BaseNights;
                }
                else {
                    $price = $nights*$BasePrice/$BaseNights;
                }
            }
            elseif ($nights <= $MaxNights) {
                if ($mode) {
                    $price = min($season_days['Holiday'], $BaseNights) * $HolidayPrice;
                    $price += max(min($season_days['High'], $BaseNights - $season_days['Holiday']), 0) * $HighPrice;
                    $price += max(min($nights - $season_days['High'] - $season_days['Holiday'], $BaseNights - $season_days['High'] - $season_days['Holiday']), 0) * $BasePrice;
                    $price /= $BaseNights;
                }
                else {
                    $price = $BasePrice;
                }

                //add additional days
                //calculate number of high season additional days
                $season = end($season_dates);
                for ($night = $nights; $night > $BaseNights; --$night) {
                  if ($season == 'High' and $HighAddPrice) {
                    $price += $HighAddPrice;
                  } else {
                    $price += $AddPrice;
                  }
                  $season = prev($season_dates);
                }
            }
            
			// End of holiday-cancun-cancun-arenas


        //add price of options
        foreach ($params as $key => $value) {
          if (isset($configs[$value])) { //this option is selected and has a price
            $price += $configs[$value];
          }
        }

         $price = round($price,2);
            $r = array( "txt"    => $price ? $configs["Currency"].$price : 'n/a',
                        "decimal"=> (float)$price,
                      );
            return $r;
        }

        function calculate_season_price($type, $configs, $params, &$season_dates) {
           $arrival_date1 = strtotime($params['Arrival_Date'].' '.$params['Arrival_Month']);
           $arrival_date2 = strtotime('+'.$params['Nights'].' days',$arrival_date1);
//echo "<b>".date('Y-m-d',$arrival_date1).' :: '.date('Y-m-d',$arrival_date2)."</b><br>\r\n";

           if ($configs["{$type}SeasonPrice"]!=0 && ($dates=preg_split("/;/",$configs["{$type}SeasonDates"], -1, PREG_SPLIT_NO_EMPTY)))
           for ($i=0; $i<count($dates); $i++) {
               list($dd_mm_1, $dd_mm_2) = preg_split("/[\/-]+/", trim($dates[$i]), 2, PREG_SPLIT_NO_EMPTY);

               if ($dd_mm_1) {
                   $date1 = strtotime($dd_mm_1);
                   $date2 = $dd_mm_2 ? strtotime($dd_mm_2) : $date1;
                   if ($date2<$date1) $date2 = strtotime('+1 year',$date2);
                   if ($date2<$arrival_date1) {
                     $date1 = strtotime('+1 year',$date1);
                     $date2 = strtotime('+1 year',$date2);
                   }
/*
                   if (!($arrival_date2<$date1 || $date2<$arrival_date1))
                       return $configs["{$type}SeasonPrice"];
*/

                   $dd = $arrival_date1;
                   do {
//echo "".date('Y-m-d',$date1).' :: '.date('Y-m-d',$dd).' :: '.date('Y-m-d',$date2)."<br>\r\n";
                      if (!($date2<$dd || $dd<$date1))
                          $season_dates[strftime("%Y%m%d",$dd)] = $type;

                      $dd=strtotime("+1 day",$dd);
                   } while ($dd<$arrival_date2);
               }

            }
        }


        function fetchArray($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchArray.";
              exit;
            }
            foreach ($keys as $key) {
                $r[$key] = $a[$key];
            }
            return $r;
        }

        function fetchFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
            foreach ($keys as $key) {
                foreach ($a as $field) {
                    if ($field["name"] == $key) {
                        $r[] = $field;
                    }
                }
            }
            return $r;
        }

        function unsetFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
                foreach ($a as $field) {
                    if (!in_array($field["name"],$keys)) {
                        $r[] = $field;
                    }
                }
            return $r;
        }

        function unsetKeys(&$a,$keys,$mode = '') {
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to unsetKeys.";
              exit;
            }
            foreach ($keys as $key) {
                if ($mode == "empty") {
                    if ($a[$key] == '') unset($a[$key]);
                } else {
                    if (isset($a[$key])) {
                        unset($a[$key]);
                    }
                }
            }
        }

        function getMode(){
                $mode = '';
                if ($_REQUEST["mode_delete"]) $mode = "delete";
                if ($_REQUEST["mode_edit"]) $mode = "edit";
                if ($_REQUEST["mode_add"]) $mode = "add";
                return $mode;
        }

        function generateMenu($fullMenu,$allowedSections){
                $menu = array();
                foreach ($fullMenu as $key=>$val){
                        if (in_array($key, $allowedSections)) $menu[$key] = $val;
                }
                return $menu;
        }

/**
 * @return string
 * @param type MIME-TYPE of image
 * @desc Returns 0 if image format is supportedelse return error code. 2-unexpected format, 1-image not supported.
 */
function checkImage($type) {

        $gif = array("image/gif");
        $jpg = array("image/jpg","image/jpeg","image/jpe","image/pjpeg");
        $png = array("image/png");

        if(!in_array($type, $gif) && !in_array($type, $jpg) && !in_array($type, $png)) {
                return 2;
        }

        if(in_array($type, $gif) && (!function_exists("imagecreatefromgif") || !function_exists("imagegif"))) {
                return 1;
        }

        if(in_array($type, $jpg) && (!function_exists("imagecreatefromjpeg") || !function_exists("imagejpeg"))) {
                return 1;
        }

        if(in_array($type, $png) && (!function_exists("imagecreatefrompng") || !function_exists("imagepng"))) {
                return 1;
        }

        return 0;
}

/**
 * @return string
 * @param txt string
 * @param cnt int
 * @desc Returns input string txt truncated to cnt number of characters plus the ending of the truncated sentence.
 */
function shortly($txt, $cnt)
{
        $out = strip_tags($txt);
        $out = substr($out, 0, $cnt);
        $end = substr($txt, $cnt, strlen($txt));
        $point = strpos($end, ".");
        $end = substr($end, 0, $point);
        $out .= $end . ". ";
        return $out;
}


function checkEmail($email)
{
         if (eregi("^[a-z0-9\._]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,3}$",$email)) {
                 return true;
         }else{
                 return false;
        }
}

function alert($msg) {
        norm($msg);
        print "<script>alert('$msg')</script>";
}

function norm($s) {
   $s = ereg_replace("<","&lt;",$s);
   $s = ereg_replace(">","&gt;",$s);
   $s = ereg_replace("\"","&quot;",$s);
   $s = ereg_replace("'","`",$s);
   $s = str_replace("\xD"," ",$s);
   $s = str_replace("\xA","",$s);
   return $s;
}

function normText (&$val, $key) {
        $val = str_replace("\r\n", " ", $val);
}

function normHTML($s) {
   $s = ereg_replace("\"","",$s);
   $s = ereg_replace("'","",$s);
   return $s;
}

function unnorm($s1){
   $s1 = str_replace("&lt;","<",$s1);
   $s1 = str_replace("&gt;",">",$s1);
   $s1 = str_replace("&quot;","\"",$s1);
   $s1 = str_replace("`","'",$s1);
   return $s1;
}


function limitLength($str, $length) {
        if (strlen($str)>$length)
                return substr($str, 0, $length-3)."...";
        else return $str;
}

function stripSlashesArr($arr) {
        if (is_array($arr))
        foreach ($arr as $key=>$val) {
                if (is_scalar($val))
                        $arr[$key] = stripslashes($val);
        }
        return $arr;
}

function rangeArr($from = 0, $to = 0) {
        while($from <= $to) {
                $arr[$from]=$from;
                $from++;
        }
        return $arr;
}

function outputArr($arr, $selected = 0) {
        foreach($arr as $key=>$val) {
                print "<option value='$key'";
                if ((int)$key == (int)$selected) print " selected";
                print ">$val</option>\n";
        }
}

function beginTag($var) {
        return "<".$var.">";
}

function endTag($var) {
        return "</".$var.">\n";
}

function timeArr() {
        $today = getdate();
        return Array(
                "month1" => $today['mon'],
                "day1" => $today['mday'],
                "year1" => $today['year'],
                "hour1" => $today['hours'],
                "minute1" => $today['minutes'],
                "month2" => $today['mon'],
                "day2" => $today['mday'],
                "year2" => $today['year'],
                "hour2" => $today['hours'],
                "minute2" => $today['minutes'],
                "month" => $today['mon'],
                "day" => $today['mday'],
                "year" => $today['year'],
                "hour" => $today['hours'],
                "minute" => $today['minutes']
        );
}

function getInsertionId($tableName, $DB) {
        $query = "select (max(syndicateid)+1) as id from ".$tableName;
        $DB->query($query);
        $DB->next_record();
        return $DB->f("id");
}

function fromSQLDate($date = "0000-00-00", $delim = "-") {
        list ($year, $month, $day) = split ($delim, substr($date,0,10));
        return date("m-d-Y", mktime (0, 0, 0, $month, $day, $year));
}

function toSQLDate($date = "00-00-0000", $delim = "-") {
        list ($month, $day, $year) = split ($delim, $date);
        return date("Y-m-d", mktime (0, 0, 0, $month, $day, $year));
}

function dump($var) {
        global $dumpCounterRND;
        if (defined("DEBUG")) {
                echo "<hr><pre>".(int)$dumpCounterRND++.". ";

                if (is_array($var)) {
                        print_r($var);
                } else {
                        var_dump($var);
                }

                echo "</pre><hr>";
        }
}

function directoryList ($startDir = "./") {
        $d = dir($startDir);
        while (false !== ($entry = $d->read())) {
                $arr[$entry] = $entry;
        }
        $d->close();
        return $arr;
}

function fileinfo($filename) {
        $fileNameArr = explode(".", $filename);
        $fileNameArr[ext] = $fileNameArr[(count($fileNameArr) - 1)];
        $fileNameArr[name] = $fileNameArr[0];
        return $fileNameArr;
}

function getOriginalFileName ($dir, $ext, $prefix = "", $suffix = "") {
        do {
                $filename = $prefix.mt_rand(1, mt_getrandmax()).$suffix.".".$ext;
        } while (file_exists($dir.$filename));
        return $filename;
}

function handleFileUpload ($files, $fieldName, $imageDir) {
                if (is_uploaded_file($files[$fieldName][tmp_name])) {
                        $fileInfoArr = fileinfo($files[$fieldName][name]);
                        $originalFileName = getOriginalFileName($imageDir, $fileInfoArr[ext]);
                        move_uploaded_file($files[$fieldName][tmp_name], $imageDir.$originalFileName);
                }
                return $originalFileName;
}

function uploadedFilesNumber($arr) {
        $number = 0;
        if (is_array($arr)) {
                foreach ($arr as $key => $val) {
                        if (empty($val[error])) {
                                $number++;
                        }
                }
        }
        return $number;
}

function now() {
        return date("Y-m-d H:i:s");
}

if (!function_exists('array_intersect_assoc')) {
        function array_intersect_assoc ($arr1, $arr2) {
                foreach ($arr1 as $key => $val) {
                        if (!in_array($key, array_keys($arr2)) || ($val != $arr2[$key])) {
                                unset($arr1[$key]);
                        }
                }
                return $arr1;
        }
}

function  pagination($count, $_PER_PAGE=_CLASSIFIED_PER_PAGE) {
        $pages = Ceil( $count / $_PER_PAGE ) ;
        for ($i = 0; $i<$pages; $i++) {
                $arr [$i] = $i;
        }

        return $arr;
}

function generateNameImg ($image) {
        $mass[] = "q";
        $mass[] = "w";
        $mass[] = "e";
        $mass[] = "r";
        $mass[] = "t";
        $mass[] = "y";
        $mass[] = "u";
        $mass[] = "i";
        $mass[] = "o";
        $mass[] = "p";
        $mass[] = "a";
        $mass[] = "s";
        $mass[] = "d";
        $mass[] = "f";
        $mass[] = "g";
        $mass[] = "h";
        $mass[] = "j";
        $mass[] = "k";
        $mass[] = "l";
        $mass[] = "z";
        $mass[] = "x";
        $mass[] = "c";
        $mass[] = "v";
        $mass[] = "b";
        $mass[] = "n";
        $mass[] = "1";
        $mass[] = "2";
        $mass[] = "3";
        $mass[] = "4";
        $mass[] = "5";
        $mass[] = "6";
        $mass[] = "7";
        $mass[] = "8";
        $mass[] = "9";
        $mass[] = "0";

        $num = count($mass);
        $str = "";

        for ($i = 0; $i < 7; $i++) {
                $str .= $mass[rand(0, $num)];
        }

        return $str . strrchr($image, '.');
}

// Form sanitation
$db_post = $_POST;
$db_post = array_map('mysql_real_escape_string', $db_post);
$em_post = $_POST;
$em_post = array_map('stripslashes', $em_post);
$em_post = array_map('striptags', $em_post);

// End sanitation


function formatPhone($phone = '', $convert = false, $trim = true)
    {
    // If we have not entered a phone number just return empty
    if (empty($phone)) {
    return '';
    }
     
    // Strip out any extra characters that we do not need only keep letters and numbers
    $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
     
    // Do we want to convert phone numbers with letters to their number equivalent?
    // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
    if ($convert == true) {
    $replace = array('2'=>array('a','b','c'),
    '3'=>array('d','e','f'),
    '4'=>array('g','h','i'),
    '5'=>array('j','k','l'),
    '6'=>array('m','n','o'),
    '7'=>array('p','q','r','s'),
    '8'=>array('t','u','v'), '9'=>array('w','x','y','z'));
     
    // Replace each letter with a number
    // Notice this is case insensitive with the str_ireplace instead of str_replace
    foreach($replace as $digit=>$letters) {
    $phone = str_ireplace($letters, $digit, $phone);
    }
    }
     
    // If we have a number longer than 11 digits cut the string down to only 11
    // This is also only ran if we want to limit only to 11 characters
    if ($trim == true && strlen($phone)>11) {
    $phone = substr($phone, 0, 11);
    }
     
    // Perform phone number formatting here
    if (strlen($phone) == 7) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
    } elseif (strlen($phone) == 10) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
    } elseif (strlen($phone) == 11) {
    return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
    }
     
    // Return original phone if not 7, 10 or 11 digits long
    return $phone;
}

?>