<?php 
// Check Selected Category is a Gift Certicate or not
function CheckGiftCertificateCategory($gcatid) {
    
     include "../includes/config.php";  

    $select_gift_cat="SELECT gift_certificate_flag
							   FROM ".$tableprefix."categories
							   where category_id='".mysql_real_escape_string($gcatid)."' ";

    $rs_gift_cat= mysql_query($select_gift_cat) or die(mysql_error);
    if(mysql_num_rows($rs_gift_cat) > 0) {
        $giftRow=mysql_fetch_assoc($rs_gift_cat);
    }

    return $giftRow['gift_certificate_flag'];

} // end shipping method

/*----------function to display the content management details----------*/

function displayCMS($cms_name) {
    include "../includes/config.php"; 
    $path = $rootserver."/images/";

    $cms_array = array();

    $select_cms = "SELECT content_heading,content_text FROM ".$tableprefix."content_management
				   WHERE content_name = '".$cms_name."'";
    
    $result_cms = mysql_query($select_cms);
    if(mysql_num_rows($result_cms) > 0) {

        $cms_row = mysql_fetch_assoc($result_cms);
        array_push($cms_array,$cms_row['content_heading'],$cms_row['content_text']);

    }

    return $cms_array;
}

function getShippingMethods(){
    include "../includes/config.php"; 
    $path = $rootserver."/images/";
    $sql = "SELECT * FROM " . $tableprefix . "settings ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $row = mysql_fetch_array($result);        
        $arrShipping[0]['name'] = "Fedex Express Ground Shipping ";
        $arrShipping[0]['mode'] = ($row['enable_fedexshipping']=="FDXG")?"Y":"N";
        $arrShipping[0]['code'] = "FDXG";
        $arrShipping[0]['img'] = $path."fedex.gif";
        
        $arrShipping[1]['name'] = "UPS Shipping ";
        $arrShipping[1]['mode'] = $row['enable_shipping'];
        $arrShipping[1]['code'] = "UPS";
        $arrShipping[1]['img']  = $path."ups.gif";   
        
        $arrShipping[2]['name'] = "USPS Shipping ";
        $arrShipping[2]['mode'] = $row['enable_uspsshipping'];
        $arrShipping[2]['code'] = "USPS";
        $arrShipping[2]['img']  = $path."usps.gif";
        
        $arrShipping[3]['name'] = "Canada Post Shipping";
        $arrShipping[3]['mode'] = $row['enable_canadapost'];
        $arrShipping[3]['code'] = "CP";
        $arrShipping[3]['img']  = $path."canadapost.gif";
        
        $arrShipping[4]['name'] = "Australia Post Shipping ";
        $arrShipping[4]['mode'] = $row['enable_australiapost'];
        $arrShipping[4]['code'] = "AP";
        $arrShipping[4]['img']  = $path."australiapost.jpg";
        
        $arrShipping[4]['name'] = "Flat Rate";
        $arrShipping[4]['mode'] = $row['enable_flatrate'];
        $arrShipping[4]['code'] = "Flat Rate";
        $arrShipping[4]['img']  = "";
    }
    return $arrShipping;
}

function randomDigitalProduct() {
    include "../includes/config.php"; 

    $string = "";
    $possible_charactors = "PaNbIuJcMOfgnTopRUjkXlSmFxGqrdeKsLvzAwyBZDtEhiHQVWCY";

    while(strlen($string)<2) {
        $string .= substr($possible_charactors, rand()%(strlen($possible_charactors)),2);
    }
    $string .=	gmdate("mdYHis").substr(microtime(),2,6);
    $string	=	str_replace("-","",$string);
    $string	=	str_replace(":","",$string);
    $string	=	str_replace(" ","",$string);

    $select_digital_product = "SELECT ndigital_id FROM ".$tableprefix."digital_product WHERE vdigital_product_name = '".$string."'";
    $result_digital_product = mysql_query($select_digital_product);
    if(mysql_num_rows($result_digital_product) > 0) {
        $string = randomKey();
    }

    return($string);
}

function adjustStock($userid, $mode) {
    include "../includes/config.php"; 
    include_once('../classes/cls_cart.php');
    $sql = "SELECT * FROM " . $tableprefix . "cart WHERE user_id = '" . addslashes($userid) . "' ";
    
    $result = mysql_query($sql);
    $parr = array();
    $itemcount = 0;
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {
            $parr[$itemcount]["cartid"] = $row["cart_id"];
            $parr[$itemcount]["productid"] = $row["product_id"];
            $parr[$itemcount]["product_option_id"] = $row["product_option_id"];
            $parr[$itemcount]["quantity"] = $row["quantity"];
            $itemcount++;
        }
    }

    $stockadjusted = false;
    for($i = 0; $i < $itemcount;$i++) {
        $cartid = $parr[$i]["cartid"];
        $productid = $parr[$i]["productid"];
        $product_option_id = $parr[$i]["product_option_id"];
        $value = $parr[$i]["quantity"];
        $qtyavailable = getProductStock($product_option_id);
      
        if ($mode == "+") {
            $newstock = $qtyavailable + $value;
            $sqlstatus = "UPDATE  " . $tableprefix . "product_options SET product_stock='".$newstock."' WHERE product_option_id = '" . addslashes($product_option_id) . "' ";
        } else if ($mode == "-") {
            $newstock = $qtyavailable - $value;
            $sqlstatus = "UPDATE  " . $tableprefix . "product_options SET product_stock='".$newstock."' WHERE product_option_id = '" . addslashes($product_option_id) . "' ";
        }

        mysql_query($sqlstatus) ;


        //*****************************Multicart3.0 Scalability  Update Product main stock

        $cartqtyobj    =    Cart::getCartItemQuantity($userid);

        if(!empty($cartqtyobj))
            {
                   foreach($cartqtyobj as $cartVals)
                        {
                            $item_id        =    $cartVals->product_id;
                            $item_qty       =    $cartVals->cartQuantity;
                            $data           =   Products::updateProduct_Stock($item_id,$item_qty,$tableprefix);
                        }
            }
      //*****************************Multicart3.0 Scalability  End Update Product main stock

    }



    return $stockadjusted;
}

function emptyCart($userid) {
    include "../includes/config.php"; 
    $sql = "DELETE FROM " . $tableprefix . "cart  WHERE user_id = '" . $userid . "' ";
    $result = mysql_query($sql);
    return;
}

function getClientIP() {
    // Get REMOTE_ADDR as the Client IP.
    $client_ip = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : $REMOTE_ADDR);
    // Check for headers used by proxy servers to send the Client IP. We should look for HTTP_CLIENT_IP before HTTP_X_FORWARDED_FOR.
    if ($_SERVER["HTTP_CLIENT_IP"])
        $proxy_ip = $_SERVER["HTTP_CLIENT_IP"];
    elseif ($_SERVER["HTTP_X_FORWARDED_FOR"])
        $proxy_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    // Proxy is used, see if the specified Client IP is valid. Sometimes it's 10.x.x.x or 127.x.x.x... Just making sure.
    if ($proxy_ip) {
        if (preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $proxy_ip, $ip_list)) {
            $private_ip = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.16\..*/', '/^10.\.*/', '/^224.\.*/', '/^240.\.*/');
            $client_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
        }
    }
    // Return the Client IP.
    return $client_ip;
}

function sendStockreordermail($product_option_id,$quantity=0) {
    include "../includes/config.php"; 

    $queryOrderDetail = "SELECT p.*,s.*,po.product_stock
                                    FROM ".$tableprefix."product_options po
                                    INNER JOIN ".$tableprefix."products p ON p.product_id = po.product_id
                                    INNER JOIN ".$tableprefix."artists s ON s.artist_id = p.product_artist_id
                                    WHERE po.product_option_id=".$product_option_id." ";
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $optionVal = getProductOptionsName($product_option_id);



    if(mysql_num_rows($orderDetailQ)>0) {

        $productObj=mysql_fetch_object($orderDetailQ);

        $currentStock	= $productObj->product_stock-$quantity;

        $mailcontent='<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_STOCK_RE_ORDER_INFO.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailcontent .= '<tr>
		<td >'.MAIL_ORDER_TEXT_PRODUCT_NAME.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.stripslashes($productObj->product_name)." ".$optionVal.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_STOCK_RE_ORDER_CURRENT_STOCK.' </td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currentStock.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr></table>';

        $mailcontent_reorder = readEmailTemplate('stock_reorder');
        $mailcontent_reorder = str_replace('[product_details]',$mailcontent,$mailcontent_reorder);

        //   echo $mailcontent_reorder;



        $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA" >
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td bgcolor="#EAEAEA" ><img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
			<tr>
			<td align="left" height="50"> '.MAIL_ORDER_TEXT_DEAR.' '.$productObj->first_name.'&nbsp;'.$productObj->last_name.', </td>
			<tr>
			<tr>
			<td align="left">'.MAIL_STOCK_RE_ORDER_NOTE.' - '.SITE_NAME.'. '.MAIL_ORDER_TEXT_THE_DETAILS_ARE_AS_FOLLOWS.'</td>
			</tr>

			<tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left">'.$mailcontent_reorder.'</td>
                </tr>

              </table></td>
            </tr>

            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>
</body>
</html>';

        // echo $mail_send_details_seller;
        $headers  = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
        $headers .= "Organization: ".SITE_NAME."\r\n";
        $ordersubject_fillstock = MAIL_STOCK_RE_ORDER_SUBJECT." ".SITE_NAME;
        //echo $productObj->email;
        //$productObj->email="asha.s@armiasystems.com";

        $mailsent = mail($productObj->email,$ordersubject_fillstock,$mail_send_details_seller,$headers);


    }

    //$productlist_fillstock

}
/*function to check whether shipping is enabled or not*/

function checkShippingEnable() {
    include "../includes/config.php"; 
    
    $shippingmode   = 'N';

    $select_settings = "SELECT * FROM ".$tableprefix."settings WHERE 1";
    $result_settings = mysql_query($select_settings) or die(mysql_error());
    $row = mysql_fetch_assoc($result_settings);
    $fedexmode = $row['enable_fedexshipping'];
    $upsmode = $row['enable_shipping'];
    $uspsmode = $row['enable_uspsshipping'];
    $canadapost = $row['enable_canadapost'];
    $australiapost = $row['enable_australiapost'];
    $flatrate = $row['enable_flatrate'];
   if ($upsmode != 'N' || $fedexmode != 'N' || $uspsmode != 'N' || $canadapost != 'N' || $australiapost != 'N' || $flatrate == "Y") { // check whether shipping Enabled or Not
        $shippingmode = "Y";
} // end Shipping Check
    
    return $shippingmode;
}


function getCartTotal($userid) {
    include "../includes/config.php";  

    $sql = "SELECT c.*, (p.product_price+po.additional_price) AS product_price,p.product_artist_id,po.discount
           FROM " . $tableprefix . "cart c
           INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
           INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
           WHERE c.user_id = '" . addslashes($userid) . "' ";
    $result = mysql_query($sql);
    $total = 0;
    $itemcount = 0;
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {
            $converted_price 	= 	$row['product_price'] ;

            $converted_price =	number_format($converted_price,2,".","");

            $rate			  = $converted_price;


            $qty = $row["quantity"];
            $price = $qty * $rate;
            $discountstr="";
            $discountprice =0;
            if($row["discount"] !="0") {
                $price = number_format($price, 2, ".", "");
                $discountprice = $rate - ($rate * $row["discount"]) / 100;
                $discountprice = number_format($discountprice, 2, ".", "");
                $discountrate = ($discountprice * $qty);
                $price = $discountrate;
            }
            $total += $price;
        }
    }
    return $total;
}

function getProductStock($poId) {
     include "../includes/config.php";  
    $sql = "SELECT product_stock
        FROM " . $tableprefix . "product_options where product_option_id = '" . $poId . "' ";

    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $rw = mysql_fetch_array($result);
        return $rw["product_stock"];
    }
    return 0;
}

function isValidEmail($email) {
    $email = trim($email);
    if ($email == "") {
        return false;
    }
    if (!eregi("^" . "[a-z0-9]+([_\\.-][a-z0-9]+)*" . // user
    "@" . "([a-z0-9]+([\.-][a-z0-9]+)*)+" . // domain
    "\\.[a-z]{2,}" . // sld, tld
    "$", $email, $regs)) {
        return false;
    } else {
        return true;
    }
}

function getOrderStatus($oid) {
    include "../includes/config.php";  
    $cnt = 0;
    $statuses = array();
    $sql = "SELECT s.order_status FROM " . $tableprefix . "order_details od
            INNER JOIN " . $tableprefix . "order_status s ON od.item_status = s.order_status_id
            WHERE order_id = '" . addslashes($oid) . "' ";
    $resoptions = mysql_query($sql);
    // echo $sql;
    if (mysql_num_rows($resoptions) > 0) {
        while ($rw = mysql_fetch_array($resoptions)) {
            $statuses[$cnt] = $rw["order_status"];
            $cnt++;
        }
    }
    $statuses = array_unique(array_values($statuses));
    if (count($statuses) == 1) {
        return $statuses[0];
    } else {
        $status = implode(" / ", $statuses);
        return $status;
    }
}

function checkProductType($product_id) {
    include "../includes/config.php";  
    $cnt = 0;
    $statuses = array();
    $sql = "SELECT vdigital_product FROM " . $tableprefix . "products
            WHERE product_id = '" . $product_id . "' ";
    $resoptions = mysql_query($sql);    
    if (mysql_num_rows($resoptions) > 0) {
        $res=mysql_fetch_row($resoptions);
        return $res[0];       
    }else {        
        return "";
    }
}

function getShippingTotal($order_id) {
    include "../includes/config.php";      
    $sql = "SELECT SUM(nshipping_cost) FROM " . $tableprefix . "shipping_details
            WHERE norder_id = '" . $order_id . "' ";
    $result = mysql_query($sql);    
    if (mysql_num_rows($result) > 0) {
        $res=mysql_fetch_row($result);        
        return $res[0];       
    }else {        
        return "";
    }
}

function getOrderArtists($oid) {
    include "../includes/config.php";  
    $artists = array();
    $cnt = 0;

    $sql = " SELECT artist_id FROM " . $tableprefix . "order_details WHERE order_id = '" . addslashes($oid) . "' ";
    
    $resoptions = mysql_query($sql);
    if (mysql_num_rows($resoptions) > 0) {
        while ($rw = mysql_fetch_array($resoptions)) {
            $artists[$cnt] = $rw["artist_id"];
            $cnt++;
        }
    }
    
    // $artists = array_unique(array_values($artists));
    $artists = array_unique($artists);    
    return implode(",", $artists);
}

function getArtistCompanyName($sid) {
    include "../includes/config.php";  
    $sql = "SELECT company FROM `" . $tableprefix . "artists` where artist_id = '" . $sid . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $rw = mysql_fetch_array($result);
        return $rw["company"];
    }
    return "";
}

function dateFormat($input_date, $input_format, $output_format) {

    @preg_match("/^([\w]*)/i", $input_date, $regs);
    $sep = @substr($input_date, strlen($regs[0]), 1);
    $label = @explode($sep, $input_format);
    $value = @explode($sep, $input_date);
    $array_date = @array_combine($label, $value);
    if (@in_array('Y', $label)) {
        $year = $array_date['Y'];
    } elseif (@in_array('y', $label)) {
        $year = $year = $array_date['y'];
    } else {
        return false;
    }

    $output_date = @date($output_format, @mktime(0, 0, 0, $array_date['m'], $array_date['d'], $year));
    return $output_date;
}

function getProductOptionsName($productOptionId,$arr=array()) {
    include "../includes/config.php";  
    $option .= "";
    $query_available_options = "SELECT GROUP_CONCAT(concat(o.option_name, '-', pov.value) ORDER BY o.option_name ASC SEPARATOR ', ') AS option_val FROM ".$tableprefix."product_option_values pov
	INNER JOIN ".$tableprefix."options o ON o.option_id = pov.option_id WHERE pov.product_option_id = '".$productOptionId."' ORDER BY o.option_name";
    $query_available_optionsQ = mysql_query($query_available_options);
    while($product_options_val_obj = mysql_fetch_object($query_available_optionsQ)) {
        $option .= $product_options_val_obj->option_val;
    }

    return $option;
}

function checkSellerStock($product_option_id,$quantity=0) {
    include "../includes/config.php";  

    $queryStockDetail = "SELECT po.product_stock,po.reorder_level
  						FROM ".$tableprefix."product_options po
						WHERE po.product_option_id=".$product_option_id." ";
    $stockDetailQ     = mysql_query($queryStockDetail);

    $reorderStatus=0;
    if(mysql_num_rows($stockDetailQ)>0) {
        $rowObj=mysql_fetch_object($stockDetailQ);
        $productstock=$rowObj->product_stock;
        $newStock	= $productstock -$quantity;
        $reorderlevel=$rowObj->reorder_level;
        if($newStock<=$reorderlevel) {
            $reorderStatus=1;
        }
    }

    return $reorderStatus;
}


function count_digit($number) {
    return  strlen((string) $number);
}

//--Get State Country from Code--//
function getCodeValue($code,$flag,$countryCode=NULL){
// Flag 1 - country, 2-state, 3-complete country list, 4-State list for corresponding country
// countryCode is required for fetching state, not mandatory for fetching country
$country = array("AF"=>"Afghanistan",
    "AL"=>"Albania",
    "DZ"=>"Algeria",
    "AS"=>"American Samoa",
    "AD"=>"Andorra",
    "AO"=>"Angola",
    "AI"=>"Anguilla",
    "AQ"=>"Antarctica",
    "AG"=>"Antigua and Barbuda",
    "AR"=>"Argentina",
    "AM"=>"Armenia",
    "AW"=>"Aruba",
    "AU"=>"Australia",
    "AT"=>"Austria",
    "AZ"=>"Azerbaijan",
    "AP"=>"Azores",
    "BS"=>"Bahamas",
    "BH"=>"Bahrain",
    "BD"=>"Bangladesh",
    "BB"=>"Barbados",
    "BY"=>"Belarus",
    "BE"=>"Belgium",
    "BZ"=>"Belize",
    "BJ"=>"Benin",
    "BM"=>"Bermuda",
    "BT"=>"Bhutan",
    "BO"=>"Bolivia",
    "BA"=>"Bosnia And Herzegowina",
    "XB"=>"Bosnia-Herzegovina",
    "BW"=>"Botswana",
    "BV"=>"Bouvet Island",
    "BR"=>"Brazil",
    "IO"=>"British Indian Ocean Territory",
    "VG"=>"British Virgin Islands",
    "BN"=>"Brunei Darussalam",
    "BG"=>"Bulgaria",
    "BF"=>"Burkina Faso",
    "BI"=>"Burundi",
    "KH"=>"Cambodia",
    "CM"=>"Cameroon",
    "CA"=>"Canada",
    "CV"=>"Cape Verde",
    "KY"=>"Cayman Islands",
    "CF"=>"Central African Republic",
    "TD"=>"Chad",
    "CL"=>"Chile",
    "CN"=>"China",
    "CX"=>"Christmas Island",
    "CC"=>"Cocos (Keeling) Islands",
    "CO"=>"Colombia",
    "KM"=>"Comoros",
    "CG"=>"Congo",
    "CD"=>"Congo, The Democratic Republic O",
    "CK"=>"Cook Islands",
    "XE"=>"Corsica",
    "CR"=>"Costa Rica",
    "CI"=>"Cote d` Ivoire (Ivory Coast)",
    "HR"=>"Croatia",
    "CU"=>"Cuba",
    "CY"=>"Cyprus",
    "CZ"=>"Czech Republic",
    "DK"=>"Denmark",
    "DJ"=>"Djibouti",
    "DM"=>"Dominica",
    "DO"=>"Dominican Republic",
    "TP"=>"East Timor",
    "EC"=>"Ecuador",
    "EG"=>"Egypt",
    "SV"=>"El Salvador",
    "GQ"=>"Equatorial Guinea",
    "ER"=>"Eritrea",
    "EE"=>"Estonia",
    "ET"=>"Ethiopia",
    "FK"=>"Falkland Islands (Malvinas)",
    "FO"=>"Faroe Islands",
    "FJ"=>"Fiji",
    "FI"=>"Finland",
    "FR"=>"France (Includes Monaco)",
    "FX"=>"France, Metropolitan",
    "GF"=>"French Guiana",
    "PF"=>"French Polynesia",
    "TA"=>"French Polynesia (Tahiti)",
    "TF"=>"French Southern Territories",
    "GA"=>"Gabon",
    "GM"=>"Gambia",
    "GE"=>"Georgia",
    "DE"=>"Germany",
    "GH"=>"Ghana",
    "GI"=>"Gibraltar",
    "GR"=>"Greece",
    "GL"=>"Greenland",
    "GD"=>"Grenada",
    "GP"=>"Guadeloupe",
    "GU"=>"Guam",
    "GT"=>"Guatemala",
    "GN"=>"Guinea",
    "GW"=>"Guinea-Bissau",
    "GY"=>"Guyana",
    "HT"=>"Haiti",
    "HM"=>"Heard And Mc Donald Islands",
    "VA"=>"Holy See (Vatican City State)",
    "HN"=>"Honduras",
    "HK"=>"Hong Kong",
    "HU"=>"Hungary",
    "IS"=>"Iceland",
    "IN"=>"India",
    "ID"=>"Indonesia",
    "IR"=>"Iran",
    "IQ"=>"Iraq",
    "IE"=>"Ireland",
    "EI"=>"Ireland (Eire)",
    "IL"=>"Israel",
    "IT"=>"Italy",
    "JM"=>"Jamaica",
    "JP"=>"Japan",
    "JO"=>"Jordan",
    "KZ"=>"Kazakhstan",
    "KE"=>"Kenya",
    "KI"=>"Kiribati",
    "KP"=>"Korea, Democratic People'S Repub",
    "KW"=>"Kuwait",
    "KG"=>"Kyrgyzstan",
    "LA"=>"Laos",
    "LV"=>"Latvia",
    "LB"=>"Lebanon",
    "LS"=>"Lesotho",
    "LR"=>"Liberia",
    "LY"=>"Libya",
    "LI"=>"Liechtenstein",
    "LT"=>"Lithuania",
    "LU"=>"Luxembourg",
    "MO"=>"Macao",
    "MK"=>"Macedonia",
    "MG"=>"Madagascar",
    "ME"=>"Madeira Islands",
    "MW"=>"Malawi",
    "MY"=>"Malaysia",
    "MV"=>"Maldives",
    "ML"=>"Mali",
    "MT"=>"Malta",
    "MH"=>"Marshall Islands",
    "MQ"=>"Martinique",
    "MR"=>"Mauritania",
    "MU"=>"Mauritius",
    "YT"=>"Mayotte",
    "MX"=>"Mexico",
    "FM"=>"Micronesia, Federated States Of",
    "MD"=>"Moldova, Republic Of",
    "MC"=>"Monaco",
    "MN"=>"Mongolia",
    "MS"=>"Montserrat",
    "MA"=>"Morocco",
    "MZ"=>"Mozambique",
    "MM"=>"Myanmar (Burma)",
    "NA"=>"Namibia",
    "NR"=>"Nauru",
    "NP"=>"Nepal",
    "NL"=>"Netherlands",
    "AN"=>"Netherlands Antilles",
    "NC"=>"New Caledonia",
    "NZ"=>"New Zealand",
    "NI"=>"Nicaragua",
    "NE"=>"Niger",
    "NG"=>"Nigeria",
    "NU"=>"Niue",
    "NF"=>"Norfolk Island",
    "MP"=>"Northern Mariana Islands",
    "NO"=>"Norway",
    "OM"=>"Oman",
    "PK"=>"Pakistan",
    "PW"=>"Palau",
    "PS"=>"Palestinian Territory, Occupied",
    "PA"=>"Panama",
    "PG"=>"Papua New Guinea",
    "PY"=>"Paraguay",
    "PE"=>"Peru",
    "PH"=>"Philippines",
    "PN"=>"Pitcairn",
    "PL"=>"Poland",
    "PT"=>"Portugal",
    "PR"=>"Puerto Rico",
    "QA"=>"Qatar",
    "RE"=>"Reunion",
    "RO"=>"Romania",
    "RU"=>"Russian Federation",
    "RW"=>"Rwanda",
    "KN"=>"Saint Kitts And Nevis",
    "SM"=>"San Marino",
    "ST"=>"Sao Tome and Principe",
    "SA"=>"Saudi Arabia",
    "SN"=>"Senegal",
    "XS"=>"Serbia-Montenegro",
    "SC"=>"Seychelles",
    "SL"=>"Sierra Leone",
    "SG"=>"Singapore",
    "SK"=>"Slovak Republic",
    "SI"=>"Slovenia",
    "SB"=>"Solomon Islands",
    "SO"=>"Somalia",
    "ZA"=>"South Africa",
    "GS"=>"South Georgia And The South Sand",
    "KR"=>"South Korea",
    "ES"=>"Spain",
    "LK"=>"Sri Lanka",
    "NV"=>"St. Christopher and Nevis",
    "SH"=>"St. Helena",
    "LC"=>"St. Lucia",
    "PM"=>"St. Pierre and Miquelon",
    "VC"=>"St. Vincent and the Grenadines",
    "SD"=>"Sudan",
    "SR"=>"Suriname",
    "SJ"=>"Svalbard And Jan Mayen Islands",
    "SZ"=>"Swaziland",
    "SE"=>"Sweden",
    "CH"=>"Switzerland",
    "SY"=>"Syrian Arab Republic",
    "TW"=>"Taiwan",
    "TJ"=>"Tajikistan",
    "TZ"=>"Tanzania",
    "TH"=>"Thailand",
    "TG"=>"Togo",
    "TK"=>"Tokelau",
    "TO"=>"Tonga",
    "TT"=>"Trinidad and Tobago",
    "XU"=>"Tristan da Cunha",
    "TN"=>"Tunisia",
    "TR"=>"Turkey",
    "TM"=>"Turkmenistan",
    "TC"=>"Turks and Caicos Islands",
    "TV"=>"Tuvalu",
    "UG"=>"Uganda",
    "UA"=>"Ukraine",
    "AE"=>"United Arab Emirates",
    "UK"=>"United Kingdom",
    "GB"=>"Great Britain",
    "US"=>"United States",
    "UM"=>"United States Minor Outlying Isl",
    "UY"=>"Uruguay",
    "UZ"=>"Uzbekistan",
    "VU"=>"Vanuatu",
    "XV"=>"Vatican City",
    "VE"=>"Venezuela",
    "VN"=>"Vietnam",
    "VI"=>"Virgin Islands (U.S.)",
    "WF"=>"Wallis and Furuna Islands",
    "EH"=>"Western Sahara",
    "WS"=>"Western Samoa",
    "YE"=>"Yemen",
    "YU"=>"Yugoslavia",
    "ZR"=>"Zaire",
    "ZM"=>"Zambia",
    "ZW"=>"Zimbabwe");

$state = array("US"=>array("AK"=>"Alaska",
"AL"=>"Alabama",
"AR"=>"Arkansas",
"AS"=>"American Samoa",
"AZ"=>"Arizona",
"CA"=>"California",
"CO"=>"Colorado",
"CT"=>"Connecticut",
"DC"=>"D.C.",
"DE"=>"Delaware",
"FL"=>"Florida",
"FM"=>"Micronesia",
"GA"=>"Georgia",
"GU"=>"Guam",
"HI"=>"Hawaii",
"IA"=>"Iowa",
"ID"=>"Idaho",
"IL"=>"Illinois",
"IN"=>"Indiana",
"KS"=>"Kansas",
"KY"=>"Kentucky",
"LA"=>"Louisiana",
"MA"=>"Massachusetts",
"MD"=>"Maryland",
"ME"=>"Maine",
"MH"=>"Marshall Islands",
"MI"=>"Michigan",
"MN"=>"Minnesota",
"MO"=>"Missouri",
"MP"=>"Marianas",
"MS"=>"Mississippi",
"MT"=>"Montana",
"NC"=>"North Carolina",
"ND"=>"North Dakota",
"NE"=>"Nebraska",
"NH"=>"New Hampshire",
"NJ"=>"New Jersey",
"NM"=>"New Mexico",
"NV"=>"Nevada",
"NY"=>"New York",
"OH"=>"Ohio",
"OK"=>"Oklahoma",
"OR"=>"Oregon",
"PA"=>"Pennsylvania",
"PR"=>"Puerto Rico",
"PW"=>"Palau",
"RI"=>"Rhode Island",
"SC"=>"South Carolina",
"SD"=>"South Dakota",
"TN"=>"Tennessee",
"TX"=>"Texas",
"UT"=>"Utah",
"VA"=>"Virginia",
"VI"=>"Virgin Islands",
"VT"=>"Vermont",
"WA"=>"Washington",
"WI"=>"Wisconsin",
"WV"=>"West Virginia",
"WY"=>"Wyoming",
"AA"=>"Military Americas",
"AE"=>"Military Europe/ME/Canada",
"AP"=>"Military Pacific"),
"CA"=>array("AB"=>"Alberta",
"MB"=>"Manitoba",
"AB"=>"Alberta",
"BC"=>"British Columbia",
"MB"=>"Manitoba",
"NB"=>"New Brunswick",
"NL"=>"Newfoundland and Labrador",
"NS"=>"Nova Scotia",
"NT"=>"Northwest Territories",
"NU"=>"Nunavut",
"ON"=>"Ontario",
"PE"=>"Prince Edward Island",
"QC"=>"Quebec",
"SK"=>"Saskatchewan",
"YT"=>"Yukon Territory"),
"AU"=>array("AAT"=>"Australian Antarctic Territory",
"ACT"=>"Australian Capital Territory",
"NT"=>"Northern Territory",
"NSW"=>"New South Wales",
"QLD"=>"Queensland",
"SA"=>"South Australia",
"TAS"=>"Tasmania",
"VIC"=>"Victoria",
"WA"=>"Western Australia"),
"BR"=>array("AC"=>"Acre",
"AL"=>"Alagoas",
"AM"=>"Amazonas",
"AP"=>"Amapa",
"BA"=>"Baia",
"CE"=>"Ceara",
"DF"=>"Distrito Federal",
"ES"=>"Espirito Santo",
"FN"=>"Fernando de Noronha",
"GO"=>"Goias",
"MA"=>"Maranhao",
"MG"=>"Minas Gerais",
"MS"=>"Mato Grosso do Sul",
"MT"=>"Mato Grosso",
"PA"=>"Para",
"PB"=>"Paraiba",
"PE"=>"Pernambuco",
"PI"=>"Piaui",
"PR"=>"Parana",
"RJ"=>"Rio de Janeiro",
"RN"=>"Rio Grande do Norte",
"RO"=>"Rondonia",
"RR"=>"Roraima",
"RS"=>"Rio Grande do Sul",
"SC"=>"Santa Catarina",
"SE"=>"Sergipe",
"SP"=>"Sao Paulo",
"TO"=>"Tocatins"),
"NL"=>array("DR"=>"Drente",
"FL"=>"Flevoland",
"FR"=>"Friesland",
"GL"=>"Gelderland",
"GR"=>"Groningen",
"LB"=>"Limburg",
"NB"=>"Noord Brabant",
"NH"=>"Noord Holland",
"OV"=>"Overijssel",
"UT"=>"Utrecht",
"ZH"=>"Zuid Holland",
"ZL"=>"Zeeland"),
"UK"=>array("AVON"=>"Avon",
"BEDS"=>"Bedfordshire",
"BERKS"=>"Berkshire",
"BUCKS"=>"Buckinghamshire",
"CAMBS"=>"Cambridgeshire",
"CHESH"=>"Cheshire",
"CLEVE"=>"Cleveland",
"CORN"=>"Cornwall",
"CUMB"=>"Cumbria",
"DERBY"=>"Derbyshire",
"DEVON"=>"Devon",
"DORSET"=>"Dorset",
"DURHAM"=>"Durham",
"ESSEX"=>"Essex",
"GLOUS"=>"Gloucestershire",
"GLONDON"=>"Greater London",
"GMANCH"=>"Greater Manchester",
"HANTS"=>"Hampshire",
"HERWOR"=>"Hereford & Worcestershire",
"HERTS"=>"Hertfordshire",
"HUMBER"=>"Humberside",
"IOM"=>"Isle of Man",
"IOW"=>"Isle of Wight",
"KENT"=>"Kent",
"LANCS"=>"Lancashire",
"LEICS"=>"Leicestershire",
"LINCS"=>"Lincolnshire",
"MERSEY"=>"Merseyside",
"NORF"=>"Norfolk",
"NHANTS"=>"Northamptonshire",
"NTHUMB"=>"Northumberland",
"NOTTS"=>"Nottinghamshire",
"OXON"=>"Oxfordshire",
"SHROPS"=>"Shropshire",
"SOM"=>"Somerset",
"STAFFS"=>"Staffordshire",
"SUFF"=>"Suffolk",
"SURREY"=>"Surrey",
"SUSS"=>"Sussex",
"WARKS"=>"Warwickshire",
"WMID"=>"West Midlands",
"WILTS"=>"Wiltshire",
"YORK"=>"Yorkshire"),
"EI"=>array("CO ANTRIM"=>"County Antrim",
"CO ARMAGH"=>"County Armagh",
"CO DOWN"=>"County Down",
"CO FERMANAGH"=>"County Fermanagh",
"CO DERRY"=>"County Londonderry",
"CO TYRONE"=>"County Tyrone",
"CO CAVAN"=>"County Cavan",
"CO DONEGAL"=>"County Donegal",
"CO MONAGHAN"=>"County Monaghan",
"CO DUBLIN"=>"County Dublin",
"CO CARLOW"=>"County Carlow",
"CO KILDARE"=>"County Kildare",
"CO KILKENNY"=>"County Kilkenny",
"CO LAOIS"=>"County Laois",
"CO LONGFORD"=>"County Longford",
"CO LOUTH"=>"County Louth",
"CO MEATH"=>"County Meath",
"CO OFFALY"=>"County Offaly",
"CO WESTMEATH"=>"County Westmeath",
"CO WEXFORD"=>"County Wexford",
"CO WICKLOW"=>"County Wicklow",
"CO GALWAY"=>"County Galway",
"CO MAYO"=>"County Mayo",
"CO LEITRIM"=>"County Leitrim",
"CO ROSCOMMON"=>"County Roscommon",
"CO SLIGO"=>"County Sligo",
"CO CLARE"=>"County Clare",
"CO CORK"=>"County Cork",
"CO KERRY"=>"County Kerry",
"CO LIMERICK"=>"County Limerick",
"CO TIPPERARY"=>"County Tipperary",
"CO WATERFORD"=>"County Waterford"));


    if ($flag == 1) { 
        //Find country
        return $country[$code];
    } 
    elseif ($flag == 2) { //Find State       
        foreach ($state[$countryCode] as $key => $value) {
            if($key==$code){
                return $state[$countryCode][$key];
            }else{
                continue;
            }
        }
    }
    elseif($flag == 3){ // return country list
        return $country;
    }
    elseif($flag == 4){ // return state List for each country
        return $state[$countryCode];
    }

}

    // Get product seller user name
   function getProduct_Seller_UserName($productid,$tableprefix)
    {             
                 $productid = strip_tags(trim($productid));
    if (!empty($productid)) {
        $QueryCartItems = "SELECT s.artist_name
                                        FROM " . $tableprefix . "products p
                                        INNER JOIN " . $tableprefix . "artists s ON s.artist_id = p.product_artist_id
                                        WHERE p.product_id ='" . $productid . "' ";
        /* $resSet = DbHelper::execute($QueryCartItems);
          $data   = DbHelper::fetchOne($resSet);
          return $data; */
        
        $result = mysql_query($sql);
        if (mysql_num_rows($QueryCartItems) != 0) {
            $rw = mysql_fetch_array($result);
            return $rw["artist_name"];
        }
    }

    }

    function ReplaceArrayImage($name) { // function for replace quotes in image
    $name   = trim(strip_tags($name));
    $name=str_replace(' ','_',$name);
    $name=str_replace("'",'_',$name);
    return ($name);
}//end fucnction
 include "../includes/config.php";
$sql = "SELECT * FROM ".$tableprefix."settings";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result); //print_r($row);

define("AMAZON_BUCKET_NAME", $row["amazon_bucket_name"]);
define("AMAZON_ACCESS_KEY", $row["amazon_access_key"]);
define("AMAZON_SECRET_KEY", $row["amazon_secret_key"]);
define("ENABLE_AMAZON_S3_IMAGES", $row["enable_amazon_cdn_images"]);
define("AMAZON_S3_DOMAIN_URL", 'http://'.AMAZON_BUCKET_NAME.'.s3.amazonaws.com/');

function moveImageToCDN($imagePath,$imageName){

	if(ENABLE_AMAZON_S3_IMAGES=="Y"){
		$s3 = new S3(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
		$size = getimagesize($imagePath);
                $content_type = $size['mime'];
                $requestHeaders = array(
                        'Cache-Control' => 'max-age=2692000',
                        'Expires' => gmdate('D, d M Y H:i:s T', strtotime('+1 year')),
                        'Content-Type' => $content_type,
                    );

		if ($s3->putObjectFile($imagePath,AMAZON_BUCKET_NAME,$imageName, S3::ACL_PUBLIC_READ,'',$requestHeaders)) {

			return true;
		}else{
			return false;

		}

	}
	return false;
}

function getProduct_Default_Option_Values($productid)
    {
    
                 $sql = "SELECT * FROM " . $tableprefix . "product_options p
                                        WHERE p.product_id ='" . $productid . "' AND default_option='YES'";
                  $result = mysql_query($sql);
             if (mysql_num_rows($result) != 0) {
                 
                 $row = mysql_fetch_object($result);
                 return $row;
                 
             }

    }
   

?>