<?php
class General extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
	
    
    function getimagename($imagename)
    {
        return reset(explode(".",$imagename));        
    }
    
    function naming($imagename,$ext,$table,$field)
    {
        $imagefullname = $imagename.".".$ext;
        $imagerecord = $this->general->getRecordWhere($table,array($field => $imagefullname),$field,"asc");                    
                        
        if(count($imagerecord) > 0)
        {
            $imagelastname =  $imagerecord->$field;
            $i = 1;
            while(count($imagerecord) > 0)
            {                       
                $imagelastname = $imagename."-".$i.".".$ext;  
                $imagerecord = $this->general->getRecordWhere($table,array($field => $imagelastname),$field,"asc");
                if(count($imagerecord) > 0)
                {
                    $i++;
                }
                else
                {return $imagename."-".$i.".".$ext;}
            }
        }
        else        
        {return $imagefullname;}
    }
    
       
            
    function imagenaming($imagename,$ext,$table,$arrayfield,$field,$id,$primarykey)
    {
        $imagefullname = $imagename.".".$ext;
        $result = $this->general->get_where_array($imagefullname,$arrayfield);                
        $imagerecord = $this->general->getAllRecordsWhereOr($table,$result,"$primarykey","asc");                    
                        
        if(count($imagerecord) > 0)
        {
            $i = 1;
            while(count($imagerecord) > 0)
            {                       
                $imagelastname = $imagename."-".$i.".".$ext;  
                $result = $this->general->get_where_array($imagelastname,$arrayfield);                
                $imagerecord = $this->general->getAllRecordsWhereOr($table,$result,"$primarykey","asc");
                if(count($imagerecord) > 0)
                {
                    $i++;
                }
                else
                {
                    $updateData = array(
                        "id" => $id,
                        $field => $imagename."-".$i.".".$ext
                    );
                    $this->general->updateRecord($table, $updateData, "$primarykey");
                    return $imagename."-".$i.".".$ext;                    
                }
            }
        }
        else        
        {
         $updateData = array(
                        "$primarykey" => $id,
                        $field => $imagefullname
                    );
       $this->general->updateRecord($table, $updateData, "$primarykey");
        return $imagefullname;        
        }
    }
    
    
    function get_where_array($imagefullname,$arrayfield)
    {
        $result = "";
        $wherearray = array();
        foreach($arrayfield as $row)
        {
            $result =$row." = '".$imagefullname."'";
            array_push($wherearray, $result);
        }
        return$wherearray;
    }
    
    function getAllRecordsWhereOr($tblname, $where=array(), $orderby=false, $order=false, $limit=false, $limitStart = 0){       
            $i=0;       
            foreach($where as $row)
            {
                if($i == 0)
                {
                    $this->db->where($row);
                }
                else
                {
                    $this->db->or_where($row);
                }            
                    $i++;                            
            }
            if($orderby)
            { $this->db->order_by($orderby, $order);}
            if($limit)	
            {$this->db->limit($limit, $limitStart);}

            $query = $this->db->get($tblname);
            return $query->result();
       }
       
       
       
    
    function getarabicmonth($your_date)
    {
            $months = array(
                "Jan" => "يناير",
                "Feb" => "فبراير",
                "Mar" => "مارس",
                "Apr" => "أبريل",
                "May" => "مايو",
                "Jun" => "يونيو",
                "Jul" => "يوليو",
                "Aug" => "أغسطس",
                "Sep" => "سبتمبر",
                "Oct" => "أكتوبر",
                "Nov" => "نوفمبر",
                "Dec" => "ديسمبر"
            );
            
            $en_month = date("M", strtotime($your_date));
            $ar_month = $months[$en_month];
            return $ar_month;                                 
    }
    
    
    function GEN_SLUG($str, $replace=array(), $delimiter='-') 
        {
			$str=trim($str);                        
			if( !empty($replace) )
			{
				 $str = str_replace((array)$replace, ' ', $str);
			}
			$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
			$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
			$clean = strtolower(trim($clean, '-'));
			$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
			return $clean;
	}
        
        
	//Function to get record count
	function getCount($tablename, $where=false){
		if($where)
			$query = $this->db->get_where($tablename, $where);
		else
			$query = $this->db->get($tablename);
		
		return $query->num_rows();
	}
                
        
        function getCountWhereINWhere($tablename, $where=false,$field = "",$values = array()){
            if($where)
                $this->db->where($where);
            if($field != "")
                $this->db->where_in($field,$values);	
                
            $query = $this->db->get($tablename);

            return $query->num_rows();                		
	}
        
        function getCountWhereINWhere2($where=false,$field = "",$values = array(),$allfillchoices = array()){                                    
            $this->db->select(PRODUCTS.'.*');       
            
            $this->db->from(PRODUCTS);  
            
            
            $this->db->join(PRODUCTSJOIN, PRODUCTSJOIN.'.ProductID = '.PRODUCTS.'.ProductID');
            $this->db->join(CHOICES, CHOICES.'.Choice = '.PRODUCTSJOIN.'.Value');
            $this->db->join(CATEGORIES, CATEGORIES.'.CategoryID = '.PRODUCTS.'.CategoryID');                        
            $this->db->join(FIELDSGROUPS, FIELDSGROUPS.'.FieldCatID = '.CATEGORIES.'.FGID');
            $this->db->join(FIELDSJOIN, FIELDSJOIN.'.CID = '.FIELDSGROUPS.'.FieldCatID');             
            $this->db->join(FIELDS, FIELDS.'.FieldID = '.FIELDSJOIN.'.FID');                
            //$this->db->join(CHOICESJOIN, CHOICESJOIN.'.FID = '.FIELDS.'.FieldID');            
            //$this->db->join(CHOICES, CHOICES.'.ChoiceID = '.CHOICESJOIN.'.CHID');
                                    
            $this->db->where(FIELDS.'.FieldType' ,'1');
            //$this->db->where(PRODUCTSJOIN.'.Value' ,'8GB');
            
            if($where)
            {                
                $where[PRODUCTS.".CategoryID"] = $where["CategoryID"];
                unset($where["CategoryID"]);
                $this->db->where($where);
            }
            if($field != "")
                $this->db->where_in($field,$values);	
                                    
            $queryfilgroup = "";
            $start = "";
            foreach($allfillchoices as $row)
            {
                $resultexp = explode("_",$row);                                
                //$this->db->where(PRODUCTSJOIN.'.FieldID' ,$resultexp[0]);
                //$this->db->or_where(CHOICES.'.ChoiceID' ,$resultexp[1]);
               // print_r($resultexp[0] ." _ ".$resultexp[1]);
                if($queryfilgroup == "")$start=" (";else $start=" or ";
                $queryfilgroup .= $start."(".PRODUCTSJOIN.'.FieldID'." = ".$resultexp[0]." and ".CHOICES.'.ChoiceID' ." = ".$resultexp[1].")";                
            }
            $queryfilgroup.= ")";
            $this->db->where($queryfilgroup);
            
            
            $this->db->group_by(PRODUCTSJOIN.'.ProductID'); 
            
            $query = $this->db->get();
            return $query->num_rows();                           
	}
        
	
        function getMaxWhere($tablename,$field, $where=false)
        {
            $this->db->select_max($field);
            if($where)
                $query = $this->db->get_where($tablename, $where);
            else
                $query = $this->db->get($tablename);

            return $query->row();
        }
        
        function getMinWhere($tablename,$field, $where=false)
        {
            $this->db->select_min($field);
            if($where)
                $query = $this->db->get_where($tablename, $where);
            else
                $query = $this->db->get($tablename);

            return $query->row();
        }
        
	function getPriceRages($tablename,$field, $where=false)
        {
            $this->db->select($field);
            if($where)
                $query = $this->db->get_where($tablename, $where);
            else
                $query = $this->db->get($tablename);

            $result = $query->result();
                                    
            $resultset = array();
            foreach($result as  $v)
            {
                $resultset[]=$v->UnitPrice;            
            }                      
            return $this->createRange($resultset);
        }
        
        
         private function createRange($array){
            sort($array);

            //Setting range limits.
            //Check if array has 5 digit number.
            $countDigitedNumbers = preg_grep('/\d{5}/',$array);
           
            
            if(count($countDigitedNumbers) > 0){
                $rangeLimits = array(0,1000,2500,5000,10000,15000,25000);
            }else{
                $rangeLimits = array(0,50,250,500,1000,2000,9999);
            }
            $ranges = array();

            for($i = 0; $i < count($rangeLimits) && $rangeLimits[$i] <= max($array) ; $i++){
                if($i == count($rangeLimits)-1){
                    break;
                }
                $lowLimit = $rangeLimits[$i];
                $highLimit = $rangeLimits[$i+1];

                $ranges[$i]['ranges']['min'] = $lowLimit+1;
                $ranges[$i]['ranges']['max'] = $highLimit;

                foreach($array as $perPrice){
                    if($perPrice >= $lowLimit && $perPrice < $highLimit){
                        $ranges[$i]['values'][] = $perPrice;
                    }
                }
            }
            return $ranges;
        }
        
	//Function to insert a record
	function insertRecord($tablename, $data){
		if($this->db->insert($tablename, $data)){
			return true;
		}else{
			return false;
		}
	}
	
	//Function to update a record
	function updateRecord($tablename, $data, $where){		
		$this->db->where($where, $data[$where]);
		if($this->db->update($tablename, $data)){
			return true;
		}else{
			return false;
		}
	}
	
	//Function to delete a record
	function deleteRecord($tablename, $whereArray){
		$this->db->where($whereArray);
		if($this->db->delete($tablename)){
			return true;
		}else{
			return false;
		}
	}
	
	//Function to get result set from database
	function getAllRecords($tblname, $orderby=false, $order=false, $limit=false, $limitStart = 0){

		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
			
		$query = $this->db->get($tblname);
		
		return $query->result();
	}
	
	//Function to get result set from database with Where Clause
	function getAllRecordsWhere($tblname, $where=false, $orderby=false, $order=false, $limit=false, $limitStart = 0){

		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
			
		$query = $this->db->get_where($tblname,$where);
		
		return $query->result();
	}
        
        //Function to get result set from database with Where Clause
	function getAllRecordsWhereIN($tblname,$field ,$values, $orderby=false, $order=false, $limit=false, $limitStart = 0){

		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
                		                
                $this->db->where_in($field,$values);		                
                $query = $this->db->get($tblname);
                
		return $query->result();
	}
        
        function getAllRecordsWhereINWhere($tblname,$field = "" ,$values,$where = false, $orderby=false, $order=false, $limit=false, $limitStart = 0){
		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
                		                
                if($where)
                $this->db->where($where);
                
                if($field != "")
                $this->db->where_in($field,$values);	
                
                $query = $this->db->get($tblname);
                
		return $query->result();
	}
	
        
        function getAllRecordsWhereINWhere2($field = "" ,$values,$where = false, $orderby=false, $order=false, $limit=false, $limitStart = 0,$allfillchoices= array()){	
            
            $this->db->select(PRODUCTS.'.*');                            
            $this->db->from(PRODUCTS);   
            
            
            $this->db->join(PRODUCTSJOIN, PRODUCTSJOIN.'.ProductID = '.PRODUCTS.'.ProductID');
            $this->db->join(CHOICES, CHOICES.'.Choice = '.PRODUCTSJOIN.'.Value');
            $this->db->join(CATEGORIES, CATEGORIES.'.CategoryID = '.PRODUCTS.'.CategoryID');                        
            $this->db->join(FIELDSGROUPS, FIELDSGROUPS.'.FieldCatID = '.CATEGORIES.'.FGID');
            $this->db->join(FIELDSJOIN, FIELDSJOIN.'.CID = '.FIELDSGROUPS.'.FieldCatID');             
            $this->db->join(FIELDS, FIELDS.'.FieldID = '.FIELDSJOIN.'.FID');                
            //$this->db->join(CHOICESJOIN, CHOICESJOIN.'.FID = '.FIELDS.'.FieldID');            
            //$this->db->join(CHOICES, CHOICES.'.ChoiceID = '.CHOICESJOIN.'.CHID');
                                    
            $this->db->where(FIELDS.'.FieldType' ,'1');                       
            
            //$this->db->where(PRODUCTSJOIN.'.Value' ,'8GB');
            
            if($where)
            {
                $where[PRODUCTS.".CategoryID"] = $where["CategoryID"];
                unset($where["CategoryID"]);
                $this->db->where($where);
            }
            if($field != "")
                $this->db->where_in($field,$values);	
                                    
            
            $queryfilgroup = "";
            $start = "";
            foreach($allfillchoices as $row)
            {
                $resultexp = explode("_",$row);                                
                //$this->db->where(PRODUCTSJOIN.'.FieldID' ,$resultexp[0]);
                //$this->db->or_where(CHOICES.'.ChoiceID' ,$resultexp[1]);
               // print_r($resultexp[0] ." _ ".$resultexp[1]);
                if($queryfilgroup == "")$start=" (";else $start=" or ";
                $queryfilgroup .= $start."(".PRODUCTSJOIN.'.FieldID'." = ".$resultexp[0]." and ".CHOICES.'.ChoiceID' ." = ".$resultexp[1].")";                
            }
            $queryfilgroup.= ")";
            $this->db->where($queryfilgroup);
            
            if($orderby)
                    $this->db->order_by($orderby, $order);
            if($limit)	
                    $this->db->limit($limit, $limitStart);
              
            $this->db->group_by(PRODUCTSJOIN.'.ProductID'); 
            
            $query = $this->db->get();
            return $query->result();                        
	}
        
        
	//Function to get a single row
	function getRecordWhere($tblname, $where=false, $orderby=false, $order=false, $limit=false, $limitStart = 0){

		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
			
		$query = $this->db->get_where($tblname,$where);
		
		return $query->row();
	}
	
	//Function to get a single row
	function getArrayRecordWhere($tblname, $where=false, $orderby=false, $order=false, $limit=false, $limitStart = 0){

		if($orderby)
			$this->db->order_by($orderby, $order);
		if($limit)	
			$this->db->limit($limit, $limitStart);
			
		$query = $this->db->get_where($tblname,$where);
		
		return $query->row_array();
	}
        
        
        function get_query_result($query)
        {
            $queryres = $this->db->query($query);
            return $queryres->result();
        }
		
	//Function to get User Permissions
	function getPermissions($module, $type, $uid)
	{
		if(!$uid)
			return false;
		
		$this->db->select($module."_".$type." as opt");
		$this->db->where('userid', $uid);
		$query	 = $this->db->get("user_rights");
		$row 	 = $query->row();
		
		return $row->opt;
	}
	
	//Function to adjust date
	function adjustDate($month, $year)
	{
		$date = array();

		$date['month']	= $month;
		$date['year']	= $year;

		while ($date['month'] > 12)
		{
			$date['month'] -= 12;
			$date['year']++;
		}

		while ($date['month'] <= 0)
		{
			$date['month'] += 12;
			$date['year']--;
		}

		if (strlen($date['month']) == 1)
		{
			$date['month'] = '0'.$date['month'];
		}

		return $date;
	}
	
	//Function to generate user frienldy slugs for urls.
//	function createSlug($str, $table = "")
//	{
//		$str = strtolower($this->trimData($str));
//		if($table){
//			if($this->getCount($table, array("slug"=>$str))){
//				return $str."-1";
//			}else{
//				return $str;
//			}
//		}
//		return $str;
//	}

	function trimData($str){
		
		$str = trim($str);
		$str = str_replace(" ","-",$str);
		$str = str_replace(".","-",$str);
		$str = str_replace("'","",$str);
		$str = str_replace("&","-n-",$str);
		$str = str_replace("/","",$str);
		$str = str_replace("\\","",$str);
		$str = str_replace("(","",$str);
		$str = str_replace(")","",$str);
		
		return $str;
	}
		
	function generateMessage($msg, $type){

		$str = "";
		$str .= '<div id="message-'.$type.'">';
		$str .= '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
		$str .= '<tr>';
		$str .= '<td class="'.$type.'-left">'.$msg.'</td>';
		$str .= '<td class="'.$type.'-right"><a class="close-'.$type.'"><img src="'.base_url().'images/admin/table/icon_close_'.$type.'.gif" alt="" /></a></td>';
		$str .= '</tr>';
		$str .= '</table>';
		$str .= '</div>';
		
		return $str;
		
	}
	
	function getModeratorsPermissions($id){
		if(!$id)
			return false;
		
		return $this->getRecordWhere(MODERATORSPERM, array("moderator_id"=>$id));
		
	}
	
	function uploadFile($docName, $docOrgName, $docTmp, $docPath){
		
		// grab the path to the temporary file (image) that the user uploaded
		$file = $docTmp;
		
		// check if it exists
		if(is_uploaded_file($file)){
			//the real image file name
			move_uploaded_file($docTmp, $docPath.$docName);
		}
	}
	
//	function uploadImageWithThumb($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight, $thumbWidth, $thumbHeight){
//		
//		if($imageOrgName){
//			
//			// grab the path to the temporary file (image) that the user uploaded
//			$photo = $imageTmp;
//			
//			// check if it exists
//			if(is_uploaded_file($photo)){
//			
//				//the real image file name
//				$real_name = strtolower($imageOrgName);
//				// image type based on image file name extension:
//				if(strstr($real_name,".png")){
//					$image_type = "png";
//				}else if(strstr($real_name,".jpg")){
//					$image_type = "jpg";
//				}else if(strstr($real_name,".gif")){
//					$image_type = "gif";
//                                }else{
//					die("Unsupported image type");
//				}
//				
//				// find the next image name we are going to save
//				$x=1;
//				//while(true){
//					$it = end(explode(".",$imageName));
//					
//					if( $it=="jpg" || $it=="jpeg" || $it=="png" || $it=="gif"){
//						$image_name = $imagePath.$imageName;
//						$thumb_name = $imagePath."thumb-".$imageName;
//					}else{
//						$image_name = $imagePath.$imageName.".".$image_type;
//						$thumb_name = $imagePath."thumb-".$imageName.".".$image_type;
//					}
//					
//					//if(!is_file($image_name))break;
//					//$x++;
//				//}
//				
//				//	die($image_name);
//				// start processing the main bigger image:
//				$max_width 	= $imageWidth; $max_height = $imageHeight;
//				$size 		= getimagesize($photo);
//				$width 		= $size[0];
//				$height 	= $size[1];
//				$x_ratio 	= $max_width / $width;
//				$y_ratio 	= $max_height / $height;
//				
//				if(($width <= $max_width)&&($height <= $max_height)){
//					$tn_width = $width;
//					$tn_height = $height;
//				}else{
//					if(($x_ratio * $height) < $max_height){
//						$tn_height = ceil($x_ratio * $height);
//						$tn_width = $max_width;
//					}else{
//						$tn_width = ceil($y_ratio * $width);
//						$tn_height = $max_height;
//					}
//				}
//				
//				switch($image_type){
//					case "png": $src=imagecreatefrompng($photo); break;
//					case "jpg": $src=imagecreatefromjpeg($photo); break;
//					case "gif": $src=imagecreatefromgif($photo); break;
//				}
//				
//				
//				// destination resized image:
//				$dst = imagecreatetruecolor($tn_width, $tn_height);
//                                
//                                
//                                if($image_type == "png")
//                                {    
//                                    imagealphablending($dst, false);
//                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
//                                    imagefill($dst, 0, 0, $colorTransparent);
//                                    imagesavealpha($dst, true);
//                                }
//                                
//				// resize original image onto $dst
//				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
//				// write the final jpeg image..
//                                
//                               if($image_type == "png")                                 
//                                     imagepng($dst, $image_name);                                
//                               else
//                                 imagejpeg($dst, $image_name) or die("Error: your photo	has not been saved. Please contact the administrator");  
//				
//				// time to clean up
//				imagedestroy($src);
//				imagedestroy($dst);
//				
//				
//				// and now we do it alll again for the thumbnail:
//				$max_width = $thumbWidth; $max_height = $thumbHeight;
//				$size = GetImageSize($photo);
//				$width = $size[0];
//				$height = $size[1];
//				$x_ratio = $max_width / $width;
//				$y_ratio = $max_height / $height;
//				if(($width <= $max_width)&&($height <= $max_height)){
//					$tn_width = $width;
//					$tn_height = $height;
//				}else{
//					if(($x_ratio * $height) < $max_height){
//						$tn_height = ceil($x_ratio * $height);
//						$tn_width = $max_width;
//					}else{
//						$tn_width = ceil($y_ratio * $width);
//						$tn_height = $max_height;
//					}
//				}
//				
//				switch($image_type){
//					case "png": $src=imagecreatefrompng($photo); break;
//					case "jpg": $src=imagecreatefromjpeg($photo); break;
//					case "gif": $src=imagecreatefromgif($photo); break;
//				}
//				
//				$dst = imagecreatetruecolor($tn_width, $tn_height);
//                                
//                                
//                                if($image_type == "png")
//                                {    
//                                    imagealphablending($dst, false);
//                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
//                                    imagefill($dst, 0, 0, $colorTransparent);
//                                    imagesavealpha($dst, true);
//                                }
//                                
//				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
//				$thumbfile = $thumb_name;
//				if(file_exists($thumbfile))unlink($thumbfile);
//                                
//                                if($image_type == "png")                                 
//                                imagepng($dst, $thumbfile,9);    
//                                else
//				imagejpeg($dst, $thumbfile, 30) or die("Error: your photo thumb has not been saved. Please contact the administrator");
//                                
//                                
//				imagedestroy($src);
//				imagedestroy($dst);
//			}
//		}
//	}
	
	
        function uploadImageWithThumb($imageName,$imageThumbName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight, $thumbWidth, $thumbHeight){
		
		if($imageOrgName){
			
			// grab the path to the temporary file (image) that the user uploaded
			$photo = $imageTmp;
			
			// check if it exists
			if(is_uploaded_file($photo)){
			
				//the real image file name
				$real_name = strtolower($imageOrgName);
				// image type based on image file name extension:
				if(strstr($real_name,".png")){
					$image_type = "png";
				}else if(strstr($real_name,".jpg")){
					$image_type = "jpg";
				}else if(strstr($real_name,".gif")){
					$image_type = "gif";
                                }else if(strstr($real_name,".jpeg")){
					$image_type = "jpeg";
                                }else{
					die("Unsupported image type");
				}
				
				// find the next image name we are going to save
				$x=1;
				//while(true){
					$it = end(explode(".",$imageName));
					//$tname = reset(explode(".",$imageThumbName));
                                        
					if( $it=="jpg" || $it=="jpeg" || $it=="png" || $it=="gif"){
						$image_name = $imagePath.$imageName;		
                                                $thumb_name = $imagePath.$imageThumbName;
//                                                $thumb_name = $imagePath."sm/".$imageThumbName;
					}else{
						$image_name = $imagePath.$imageName.".".$image_type;	
                                                $thumb_name = $imagePath.$imageThumbName.".".$image_type;
//                                                $thumb_name = $imagePath."sm/".$imageThumbName.".".$image_type;
					}
								
                                       			                                        
				// start processing the main bigger image:
				$max_width 	= $imageWidth; 
                                $max_height     = $imageHeight;
				$size 		= getimagesize($photo);
				$width 		= $size[0];
				$height 	= $size[1];
				$x_ratio 	= $max_width / $width;
				$y_ratio 	= $max_height / $height;
				
                                
                                if($height < $max_height && $width < $max_width)    
                                {
                                        $tn_width = $width;
                                        $tn_height = $height;
                                }
                                elseif($height >= $width)
                                {
                                        $percentage = ($max_height / $height);    
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($wround > $max_width)
                                        {
                                            $percentage = ($max_width / $width);    
                                            $wround = $max_width;                                            
                                            $hround = round($height * $percentage);
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
                                else {
                                        $percentage = ($max_width / $width);                                           
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($hround > $max_height)
                                        {
                                            $percentage = ($max_height / $height);    
                                            $wround = round($width * $percentage);
                                            $hround = $max_height;
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
				
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
                                        case "jpeg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				
				
				// destination resized image:
				$dst = imagecreatetruecolor($tn_width, $tn_height);
                                                                
                                if($image_type == "png")
                                {    
                                    imagealphablending($dst, false);
                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                    imagefill($dst, 0, 0, $colorTransparent);
                                    imagesavealpha($dst, true);
                                }
                                
				// resize original image onto $dst
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				// write the final jpeg image..
                                
                               if($image_type == "png")                                 
                                 imagepng($dst, $image_name);                                
                               else
                                 imagejpeg($dst, $image_name) or die("Error: your photo	has not been saved. Please contact the administrator");  
				
				// time to clean up
				imagedestroy($src);
				imagedestroy($dst);
				
				
				// and now we do it alll again for the thumbnail:
				$max_width = $thumbWidth; 
                                $max_height = $thumbHeight;
				$size = GetImageSize($photo);
				$width = $size[0];
				$height = $size[1];
				$x_ratio = $max_width / $width;
				$y_ratio = $max_height / $height;
                                
				if($height < $max_height && $width < $max_width)    
                                {
                                        $tn_width = $width;
                                        $tn_height = $height;
                                }
                                elseif($height >= $width)
                                {
                                        $percentage = ($max_height / $height);    
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($wround > $max_width)
                                        {
                                            $percentage = ($max_width / $width);    
                                            $wround = $max_width;                                            
                                            $hround = round($height * $percentage);
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
                                else {
                                        $percentage = ($max_width / $width);                                           
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($hround > $max_height)
                                        {
                                            $percentage = ($max_height / $height);    
                                            $wround = round($width * $percentage);
                                            $hround = $max_height;
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
				
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
                                        case "jpeg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				
				$dst = imagecreatetruecolor($tn_width, $tn_height);
                                
                                
                                if($image_type == "png")
                                {    
                                    imagealphablending($dst, false);
                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                    imagefill($dst, 0, 0, $colorTransparent);
                                    imagesavealpha($dst, true);
                                }
                                
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				$thumbfile = $thumb_name;
				if(file_exists($thumbfile))unlink($thumbfile);
                                
                                if($image_type == "png")                                 
                                imagepng($dst, $thumbfile);    
                                else
				imagejpeg($dst, $thumbfile) or die("Error: your photo thumb has not been saved. Please contact the administrator");
                                
                                
				imagedestroy($src);
				imagedestroy($dst);
			}
		}
	}







function uploadImageWithoutThumb($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight){
		
		if($imageOrgName){
			
			// grab the path to the temporary file (image) that the user uploaded
			$photo = $imageTmp;
			
			// check if it exists
			if(is_uploaded_file($photo)){
			
				//the real image file name
				$real_name = strtolower($imageOrgName);
				// image type based on image file name extension:
				if(strstr($real_name,".png")){
					$image_type = "png";
				}else if(strstr($real_name,".jpg")){
					$image_type = "jpg";
				}else if(strstr($real_name,".gif")){
					$image_type = "gif";
                                }else if(strstr($real_name,".jpeg")){
					$image_type = "jpeg";
                                }else{
					die("Unsupported image type");
				}
				
				// find the next image name we are going to save
				$x=1;
				//while(true){
					$it = end(explode(".",$imageName));
					$fname = reset(explode(".",$imageName));
                                        
					if( $it=="jpg" || $it=="jpeg" || $it=="png" || $it=="gif"){
						$image_name = $imagePath.$imageName;						
					}else{
						$image_name = $imagePath.$imageName.".".$image_type;						
					}
					
					
				// start processing the main bigger image:
				$max_width 	= $imageWidth; 
                                $max_height     = $imageHeight;
				$size 		= getimagesize($photo);
				$width 		= $size[0];
				$height 	= $size[1];
				$x_ratio 	= $max_width / $width;
				$y_ratio 	= $max_height / $height;
				
                                
                                if($height < $max_height && $width < $max_width)    
                                {
                                        $tn_width = $width;
                                        $tn_height = $height;
                                }
                                elseif($height >= $width)
                                {
                                        $percentage = ($max_height / $height);    
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($wround > $max_width)
                                        {
                                            $percentage = ($max_width / $width);    
                                            $wround = $max_width;                                            
                                            $hround = round($height * $percentage);
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
                                else {
                                        $percentage = ($max_width / $width);                                           
                                        $wround = round($width * $percentage);
                                        $hround = round($height * $percentage);
                                        
                                        if($hround > $max_height)
                                        {
                                            $percentage = ($max_height / $height);    
                                            $wround = round($width * $percentage);
                                            $hround = $max_height;
                                        }
                                        
                                        $tn_width = $wround;
                                        $tn_height = $hround;
                                }
				
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
                                        case "jpeg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				
				
				// destination resized image:
				$dst = imagecreatetruecolor($tn_width, $tn_height);
                                                                
                                if($image_type == "png")
                                {    
                                    imagealphablending($dst, false);
                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                    imagefill($dst, 0, 0, $colorTransparent);
                                    imagesavealpha($dst, true);
                                }
                                
				// resize original image onto $dst
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				// write the final jpeg image..
                                
                               if($image_type == "png")                                 
                                     imagepng($dst, $image_name);                                
                               else
                                 imagejpeg($dst, $image_name) or die("Error: your photo	has not been saved. Please contact the administrator");  
				
				// time to clean up
				imagedestroy($src);
				imagedestroy($dst);												
			}
		}
	}



        function saveImage($tablename,$imagefieldid,$imagefieldslist,$inputName,$oldimagename,$oldthumbimagename,$imagefolder,$slugfield,$updatedfield,$thumbupdatedfield,$imageWidth,$imageHeight,$thumbimageWidth,$thumbimageHeight)
        {
                            $mime = array(
                                            'image/gif' => 'gif',
                                            'image/jpeg' => 'jpg',
                                            'image/png' => 'png'
                                    );
             
                            // =======  delete old images
                            $oldimage = $this->input->post($oldimagename);                                                                                                   
                            $oldthumbimage = $this->input->post($oldthumbimagename);                                                                                                   
                            if(@file_exists("images/$imagefolder/$oldimage")){
                                                                    @unlink("images/$imagefolder/$oldimage");                                                                    
                                                                    @unlink("images/$imagefolder/$oldthumbimage");                                                                    
                                                            };                                                                                        
                            // ===============  create new images                                
                            $imageType = $_FILES[$inputName]['type'];
                            $ext       = $mime[$imageType];        
                            $slug = $this->general->gen_string2($this->general->GEN_SLUG($this->input->post($slugfield)),28);                            
                            $imageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$updatedfield,$imagefieldid);                                                          
                            $thumbimageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$thumbupdatedfield,$imagefieldid);    
                                                        
                            $imageOrgName = $_FILES[$inputName]['name'];                            
                            $imageTmp  = $_FILES[$inputName]['tmp_name'];
                            $imagePath = "images/$imagefolder/";
                                                                                  
                            $this->general->uploadImageWithThumb($imageName,$thumbimageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight,$thumbimageWidth,$thumbimageHeight);                            
                            $updateData[$updatedfield] = $imageName;                                                        
                            $updateData[$thumbupdatedfield] = $thumbimageName;
                            return $updateData;                        
        }
        
        
        function saveImageWithThumb($tablename,$imagefieldid,$imagefieldslist,$inputName,$oldimagename,$imagefolder,$slugfield,$updatedfield,$imageWidth,$imageHeight,$thumbimageWidth,$thumbimageHeight,$slugforce=true,$image_fixed_name="",$primarykeyid="id")
        {
                            $mime = array(
                                            'image/gif' => 'gif',
                                            'image/jpeg' => 'jpg',
                                            'image/png' => 'png'                               
                                    );    
                                                       
                            // =======  delete old images
                            $oldimage = $this->input->post($oldimagename);                               
                            if(@file_exists("images/$imagefolder/$oldimage")){
                                @unlink("images/$imagefolder/$oldimage");                                                                    
                                @unlink("images/$imagefolder/".$this->general->returnThumb($oldimage));                                                                    
                            };                         
                             
                            // ===============  create new images                                
                            $imageType = $_FILES[$inputName]['type'];
                            $ext       = $mime[$imageType];        
                            
                                                       
                            if($slugforce)
                            {
                              $slug = $this->general->gen_string3($this->general->GEN_SLUG($this->input->post($slugfield)),30);                                                                                      
                             $imageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$updatedfield,$imagefieldid,$primarykeyid);                                                                                        
                            }
                            else
                            {
                            $old_image_re = $this->general->getRecordWhere($tablename,array("$primarykeyid" => $imagefieldid),"$primarykeyid","desc");
                            $imagfield = $old_image_re->$updatedfield;
                            
                            
                            if($imagfield == "")
                            {
                                if($image_fixed_name != "")
                                {
                                    $imageName = $image_fixed_name;
                                }
                                else
                                {
                                $slug = $this->general->gen_string3($this->general->GEN_SLUG($this->input->post($slugfield)),28);                            
                                $imageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$updatedfield,$imagefieldid,$primarykeyid);                                                                                      
                                }
                            }
                            else {
                                $imageName = $imagfield;                                
                            }
                            }
                                                        
                            $thumbimageName = $this->general->returnThumb($imageName);    
                                                        
                            $imageOrgName = $_FILES[$inputName]['name'];                            
                            $imageTmp  = $_FILES[$inputName]['tmp_name'];
                            $imagePath = "images/$imagefolder/";
                                                                                  
                            $this->general->uploadImageWithThumb($imageName,$thumbimageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight,$thumbimageWidth,$thumbimageHeight);                                                                                    
                            return $imageName;                        
        }
        
        
        
        function saveImageWithoutThumb($tablename,$imagefieldid,$imagefieldslist,$inputName,$oldimagename,$imagefolder,$slugfield,$updatedfield,$imageWidth,$imageHeight,$slugforce=true,$image_fixed_name="")
        {
            $mime = array(
                                            'image/gif' => 'gif',
                                            'image/jpeg' => 'jpg',
                                            'image/png' => 'png'
                                    );
             if(isset($_FILES[$inputName]) &&  $_FILES[$inputName]['name'] != ""){                                                          
                            // =======  delete old images
                            $oldimage = $this->input->post($oldimagename);                                                                                                                               
                            if(@file_exists("images/$imagefolder/$oldimage")){
                                                                    @unlink("images/$imagefolder/$oldimage");                                                                                                                                        
                                                            };        
                                                            
                            // ===============  create new images                                
                            $imageType = $_FILES[$inputName]['type'];
                            $ext       = $mime[$imageType];  
                            
                            if($slugforce)
                            {
                              $slug = $this->general->gen_string3($this->general->GEN_SLUG($this->input->post($slugfield)),30);                                                                                      
                             $imageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$updatedfield,$imagefieldid);                                                                                        
                            }
                            else
                            {
                            $old_image_re = $this->general->getRecordWhere($tablename,array("id" => $imagefieldid),"id","desc");
                            $imagfield = $old_image_re->$updatedfield;
                                          
                            if($imagfield == "")
                            {
                                if($image_fixed_name != "")
                                {
                                    $imageName = $image_fixed_name;
                                }
                                else
                                {                                                                    
                                    $slug = $this->general->gen_string3($this->general->GEN_SLUG($this->input->post($slugfield)),30);                                                                                      
                                    $imageName	= $this->general->imagenaming($slug,$ext,$tablename,$imagefieldslist,$updatedfield,$imagefieldid);                                                                                      
                                }
                            }
                            else {
                                $imageName = $imagfield;                                
                            }
                            }
                            
                                                                                                                                                                                                     
                            $imageOrgName = $_FILES[$inputName]['name'];                            
                            $imageTmp  = $_FILES[$inputName]['tmp_name'];
                            $imagePath = "images/$imagefolder/";
                                                                       
                            $this->general->uploadImageWithoutThumb($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight);                                                        
                            return $imageName;
                        }
        }
        
        
        function returnThumb($image)
        {
            $iname = reset(explode(".",$image));
            $iext = end(explode(".",$image)); 
            return $iname."-sm.".$iext;
        }
        
        


        
        function uploadImageWithThumb2($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight, $thumbWidth, $thumbHeight){		
		if($imageOrgName){			
			// grab the path to the temporary file (image) that the user uploaded
			$photo = $imageTmp;			
			// check if it exists
			if(is_uploaded_file($photo)){
				//the real image file name
				$real_name = strtolower($imageOrgName);
				// image type based on image file name extension:
				if(strstr($real_name,".png")){
					$image_type = "png";
				}else if(strstr($real_name,".jpg")){
					$image_type = "jpg";
				}else if(strstr($real_name,".gif")){
					$image_type = "gif";
				}else{
					die("Unsupported image type");
				}
				// find the next image name we are going to save
				$x=1;
				while(true){
					$image_name = $imagePath.$imageName;
					$thumb_name = $imagePath."thumb-".$imageName;
					if(!is_file($image_name))break;
					$x++;
				}
			//	die($image_name);
				
				// start processing the main bigger image:
				$max_width = $imageWidth; $max_height = $imageHeight;
				$size = getimagesize($photo);
				$width = $size[0];
				$height = $size[1];
				$x_ratio = $max_width / $width;
				$y_ratio = $max_height / $height;
				if(($width <= $max_width)&&($height <= $max_height)){
					$tn_width = $imageWidth;
					$tn_height = $imageHeight;
				}else{
					if(($x_ratio * $height) < $max_height){
						$tn_height = $imageHeight;
						$tn_width = $imageWidth;
					}else{
						$tn_width = $imageWidth;
						$tn_height = $imageHeight;
					}
				}
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				// destination resized image:
				$dst = imagecreatetruecolor($tn_width, $tn_height);
				// resize original image onto $dst
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				// write the final jpeg image..
				imagejpeg($dst, $image_name, 100) or die("Error: your photo	has not been saved. Please contact the administrator");
				// time to clean up
				imagedestroy($src);
				imagedestroy($dst);
				
				// and now we do it all again for the thumbnail:
				$max_width = $thumbWidth; $max_height = $thumbHeight;
				$size = GetImageSize($photo);
				$width = $size[0];
				$height = $size[1];
				$x_ratio = $max_width / $width;
				$y_ratio = $max_height / $height;
				if(($width <= $max_width)&&($height <= $max_height)){
					$tn_width = $thumbWidth;
					$tn_height = $thumbHeight;
				}else{
					if(($x_ratio * $height) < $max_height){
						$tn_height = $thumbHeight;
						$tn_width = $thumbWidth;
					}else{
						$tn_width = $thumbWidth;
						$tn_height = $thumbHeight;
					}
				}
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				$dst = imagecreatetruecolor($tn_width, $tn_height);
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				$thumbfile = $thumb_name;
				if(file_exists($thumbfile))unlink($thumbfile);
				imagejpeg($dst, $thumbfile, 100) or die("Error: your photo thumb has not been saved. Please contact the administrator");
				imagedestroy($src);
				imagedestroy($dst);
			}
		}
	}
        
        
        
        
	function uploadGalleryImageWithThumbs($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight, $thumbWidth, $thumbHeight){

		$sizesAllowed = array(
							array("width"=>1600, "height"=>1200),
							array("width"=>1280, "height"=>960),
							array("width"=>1024, "height"=>768),
							array("width"=>800,  "height"=>600),
						);
	
		if($imageOrgName){
			
			// grab the path to the temporary file (image) that the user uploaded
			$photo = $imageTmp;
			
			// check if it exists
			if(is_uploaded_file($photo)){
				//the real image file name
				$real_name = strtolower($imageOrgName);
				// image type based on image file name extension:
				if(strstr($real_name,".png")){
					$image_type = "png";
				}else if(strstr($real_name,".jpg")){
					$image_type = "jpg";
				}else if(strstr($real_name,".gif")){
					$image_type = "gif";
				}else{
					die("Unsupported image type");
				}
				// find the next image name we are going to save
				$x=1;
				while(true){
					$image_name = $imagePath.$imageName.".".$image_type;
					$thumb_name = $imagePath."thumb-".$imageName.".".$image_type;
					if(!is_file($image_name))break;
					$x++;
				}
			//	die($image_name);
				
				// start processing the main bigger image:
				$max_width = $imageWidth; $max_height = $imageHeight;
				$size = getimagesize($photo);
				$width = $size[0];
				$height = $size[1];
				$x_ratio = $max_width / $width;
				$y_ratio = $max_height / $height;
				if(($width <= $max_width)&&($height <= $max_height)){
					$tn_width = $width;
					$tn_height = $height;
				}else{
					if(($x_ratio * $height) < $max_height){
						$tn_height = ceil($x_ratio * $height);
						$tn_width = $max_width;
					}else{
						$tn_width = ceil($y_ratio * $width);
						$tn_height = $max_height;
					}
				}
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				// destination resized image:
				$dst = imagecreatetruecolor($tn_width, $tn_height);
                                
                                
                                if($image_type == "png")
                                {    
                                    imagealphablending($dst, false);
                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                    imagefill($dst, 0, 0, $colorTransparent);
                                    imagesavealpha($dst, true);
                                }
                                
			       // resize original image onto $dst
			       imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
                                
                                
			       // write the final jpeg image..                                
                               if($image_type == "png")                                 
                                     imagepng($dst, $image_name);                                
                               else
                                     imagejpeg($dst, $image_name, 100) or die("Error: your photo	has not been saved. Please contact the administrator");  
				
                               
                               
				// resize original image onto $dst
				//imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				// write the final jpeg image..
				//imagejpeg($dst, $image_name, 100) or die("Error: your photo	has not been saved. Please contact the administrator");
				// time to clean up
				imagedestroy($src);
				imagedestroy($dst);
				
				//print_r($sizesAllowed);
                                
                                $i = 0;
                                
				foreach($sizesAllowed as $item){
                                        $i++;                                        
					//echo $item['width']."x".$item['height']."<br />";
					
					$max_width = $item['width']; 
					$max_height = $item['height'];
					$size = getimagesize($photo);
					$width = $size[0];
					$height = $size[1];
					$x_ratio = $max_width / $width;
					$y_ratio = $max_height / $height;
					if(($width <= $max_width)&&($height <= $max_height)){
						$tn_width = $width;
						$tn_height = $height;
					}else{
						if(($x_ratio * $height) < $max_height){
							$tn_height = ceil($x_ratio * $height);
							$tn_width = $max_width;
						}else{
							$tn_width = ceil($y_ratio * $width);
							$tn_height = $max_height;
						}
					}
					switch($image_type){
						case "png": $src=imagecreatefrompng($photo); break;
						case "jpg": $src=imagecreatefromjpeg($photo); break;
						case "gif": $src=imagecreatefromgif($photo); break;
					}
					$dst = imagecreatetruecolor($tn_width, $tn_height);
                                        
                                        if($image_type == "png")
                                        {    
                                            imagealphablending($dst, false);
                                            $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                            imagefill($dst, 0, 0, $colorTransparent);
                                            imagesavealpha($dst, true);
                                        }

                                        imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
                                        $thumb_name = $imagePath."thumb".$i."-".$imageName.".".$image_type;
                                        $thumbfile = $thumb_name;
                                        if(file_exists($thumbfile))unlink($thumbfile);

                                        if($image_type == "png")                                 
                                        imagepng($dst, $thumbfile);    
                                        else
                                        imagejpeg($dst, $thumbfile, 100) or die("Error: your photo thumb has not been saved. Please contact the administrator");
                                        
//					imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
//					$thumbfile = $thumb_name;
//					if(file_exists($thumbfile))unlink($thumbfile);
//					imagejpeg($dst, $thumbfile, 100) or die("Error: your photo thumb has not been saved. Please contact the administrator");// and now we do it alll again for the thumbnail:													
				}
				
				imagedestroy($src);
				imagedestroy($dst);								
			}
		}
	}
	
	function imageDimensions($imageDimensions, $id){
		
		$sizesAllowed = array(
							array("width"=>1600, "height"=>1200),
							array("width"=>1280, "height"=>960),
							array("width"=>1024, "height"=>768),
							array("width"=>800,  "height"=>600),
						);
		$array = array("width"=>$imageDimensions[0], "height"=>$imageDimensions[1]);
		
		$key = array_search($array, $sizesAllowed);

		for($i=$key; $i<sizeof($sizesAllowed);$i++){
			$d1 = $sizesAllowed[$i]["width"]."|".$sizesAllowed[$i]["height"]."|".$id;
			$d2 = $sizesAllowed[$i]["width"]."x".$sizesAllowed[$i]["height"];
			echo "<a href='".site_url(WDOWNLOADPAGE.base64_encode($d1))."' target='_blank'>".$d2."</a><br>";
		}
		
	}
	
	
	function getMicroTime(){ 
		list($usec, $sec) = explode(" ",microtime()); 
		return ((float)$usec + (float)$sec); 
	}
	
	function isValidURL($url)
	{
		return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
	}
	
	function allowedChars($str){
		
		$arr = array(
					"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
					"0","1","2","3","4","5","6","7","8","9",
					"-");
					
		for($i=0; $i<strlen($str); $i++){
			if(!in_array($str[$i],$arr))
				return false;
				//echo $str[$i];
		}
		//die();
		return true;
	}
	
	
	function get404Array(){
		
		$data['pageTitle']			= TITLE404;
		$data['metaKeywords']		= METAKEYWORDS404;
		$data['metaDescription']	= METADESCRIPTION404;
		$data['heading']			= HEADING404;
		$data['pageContent']		= CONTENT404;
			
		return $data;
	}
	
	function check_email_address($email) 
	{
		if(!@ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
			return false;
	  	}
	  
	  	// Split it into sections to make life easier
	  	$email_array = explode("@", $email);
	  	$local_array = explode(".", $email_array[0]);
	  	for ($i = 0; $i < sizeof($local_array); $i++) {
			if(!@ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])){
				return false;
			}
	  	}
		
	  	// Check if domain is IP. If not, 
	  	// it should be valid domain name
	  	if (!@ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
			$domain_array = explode(".", $email_array[1]);
			if (sizeof($domain_array) < 2) {
				return false; // Not enough parts to domain
			}
			for ($i = 0; $i < sizeof($domain_array); $i++) {
		  		if(!@ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",	$domain_array[$i])) {
					return false;
		  		}
			}
	  	}
	  	return true;
	}
	 
	function getSummitList(){
		
		$allSummits = $this->getAllRecordsWhere(EVENTS, array("is_active"=>1), "id", "DESC");	
		
		$content  = "";
		$content .= "<div class='grey-line'>&nbsp;</div>";
		foreach($allSummits as $item){
			$content .= "<div class='item'><span class='hideimage'><img class='left-border-repeat3' src='".base_url()."images/events/thumb_".$item->image."' /></span>";
			$content .= "<h2><a href='".site_url("members-programs-n-events/summits/".$item->id)."'>".$item->event_title."</a></h2>";
			$content .= "<p>".substr(strip_tags($item->description),0,200)."...</p>";
			$content .= "<p class='readmore'><a href='".site_url("members-programs-n-events/summits/".$item->id)."'>read more</a></p>";
			$content .= "</div>";
			$content .= "<div class='clear'></div>";
			$content .= "<div class='grey-line'>&nbsp;</div>";
		}
		//print_r($allSummits);
		
		return $content;		
	}
        
        
        function SEF_URLS($str, $replace=array(), $delimiter='-') 
        {
			$str=trim($str);                        
			if( !empty($replace) )
			{
				 $str = str_replace((array)$replace, ' ', $str);
			}
			$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
			$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
			$clean = strtolower(trim($clean, '-'));
			$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
			return $clean;
	}
        
        function SEF_URLS2($clean, $replace=array(), $delimiter='-') 
        {			
            //$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
            $clean = trim($clean, '-');
            $clean = preg_replace("/[\/_|+ -]+()/", $delimiter, $clean);
            
//            $seo_st = str_replace(' ', '-', $title);
            //$clean = str_replace('--', '-', $clean);
            $clean = str_replace('(', '', $clean);
            $clean = str_replace(')', '', $clean);
            return mb_strtolower($clean, 'UTF-8');
	}
        
        function send_email($sender , $receiver ,$subject ,$sendername , $message)
        {       
            // send email    
             $this->load->library( 'email' );
             $config['protocol']='sendmail';
             $config['charset']='utf-8';
             $config['mailtype']='html';             
             $this->email->initialize($config);                                                                            

             $this->email->from($sender, $sendername);                        
             $this->email->to($receiver);            

             $this->email->subject($subject);

             $this->email->message($message);	                        
             $this->email->send();                                                            
            // ==========================                                                
        }
        
        public function send_email_with_attachment($from,$email,$subject,$message,$attachment)
    {
//            $config = Array(
//              'protocol' => 'smtp',
//              'smtp_host' => 'ssl://smtp.googlemail.com',
//              'smtp_port' => 465,
//              'smtp_user' => 'abc@gmail.com', 
//              'smtp_pass' => 'passwrd', 
//              'mailtype' => 'html',
//              'charset' => 'iso-8859-1',
//              'wordwrap' => TRUE
//            );
//
//         $this->load->library('email', $config);
               
    
        $this->load->library( 'email' );
        $config['protocol']='sendmail';
        $config['charset']='iso-8859-1';
        $config['mailtype']='html';             
        $config['wordwrap']='TRUE';             
        $this->email->initialize($config); 
             
         
        foreach($email as $row)
        {            
         $this->email->clear();   
         $this->email->set_newline("\r\n");
         $this->email->from($from);
         $this->email->to($row);
         $this->email->subject($subject);
         $this->email->message($message);
         $this->email->attach($attachment);
         
         if($this->email->send())
         {
          
         }
        else
        {
          show_error($this->email->print_debugger());
        }
        }
    }

        
        function creat_thumbold($image_name,$wi,$hi,$folder)
        {                                                                    
                        $this->load->library('image_lib');
                        $config['image_library'] = 'gd2';
			$config['source_image'] = 'images/'.$folder.'/'.$image_name;
			$config['new_image']	= 'images/'.$folder.'/'.$image_name;
			$config['maintain_ratio'] = TRUE;
			$config['width'] = $wi;
			$config['height'] = $hi;
			$this->image_lib->initialize($config); 
			$this->image_lib->resize();
			$this->image_lib->clear();                                                        
        }
        
        
        
        function creat_thumb($imageName, $imageOrgName, $imageTmp, $imagePath, $imageWidth, $imageHeight, $thumbWidth, $thumbHeight,$prefix){
		
		if($imageOrgName){
			
			// grab the path to the temporary file (image) that the user uploaded
			$photo = $imageTmp;
			
			// check if it exists
			if(is_uploaded_file($photo)){
			
				//the real image file name
				$real_name = strtolower($imageOrgName);
				// image type based on image file name extension:
				if(strstr($real_name,".png")){
					$image_type = "png";
				}else if(strstr($real_name,".jpg")){
					$image_type = "jpg";
				}else if(strstr($real_name,".gif")){
					$image_type = "gif";
                                }else{
					die("Unsupported image type");
				}
				
				// find the next image name we are going to save
				$x=1;
				//while(true){
					$it = end(explode(".",$imageName));
					
					if( $it=="jpg" || $it=="jpeg" || $it=="png" || $it=="gif"){
						$image_name = $imagePath.$imageName;
						$thumb_name = $imagePath.$prefix.$imageName;
					}else{
						$image_name = $imagePath.$imageName.".".$image_type;
						$thumb_name = $imagePath.$prefix.$imageName.".".$image_type;
					}
					
					//if(!is_file($image_name))break;
					//$x++;
				//}
				
				//	die($image_name);
				// start processing the main bigger image:
				$max_width 	= $imageWidth; 
                                $max_height = $imageHeight;
				$size 		= getimagesize($photo);
				$width 		= $size[0];
				$height 	= $size[1];
				$x_ratio 	= $max_width / $width;
				$y_ratio 	= $max_height / $height;
				
				if(($width <= $max_width)&&($height <= $max_height)){
					$tn_width = $width;
					$tn_height = $height;
				}else{
					if(($x_ratio * $height) < $max_height){
						$tn_height = ceil($x_ratio * $height);
						$tn_width = $max_width;
					}else{
						$tn_width = ceil($y_ratio * $width);
						$tn_height = $max_height;
					}
				}
				
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
																
				
				// and now we do it alll again for the thumbnail:
				$max_width = $thumbWidth; $max_height = $thumbHeight;
				$size = GetImageSize($photo);
				$width = $size[0];
				$height = $size[1];
				$x_ratio = $max_width / $width;
				$y_ratio = $max_height / $height;
				if(($width <= $max_width)&&($height <= $max_height)){
					$tn_width = $width;
					$tn_height = $height;
				}else{
					if(($x_ratio * $height) < $max_height){
						$tn_height = ceil($x_ratio * $height);
						$tn_width = $max_width;
					}else{
						$tn_width = ceil($y_ratio * $width);
						$tn_height = $max_height;
					}
				}
				
				switch($image_type){
					case "png": $src=imagecreatefrompng($photo); break;
					case "jpg": $src=imagecreatefromjpeg($photo); break;
					case "gif": $src=imagecreatefromgif($photo); break;
				}
				
				$dst = imagecreatetruecolor($tn_width, $tn_height);
                                
                                
                                if($image_type == "png")
                                {    
                                    imagealphablending($dst, false);
                                    $colorTransparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                                    imagefill($dst, 0, 0, $colorTransparent);
                                    imagesavealpha($dst, true);
                                }
                                
				imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
				$thumbfile = $thumb_name;
				if(file_exists($thumbfile))unlink($thumbfile);
                                
                                if($image_type == "png")                                 
                                imagepng($dst, $thumbfile);    
                                else
				imagejpeg($dst, $thumbfile, 100) or die("Error: your photo thumb has not been saved. Please contact the administrator");
                                
                                
				imagedestroy($src);
				imagedestroy($dst);
			}
		}
	}
        
        
        
        function gen_string($string,$max=20)
        {
            $tok=  strip_tags($string);            
            $tok=strtok($tok,' ');
            $string='';
            
            while($tok!==false && strlen($string)<$max)
            {
                if (strlen($string)+strlen($tok)<=$max)
                    $string.=$tok.' ';
                else
                    break;
                $tok=strtok(' ');
            }
            
            return trim($string).'...';
        }
        
        
        function gen_string2($string,$max=20)
        {
            $tok=  strip_tags($string,"-");            
            $tok=strtok($tok,' ');
            $string='';
            
            while($tok!==false && strlen($string)<$max)
            {
                if (strlen($string)+strlen($tok)<=$max)
                    $string.=$tok.' ';
                else
                    break;
                $tok=strtok(' ');
            }
            
            return trim($string);
        }
        
        function gen_string3($string,$max=20)
        {
            return substr($string,0, $max);
        }
        
        
        function getFilterChoices($id)
        {
            $this->db->select('*');    
            $this->db->from(CHOICES);
            $this->db->join(CHOICESJOIN, CHOICES.'.ChoiceID = '.CHOICESJOIN.'.CHID');
            $this->db->join(FIELDS, FIELDS.'.FieldID = '.CHOICESJOIN.'.FID');            
            $this->db->join(FIELDSJOIN, FIELDSJOIN.'.FID = '.FIELDS.'.FieldID');            
            $this->db->join(FIELDSGROUPS, FIELDSGROUPS.'.FieldCatID = '.FIELDSJOIN.'.CID');
            $this->db->join(CATEGORIES, CATEGORIES.'.FGID = '.FIELDSGROUPS.'.FieldCatID');
            $this->db->where(CATEGORIES.'.CategoryID' ,$id);
            $this->db->where(FIELDS.'.FieldType' ,'1');
            $this->db->group_by(CHOICES.".Choice");
            $query = $this->db->get();
            return $query->result();          
        }
        
        
         
}