<?php
	function GetCaseOf($customer_id)
    {   
        $sql = "SELECT * FROM customer WHERE customer_id = ".$customer_id;
        
        $tmprs = mysql_query($sql);
        $tmprow = mysql_fetch_array($tmprs);
        
        $customer_type = $tmprow["customer_type"];
        
        switch ($customer_type)
		{
			case "Particulier"	: $case_of = $tmprow["customer_lastname"]." ".$tmprow["customer_firstname"] ; break;
			case "Société"		: $case_of = $tmprow["customer_company"]; break;
			case "Gouvernement"	: $case_of = $tmprow["customer_company"]; break;
		}
		        
        return $case_of;
    }
	
    function GetCaseReference($case_type, $case_id, $customer_id)
    {   
        $sql = "SELECT customer_type FROM customer WHERE customer_id = ".$customer_id;
        
        $tmprs = mysql_query($sql);
        $tmprow = mysql_fetch_array($tmprs);
        
        $customer_type = $tmprow["customer_type"];
        
        switch ($customer_type)
		{
			case "Particulier"	: $customer_type_initial = "P"; break;
			case "Société"		: $customer_type_initial = "S"; break;
			case "Gouvernement"	: $customer_type_initial = "G"; break;
		}
		
        $case_reference = substr($case_type,0,1).$customer_type_initial.date("m").$case_id;            
        
        return $case_reference;
    }
    
    function fatal_error($sErrorMessage = '')
    {
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
        die($sErrorMessage);
    }
    
    function validateUpload($fieldname, $arr_allowedext)
    { // Allowed ext in pipe format
        $validupload = true;

        $f_name 	= $_FILES[$fieldname]["name"];
        $f_tmp_name = $_FILES[$fieldname]["tmp_name"];
        $f_type 	= $_FILES[$fieldname]["type"];
        $f_size 	= $_FILES[$fieldname]["size"];
        $f_error 	= $_FILES[$fieldname]["error"];

        if ($f_size > 0)
        {
            if (array_search($f_type, $arr_allowedext) === false)
            {
                //$errors[] = "Invalid Image Format.  Valid format are .png";
                $validupload = false;
            }
        }

        return $validupload;
    }

    function set_value($field = '', $default = '')
    {
        if (!isset($_POST[$field]))
        {
            return $default;
        }

        return $_POST[$field];
    }

    function PrintValidateErrors($errors)
    {
        if (!empty($errors))
        {
            echo "<div class='validation-error'>Veuillez corriger les erreurs suivantes:\n";
            echo "<ul>";

            foreach ($errors as $error)
            {
                echo "<li>$error</li>\n";
            }
            
            echo "</ul></div>";
        }
    }    
    
    function getrecentlyinsertedid($tablename, $idfldname, $sessionid = false)
    {
        global $PHPSESSID;

        if ($sessionid == true)
        {
            $sql = "select max($idfldname) as mymax 
                from $tablename";
        }
        else
        {
            $sql = "select max($idfldname) as mymax from $tablename";
        }

        if (!$rs = mysql_query($sql))
        {
            queryerror($sql);
            exit;
        }

        $row = mysql_fetch_array($rs);
        $mymax = $row["mymax"];

        mysql_free_result($rs);
        return $mymax;
    }
    
	function makeconnection()
    {
        $link = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
        if (!$link)
        {
            die('Error while connecting to MySQL : ' . mysql_error());
        }

        $db = mysql_select_db(DB_LOCALDB, $link);
        if (!$db)
        {
            die('Can\'t Open Database : ' . mysql_error());
        }
    }

    function queryerror($sql, $exit = 1)
    {
        echo "<p>Error occured while executing query => " . $sql . "</p>";

        if ($exit == 1)
        {
            exit;
        }
    }

    function p($arr, $exit = 1)
    {
        echo "<pre>";
        print_r($arr);
        echo "</pre>";

        if ($exit == 1)
        {
            exit;
        }
    }

    function loggedin()
    {         
        if (isset($_COOKIE['username']))        return TRUE;
        else									return FALSE;
    }
	
	//Function to redirect browser
    function redirect($url)
    {
        if (!headers_sent())
        {
            session_write_close();
            session_start();			
            header('Location: ' . $url);
            exit;
        }
        else
        {
            echo '<script type="text/javascript">';
            echo 'window.location.href="' . $url . '";';
            echo '</script>';
            echo '<noscript>';
            echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
            echo '</noscript>';
        }
    }

    function createdropdown_array($dropdownname, $arr, $selid, $first_option_blank = true, $blank = "", $classname = "")
    {
        $dropdown = "";
        
        if ($classname == "")
        {
            $classname_str = "";
        }
        else
        {
            $classname_str = "class='$classname'";
        }
        
        $dropdown = "<select name='$dropdownname' id='$dropdownname' $classname_str>\n";

        if ($first_option_blank == true)
        {
            $dropdown .= "<option value=''>$blank</option>\n";
        }
        
        foreach ($arr as $key => $val)
        {
            if ($key == $selid)
            {
                $sel = "selected = 'selected' ";
            }
            else
            {
                $sel = "";
            }
            
            $dropdown .=  "<option value='$key' $sel>$val</option>\n";
        }

        $dropdown .=  "</select>";
        
        echo $dropdown;
    }

    function createdropdown($dropdownname, $sql, $idfldname, $fldname, $selid, $blank = "", $classname = "", $first_option_blank = true, $extra = array())
    {
//        echo $sql;exit;
        $rs = mysql_query($sql);

        if ($classname == "")
            $classname_str = "";
        else
            $classname_str = "class='$classname'";

        if (!empty($extra))
        {
            $extras = implode(" ", $extra);
        }


        echo "<select name='$dropdownname' id='$dropdownname' $classname_str $extras>\n";

        //if(isset($blank))
        if ($first_option_blank == true)
            echo "<option value=''>$blank</option>\n";

        while ($row = mysql_fetch_array($rs))
        {
            if ($row[$idfldname] == $selid)
                $sel = "selected";
            else
                $sel = "";

            echo "<option value='$row[$idfldname]' $sel>$row[$fldname]</option>\n";
        }

        echo "</select>";
    }

    function db_makequery($table, $data, $action = 'insert', $parameters = '')
    {
        reset($data);

        if ($action == 'insert')
        {
            $query = 'INSERT INTO ' . $table . ' (';
            while (list($columns, ) = each($data))
            {
                $query .= $columns . ', ';
            }

            $query = substr($query, 0, -2) . ') VALUES (';

            reset($data);
            while (list($columns, $value) = each($data))
            {
                switch ((string) $value)
                {
                    case 'now()': $query .= 'now(), '; break;
                    case NULL   : $query .= 'NULL, '; break; 
                    default		: $query .= '\'' . trim($value) . '\', '; break;
                }								
            }
            $query = substr($query, 0, -2). ')';
        }
        elseif ($action == 'update')
        {
            $query = 'UPDATE ' . $table . ' SET ';
            while (list($columns, $value) = each($data))
            {
                switch ((string) $value)
                {
                    case 'now()': $query .= $columns . ' = now(), '; break;
                    case NULL   : $query .= $columns .= ' = NULL, '; break; 
                    default		: $query .= $columns . ' = \'' . trim($value) . '\', '; break;
                }
            }
            $query = substr($query, 0, -2) . ' WHERE ' . $parameters;
        }

        return $query;
    }
	
	function isduplicate($tablename, $arr, $arr_extra = array())
    {
        $tmparr = array();
        foreach ($arr as $key => $value)
        {
            $tmparr[] = $key . " = '" . $value . "'";
        }

        $condition = implode(" and ", $tmparr);

        if (count($arr_extra) > 0)		//arr_extra is for duplicate row when update a record (it inculde the ID in general)  
        {
            $tmparr = array();
            foreach ($arr_extra as $key => $value)
            {
                $tmparr[] = $key . " <> '" . $value . "'";
            }
            $extra_condition = " and (" . implode(" and ", $tmparr) . ")";
        }

        $sql = "SELECT $key FROM $tablename WHERE $condition $extra_condition";
        if (!$rs = mysql_query($sql))
        {
            queryerror($sql);
            exit;
        }

        if (mysql_num_rows($rs) == 0)			$isduplicate = false;
        else									$isduplicate = true;

        mysql_free_result($rs);
        return $isduplicate;
    }

    function createlocalvars()
    {
        foreach ($_POST as $varname => $varval)
        {
            global $$varname;
            $$varname = stripslashes($varval);
            //~ echo "$$varname=$varval<br>";
        }
    }
    