\!/ KyuuKazami \!/

Path : /home/kohli/public_html/application/libraries/
Upload :
Current File : /home/kohli/public_html/application/libraries/common_lib_bck.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Common_lib{
    
    public $ci;
    
    function __construct(){
        $this->ci =& get_instance();
        $this->ci->load->helper(array('form','url'));        
        $this->ci->load->library('session');
        $this->ci->load->library('security');
        $this->ci->load->library('encrypt');
        $this->ci->load->library("cart");
        $this->ci->load->library('form_validation');        		
        $this->ci->load->database();        
    }
    
    function get_base_url(){
        return base_url();
    }
    
    function get_site_logo_path(){
        $logo_name = $this->get_setting("logo");
        return base_url().$this->ci->config->item("logo_path")."/".$logo_name;
    }
    
    function get_site_logo(){
        $settings = $this->get_setting("logo",true);        
        return "<a class='site-logo' title='".$settings->site_title."' href='".$this->get_base_url()."'><img class='site-logo-img' alt='".$settings->site_title."' src='".base_url().$this->ci->config->item("logo_path")."/".$settings->logo."' /></a>";
    }
        
    function is_secure_page(){
        
    }
    
    function get_setting_cache_file($type="general"){
        return $this->ci->config->item($type."_setting_cache");
    }        
    
    
    function get_add_cart_name($string){        
        $string = str_replace("/"," ",$string);
        $string = str_replace("%"," ",$string);
        $string = str_replace("_"," ",$string);
        $string = str_replace("-"," ",$string);
        $string = str_replace(")","",$string);
        $string = str_replace("(","",$string);
        $string = str_replace("'","",$string);                 
        return trim(str_replace(" "," ",$string));
    }
    
    function get_url_string($string){
        $string = str_replace("&","and",$string);
        $string = str_replace("/","-",$string);
        $string = str_replace("%","-",$string);
        $string = str_replace("_","-",$string);
        $string = str_replace(")","",$string);
        $string = str_replace("(","",$string);        
        $string = str_replace("------","-",$string);
        $string = str_replace("-----","-",$string);
        $string = str_replace("----","-",$string);
        $string = str_replace("---","-",$string);
        $string = str_replace("--","-",$string);
        return trim(str_replace(" ","-",strtolower($string)));
    }
    
    function get_display_string($string){
        return trim(ucwords(strtolower($string)));
    }
    
    function get_product_detail_url($obj){
        return site_url("products/detail/".$obj->product_id."/".$this->get_url_string($obj->product_name));
    }
    
    function get_category_prod_url($obj){
        return site_url("category-products/".$obj->category_id."/".$this->get_url_string($obj->category_name));
    }        
    
    function _collections(){
        
    }
    
    function _category($li_classes="",$current_category=0,$collection_id=0){
        $this->ci->load->model("categorym");
        
        if($collection_id > 0){
            $result = $this->ci->categorym->get_all_categories(array("collection_id" => $collection_id));    
        }elseif($current_category > 0){
            $result = $this->ci->categorym->get_all_categories(array("category_id" => $current_category));
        }else{
            $result = $this->ci->categorym->get_all_categories();
        }
        
        
        return $this->_wrap_li_single($result, 0,$li_classes,$current_category,$collection_id);
    }
    
    function _wrap_brand_li_single($result, $parent,$li_classes=""){
        $list = "";
        foreach($result as $value){
            $active_class = '';
            if($value->category_id == $current_category){
                //$active_class = 'active';
            }
            $anchor_arrow = "";
            if($li_classes != ""){
                $anchor_arrow = '<i class="fa fa-angle-right"></i>';     
            }
            $list .= '<li class="'.$li_classes.' '.$active_class.'"><a href="#" title="'.$this->get_display_string($value->manufacturer_name).'">'.$anchor_arrow.' '.$this->get_display_string($value->manufacturer_name).'</a>';    		      	  
        }      
        return $list;
    }
    
    function _wrap_li_single($result, $parent,$li_classes="",$current_category=0,$collection_id=0){
        $list = "";
        foreach($result as $value){
            $active_class = '';
            if($value->category_id == $current_category){
                $active_class = 'active';
            }
            $anchor_arrow = "";
            if($li_classes != ""){
                $anchor_arrow = '<i class="fa fa-angle-right"></i>';     
            }
            $list .= '<li class="'.$li_classes.' '.$active_class.'"><a href="'.$this->get_category_prod_url($value).'" title="'.$this->get_display_string($value->category_name).'">'.$anchor_arrow.' '.$this->get_display_string($value->category_name).'</a>';    		      	  
        }      
        return $list;
    }
    
    function _wrap_li($result, $parent){
          $has_childs	= FALSE;
          static $list	= "";
          foreach($result as $value){
        	  if($value->parent_id == $parent){
        		  if($has_childs === FALSE){
        			  $has_childs = TRUE;
        			  $list .= ($parent == 0)?'<ul class="sf-menu sf-vertical">':'<ul>';
        		  }
        		  $list .= '<li><a href="'.base_url().'cat/'.url_title(ucwords(strtolower($value['name']))).'/'.$key.'" title="'.ucwords(strtolower($value['name'])).'">'.character_limiter(ucwords(strtolower($value['name'])), 15).'</a>';
        		  $this->_wrap_li($result, $key);
        		  $list .= '</li>';
        	  }
          }
          if($has_childs === TRUE) $list .= '</ul>';
          return $list;
    }
    
    
    function send_mail($from_address,$to_address,$subject,$body,$cc="",$bcc=""){
        
        $this->ci->load->library('email');
        
        /*$config['protocol'] = 'smtp';
        $config['smtp_host'] = '';
        $config['smtp_user'] = '';
        $config['smtp_pass'] = '';
        $config['smtp_port'] = 587;
        */
        //$config['protocol'] = 'sendmail';
        //$config['mailpath'] = '/usr/sbin/sendmail';
        //$config['charset'] = 'iso-8859-1';
        //$config['wordwrap'] = TRUE;
        $config['mailtype'] = 'html';                
        
        $this->ci->email->initialize($config);
        
        $this->ci->email->from($from_address, '');
        $this->ci->email->to($to_address);                 
        $this->ci->email->subject($subject);
        $this->ci->email->message($body);	        
        
        if($cc != "") $this->ci->email->cc($cc);
        if($bcc != "") $this->ci->email->bcc($bcc);        
                 
        $this->ci->email->send();        
    }
    
    function render_pagination($base_url,$total_item,$page_segment,$page_limit){
        $this->ci->load->library('pagination');                            
        $config['base_url'] = $base_url;
        $config['total_rows'] = $total_item;
        $config['per_page'] = $page_limit;
        $config['num_links'] = 4;
        $config['uri_segment'] = $page_segment;
        $config['full_tag_open'] = '<ul class="pagination pull-right">';                        
        $config['full_tag_close'] = '</ul>';
        
        $config['num_tag_open'] = '<li>';        
        $config['num_tag_close'] = '</li>';
        
        $config['first_link'] = '&laquo;';
        $config['first_tag_open'] = '<li>';            
        $config['first_tag_close'] = '</li>';
        
        $config['last_link'] = '&raquo;';
        $config['last_tag_open'] = '<li>';            
        $config['last_tag_close'] = '</li>';
        
        $config['next_link'] = '&gt;';
        $config['next_tag_open'] = '<li>';            
        $config['next_tag_close'] = '</li>';
        
        $config['prev_link'] = '&lt;';
        $config['prev_tag_open'] = '<li>';            
        $config['prev_tag_close'] = '</li>';
        
        $config['cur_tag_open'] = '<li><span>';        
        $config['cur_tag_close'] = '</span></li>';                                                           
        $this->ci->pagination->initialize($config);
        return $this->ci->pagination->create_links();
    }
    
    function generate_pagination_row($base_url,$total_item,$page_segment){
        ?>
        <div class="col-md-4 col-sm-4 items-info">Items 1 to 9 of <?php echo $total_item ?> total</div>
        <div class="col-md-8 col-sm-8">
            <?php echo $pagination ?>
        </div>
        <?php   
    }        
    
    function get_status_class($status_code){
        $status_array = array(        
        "A" => "bg-info",
        "C" => "bg-danger",
        "D" => "bg-success",
        "I" => "bg-info",
        "K" => "bg-info",
        "L" => "bg-success",
        "P" => "",
        "R" => "bg-info",
        "S" => "bg-success",
        "X" => "bg-danger");
        return $status_array[$status_code];
    }
    
    function get_status_detail($status_code){
        $status_array = array(        
        "A" => "Approved",
        "C" => "Cancelled",
        "D" => "Done",
        "I" => "InProcess/Packaging",
        "K" => "Packed",
        "L" => "Delivered",
        "P" => "Pending",
        "R" => "Ready for Shipment",
        "S" => "Shipped",
        "X" => "Deleted");
        return $status_array[$status_code];
    }
    
    function get_product_other_images($product_id){
        $this->ci->load->model("productm");
        $rsImages = $this->ci->productm->get_product_images($product_id);
        return $rsImages;
    }
    
    function get_product_list(){
        $this->ci->load->model("productm");
        
        $per_page_limit = $this->ci->config->item('product_list_limit');
        $column = "product_name";
        $sort = "asc";
        if($this->input->get("sort") != ""){                
            $sort_pair = explode(":",urldecode($this->input->get("sort")));                
            if(count($sort_pair) == 2){                    
                if($sort_pair[0] == "price"){
                    $column = "price";                        
                }else{
                    $column = "product_name";                        
                }                    
                if($sort_pair[1] == "asc"){
                    $sort = "asc";
                }else{
                    $sort = "desc";   
                }
                        
            }
        }
        
        $sort_data['sort_column'] = $this->input->get("sort");
        $sort_data['limit'] = $this->input->get("limit");
        
        if($this->get_n_get("limit") > 0 && $this->get_n_get("limit") <= 150){
            $per_page_limit = $this->get_n_get("limit");
        }
        
        $cname = $this->uri->segment(3);
        $offset = $this->fSafeNum($this->uri->segment(4));
        $product_list_count = $this->ci->productm->get_category_products($cid);
    
        $product_list = $this->ci->productm->get_category_products($cid,$offset,$per_page_limit,$column,$sort);
        
        $data['sort_data'] = $sort_data;
        
        $data['current_category'] = $cid;
        $data['pagination'] = $this->render_pagination(site_url("category-products")."/$cid/$cname",count($product_list_count),4,$per_page_limit);
        $data['offset'] = $offset;
        $data['total_items'] = count($product_list_count);
        
        return $data;
    }
    
    function get_product_main_box($obj,$show_wrap = true){
        $product_box = "";
        if($show_wrap){
            $product_box .= '
            <div class="col-md-4 col-sm-6 col-xs-12">';
        }
        $data_array = array("is_live_inventory"=>$obj->do_inventory_check,"id"=>$obj->product_id,"name"=>$this->get_add_cart_name($obj->product_name),"price"=>$this->get_cal_price($obj));
        $data_serialize = json_encode($data_array);
        $coming_soon_badge = "";
        if($obj->coming_soon == 1){
            $coming_soon_badge = "<div class='coming_soon_badge'><img src='".$this->get_base_url()."assets/frontend/pages/img/coming_soon.png' /></div>";
        }
        $out_of_stock_badge = "";
        if($obj->out_of_stock == 1 && $obj->coming_soon == 0){
            $out_of_stock_badge = "<div class='coming_soon_badge'><img src='".$this->get_base_url()."assets/frontend/pages/img/out_of_stock.png' /></div>";
        }
        $product_box .= '
        <div class="product-item">
            '.$coming_soon_badge.$out_of_stock_badge.'
            <div class="pi-img-wrapper">
                <a href="'.$this->get_product_detail_url($obj).'">
                <img src="'.$this->get_product_image($obj,'small').'" class="img-responsive" alt="'.$obj->product_name.'">
                </a>
                <div>
                    <a href="'.$this->get_product_image($obj,"medium").'" class="btn btn-default fancybox-button">Zoom</a>
                    <a href="#product-pop-up-'.$obj->product_id.'" class="btn btn-default fancybox-fast-view">View</a>
                </div>
            </div>
            <h3><a href="'.$this->get_product_detail_url($obj).'">'.$obj->product_name.'</a></h3>
            <div class="pi-price">'.$this->get_product_price($obj,true,"main").'</div>';
            $stock_left = $obj->stock; 
            $show_size_option = $this->get_product_setting("show_size_option");                   
            if($show_size_option == 1){
                $stock_left = $this->get_product_size_stock($obj->product_id);
            }      
            $product_box .= '
                <div class="cart-buttons ">
                    <a href="'.$this->get_product_detail_url($obj).'" class="pull-right btn btn-primary">View Detail</a>                    
                </div>';      
            if($obj->do_inventory_check == 1 && $stock_left == 0 && false){
                $product_box .= '
                <div class="cart-buttons ">
                    <button type="button" href="#" class="btn btn-primary add2cart">Out of Stock</button>                    
                </div>';
            }elseif(false){
                $product_box .= '
                <div class="cart-buttons ">
                    <button data-add-to-cart="'.$this->encode($data_serialize).'" type="submit" data-ref="'.$obj->product_id.'" href="#" id="" class="btn btn-primary add-to-cart-init add2cart">Add to cart</button>
                    <div class="progress add-progress" style="left:128px;width:135px;height:37px">
                        <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%;">
                            Adding...
                        </div>
                    </div>
                </div>';
                
            }
            $product_box .= '
        </div>'.$this->get_product_quick_box($obj);
        if($show_wrap){
            $product_box .= '
            </div>';    
        }
        
        return $product_box;
    }
    
    function get_product_quick_box($obj){
        
        $data_array = array("is_live_inventory"=>$obj->do_inventory_check,"id"=>$obj->product_id,"name"=>$this->get_add_cart_name($obj->product_name),"price"=>$this->get_cal_price($obj));
        $data_serialize = json_encode($data_array);
        
        $coming_soon_badge = "";
        if($obj->coming_soon == 1){
            $coming_soon_badge = "<div class='coming_soon_badge'><img src='".$this->get_base_url()."assets/frontend/pages/img/coming_soon.png' /></div>";
        }
        $out_of_stock_badge = "";
        if($obj->out_of_stock == 1 && $obj->coming_soon == 0){
            $out_of_stock_badge = "<div class='coming_soon_badge'><img src='".$this->get_base_url()."assets/frontend/pages/img/out_of_stock.png' /></div>";
        }
        
        $product_view = "";
        $product_view = '        
        <div id="product-pop-up-'.$obj->product_id.'" style="display: none; width: 700px;">
            <div class="product-page product-pop-up">
                <div class="row">
                    <div class="col-md-6 col-sm-6 col-xs-3">
                        '.$coming_soon_badge.$out_of_stock_badge.'
                        <div class="product-main-image">
                            <img src="'.$this->get_product_image($obj,"medium").'" alt="'.$obj->product_name.'" class="img-responsive">
                        </div>                       
                    </div>
                    <div class="col-md-6 col-sm-6 col-xs-9">
                        <h1>'.$this->str_limiter($obj->product_name,100).'</h1>
                        <h4><b>SKU:</b> #<span id="sku-'.$obj->product_id.'">'.$obj->sku.'</span></h4>
                        <div class="price-availability-block clearfix">
                            <div class="pi-price">'.$this->get_product_price($obj).'</div>';                                                                                    
                            
                            $product_view .= '
                        </div>';
                        $stock_left = $obj->stock; 
                        $global_product_settings = $this->get_product_setting("show_social_widget",true);                   
                        if($global_product_settings->show_size_option == 1){
                            $stock_left = $this->get_product_size_stock($obj->product_id);
                        }
                        if( ($obj->do_inventory_check == 1 && $stock_left == 0) || $obj->coming_soon == 1 || $obj->out_of_stock == 1){                        
                            $product_view .= '
                            <div class="outofstock">
                                Availability: <strong>Out of Stock</strong>
                            </div>';
                        }else{
                            $product_view .= '
                            <div class="availability">
                                Availability: <strong>In Stock</strong>
                            </div>';
                            
                        }
                        $product_view .= '
                        <div class="description">'.$obj->short_description.'</div>
                        <div class="product-page-options row">';
                            if($global_product_settings->show_required_date == 1){
                                $product_view .= '
                                <div class="col-md-12">
                                <label class="control-label">Required Date:</label>
                                <div class="input-group date datepicker-pastdisabled-rd">
                                    <input readonly="" value="'.date("m/d/Y").'" class="form-control" type="text" id="rd-'.$obj->product_id.'">
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                    </div>
                                </div>';
                            }
                            $product_view .= '
                            <div class="clearfix"></div>';
                            if($global_product_settings->show_promising_date == 1){
                                $product_view .= '
                                <div class="col-md-12">
                                    <label class="control-label">Performance Date:</label>
                                    <div class="input-group date datepicker-pastdisabled-pd">
                                        <input readonly="" value="'.date("m/d/Y").'" class="form-control" type="text" id="pd-'.$obj->product_id.'">
                                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                    </div>
                                </div>';
                            }
                            if($global_product_settings->show_size_option == 1){
                                $product_view .= '
                                <div class="clearfix"></div>
                                <div class="col-md-12">
                                    <label class="control-label">Size:</label>
                                    '.$this->get_product_sizes_list($obj->product_id,$obj->show_inventory_level,$obj->do_inventory_check).'
                                </div>';
                            }
                            $product_view .= '                            
                        </div>
                        <div class="product-page-cart">';
                            if( ($obj->do_inventory_check == 1 && $stock_left == 0) || $obj->coming_soon == 1 || $obj->out_of_stock == 1){
                                if($product_detail->coming_soon == 1){
                                    $product_view .= '                                
                                    <div class="pull-left  cart-buttons">
                                        <button class="btn btn-success" type="button">Coming Soon</button>                                
                                    </div>
                                    ';
                                }else{                                                            
                                    $product_view .= '                                
                                    <div class="pull-left  cart-buttons">
                                        <button class="btn btn-primary" type="button">Out of Stock</button>                                
                                    </div>
                                    ';
                                }                                
                            }else{
                                $product_view .= '
                                <div class="product-quantity pull-left">
                                    <input id="product-quantity-'.$obj->product_id.'" type="text" value="1" readonly name="product-quantity" class="form-control input-sm qty-'.$obj->product_id.'">
                                </div>
                                <div class="pull-left  cart-buttons">
                                    <button class="btn btn-primary add-to-cart-init" type="submit"  data-ref="'.$obj->product_id.'" data-add-to-cart="'.$this->encode($data_serialize).'">Add to cart</button>
                                    <div class="progress add-progress">
                                        <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                                            Adding...
                                        </div>
                                    </div>
                                </div>
                                ';
                            }
                            $product_view .= '
                            <a href="'.$this->get_product_detail_url($obj).'" class="btn btn-default more-detail-btn">More details</a>
                        </div>
                    </div>
                    
                    <div class="sticker sticker-sale"></div>
                </div>
            </div>
        </div>';
        return $product_view;
    }
    
    function insert_update_order(){
        $order_data = array();
        
        $shipping_amount = 0;        
        
        $payment_mode = $this->get_post("checkout_payment_method");                        
        $checkout_credit_card_number = $this->get_n_post("checkout_credit_card_number");
        $checkout_cvv_number = $this->get_n_post("checkout_cvv_number");
        $checkout_expiry_month = $this->get_n_post("checkout_expiry_month");
        $checkout_expiry_year = $this->get_n_post("checkout_expiry_year");        
        $checkout_comments = $this->get_n_post("checkout_comments");
        $partial_amount = $this->get_post("partial_amount");
        $partial_amount = str_replace("%","",$partial_amount);
        
        $cart_total = $this->ci->cart->total();
        $cart_data = $this->ci->cart->contents();
        $this->ci->load->model("productm");
        $shipping_amount = $this->calculate_shipping($cart_total);
        $required_date = array();
        foreach($cart_data as $items){
            if(!in_array($items['rd'],$required_date)){
                $required_date[] = $items['rd'];
            }
        }
        
        $shipping_amount = 0;         
        if($this->get_shipping_method() == "range"){            
            $shipping_amount = $this->calculate_shipping($cart_total);
        $shipping_amount = $shipping_amount * count($required_date);                        
        }
        
        if($this->get_shipping_method() == "ups"){
            $shipping_amount = $this->get_session("ups_shipping_price");
        }        
        
        $shipping_discount = 0;
        $promo_discount = 0;
        
        if($this->get_session("coupon_code") != ""){
            $promo_discount = $this->calculate_promo_discount($cart_total,$this->get_session("coupon_code"));
        }
        
        $total = ($cart_total + $shipping_amount) - ($shipping_discount + $promo_discount);
        
        $amount_remaining = 0;
        $payment_status = 'D';
        if($payment_mode == "COD"){
            $payment_status = 'P'; 
            $amount_remaining = $total;
        }
        
        if($partial_amount == 75 || $partial_amount == 50){
            $amount_remaining = ceil(($partial_amount/$total) * 100);
        }
        
        if($payment_mode == "CC"){
            $order_data['credit_card_number'] = $this->encode($checkout_credit_card_number);
            $order_data['cv_number'] = $this->encode($checkout_cvv_number);
            $order_data['expiry_year'] = $this->encode($checkout_expiry_year);
            $order_data['expiry_month'] = $this->encode($checkout_expiry_month);
        }
                                
        $order_data['payment_method'] = $payment_mode;
        $order_data['payment_status'] = $payment_status;
        $order_data['payment_desc'] = "";
        $order_data['transaction_id'] = "";
        $order_data['comments'] = $checkout_comments;
        
        
        $user_login_detail = $this->get_login_detail();
        $order_data['ship_first_name'] = $user_login_detail['shipping_first_name'];
        $order_data['ship_middle_name'] = $user_login_detail['shipping_middle_name'];
        $order_data['ship_last_name'] = $user_login_detail['shipping_last_name'];
        $order_data['ship_address'] = $user_login_detail['shipping_address'];
        $order_data['ship_address1'] = $user_login_detail['shipping_address1'];
        $order_data['ship_city'] = $user_login_detail['shipping_city'];
        $order_data['ship_state'] = $user_login_detail['shipping_state'];
        $order_data['ship_country'] = $user_login_detail['shipping_country'];
        $order_data['ship_zipcode'] = $user_login_detail['shipping_zipcode'];
        $order_data['ship_mobile'] = $user_login_detail['shipping_mobile'];
        
        
        
        $order_data['shipping'] = $shipping_amount;
        $order_data['shipping_method'] = 'Range Price';
        $order_data['shipping_discount'] = $shipping_discount;
        $order_data['order_amount'] = $total;
        $order_data['sub_total'] = $cart_total;
        $order_data['promo_discount'] = $promo_discount;
        $order_data['amount_remaining'] = $amount_remaining;
        
        $order_data['order_date'] = $this->get_date();
        $order_data['user_id'] = $this->get_login_id();
        
        $this->ci->load->model("commonm");
        if($this->get_session("current_order_id") > 0){
            $current_order_id = $this->get_session("current_order_id");
            $this->ci->commonm->db_update($order_data,"orders","order_id",$current_order_id);
        }else{
            $current_order_id = $this->ci->commonm->db_insert($order_data,"orders");
            $this->set_session(array("current_order_id" => $current_order_id));
        }
        
        
        $this->insert_order_items();
        
        return $total;
    }
    
    /**
     *      
     * @param string $default_date
     */
    function get_date($default_date = ""){
        if($default_date == ""){
            return date("Y-m-d H:i:s");
        }
    }
    
    function insert_order_items(){
        $this->ci->load->model("commonm");
        $cart_data = $this->ci->cart->contents();
        $order_items_data = array();
        foreach($cart_data as $items){
            $item_array = array();            
            $product_id = $items['id'];
            $product_price = $items['price'];
            $required_date = strtotime($items['rd']);
            $performing_date = strtotime($items['pd']);
            $product_quantity = $items['qty'];            
            $size_id = $items['size'];
            
            $item_array['order_id'] = $this->get_session("current_order_id");
            $item_array['product_id'] = $product_id;
            $item_array['size_id'] = $size_id;
            $item_array['color_id'] = 0;
            $item_array['is_live_inventory'] = $items['is_live_inventory'];
            $item_array['quantity'] = $product_quantity;
            $item_array['qty_remaining'] = $product_quantity;
            $item_array['price'] = $product_price;
            $item_array['item_status'] = "P";
            $item_array['date_required'] = $this->mysqlDateFormat($required_date);
            $item_array['performance_date'] = $this->mysqlDateFormat($performing_date);
            $item_array['promising_date'] = $this->mysqlDateFormat(strtotime("-15 days",$required_date));
            
            $order_items_data[] = $item_array;
            
            if($items['is_live_inventory'] == 1){                
                $product_size = $this->ci->commonm->get_all("product_sizes",array("product_id"=>$product_id,"size_id"=>$size_id));                
                
                $stock_left = ($product_size[0]->stock_available - $product_quantity);
                
                $inventory_data['order_id'] = $this->get_session("current_order_id");
                $inventory_data['stock_added'] = -$product_quantity;
                $inventory_data['description'] = "New order placed by user";
                $inventory_data['user_id'] = $this->get_login_id();
                $inventory_data['product_id'] = $product_id;
                $inventory_data['size_id'] = $size_id;
                $inventory_data['stock_left'] = $stock_left;
                $inventory_data['date_added'] = $this->mysqlDateFormat();                
                
                $this->log_inventory_history($inventory_data);
                $this->ci->commonm->db_update(array("stock_available"=>$stock_left),"product_sizes","product_size_id",$product_size[0]->product_size_id);
                $this->ci->commonm->db_update(array("stock"=>$stock_left),"products","product_id",$product_id);           
            }
            
        }
        
        $this->ci->commonm->db_insert_batch($order_items_data,"order_items");        
    }
    
    function log_inventory_history($inventory_data){
        $this->ci->load->model("commonm");
        $this->ci->commonm->db_insert($inventory_data,"inventory_history");
    }
    
    function get_country_by_id($country_id){
        $this->ci->load->model("commonm");
        $country_data = $this->ci->commonm->get_by_primary("countries","country_id",$country_id,array("country"));
        return $country_data[0]->country;
    }
    
    function get_order_data($order_id){
        
        $this->ci->load->model("commonm");
        $this->ci->load->model("productm");
        
        $order_data = $this->ci->commonm->get_all("orders",array("order_id" => $order_id));
        $order_item_data = $this->ci->commonm->get_all("order_items",array("order_id" => $order_id));
        $user_detail = $this->ci->commonm->get_all("users",array("user_id" => $order_data[0]->user_id));
                 
        return array($order_data,$order_item_data,$user_detail);        
    }
    
    function get_order_detail_template($order_id,$hide_text=false){
        
        $order_data_detail = array();
        
        $this->ci->load->model("productm");
        $this->ci->load->model("commonm");
        $order_data = $this->ci->commonm->get_all("orders",array("order_id" => $order_id));
        $order_item_data = $this->ci->commonm->get_all("order_items",array("order_id" => $order_id));
        $user_detail = $this->ci->commonm->get_all("users",array("user_id" => $order_data[0]->user_id));
        
        $order_data_detail['order_heading'] = $this->site_title()." - Order (#$order_id) (".date("Y-m-d",strtotime($order_data[0]->order_date)).")";
        if(!$hide_text)
            $order_data_detail['order_text'] = "Congratulation, you order has been placed successfully. An confirmation email of your order has been sent to your email address. Your order id is <b>#$order_id</b>";
        else
            $order_data_detail['order_text'] = "";
        
        $order_item_details_detail = array();
                
        foreach($order_item_data as $items){
            $order_item_data = array();
            $product_id = $items->product_id;
            $product_detail = $this->ci->productm->get_product_detail($items->product_id);
            $product_detail = $product_detail[0];
            $size_detail = "";
            if($items->size_id > 0){
                $size_detail = $this->ci->commonm->get_all("sizes",array("size_id"=>$items->size_id));
                if(count($size_detail) > 0){
                    $size_detail = $size_detail[0]->size;
                }
            }
            
            $order_item_data['item_link'] = $this->get_product_detail_url($product_detail);
            $order_item_data['item_name'] = $product_detail->product_name;
            $order_item_data['item_code'] = $product_detail->sku;            
            $order_item_data['item_image_path'] = $this->get_product_image($product_detail,'small');
            $order_item_data['item_size'] = $size_detail;
            $order_item_data['item_qty'] = $items->quantity;
            $order_item_data['item_unit_price'] = $this->currency_price($items->price);
            $order_item_data['item_price'] = $this->currency_price($items->price * $items->quantity);
            $order_item_data['required_date'] = $items->date_required;
            $order_item_data['performance_date'] = $items->performance_date;            
            $order_item_details_detail[] = $order_item_data;
        }   
        $order_data_detail['order_items'] = $order_item_details_detail;
        
        $order_data_detail['shipping_amount'] = $this->currency_price($order_data[0]->shipping);
        $order_data_detail['promo_discount'] = $this->currency_price($order_data[0]->promo_discount);
        $order_data_detail['sub_total'] = $this->currency_price($order_data[0]->sub_total);
        $order_data_detail['order_amount'] = $this->currency_price($order_data[0]->order_amount);
        $order_data_detail['remaining_amount'] = $this->currency_price($order_data[0]->amount_remaining);
        
        $order_data_detail['shipping_name'] = $order_data[0]->ship_first_name." ".$order_data[0]->ship_last_name;
        $order_data_detail['shipping_address'] = $order_data[0]->ship_address;
        $order_data_detail['shipping_address1'] = $order_data[0]->ship_address1;
        $order_data_detail['shipping_city'] = $order_data[0]->ship_city;
        $order_data_detail['shipping_state'] = $order_data[0]->ship_state;
        $order_data_detail['shipping_zipcode'] = $order_data[0]->ship_zipcode;
        $order_data_detail['shipping_country'] = $this->get_country_by_id($order_data[0]->ship_country);
        $order_data_detail['shipping_mobile'] = $order_data[0]->ship_mobile;
        
        $order_data_detail['full_name'] = $user_detail[0]->first_name." ".$user_detail[0]->last_name;
        $order_data_detail['address'] = $user_detail[0]->address;
        $order_data_detail['address1'] = $user_detail[0]->address1;
        $order_data_detail['city'] = $user_detail[0]->city;
        $order_data_detail['email'] = $user_detail[0]->email;
        $order_data_detail['state'] = $user_detail[0]->state;
        $order_data_detail['zipcode'] = $user_detail[0]->zipcode;
        $order_data_detail['country'] = $this->get_country_by_id($user_detail[0]->country);
        $order_data_detail['mobile'] = $user_detail[0]->mobile;
        
        $this->ci->load->library('parser');
        
        if($hide_text){
            $order_detail_string = $this->ci->parser->parse('email_templates/order_detail_view_tpl', $order_data_detail, TRUE);
        }else{
            $order_detail_string = $this->ci->parser->parse('email_templates/order_email_tpl', $order_data_detail, TRUE);
        }
        
        return $order_detail_string;
    }
    
    function get_order_summary($order_id,$hide_text=false){
        $get_cart_detail = "";
        if($order_id > 0){
            $get_cart_detail = '
            <div class="table-wrapper-responsive">';
                if(!$hide_text){
                    $get_cart_detail .= $this->render_messages("Congratulation, you order has been placed successfully. An confirmation email of your order has been sent to your email address. Your order id is <b>#$order_id</b>","success");
                }
                $get_cart_detail .= '
                <table summary="Shopping cart">
                    <tr>
                        <th colspan="2" class="goods-page-description goods-page-image">Item Detail</th>                                
                        <th class="goods-page-quantity">Quantity</th>
                        <th class="goods-page-price">Unit price</th>
                        <th class="goods-page-total" colspan="2">Total</th>
                    </tr>';
                    
                    $this->ci->load->model("productm");
                    $this->ci->load->model("commonm");
                    $order_data = $this->ci->commonm->get_all("orders",array("order_id" => $order_id));                    
                    $order_item_data = $this->ci->commonm->get_all("order_items",array("order_id" => $order_id));
                    
                    foreach($order_item_data as $items){
                        $product_id = $items->product_id;
                        $product_detail = $this->ci->productm->get_product_detail($items->product_id);
                        $product_detail = $product_detail[0];
                        $size_detail = "";
                        if($items->size_id > 0){
                            $size_detail = $this->ci->commonm->get_all("sizes",array("size_id"=>$items->size_id));
                            if(count($size_detail) > 0){
                                $size_detail = $size_detail[0]->size; 
                            }
                        }
                        $get_cart_detail .= '
                        <tr id="'.$items->order_item_id.'">
                            <td class="goods-page-image">
                            <a href="'.$this->get_product_detail_url($product_detail).'">
                                <img width="75" src="'.$this->get_product_image($product_detail,'small').'" alt="'.$product_detail->product_name.'" /></a>
                            </td>
                            <td class="goods-page-description">
                                <h3><a href="'.$this->get_product_detail_url($product_detail).'">'.$product_detail->product_name.'</a></h3>
                                <p><strong>Size:</strong> '.$size_detail.'</p>
                                <p><strong>Item Code:</strong> '.$product_detail->sku.'</p>';
                                $general_settings = $this->get_product_setting("show_required_date",true);
                                if($general_settings->show_required_date == 1){
                                    $get_cart_detail .= '
                                    <p><strong>Required Date:</strong> <code>'.$items->promising_date.'</code></p>';
                                }
                                if($general_settings->show_promising_date == 1){
                                    $get_cart_detail .= '
                                    <p><strong>Performance Date:</strong> <code>'.$items->performance_date.'</code></p>';
                                }
                                '
                              <!--em>More info is here</em-->
                            </td>                            
                            <td class="goods-page-quantity">
                              <div class="product-quantity">
                                  '.$items->quantity.'
                              </div>
                            </td>
                            <td class="goods-page-price">
                              <strong>'.$this->currency_price($items->price).'</strong>
                            </td>
                            <td class="goods-page-total">
                              <strong>'.$this->currency_price($items->price * $items->quantity).'</strong>
                            </td>                            
                          </tr>
                          ';
                    }        
                    $get_cart_detail .= ' 
                </table>
            </div>
            <div class="shopping-total">
                <ul>
                    <li>
                        <em>Sub total</em>
                        <strong class="price cart-price-row">'.$this->currency_price($order_data[0]->sub_total).'</strong>
                    </li>
                    <li>
                        <em>Shipping</em>
                        <strong class="price cart-price-row">'.$this->currency_price($order_data[0]->shipping).'</strong>
                    </li>
                    <li>
                        <em>Promo Discount</em>
                        <strong class="price cart-price-row">'.$this->currency_price($order_data[0]->promo_discount).'</strong>
                    </li>
                    <li class="shopping-total-price">
                        <em>Total</em>
                        <strong class="price cart-price-row">'.$this->currency_price($order_data[0]->order_amount).'</strong>
                    </li>';
                    if($order_data[0]->amount_remaining > 0){
                        $get_cart_detail .= '
                        <li class="shopping-total-price">
                            <em>Amount Remaining</em>
                            <strong class="price cart-price-row">'.$this->currency_price($order_data[0]->amount_remaining).'</strong>
                        </li>';
                    }
                    $get_cart_detail .= ' 
                </ul>
            </div>
            <div class="clearfix"></div>
            ';
        }else{
            $this->set_session(array("danger-msg" => "Shopping cart is empty"));
            redirect("cart");
            exit;
        }
        return $get_cart_detail;
        
    }
    
    function render_modal_window($title,$id){
        $modal_data['modal_title'] = $title;
        $modal_data['modal_id'] = $id;
        $this->ci->load->view("admin/layout/_add_vendor_order_modal",$modal_data);
    }
    
    function clear_cart_session(){
        $this->ci->cart->destroy();
        $this->remove_session("current_order_id");        
    }
    
    function send_order_email($order_id,$to_address,$html){
        $this->send_mail($this->admin_email(), $to_address, $this->site_title()." Order #$order_id", $html,$this->admin_email());
    }
    
    function generate_verification_link($username){
        //return site_url("user/verify_email")."/".urlencode($this->encode($username))."/".md5($this->encode($username));
        return site_url("user/verify_email")."/".$username."/".md5($this->encode($username));
    }
    
    function run_feedback_information(){    
        $this->ci->form_validation->set_rules('f_name', 'Your Name', 'trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('f_email', 'Your Email', 'valid_email|trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('f_phone', 'Your Phone', 'trim|required|numeric|greater_than[24]|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('best_time', 'Best_time', 'required|callback_check_default');
        //$this->ci->form_validation->set_rules('item', 'Item', 'required|callback_check_default');
        $this->ci->form_validation->set_rules('f_message', 'Message', 'trim|required|max_length[400]|xss_clean');   
        return $this->ci->form_validation->run();
    }

    function run_forgot_password_validation(){        
        $this->ci->form_validation->set_rules('email', 'Email', 'valid_email|trim|required|max_length[40]|xss_clean');
        return $this->ci->form_validation->run();
    }
    
    function send_forgot_password($username,$email){
        $data['customer_name'] = $username;
        $reset_link = site_url("user/resetpassword")."/".$username."/".md5($this->ci->config->item("encryption_key").$username);
        $data['reset_link'] = $reset_link;
        $this->ci->load->library('parser');
        $forgot_password_email_body = $this->ci->parser->parse('email_templates/forgot_password_email_tpl', $data, TRUE);
        $this->send_mail($this->admin_email(),$email,"Forgot Password? - ".$this->site_title(),$forgot_password_email_body);
    }
    
    function send_registration_email($data,$to_address){
        $data['company_name'] = $this->site_title();
        $this->ci->load->library('parser');
        $registration_email = $this->ci->parser->parse('email_templates/register_view_tpl', $data, TRUE);
        
        $this->send_mail($this->admin_email(),$to_address,"Welcome to ".$this->site_title(),$registration_email,$this->admin_email());
    }
    
    function send_newsletter_subscribe($data,$to_address){
        $data['company_name'] = $this->site_title();
        $this->ci->load->library('parser');
        $registration_email = $this->ci->parser->parse('email_templates/newsletter_user_tpl', $data, TRUE);
        
        $this->send_mail($this->admin_email(),$to_address,"Newsletter Subscription for ".$this->site_title(),$registration_email);
    }
    
    function admin_email(){
        //return $this->ci->config->item("admin_email_address");
        return $this->get_setting("admin_email_address");
    }
    
    function get_newsletter_settings(){
        $settings = $this->parse_cache_data("newsletter");                                     
        return $settings[0];                           
    }
    
    function parse_cache_data($file="general"){
        $settings = file_get_contents($this->get_setting_cache_file($file));        
        $settings = json_decode($settings);
        $new_settings = array();
        foreach($settings[0] as $key => $val){
            $new_settings[$key] = $this->decode(urldecode($val));  
        }
        
        $new_settings = (object) $new_settings;
        $new_settings = array($new_settings);
        return $new_settings;
    }    
    
    function get_product_setting($item,$get_all=false){
        
        $settings = $this->parse_cache_data("product");
        if($get_all){
            return $settings[0];
        }        
        return $settings[0]->$item;        
    }
    
    
    function is_cancelled_status($status){        
        return in_array($status,$this->ci->config->item("restock_status"));
    }
    
    function is_restock_status($status){        
        return in_array($status,$this->ci->config->item("stock_status"));
    }
    
    function get_setting($item="",$get_all=false){                
        $settings = $this->parse_cache_data("general");
        if($get_all){                             
            return $settings[0];
        }        
        return $settings[0]->$item;
    }
    
    function site_title(){
        //return $this->ci->config->item("site_title");
        return $this->get_setting("site_title");
    }
    
    function remote_addr(){        
        return $this->ci->input->server('REMOTE_ADDR');        
    }
    
    function site_domain(){        
        return $this->ci->input->server('SERVER_NAME');        
    }
    
    function get_detail_cart_summary($readonly=false){
        $get_cart_detail = "";
        if($this->ci->cart->total_items() > 0){
            $get_cart_detail = '
            <div class="table-wrapper-responsive ">
                <table summary="Shopping cart" class="table-condensed">
                    <tr>
                        <th colspan="2" class="goods-page-image">Item Detail</th>                        
                        <th class="goods-page-quantity">Quantity</th>
                        <th class="goods-page-price">Unit price</th>
                        <th class="goods-page-total" colspan="2">Total</th>
                    </tr>';
                    $cart_data = $this->ci->cart->contents();
                    $this->ci->load->model("productm");
                    $this->ci->load->model("commonm");
                    $cart_total = $this->ci->cart->total();
                    $shipping_price = 0;
                    if($this->get_shipping_method() == "range"){
                    $shipping_price = $this->calculate_shipping($cart_total);
                    }
                    if($this->get_shipping_method() == "ups"){
                        $shipping_price = $this->get_session("ups_shipping_price");
                    }        
                    $grand_total = $cart_total;
                    
                    $required_date = array();
                    $shipping_warning = "";
                    foreach($cart_data as $items){
                        if(!in_array($items['rd'],$required_date)){
                            $required_date[] = $items['rd'];
                        }
                        $product_id = explode("-",$items['id']);
                        $product_id = $product_id[0];
                        $product_detail = $this->ci->productm->get_product_detail($product_id);
                        $product_detail = $product_detail[0];
                        $size_detail = "";
                        if($items['size'] > 0){
                            $size_detail = $this->ci->commonm->get_all("sizes",array("size_id"=>$items['size']));
                            if(count($size_detail) > 0){
                                $size_detail = $size_detail[0]->size; 
                            }
                        }
                        $get_cart_detail .= '
                        <tr id="'.$items['rowid'].'">
                            <td class="goods-page-image">
                                <a href="'.$this->get_product_detail_url($product_detail).'">
                                    <img width="75" src="'.$this->get_product_image($product_detail,'small').'" alt="'.$product_detail->product_name.'" />
                                </a>
                            </td>
                            <td class="goods-page-description">
                                <h3><a href="'.$this->get_product_detail_url($product_detail).'">'.$product_detail->product_name.'</a></h3>
                                <p><strong>Size:</strong> '.$size_detail.'</p>
                                <p><strong>Item Code:</strong> '.$product_detail->sku.'</p>';
                                $global_product_settings = $this->get_product_setting("show_social_widget",true);
                                if($global_product_settings->show_required_date == 1){
                                    $get_cart_detail .= '
                                    <p><strong>Required Date:</strong> <code>'.$items['rd'].'</code></p>';
                                }
                                if($global_product_settings->show_promising_date == 1){
                                    $get_cart_detail .= '
                                    <p><strong>Performance Date:</strong> '.$items['pd'].'</p>';
                                }
                                $get_cart_detail .= '        
                            </td>                            
                            <td class="goods-page-quantity">
                                <div class="product-quantity">';
                                    if($readonly){
                                        $get_cart_detail .= $items['qty'];
                                    }else{
                                        $get_cart_detail .= '<input id="product-quantity" data-id="'.$items['rowid'].'" type="text" value="'.$items['qty'].'" readonly class="form-control input-sm cart-qty">';
                                    }                                    
                                    $get_cart_detail .= '
                                </div>
                            </td>
                            <td class="goods-page-price">
                                <strong>'.$this->currency_price($items['price']).'</strong>
                            </td>
                            <td class="goods-page-total" id="cart-row-total-'.$items['rowid'].'">
                                <strong>'.$this->currency_price($items['price'] * $items['qty']).'</strong>
                            </td>';
                            if(!$readonly){
                                $get_cart_detail .= '
                                <td class="del-goods-col">
                                    <a class="move-to-wishlist fa-wishlist" data-id="'.$items['rowid'].'" href="#" data-toggle="tooltip" data-placement="top" title="Move to Wishlist"><i class="fa fa-star"></i></a>  
                                    <a class="del-goods remove-from-cart" data-id="'.$items['rowid'].'" href="'.site_url("cart/index/del/".$items['rowid']).'" data-toggle="tooltip" data-placement="top" title="Delete from Cart">&nbsp;</a>
                                </td>
                                ';
                            }
                            $get_cart_detail .= '
                        </tr>
                        ';
                    }                    
                    
                    $total_shipping_price = $shipping_price;
                    
                    if(count($required_date) > 1){
                        $total_shipping_price = $shipping_price * count($required_date);
                        $shipping_warning = "Shipping Price is <b>".$this->currency_price($shipping_price)."</b>, But you have choosen \"<b>".count($required_date)." Required Date\"</b>. So you will be charged shipping <b>".count($required_date)." times</b>";
                    }                    
                    if($this->get_session("coupon_code") != ""){
                        $promo_discount = $this->calculate_promo_discount($cart_total,$this->get_session("coupon_code"));
                    }
                    
                    $grand_total = ($cart_total + $total_shipping_price) - $promo_discount;
                    $get_cart_detail .= ' 
                </table>
            </div>
            <div class="shopping-total">
                <ul>
                    <li>
                        <em>Sub total</em>
                        <strong class="price cart-price-row">'.$this->currency_price($cart_total).'</strong>
                    </li>
                    <li>
                        <em>Shipping</em>
                        <strong class="price cart-price-row">'.count($required_date)." * ".$this->currency_price($shipping_price).' = '.$this->currency_price($shipping_price * count($required_date)).'</strong>
                        <div class="clearfix"></div>
                        ';
                        if($shipping_warning != ''){
                            $get_cart_detail .= "<br>".$this->render_messages($shipping_warning,"warning");
                        }
                        $get_cart_detail .= '  
                    </li>';
                    
                    if($promo_discount > 0){
                        $get_cart_detail .= '
                        <li>
                            <em>Discount</em>
                            <strong class="price cart-price-row">'.$this->currency_price($promo_discount).'</strong>
                        </li>';
                    }
                    
                    $get_cart_detail .= '
                    <li class="shopping-total-price">
                        <em>Total</em>
                        <strong class="price cart-price-row">'.$this->currency_price($grand_total).'</strong>
                    </li>
                </ul>
            </div>
            <div class="clearfix"></div>';
            if(!$readonly){
                $get_cart_detail .= '
                <a class="btn btn-default" href="'.site_url("cart").'">Continue shopping <i class="fa fa-shopping-cart"></i></a>
                <a class="btn btn-primary" href="'.site_url("cart/checkout").'">Checkout <i class="fa fa-check"></i></a>
                ';
            }
        }else{
            $get_cart_detail = $this->render_messages("Shopping cart is empty!","warning");
        }
        return $get_cart_detail;
        
    }
    
    function calculate_promo_discount($cart_total,$coupon_code){
        $this->ci->load->model("commonm");
        $coupon_detail = $this->ci->commonm->get_all("coupons",array("coupon_code" => $coupon_code,"is_active" => 1));        
        $coupon_detail = $coupon_detail[0];
        $discount_amount = $coupon_detail->discount_value; 
        if($coupon_detail->discount_percent == 1){            
            $discount_amount = ($coupon_detail->discount_value/100) * $cart_total;   
        }                              
        return $discount_amount;
    }
    
    function calculate_ups_shipping($postal_code,$total_weight,$selected=""){
        $service_array = array(
							   '03' => 'UPS Ground',
							   '12' => 'UPS Three-Day Select',
							   '02' => 'UPS Second Day Air',
							   '13' => 'UPS Next Day Air Saver',
							   '01' => 'UPS Next Day Air',
							   '14' => 'UPS Next Day Air Early A.M.',
							   '59' => 'UPS Second Day Air A.M.',
							   '65' => 'UPS Saver'
							   );
        $this->ci->load->library('upsrate');
		$this->ci->upsrate->setCredentials(UPS_ACCESSLICENSENUMBER, UPS_USERID, UPS_PASSWORD, UPS_SHIPPERNUMBER);
        $response = '<div class="radio-list">';
        $bServiceAvailable = false;
        foreach($service_array as $key => $value){
			$result[$key] = $this->ci->upsrate->getRate(UPS_POSTALCODE, $postal_code, $key, 0, 0, 0, $total_weight);                  
            if(!in_array('FALSE', $result)){                
                if(true){
                    $ups_error	= array();
                    $ups_error_des	= '';                                                        
                    
                    if(isset($result[$key]['RESPONSE']['ERROR'])){
                        $ups_error[] = '0';
                        $ups_error_des	= 'Error: '.$result[$key]['RESPONSE']['ERROR']['ERRORDESCRIPTION'].'<br />';
                    }
			        else{
			            $bServiceAvailable = true;
			            $service_price = $this->currency_price($result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']);
                        $services_list_html .= "<option data-price='".$result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']."' data-service='$value' data-days='".$result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY']."' value='{$key}'>{$value} - ".$service_price."</option>";
                        $checked = "";
                        if($selected == $value){
                            $checked = 'checked="checked"';
                        }
                        if($selected == "" && $checked == ""){ 
                            $checked = 'checked="checked"';
                        }                        
                        $response .= '
                        <label>
                            <input '.$checked.' type="radio" name="ups_shipping_service" value="'.$this->encode($result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']."~~".$value).'"  />&nbsp;&nbsp;'.$value.' ('.$result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY'].' Days) - <b>'.$service_price.'</b>
                        </label>';
			        }
                }
            }
        }
        if(!$bServiceAvailable){            
            $response .= $this->render_messages("Sorry, no service available at your address.<br /><br /><button class='btn btn-danger' type='button' data-toggle='collapse' data-parent='#checkout-page' data-target='#shipping-address-content'>Click here to change postal code...</button>","danger");
        }
        $response .= '</div>';
        return $response;
    }

    function calculate_shipping($total_price){
        $this->ci->load->model("checkoutm");
        $result = $this->ci->checkoutm->get_shipping_price($total_price);
        if(count($result) > 0){
            return $result[0]->shipping_price;
        }
        return 0;
    } 
    
    
    function get_cart_summary(){        
        $get_cart_detail = '
        <div class="top-cart-block">
            <div class="top-cart-info">
            <a href="javascript:void(0);" class="top-cart-info-count">'.$this->ci->cart->total_items().' item(s)</a>
            <a href="javascript:void(0);" class="top-cart-info-value">'.$this->currency_price($this->ci->cart->total()).'</a>
            </div>
            <i class="fa fa-shopping-cart"></i>';
            if($this->ci->cart->total_items() > 0){
                $get_cart_detail .= '
                <div class="top-cart-content-wrapper">
                    <div class="top-cart-content">
                        <ul class="scroller" style="height: 250px;">';
                            $cart_data = $this->ci->cart->contents();
                            $this->ci->load->model("productm");                                                    
                            foreach($cart_data as $items){
                                $product_id = explode("-",$items['id']);
                                $product_id = $product_id[0];
                                $product_detail = $this->ci->productm->get_product_detail($product_id);
                                $product_detail = $product_detail[0];
                                $get_cart_detail .= '
                                <li>
                                    <a href="'.$this->get_product_detail_url($product_detail).'">
                                    <img width="30" src="'.$this->get_product_image($product_detail,'small').'" class="img-responsive" alt="'.$product_detail->product_name.'" />                                    
                                    </a>
                                    <span class="cart-content-count">x '.$items['qty'].'</span>
                                    <strong><a href="'.$this->get_product_detail_url($product_detail).'">'.$this->str_limiter($product_detail->product_name,25).'</a></strong>
                                    <em>'.$this->currency_price($items['price'] * $items['qty']).'</em>
                                </li>';
                            }
                            $get_cart_detail .= '            
                        </ul>
                        <div class="text-right">
                            <a href="'.site_url("cart").'" class="btn btn-default">View Cart</a>
                            <a href="'.site_url("cart/checkout").'" class="btn btn-primary">Checkout</a>
                        </div>
                    </div>
                </div>';
            }
        $get_cart_detail .= '</div>';
        return $get_cart_detail;        
    }
    
    function get_user_wishlist(){
        $this->ci->load->model("productm");
        $this->ci->load->model("commonm");
        $wishlist_record = $this->ci->productm->get_user_wishlist($this->get_login_id());
        $wishlist_data = "";        
        foreach($wishlist_record as $items){        
            $product_id = $items->product_id;
            $product_detail = $this->ci->productm->get_product_detail($items->product_id);
            $product_detail = $product_detail[0];
            $size_detail = "";
            if($items->size_id > 0){
                $size_detail = $this->ci->commonm->get_all("sizes",array("size_id"=>$items->size_id));
                if(count($size_detail) > 0){
                    $size_detail = $size_detail[0]->size; 
                }
            }
            $wishlist_data .= '
            <tr id="'.$items->wishlist_id.'">
                <td class="goods-page-image">
                <a href="'.$this->get_product_detail_url($product_detail).'">
                    <img width="75" src="'.$this->get_product_image($product_detail,'small').'" alt="'.$product_detail->product_name.'" /></a>
                </td>
                <td class="goods-page-description">
                  <h3><a href="'.$this->get_product_detail_url($product_detail).'">'.$product_detail->product_name.'</a></h3>
                  <p><strong>Size:</strong> '.$size_detail.'</p>
                  <p><strong>Item Code:</strong> '.$product_detail->sku.'</p>
                  <!--em>More info is here</em-->
                </td>                            
                <td class="goods-page-quantity">
                  <div class="product-quantity">
                      '.$items->quantity.'
                  </div>
                </td>
                <td class="goods-page-price">
                  <strong>'.$this->currency_price($items->price).'</strong>
                </td>
                <td class="goods-page-total">
                    <a class="move-to-cart add-goods" data-id="'.$items->wishlist_id.'" href="#" data-toggle="tooltip" data-placement="top" title="Move to Cart"></a>  
                    <a class="del-goods remove-from-wishlist" data-id="'.$items->wishlist_id.'" href="#" data-toggle="tooltip" data-placement="top" title="Delete from WishList">&nbsp;</a>
                </td>                            
            </tr>';
        }
        return $wishlist_data;
    }
    
    function add_to_wish_list($cart_data,$user_id = 0){
        $wishlist_data = array();
        $product_id = explode("-",$cart_data['id']);
        $product_id = $product_id[0];
        $wishlist['product_id'] = $product_id;
        $wishlist['size_id'] = $cart_data['size'];
        $wishlist['quantity'] = $cart_data['qty'];
        if($user_id == 0){
            $user_id = $this->get_login_id();
        }
        $wishlist['user_id'] = $user_id;
        $this->ci->load->model("commonm");
        $this->ci->commonm->db_insert($wishlist,"wishlist");
    }
    
    function get_product_image_path($is_thumb=true){        
        return $this->ci->config->item("product_image_upload_path");
    }
    
    function get_product_noimage_path($is_thumb=true){        
        return $this->ci->config->item("product_noimage_path");
    }
    
    function get_product_tmp_image_path($is_thumb=false){
        $thumb_suffux = "";
        if($is_thumb){
            $thumb_suffux = "/thumbnail";
        }
        return $this->ci->config->item("product_tmp_upload_path").$thumb_suffux;
    }
    
    function get_product_enc_path($product_id,$thumb_type="default"){
        $string = md5($this->ci->config->item("encryption_key").$product_id);
        $folder_1 = substr($string,0,1);
        $folder_2 = substr($string,1,2);
        $product_folder = substr($product_id,0,1);
        $folder_path = $this->get_product_image_path()."/$folder_1/$folder_2/$product_folder";
        if(!is_dir($folder_path)){
            mkdir($folder_path,0777,true);    
        }
        
        if($thumb_type == "other"){
            $folder_path = $folder_path."/other-images";
            if(!is_dir($folder_path)){
                mkdir($folder_path);    
            }
            return $folder_path;
        }
        
        if($thumb_type == "other-thumb"){
            $folder_path = $folder_path."/other-images/thumb";
            if(!is_dir($folder_path)){
                mkdir($folder_path,0777,true);    
            }
            return $folder_path;
        }
        
        if($thumb_type == "large"){
            $folder_path = $folder_path."/large";
            if(!is_dir($folder_path)){
                mkdir($folder_path);    
            }
            return $folder_path;
        }
        
        if($thumb_type == "small"){
            $folder_path = $folder_path."/small-thumb";
            if(!is_dir($folder_path)){
                mkdir($folder_path);    
            }
            return $folder_path;
        }
        
        if($thumb_type == "medium"){
            $folder_path = $folder_path."/medium-thumb";
            if(!is_dir($folder_path)){
                mkdir($folder_path);    
            }
            return $folder_path;
        }         
        //$folder_path = $this->get_product_image_path()."/$folder_path";
        return $folder_path;
    }      
    
    function product_other_image_path($image_name,$product_id,$thumb_type="other"){                
        $image_path = base_url().$this->get_product_enc_path($product_id,$thumb_type)."/$image_name";
        return $image_path;    
    }
    
    function get_product_image($image_obj,$thumb_type="default"){
        $image_name = pathinfo($image_obj->thumb,PATHINFO_BASENAME);        
        $image_path = base_url().$this->get_product_enc_path($image_obj->product_id,$thumb_type)."/$image_name";        
        if(!is_file($this->get_product_enc_path($image_obj->product_id,$thumb_type)."/$image_name")){
            if($thumb_type == "small"){
                return base_url().$this->get_product_noimage_path()."/no_image_small.jpg";    
            }else{
                return base_url().$this->get_product_noimage_path()."/no_image_big.jpg";
            }            
        }
        return $image_path;    
    }
    
    function sanitize_imagename($name){
        $name = str_replace("(","",$name);
        $name = str_replace(")","",$name);
        //$name = str_replace(".","-",$name);
        $name = str_replace("/","",$name);
        $name = str_replace(" ","-",$name);
        return $name; 
    }
    
    function get_product_detail($product_id){
        $this->ci->load->model("productm");
        return $this->ci->productm->get_product_detail($product_id);
    }
    
    function get_detail_product_price($obj){
        $promo_price = $this->fSafeNum($obj->promo_price);
        $price = $this->fSafeNum($obj->price);
        if($obj->promo_price > 0){            
            $price_tag = "<span id='price-".$obj->product_id."'><strong>".$this->price_format($promo_price)."</strong> <em><span>".$this->price_format($price)."</span></em></span>";  
        }else{            
            $price_tag = "<span id='price-".$obj->product_id."'><strong>".$this->price_format($price)."</strong></span>";
        }
        return $price_tag;
    }
    
    function get_cal_price($obj){
        $promo_price = $this->fSafeNum($obj->promo_price);
        $price = $this->fSafeNum($obj->price);
        if($obj->promo_price > 0){
            return $promo_price;  
        }else{
            return $price; 
        }        
    }
    
    function get_product_price($obj,$currency=true,$prefix=""){
        $promo_price = $this->fSafeNum($obj->promo_price);
        $price = $this->fSafeNum($obj->price);
        if($obj->promo_price > 0){
            $price_tag = "<span id='{$prefix}price-".$obj->product_id."'><span class='strike'>".$this->price_format($price,$currency)."</span> <span class='pr-price'>".$this->price_format($promo_price)."</span></span>";  
        }else{
            $price_tag = "<span id='{$prefix}price-".$obj->product_id."'><span class='pr-price'>".$this->price_format($price,$currency)."</span></span>";
        }
        return $price_tag;
    }
    
    function price_format($price,$currency=true){
        if($currency)
            return $this->currency_price($price);
        else
            return number_format($price,2);
    }
    
    function currency_price($price){
        return "$".number_format($price,2);
    }
    
    function fSafeNum($num){
        if(is_numeric($num)){
            return $num;
        }else{
            return 0;
        }
    }
    
    function one_way_encrypt($string){        
        $enc_text = md5($this->ci->config->item("encryption_key").$string);
        $enc_text = $this->ci->encrypt->sha1($enc_text);
        return $enc_text;
    }
    
    function gen_security_token($string){
        return md5($this->ci->config->item("encryption_key").$string);
    }
    
    function encode($string){   
        $enc_text = base64_encode($string);
        $enc_text = $this->ci->encrypt->encode($enc_text);
        return $enc_text;
    }
    
    function decode($string){
        $dec_text = $this->ci->encrypt->decode($string);
        $dec_text = base64_decode($dec_text);        
        return $dec_text;
    }
    
    function get_post($post_name,$xss_filter=false){
        $val = $this->fSafeChar($this->ci->input->post($post_name,$xss_filter));
        return $val;
    }
    
    function get_n_post($post_name,$xss_filter=false){
        $val = $this->fSafeChar($this->ci->input->post($post_name,$xss_filter));
        $val - $this->fSafeNum($val);
        return $val;
    }
    
    function get_n_get($get_name,$xss_filter=false){
        $val = $this->fSafeChar($this->ci->input->get($get_name,$xss_filter));
        $val - $this->fSafeNum($val);
        return $val;
    }
    
    function get_get($get_name,$xss_filter=false){
        $val = $this->fSafeChar($this->ci->input->get($get_name,$xss_filter));
        return $val;
    }    
    
    function fSafeChar($string){
        $string = str_replace("'","\'",$string);
        return trim($string);
    }
    
    function processInput($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return strval($data);
    }
    
    function str_limiter($string,$limit=0){
        if($limit > 0){
            if(strlen($string) > $limit){
                return substr($string,0,$limit)."...";
            }            
        }
        return $string; 
    }
    
    function date_detail_format($timestamp = "",$isTimeStamp = true){
        if($timestamp == "") $timestamp = time();
        
        if(!$isTimeStamp) $timestamp = strtotime($timestamp);
        
        return date("l, F d, Y h:i:s A",$timestamp);
    }
    
    function date_display_format($timestamp = "",$isTimeStamp = true){
        if($timestamp == "") $timestamp = time();
        
        if(!$isTimeStamp) $timestamp = strtotime($timestamp);
        
        return date("F d, Y",$timestamp);
    }
    
    function jQueryDateFormat($timestamp = "",$isTimeStamp = true){
        if($timestamp == "") $timestamp = time();
        
        if(!$isTimeStamp) $timestamp = strtotime($timestamp);
        
        return date("m/d/y",$timestamp);
    }
    
    function mysqlDateFormat($timestamp = "",$isTimeStamp = true){
        if($timestamp == "") $timestamp = time();
        
        if(!$isTimeStamp) $timestamp = strtotime($timestamp);
        
        return date("Y-m-d H:i:s",$timestamp);
    }
    
    function get_sig(){
        
    }
    
    function set_session($data){
        $this->ci->session->set_userdata($data);
    }
    
    function get_session($session,$is_encode=false){
        if($is_encode){
            return $this->decode($this->ci->session->userdata($session));
        }
        return $this->ci->session->userdata($session);
    }
    
    function remove_session($session){
        $this->ci->session->unset_userdata($session);
    }
    
    function render_flash_session($session_name,$type="success"){
        if($this->get_session($session_name) != ""){
            echo $this->render_messages($this->get_session($session_name),$type);
            $this->remove_session($session_name);
        }
    }
    
    function render_messages($messages,$type="success",$bclose=false){
        if($messages != ""){
            $messages_html = '
            <div class="alert alert-dismissable alert-'.$type.'">
            	'.$messages;
                if($bclose){
                $messages_html .= 
                '<button aria-hidden="true" data-dismiss="alert" class="close" type="button">x</button>';
                }   
                $messages_html .= '
            </div>';
            return $messages_html;
        }
        return "";
    }
    
    function get_skip_pages(){
        $skip_pages = array("login","forgotpassword","register","user_exist","email_exist","logout","check_password","resetpassword");
        return $skip_pages;
    }
    
    function get_login_id(){
        $uid = $this->decode($this->get_session("sess_uid"));
        return $uid; 
    }
    
    function get_login_detail(){
        $uid = $this->decode($this->get_session("sess_uid"));
        if($this->fSafeNum($uid) > 0){
            $this->ci->load->model("userm");
            return $this->ci->userm->_getall($uid); 
        }else{
            $data = array(
			'user_id'       => 0,
			'company_name'	=> "",
			'last_login'	=> "",						  
			'username'	=> "",
			'first_name'	=> "",
                        'middle_name'	=> "",
                        'last_name'	=> "",
			'email'		=> "",						  						  						  
			'address'	=> "",
                        'address1'	=> "",
			'phone'         => "",
                        'mobile'	=> "",
			'city'		=> "",
			'state'		=> "",
			'country'		=> "",
			'zipcode'		=> "",
                        'shipping_first_name'	=> "",
                        'shipping_middle_name'	=> "",
                        'shipping_last_name'	=> "",						  						  						  						  
			'shipping_address'	=> "",
                        'shipping_address1'	=> "",
			'shipping_phone'	=> "",
                        'shipping_mobile'	=> "",
			'shipping_city'		=> "",
			'shipping_state'	=> "",
			'shipping_country'	=> "",
			'shipping_zipcode'	=> "",
			'is_active'		=> 0						  
			);
            return $data;
        }        
    }
    
    function get_login_name($login_data){
        return $login_data['first_name']." ".$login_data['middle_name']." ".$login_data['last_name'];       
    }
    
    function render_security(){
        $skip_pages = $this->get_skip_pages();
        $uid = $this->decode($this->get_session("sess_uid"));        
        $username = $this->decode($this->get_session("sess_username"));
        $sess_sig = $this->get_session("sess_signature");
        $current_sig = $this->encode($uid.$username);
        $doLogout = false;
        
        if($this->get_route_action() == "logout"){
            $this->do_logout();
            redirect("user/login");
            exit;
        }
        
        if($this->fSafeNum($uid) == 0){
            $doLogout = true;
        }else{
            if(in_array($this->get_route_action(),$skip_pages)){
                redirect("user/account");
                exit;
            }
        }        
        if($sess_sig != $current_sig && false){
            $doLogout = true;            
        }
        if($doLogout){
            if(!in_array($this->get_route_action(),$skip_pages)){                
                $this->do_logout();
                redirect("user/login");
                exit;
            }
        }        
    } 
    
    function get_route_action(){
        return $this->ci->router->fetch_method();
    }   
    
    function do_logout(){
        $this->remove_session("sess_uid");
        $this->remove_session("sess_username");
        $this->remove_session("sess_display_name");
        $this->remove_session("sess_lastlogin");
        $this->remove_session("sess_signature");
        $this->remove_session("sess_status");
    }
    
    function render_register_form_input($type='text',$label="",$name="",$required="",$default_value=""){
        $asterik = "";
        if($required != ""){
            $asterik = "<span class='require'>*</span>";
            $required = "$required=''";
        }
        $input_html = '
        <div class="form-group">
            <label for="rg_'.$name.'_input" class="col-lg-4 control-label">'.$label.' '.$asterik.'</label>
            <div class="col-lg-8">
              <input placeholder="'.$label.'" type="'.$type.'" class="form-control" id="rg_'.$name.'_input" name="rg_'.$name.'" '.$required.' value="'.set_value("rg_".$name,$default_value).'" />
            </div>
        </div>';
        return $input_html;
    }
    
    function render_checkout_form_input($type='text',$label="",$name="",$required="",$default_value=""){
        $asterik = "";
        if($required != ""){
            $asterik = "<span class='require'>*</span>";
            $required = "$required=''";
        }
        $input_html = '
        <div class="form-group">
            <label for="rg_'.$name.'_input" class="">'.$label.' '.$asterik.'</label>
            <div class="">
              <input placeholder="'.$label.'" type="'.$type.'" class="form-control" id="rg_'.$name.'_input" name="rg_'.$name.'" '.$required.' value="'.set_value("rg_".$name,$default_value).'" />
            </div>
        </div>';
        return $input_html;
    }
    
    function render_country_list($country_data,$name="country",$selected_id=""){
        $country_html = "<select class='form-control' name='rg_{$name}' id='rg_{$name}_input'>";
        foreach($country_data as $row){
            $selected = "";
            if($selected_id == $row->country_id){
                $selected = " selected='selected' ";
            }
            $country_html .= "<option $selected value='{$row->country_id}'>{$row->country}</option>";
        }
        $country_html .= "</select>";
        return $country_html;
    }
    
    function do_login($redirect = "user/account"){
        $this->ci->form_validation->set_rules('login_u_email', 'Username', 'trim|required');
        $this->ci->form_validation->set_rules('login_u_password', 'Password', 'trim|required');
        if($this->ci->form_validation->run()){
            $username = $this->get_post('login_u_email');
            $password = $this->get_post('login_u_password');            
            $password = $this->one_way_encrypt($password);            
            $this->ci->load->model('userm');
            $data = $this->ci->userm->_auth($username, $password);
            if( ($data['success'] == 'TRUE')){				
                $sdata = array(							  
                            'sess_username' => $this->encode($data['username']),                              
                            'sess_uid' => $this->encode($data['user_id']),
                            'sess_display_name' => $this->encode($data['display_name']),
                            'sess_lastlogin' => $data['lastlogin'],
                            'sess_signature' => $this->encode($data['uid'].$data['username'])
                            );
                $this->set_session($sdata);
                $this->ci->userm->_update($data['uid'], $data['lastlogin']);
                redirect($redirect);
                exit;
            }else{				
                $this->set_session(array("danger-msg" => "Invalid username or password.")); 
                return false;
            }                     
        }else{ 
            $this->set_session(array("danger-msg" => validation_errors()));	  
            return false;              
        }
    }
    
    function get_shipping_method(){
        return $this->ci->config->item("shipping_method");
    }
    
    function is_profile_detail_pending($user_login_detail){
        $validate_fields = array("first_name","last_name","mobile","address","country","state","city","zipcode");
        foreach($validate_fields as $fields){
            if($this->fSafeChar($user_login_detail[$fields]) == ""){
                return true;
            }    
        }
        return false;
    }
    
    function is_shipping_detail_pending($user_login_detail){
        $validate_fields = array("shipping_first_name","shipping_last_name","shipping_mobile","shipping_address","shipping_country","shipping_state","shipping_city","shipping_zipcode");
        foreach($validate_fields as $fields){
            if($this->fSafeChar($user_login_detail[$fields]) == ""){
                return true;
            }    
        }
        return false;
    }

    /**
     * run_payment_validation
     *
     * Validate user payment method selection at time of checkout
     * @param (boolean) (run_credit_card) if false will not validate user credit card detail
     * @return (boolean)
     */
    function run_payment_validation($run_credit_card = false){
        $this->ci->form_validation->set_rules('checkout_payment_method', 'Payment Method', 'trim|required|max_length[3]|xss_clean');
        if($run_credit_card){
            $this->ci->form_validation->set_rules('checkout_credit_card_number', 'Credit Card Number', 'trim|integer|min_length[16]|required|max_length[16]|xss_clean');
            $this->ci->form_validation->set_rules('checkout_cvv_number', 'Cvv Number', 'trim|integer|min_length[3]|required|max_length[4]|xss_clean');
            $this->ci->form_validation->set_rules('checkout_expiry_month', 'Expiry Month', 'trim|integer|min_length[2]|required|max_length[2]|xss_clean');            
            $this->ci->form_validation->set_rules('checkout_expiry_year', 'Expiry Year', 'trim|integer|min_length[4]|required|max_length[4]|xss_clean');
        }
        return $this->ci->form_validation->run();
    }
    
    /**
     * run_shipping_validation
     *
     * Validate user shipping/delievery address detail
     *     
     * @return (boolean)
     */
    function run_shipping_validation(){
        $this->ci->form_validation->set_rules('rg_s_first_name', 'First name', 'trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_last_name', 'Last name', 'trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_address', 'Address', 'trim|required|max_length[200]|xss_clean');                
        $this->ci->form_validation->set_rules('rg_s_mobile', 'Mobile', 'trim|required|min_length[10]|integer|max_length[12]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_country', 'Country', 'trim|required|numeric|max_length[4]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_state', 'State', 'trim|required|max_length[30]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_city', 'City', 'trim|required|max_length[30]|xss_clean');
        $this->ci->form_validation->set_rules('rg_s_zipcode', 'Zip Code', 'trim|required|numeric|max_length[10]|xss_clean');
        return $this->ci->form_validation->run();
    }
    
    /**
     * run_profile_validation
     *
     * Validate user profile detail
     *
     * @param (boolean) (b_run_address_validation) if false will not validate user address detail
     * @return (boolean)
     */
    function run_profile_validation($b_run_address_validation = true){
        $this->ci->form_validation->set_rules('rg_first_name', 'First name', 'trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('rg_last_name', 'Last name', 'trim|required|max_length[40]|xss_clean');
        $this->ci->form_validation->set_rules('rg_email', 'Email', 'valid_email|trim|required|max_length[40]|xss_clean|callback_email_exist');
        if($b_run_address_validation){
            $this->ci->form_validation->set_rules('rg_address', 'Address', 'trim|required|max_length[200]|xss_clean');                
            $this->ci->form_validation->set_rules('rg_mobile', 'Mobile', 'trim|required|min_length[10]|integer|max_length[12]|xss_clean');
            $this->ci->form_validation->set_rules('rg_country', 'Country', 'trim|required|numeric|max_length[4]|xss_clean');
            $this->ci->form_validation->set_rules('rg_state', 'State', 'trim|required|max_length[30]|xss_clean');
            $this->ci->form_validation->set_rules('rg_city', 'City', 'trim|required|max_length[30]|xss_clean');
            $this->ci->form_validation->set_rules('rg_zipcode', 'Zip Code', 'trim|required|numeric|max_length[10]|xss_clean');
        }        
        return $this->ci->form_validation->run();
    }
    
    /**
     * run_register_validation
     *
     * Validate user registration detail
     *
     * @param (boolean) (validate_login_detail) if false will not validate user login detail
     * @param (boolean) (b_run_address_validation) if false will not validate user address detail
     * @return (boolean)
     */ 
    function run_register_validation($validate_login_detail = false,$b_run_address_validation = true){
        if($validate_login_detail){
            $this->ci->form_validation->set_rules('rg_username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[15]|callback_user_exist|xss_clean');
            $this->ci->form_validation->set_rules('rg_password', 'Password', 'trim|required|min_length[5]|max_length[15]|matches[rg_cpassword]|xss_clean');
            $this->ci->form_validation->set_rules('rg_cpassword', 'Confirm Password', 'trim|required|min_length[5]|max_length[15]|xss_clean');            
        }
        return $this->run_profile_validation($b_run_address_validation);
    }
    
    
    /**
     * user_form_shipping_fields
     *
     * Fetch user shipping related fields from form post and return as array
     *
     * @param (boolean) ($order_form) will return order detail related array if true
     * @return (array)
     */ 
    function user_form_shipping_fields($order_form=false){
        
        $first_name = $this->get_post('rg_s_first_name',true);
        $last_name = $this->get_post('rg_s_last_name',true);
        $middle_name = $this->get_post('rg_s_middle_name',true);
        $country = $this->get_n_post('rg_s_country',true);
        $state = $this->get_post('rg_s_state',true);
        $city = $this->get_post('rg_s_city',true);
        $mobile = $this->get_post('rg_s_mobile',true);
        $zipcode = $this->get_n_post('rg_s_zipcode',true);
        $company = $this->get_post('rg_s_company',true);
        $phone = $this->get_n_post('rg_s_phone',true);
        $fax = $this->get_post('rg_s_fax',true);
        $company_name = $this->get_post('rg_s_company_name',true);
        $address = $this->get_post('rg_s_address',true);
        $address1 = $this->get_post('rg_s_address1',true);
        
        $user_data = array();
        
        $prefix = "shipping";
        if($order_form){
            $prefix = "ship";
        }
        
        $user_data[$prefix.'_first_name'] = $first_name;
        $user_data[$prefix.'_middle_name'] = $middle_name;
        $user_data[$prefix.'_last_name'] = $last_name;            
        $user_data[$prefix.'_zipcode'] = $zipcode;
        $user_data[$prefix.'_country'] = $country;
        $user_data[$prefix.'_state'] = $state;
        $user_data[$prefix.'_city'] = $city;
        $user_data[$prefix.'_phone'] = $phone;
        $user_data[$prefix.'_mobile'] = $mobile;
        $user_data[$prefix.'_fax'] = $fax;
        $user_data[$prefix.'_address'] = $address;
        $user_data[$prefix.'_address1'] = $address1;
        return $user_data;
    }
    
    /**
     * user_form_personal_fields
     *
     * Fetch user personal data fields from form post and return as array
     *
     * @param (boolean) (return_same_shipping) will return same shipping detail as personal detail if true
     * @return (array)
     */
    function user_form_personal_fields($return_same_shipping = false){
        $email = $this->get_post('rg_email',true);
        $first_name = $this->get_post('rg_first_name',true);
        $last_name = $this->get_post('rg_last_name',true);
        $middle_name = $this->get_post('rg_middle_name',true);
        $country = $this->get_n_post('rg_country',true);
        $state = $this->get_post('rg_state',true);
        $city = $this->get_post('rg_city',true);
        $mobile = $this->get_post('rg_mobile',true);
        $zipcode = $this->get_n_post('rg_zipcode',true);
        $company = $this->get_post('rg_company',true);
        $phone = $this->get_n_post('rg_phone',true);
        $fax = $this->get_post('rg_fax',true);
        $company_name = $this->get_post('rg_company_name',true);
        $address = $this->get_post('rg_address',true);
        $address1 = $this->get_post('rg_address1',true);
        
        $user_data = array();
                
        $user_data['first_name'] = $first_name;
        $user_data['middle_name'] = $middle_name;
        $user_data['last_name'] = $last_name;
        $user_data['email'] = $email;
        $user_data['zipcode'] = $zipcode;
        $user_data['country'] = $country;
        $user_data['state'] = $state;
        $user_data['city'] = $city;
        $user_data['phone'] = $phone;
        $user_data['mobile'] = $mobile;
        $user_data['fax'] = $fax;
        $user_data['address'] = $address;
        $user_data['address1'] = $address1;
        $user_data['company_name'] = $company_name;
        
        if($return_same_shipping){
            $user_data['shipping_first_name'] = $first_name;
            $user_data['shipping_middle_name'] = $middle_name;
            $user_data['shipping_last_name'] = $last_name;            
            $user_data['shipping_zipcode'] = $zipcode;
            $user_data['shipping_country'] = $country;
            $user_data['shipping_state'] = $state;
            $user_data['shipping_city'] = $city;
            $user_data['shipping_phone'] = $phone;
            $user_data['shipping_mobile'] = $mobile;
            $user_data['shipping_fax'] = $fax;
            $user_data['shipping_address'] = $address;
            $user_data['shipping_address1'] = $address1;
        }
        
        return $user_data;
    }
    
    function check_user_exist($str){
        $this->ci->load->model("userm");
        if($this->ci->userm->_is_exists($str)){
            $this->ci->form_validation->set_message('user_exist', '%s <b>'.$str.'</b> already taken!');
            return false;
        }else{
            return true;    
        }      
    }
    
    public function check_email_exist($str){
		$this->ci->load->model("userm");
        if($this->ci->userm->_is_exists($str,"email")){
            $login_user_detail = $this->get_login_detail();
            if($login_user_detail['email'] != "" && $str == $login_user_detail['email']){
                return true;
            }
            $this->ci->form_validation->set_message('email_exist', '%s <b>'.$str.'</b> already taken!');
            return false;
        }else{
            return true;    
        }
	}
    
    public function checkout_validation($shipping = ""){
        //if()
    } 
    
    public function get_product_size_stock($product_id){
        $this->ci->load->model("productm");        
        $result = $this->ci->productm->get_size_stock($product_id);
        if(count($result) > 0){
            return $result[0]->size_stock;
        }else{
            return 0;
        }
        exit;
    }
    
    public function get_product_sizes_list($product_id = 0,$show_inventory_level = 0,$do_inventory_check = 0,$selected_id = ""){        
        $this->ci->load->model("productm");
        $rs_size_list = $this->ci->productm->get_all_sizes();        
        $product_sizes = $this->ci->productm->get_product_sizes($product_id);
        $size_list = "";
        $size_list .= '<div class="btn-group" data-toggle="buttons">';
        $required_stock = 99;
        $required_class = "";
        foreach($rs_size_list as $row){
            if(isset($product_sizes[$row->size_id])){
                if($product_sizes[$row->size_id]->active == 1){
                    $required_class = "";
                    $active_class = "";
                    $active_checked = "";                    
                    if($selected_id == ""){
                        $selected_id = $row->size_id;
                    }
                    if($selected_id == $row->size_id){
                        $active_class = "active";
                        $active_checked = "checked";                        
                        if($do_inventory_check == 1){
                            $required_stock = $product_sizes[$row->size_id]->stock_available;
                        }
                    }
                    $data_toggle = "";
                    
                    if($show_inventory_level == 1){
                        $data_toggle = ' data-id="'.$product_id.'" data-html="true" data-toggle="tooltip" title="'.$product_sizes[$row->size_id]->stock_available.' Available"';
                    }
                    
                    $global_product_setting = $this->get_product_setting("check_live_inventory",true);
                        
                    
                    if($global_product_setting->check_live_inventory == 1){                    
                        if($do_inventory_check == 1){
                            $required_class = " vsz ";
                            $data_toggle .= ' data-vsz="'.$product_sizes[$row->size_id]->stock_available.'" ';
                            
                        }
                    }
                    
                    $hide_size = false;
                    if($global_product_setting->check_live_inventory == 1 && $product_sizes[$row->size_id]->stock_available == 0){
                        $hide_size = true;
                    }
                    
                    $stock_price = $product_sizes[$row->size_id]->stock_price;
                    if($product_sizes[$row->size_id]->stock_discounted_price > 0){
                        $stock_price = $product_sizes[$row->size_id]->stock_discounted_price;
                    }
                    
                    if(!$hide_size){
                        $size_list .= '
                        <span class="btn btn-primary sizes_block '.$active_class.$required_class.'" '.$data_toggle.'>
                            <input data-ref="'.$product_id.'" type="radio" class="cart-size-input size_id size-'.$product_id.'" name="size-of-item" data-sku="'.$product_sizes[$row->size_id]->size_sku.'" data-price="'.$this->currency_price($stock_price).'" id="size-'.$product_id.'" autocomplete="off" value="'.$this->encode($row->size_id).'" '.$active_checked.'> '.$row->size.'
                        </span>';
                    }                    
                }
            }
        }
        $size_list .= '</div>';
        $size_list .= '<script>$(function(){renderTouchSpin('.$required_stock.',"#product-quantity-'.$product_id.'");});</script><input type="hidden" id="ref-size-'.$product_id.'" value="'.$required_stock.'" />';
        return $size_list;
    }
    
    public function get_product_grid_sizes_list($product_id = 0,$show_inventory_level = 0,$do_inventory_check = 0){
        $this->ci->load->model("productm");
        $rs_size_list = $this->ci->productm->get_all_sizes();        
        $product_sizes = $this->ci->productm->get_product_sizes($product_id);
        $size_list = "";
        
        $size_list .= '<form class="form-inline">';
        $size_list .= '<div class="row size-grid">';
        foreach($rs_size_list as $row){
            if(isset($product_sizes[$row->size_id])){
                if($product_sizes[$row->size_id]->active == 1){
                    
                    $data_stock = "";   
                    $data_toggle = '';
                    $data_max = '';
                    $data_validate_class = '';
                    if($show_inventory_level == 1){
                        $data_stock = '<div class="input-group-addon">'.$product_sizes[$row->size_id]->stock_available.'</div>';
                        $data_toggle = 'data-toggle="tooltip" title="'.$product_sizes[$row->size_id]->stock_available.' Available"';
                        $data_max = 'data-max="'.$product_sizes[$row->size_id]->stock_available.'"';
                        $data_validate_class = "bulk_input";
                    }
                    
                    $size_list .= '
                    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-4">
                        <div class="form-group">
                            <div class="input-group" '.$data_toggle.'>
                                <div class="input-group-addon">'.$row->size.'</div>
                                <input class="form-control '.$data_validate_class.' size-bulk-'.$product_id.'" '.$data_max.' data-size="'.$this->encode($row->size_id).'" data-price="'.$product_sizes[$row->size_id]->stock_price.'" type="text" placeholder="Qty">
                                '.$data_stock.'
                            </div>
                        </div>
                    </div>';
                }
            }
        }
        $size_list .= '<div class="clearfix"></div></div>';
        $size_list .= '</form>';
        return $size_list;
    }
    
    public function get_admin_heading_from_url(){
        
    }
    
    public function render_dropdown($dataObj,$value_field,$name_field,$field_name,$selected="",$custom_label=""){
        
        $select_box = "";
        if($custom_label == ""){
            $custom_label = $this->get_display_string(str_replace("_"," ",$field_name));
        }
        $select_box .= "<select name='$field_name' id='$field_name' class='form-control'>";
        $select_box .= "<option value=''>Select ".$custom_label."</option>";
        foreach($dataObj as $row){
            $selected_option = "";
            if($selected == $row->$value_field){
                $selected_option = "selected='selected'";
            }
            $select_box .= "<option $selected_option value='{$row->$value_field}'>{$row->$name_field}</option>";
        }
        $select_box .= "</select>";
        return $select_box;
    }
    
    public function get_all_status() {
        $this->ci->load->model("commonm");
        return $this->ci->commonm->get_all("order_status");        
    }
    
    public function get_catalog_pages(){
        $this->ci->load->model("commonm");
        $catalog = $this->ci->commonm->get_all("catalog_images");
        return $catalog;
    }
    
    public function get_seller_cities(){
        $this->ci->load->model("commonm");
        $seller_cities = $this->ci->commonm->get_all("seller_cities");        
        return $seller_cities;
    }
    
    public function get_seller_city_id(){
        return $this->fSafeNum($this->decode(urldecode($this->ci->input->cookie("seller_city"))));
    }
    
    public function get_main_navigation(){
        $this->ci->load->model("commonm");
        $main_navigation = $this->ci->commonm->get_all("main_navigation");        
        return $main_navigation;
    }
    
    public function get_main_sliders(){
        $this->ci->load->model("commonm");
        $featured_slider = $this->ci->commonm->get_all("featured_slider");        
        return $featured_slider;
    }
     public function get_main_testimonials(){
        $this->ci->load->model("commonm");
        $testimonials = $this->ci->commonm->get_all("testimonials");        
        return $testimonials;
    }
    
}

?>

@KyuuKazami