<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com  2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
include_once 'class.pager.php';
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
    $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

    switch ($theType) {
        case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "''";
            break;
        case "long":
        case "int":
            $theValue = ($theValue != "") ? intval($theValue) : "''";
            break;
        case "double":
            $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "''";
            break;
        case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "''";
            break;
        case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
    }
    return $theValue;
}


function getSellerCurrency($product_id) {
    global $tableprefix;

    $select_artist_currency = "SELECT cm.nexchange_price
							   FROM ".$tableprefix."products prd
							   JOIN ".$tableprefix."currency_master cm
							   JOIN ".$tableprefix."artists art
							   WHERE cm.vcurrency_code = art.vseller_currency
							    AND prd.product_artist_id = art.artist_id
								AND prd.product_id = ".addslashes($product_id);


    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    $artist_row_currency['nexchange_price'];
    return $artist_row_currency['nexchange_price'];
}

//Select Dealer Name from dealer table

function getDealrName($dealerid) {
    global $tableprefix;

    $select_dealers="SELECT reseller_username
							   FROM ".$tableprefix."resellers
								where reseller_id=".addslashes($dealerid);
    $result=mysql_query($select_dealers) or die(mysql_error);

    if(mysql_num_rows($result) > 0) {
        $dealers_row = mysql_fetch_assoc($result);
    }
    return $dealers_row['reseller_username'];
} // end function

function getCurrencySybol($currencyid) {
    global $tableprefix;

    $select_artist_currency = "SELECT vcurrency_symbol
							   FROM ".$tableprefix."currency_master
							   where vcurrency_code='".$currencyid."' ";
    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['vcurrency_symbol'];
}
function getCurrencyrate($currency) {
    global $tableprefix;

    $select_artist_currency = "SELECT nexchange_price
							   FROM ".$tableprefix."currency_master
							   where vcurrency_code='".$currency."' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['nexchange_price'];
}

function getDefaultCurrencyrate() {
    global $tableprefix;

    $select_artist_currency = "SELECT nexchange_price
							   FROM ".$tableprefix."currency_master
							   where vcurrency_code='USD' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['nexchange_price'];
}


function getSellerCurrencySybol($artistID) {
    global $tableprefix;

    $select_artist_currency = "SELECT vseller_currency
							   FROM ".$tableprefix."artists
							   where artist_id='".$artistID."' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['vseller_currency'];
}

function getSellerCurrencySymbolformat($artistID) {
    global $tableprefix;


    $select_artist_currency = "SELECT vcurrency_symbol
							   FROM ".$tableprefix."currency_master cm INNER JOIN  ".$tableprefix."artists a
							   ON a.vseller_currency=cm.vcurrency_code
							   where a.artist_id='".$artistID."' ";

    /*$select_artist_currency = "SELECT vseller_currency
							   FROM ".$tableprefix."artists
							   where artist_id='".$artistID."' ";*/

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['vcurrency_symbol'];
}


function is_number($str) {
    if (preg_match("/^[0-9]*\.?[0-9]+$/", $str) && !empty($str)) {
        return true;
    }
    return false;
}

function getPaginationLimit() {

    global $tableprefix;


    $sql="select  npagination_limit  FROM ".$tableprefix."settings ";
    $rs=mysql_query($sql) or die (mysql_error());
    if(mysql_num_rows($rs)>0) {
        $rr=mysql_fetch_array($rs);

        $limit=$rr['npagination_limit'];
    } // end if

    else {

        $limit=0;
    }

    return $limit;


} // end function

/*----------function to get the seller rating count---------------*/

function getSellerRating($rating_id,$seller_id) {
    global $tableprefix;

    $select_rating = "SELECT COUNT(nrating_id) AS rating_count
					  FROM ".$tableprefix."record_ratings
					   WHERE nrating_id = ".$rating_id.
            " AND nrseller_id = ".$seller_id;
    $result_rating = mysql_query($select_rating) or die(mysql_error());

    if(mysql_num_rows($result_rating) > 0) {
        $rating_count_row = mysql_fetch_assoc($result_rating);
    }

    return $rating_count_row['rating_count'];
}

//=============================================================================

function ArrayKeyVal($arrVal,$chkVal) {
    foreach($arrVal as $key=>$val) {
        if($chkVal==$val) {
            return ($key);
        }//end if
    }//end foreach
}//end funciton

function CheckValue($Array) {
    foreach($Array as $key=>$val) {
        if($key=='mailservice') {
            return ($val);
        }//end if
    }//end foreach
}//end funciton

function CheckValuePrice($Array) {
    foreach($Array as $key=>$val) {
        if($key=='rate') {
            return ($val);
        }//end if
    }//end foreach
}//end funciton
// function for getting array value

function RearrangeArray($headeArray,$chkVal,$newArray) {

    if(in_array(trim($chkVal),$headeArray)) {

        $resultArray=$newArray[$chkVal];
    }//end if

    return $resultArray;



}//end function



//Function for Showing category Name
function ShowcategoryName($catid) {
    global $_SESSION,$tableprefix;
    $select_category= "SELECT category_name FROM ".$tableprefix."categories
							 WHERE category_id = ".$catid;
    $rs=mysql_query($select_category) or die(mysql_error());
    if(mysql_num_rows($rs)>0) {
        $rr=mysql_fetch_array($rs);
        $categoryname=stripslashes($rr['category_name']);
    }
    return $categoryname;

} // end function


// Function for getting current PAges

function GetCurrentPageName() {
    $currentFile = $_SERVER["PHP_SELF"];
    $parts = Explode('/', $currentFile);
    $currentpage=$parts[count($parts) - 1];
    return $currentpage;
}

// Function for finding Duplicate VAlues in an array

function findDuplicates($data,$dupval) {
    $nb= 0;
    foreach($data as $key => $val)
        if ($val==$dupval)
            echo "yes";
    $nb++;
    return $nb;
}

//=============================================== Function For Preview Templates




//========================================================================



/*----------function to check whether the seller gift certiicate is used to purchase only his products---------------*/


function checkGiftCertificateSeller($certificate_code) {
    global $_SESSION,$tableprefix;


    $gift_certificate_flag = 0;

    $select_cart_products = "SELECT product_id FROM ".$tableprefix."cart
							 WHERE user_id = ".$_SESSION['sess_userid'];

    //echo $select_cart_products."<br>";

    $result_cart_products = mysql_query($select_cart_products) or die(mysql_error());

    if(mysql_num_rows($result_cart_products) > 0) {

        while($cart_row = mysql_fetch_array($result_cart_products)) {


            /*----------selecting the seller------------*/

            $cart_product_seller = getSellerName($cart_row['product_id']);


            /*---------------------------------*/

            $select_gift_certificate = "SELECT ngift_product_id
								FROM ".$tableprefix."giftcoupon_master
								WHERE vgift_coupon_code = '".$certificate_code."'";

            //echo $select_gift_certificate."<br>";

            $result_gift_certificate = mysql_query($select_gift_certificate) or die(mysql_error());

            if(mysql_num_rows($result_gift_certificate) > 0) {

                $gift_certificate_seller_row = mysql_fetch_assoc($result_gift_certificate);

                $gift_certificate_seller = getSellerName($gift_certificate_seller_row['ngift_product_id']);

            }


            if($cart_product_seller != $gift_certificate_seller) {
                $gift_certificate_flag = 1;

                break;

            }


            /*--------------------------------------*/


        }

    }




    return $gift_certificate_flag;
}


function getSellerName($product_id) {
    global $tableprefix;


    $select_seller_product = "SELECT product_artist_id FROM ".$tableprefix."products
							  WHERE product_id = ".$product_id;
    $result_seller_product = mysql_query($select_seller_product) or die(mysql_error());

    if(mysql_num_rows($result_seller_product) > 0) {
        $seller_product_row = mysql_fetch_assoc($result_seller_product);
    }

    return $seller_product_row['product_artist_id'];
}

/*----------function to check whether the seller gift certiicate is used to purchase only his products---------------*/


/*--------function to get the country name-----------------
	paramter is country code
*/


function getCountryName($country_code) {
    global $tableprefix;

    $select_country = "SELECT country_name FROM ".$tableprefix."countries
						WHERE country_iso_code_2 = '".$country_code."'";
    $result_country = mysql_query($select_country) or die(mysql_error());

    if(mysql_num_rows($result_country) > 0) {
        $country_row = mysql_fetch_assoc($result_country);

        $country_name = $country_row['country_name'];
    }

    return $country_name;

}



/*-------function to manage the user/admin/seller/affiliate sessions-----------*/



function manageSession($category) {
    global $_SESSION;

    /*
	1 - Admin
	2 - Seller
	3 - User
	4 - Affiliate
    */

    if($category == 1) // Admin Category
    {
        if($_SESSION['sess_affiliateid'] != "") {
            $_SESSION['sess_affiliateid'] = "";
        }
        if($_SESSION['sess_artistid'] != "") {
            $_SESSION['sess_artistid'] = "";
        }
        if($_SESSION['sess_userid'] != "") {
            $_SESSION['sess_userid'] = "";
        }
    }
    else if($category == 2) // Seller Category
    {
        if($_SESSION['sess_affiliateid'] != "") {
            $_SESSION['sess_affiliateid'] = "";
        }
        if($_SESSION['sess_adminname'] != "") {
            $_SESSION['sess_adminname'] = "";
        }
        if($_SESSION['sess_userid'] != "") {
            $_SESSION['sess_userid'] = "";
        }
    }
    else if($category == 3) // User Category
    {
        if($_SESSION['sess_affiliateid'] != "") {
            $_SESSION['sess_affiliateid'] = "";
        }
        if($_SESSION['sess_adminname'] != "") {
            $_SESSION['sess_adminname'] = "";
        }
        if($_SESSION['sess_artistid'] != "") {
            $_SESSION['sess_artistid'] = "";
        }
    }
    else if($category == 4) // Affiliate Category
    {
        if($_SESSION['sess_artistid'] != "") {
            $_SESSION['sess_artistid'] = "";
        }
        if($_SESSION['sess_adminname'] != "") {
            $_SESSION['sess_adminname'] = "";
        }
        if($_SESSION['sess_userid'] != "") {
            $_SESSION['sess_userid'] = "";
        }
    }
}



/*------function to read the email templates-----------*/


function readEmailTemplate($template_name,$table_name="",$email_address="") {
    global $tableprefix,$_SESSION;

    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];

    $select_email_template = "SELECT vemail_body FROM ".$tableprefix."email_templates WHERE vtemplate_name = '".$template_name."'";

    $result_email_template = mysql_query($select_email_template) or die(mysql_error());

    if($email_address != "") {

        $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."users
								WHERE email = '".$email_address."'";

        $result_user_details = mysql_query($select_user_details) or die(mysql_error());

        if(mysql_num_rows($result_user_details) > 0) {

            $user_details_row = mysql_fetch_assoc($result_user_details);
            $txtFirstName = ucwords($user_details_row['first_name']);
            $txtLastName = ucwords($user_details_row['last_name']);
        }


    }


    if($table_name == "" && $email_address == "") {

        if($_SESSION["sess_userid"] != "") {

            $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."users
									WHERE user_id = ".$_SESSION["sess_userid"];

            $result_user_details = mysql_query($select_user_details) or die(mysql_error());

            if(mysql_num_rows($result_user_details) > 0) {

                $user_details_row = mysql_fetch_assoc($result_user_details);

                $txtFirstName = $user_details_row['first_name'];
                $txtLastName = $user_details_row['last_name'];
            }

        }


    }
    else {

        if($table_name == "artists") {

            if($_SESSION["sess_artistid"] != "") {

                $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."artists
										WHERE artist_id = ".$_SESSION["sess_artistid"];

                $result_user_details = mysql_query($select_user_details) or die(mysql_error());

                if(mysql_num_rows($result_user_details) > 0) {

                    $user_details_row = mysql_fetch_assoc($result_user_details);

                    $txtFirstName = $user_details_row['first_name'];
                    $txtLastName = $user_details_row['last_name'];
                }

            }

        }
        else if($table_name == "affiliates") {

            if($_SESSION["sess_affiliateid"] != "" || $_SESSION["sess_affiliateid_new"] != "") {

                if($_SESSION["sess_affiliateid_new"] != "") {
                    $UserId = $_SESSION["sess_affiliateid_new"];
                }
                if($_SESSION["sess_affiliateid"] != "") {
                    $UserId = $_SESSION["sess_affiliateid"];
                }

                $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."affiliates
										WHERE affiliate_id = ".$UserId;

                $result_user_details = mysql_query($select_user_details) or die(mysql_error());

                if(mysql_num_rows($result_user_details) > 0) {

                    $user_details_row = mysql_fetch_assoc($result_user_details);

                    $txtFirstName = $user_details_row['first_name'];
                    $txtLastName = $user_details_row['last_name'];
                }

            }

        }else if($table_name == "orders") {
            $order_sql = "select order_id,product_name,product_code,product_price,product_discount,product_quantity from ".$tableprefix."order_details
		                 where order_id = '".$_SESSION["orderid_new"]."' and artist_id = '".$_SESSION["artist_new"]."'";
            $order_rs  =  mysql_query($order_sql) or die(mysql_error());
            if(mysql_num_rows($order_rs) > 0) {
                $order_row    = mysql_fetch_assoc($order_rs);
                $txtOrdrId    = $order_row['order_id'];
                $txtPdtName   = stripslashes($order_row['product_name']);
                $txtPdtCode   = $order_row['product_code'];
                $rate = $order_row["product_price"];
                $qty = $order_row["product_quantity"];
                $price = $rate * $qty;
                if($order_row["product_discount"] !="0") {
                    $price=$price-($price*$order_row["product_discount"]/100);

                }
                $txtPdtPrice  = $currency_attributes[0].' '.$price;
                $txtPdtQty    = $order_row['product_quantity'];
            }

        }

    }
    if(mysql_num_rows($result_email_template) > 0) {

        $email_template_row = mysql_fetch_assoc($result_email_template);
        $email_body = $email_template_row['vemail_body'];



        if($txtFirstName)
            $email_body = str_replace('[first_name]',$txtFirstName,$email_body);
        if($txtLastName)
            $email_body = str_replace('[last_name]',$txtLastName,$email_body);
        if($template_name!='refund_registration_seller') {
            $email_body = str_replace('[seller_first_name]',$txtFirstName,$email_body);
            $email_body = str_replace('[seller_last_name]',$txtLastName,$email_body);
        }
        $email_body = str_replace('[site_name]',SITE_NAME,$email_body);
        if($txtOrdrId)
            $email_body = str_replace('[order_id]',$txtOrdrId,$email_body);
        if($txtPdtName)
            $email_body = str_replace('[product_name]',$txtPdtName,$email_body);
        if($txtPdtCode)
            $email_body = str_replace('[product_code]',$txtPdtCode,$email_body);
        if($txtPdtDiscount)
            $email_body = str_replace('[product_discount]',$txtPdtDiscount,$email_body);
        if($txtPdtPrice)
            $email_body = str_replace('[product_price]',$txtPdtPrice,$email_body);
        $email_body = str_replace('[product_qty]',$txtPdtQty,$email_body);



    }

    $email_body = str_replace("\r\n\r\n", '<br>', $email_body);
    return $email_body;



}

// function validate Donmain name

function check_domain($site="") {
    $flag	= true;
    //$normal = "^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*.[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$";
    $normal='^[a-z0-9_\./:+-]+\.[a-zA-Z.]{2,5}$';
    if (!eregi($normal, $site))
        $flag	= false;
    return $flag;
} // end of check_email



// end function


// function to validate Phone

function check_phone($phone,$country='US') {
    //$exp = "/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/";

    $pattern = '/^[0-9-(+)]+$/';

    if (preg_match($pattern, $phone)) {
        return true;
    }
    else {
        return false;
    }
}

// end function

// function for subdomian creation

// create subdomain

// create subdomain
function subd($host,$port,$ownername,$passw,$request,$domain,$subdm,$skin) {

    $sock = fsockopen('localhost',2082);
    if(!$sock) {
        print('Socket error');
        exit();
    } // end if

    //new line code added
    //checking whether the subdomain is exists
    $subdomain=$subdm.".".$domain;
    $path="http://".$ownername.":".$passw."@".$domain.":2082/frontend/".$skin."/subdomain/index.html";
    $f = fopen($path,"r");
    if (!$f) {
        $result .='<br>Can\'t open cPanel';
    }//end if

    //check if the account exists
    while (!feof ($f)) {
        $line = fgets ($f, 1024);
        if (ereg ($subdomain, $line, $out)) {
            $result .='<br>Such subdomain already exists.';
        }//end if
    }//end while
    fclose($f); //close the file resource

    //subdomain does not already exist. So proceed to creating it
    $path="http://".$ownername.":".$passw."@".$domain.":2082/frontend/".$skin."/subdomain/doadddomain.html?domain=".$subdm."&rootdomain=".$domain;
    $f = fopen($path,"r");
    if (!$f) {
        $result .='<br>Can\'t open cPanel.';
    }//end if

    //check if the subdomain added
    while (!feof ($f)) {
        $line = fgets ($f, 1024);
        if (ereg ("has been added.", $line, $out)) {
            if(trim($result)=='') {
                $authstr = "$ownername:$passw";
                $pass = base64_encode($authstr);
                $in = "GET $request\r\n";
                $in .= "HTTP/1.0\r\n";
                $in .= "Host:$host\r\n";
                $in .= "Authorization: Basic $pass\r\n";
                $in .= "\r\n";

                fputs($sock, $in);

                /* while (!feof($sock))
  					  {
   						 $result2 .= fgets ($sock,128);
 					  }//end while*/
                fclose( $sock );

                $result .='<br>Subdomain created successfully';
                //chmod($_SERVER['DOCUMENT_ROOT'].$subdm,0777);
            }//end if
        }//end if
    }//end while
    fclose($f); //close the file resource
    //new line code added
    return $result;
}//end function
/*------function to read the email templates-----------*/

/*-----function to replace the pattern in the css files-----*/
function showRegForm($sample_filename,$sample_fields="") {
    $sample_handle = fopen($sample_filename, "r");

    if(filesize($sample_filename)>0) {
        $sample_contents = fread($sample_handle, filesize($sample_filename));
    }
    else {
        $sample_contents = "";
    }
    if ($sample_fields=='') {
        $sample_fields['dd']='';
    }
    foreach($sample_fields as $sample_key => $sample_value) {
        $sample_contents=str_replace("--$sample_key--",$sample_value,$sample_contents);
    }

    $sample_pattern = "/--(\w+)--/i";
    $sample_contents=preg_replace($sample_pattern, "", $sample_contents);
    fclose($sample_handle);
    return $sample_contents;
}






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

function displayCMS($cms_name) {
    global $tableprefix;

    $cms_array = array();

    $select_cms = "SELECT content_heading,content_text FROM ".$tableprefix."content_management
				   WHERE content_name = ".GetSQLValueString($cms_name,"text");
    $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 to hide the shipping when cart contains digital product or gift coupon----*/

function hideShipping() {
    global $tableprefix,$_SESSION;

    $hide_shipping_division = 1;
    /*********CART TOTAL************/
    if($_SESSION["sess_userid"]!='') {

        $select_cart_total = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd
									WHERE ct.product_id = prd.product_id
									AND ct.user_id = ".$_SESSION["sess_userid"];
    }

    else {
        $select_cart_total = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd
									WHERE ct.product_id = prd.product_id
									AND ct.visitor_cart_id = '".session_id()."' ";
    }


    $result_cart_total = mysql_query($select_cart_total) or die(mysql_error());
    $cart_total = mysql_num_rows($result_cart_total);

    /*********CART TOTAL************/
    if($_SESSION["sess_userid"]!='') {

        $select_cart_digital = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd
									WHERE ct.product_id = prd.product_id
									AND vdigital_product = 'Y'
									AND ct.user_id = ".$_SESSION["sess_userid"];
    }

    else {
        $select_cart_digital = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd
									WHERE ct.product_id = prd.product_id
									AND vdigital_product = 'Y'
									AND ct.visitor_cart_id = '".session_id()."' ";
    }

    $result_cart_digital = mysql_query($select_cart_digital) or die(mysql_error());
    $cart_digital = mysql_num_rows($result_cart_digital);

    if($_SESSION["sess_userid"]!='') {

        $select_cart_gift = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd,".$tableprefix."categories ctry
							  WHERE ct.product_id = prd.product_id
							   AND prd.product_category = ctry.category_id
							   AND ctry.gift_certificate_flag = 'Y'
							 AND ct.user_id = ".$_SESSION["sess_userid"];
    }

    else {
        $select_cart_gift = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd,".$tableprefix."categories ctry
							  WHERE ct.product_id = prd.product_id
							   AND prd.product_category = ctry.category_id
							   AND ctry.gift_certificate_flag = 'Y'
							  AND ct.visitor_cart_id = '".session_id()."' ";
    }

    $result_cart_gift = mysql_query($select_cart_gift) or die(mysql_error());
    $cart_gift = mysql_num_rows($result_cart_gift);

    if(((int)$cart_digital+ (int)$cart_gift) > 0) {
        if((int)$cart_total == ((int)$cart_digital + (int)$cart_gift)) {
            $hide_shipping_division = 0;

        }
    }

    /*
	if(mysql_num_rows($result_cart_digital) == 0 && mysql_num_rows($result_cart_gift) == 0)
	{

		$hide_shipping_division = 1;

	}*/

    return $hide_shipping_division;
}




function cartClearDigital($user_id) {
    global $_SESSION,$tableprefix;


    $select_gift_check = "SELECT crt.cart_id
						  FROM ".$tableprefix."categories ctry,".$tableprefix."cart crt,".$tableprefix."products prd
						   WHERE ctry.category_id = prd.product_category
						    AND crt.product_id = prd.product_id
							AND ctry.gift_certificate_flag != 'Y'
							AND  prd.vdigital_product != 'Y' AND crt.user_id='".$user_id."'
							GROUP BY crt.cart_id";

    $result_gift_check = mysql_query($select_gift_check) or die(mysql_error());

    if(mysql_num_rows($result_gift_check) > 0) {
        while($rows=mysql_fetch_array($result_gift_check)) {
            $clear_cart = "DELETE FROM ".$tableprefix."cart WHERE cart_id = ".$rows['cart_id'];
            mysql_query($clear_cart) or die(mysql_error());
        }

    }


}


function checkGiftProductsExistsinCart($user_id) {
    global $_SESSION,$tableprefix;

    $giftProducts=false;

    $select_gift_check = "SELECT crt.cart_id
						  FROM ".$tableprefix."categories ctry,".$tableprefix."cart crt,".$tableprefix."products prd
						   WHERE ctry.category_id = prd.product_category
						    AND crt.product_id = prd.product_id
							AND ctry.gift_certificate_flag = 'Y'
							AND crt.user_id='".$user_id."'
							GROUP BY crt.cart_id";

    $result_gift_check = mysql_query($select_gift_check) or die(mysql_error());

    if(mysql_num_rows($result_gift_check) > 0) {
        $giftProducts	=true;

    }
    else {
        $giftProducts	=false;
    }


    return $giftProducts;


}

function digitalProductsCartCount($user_id) {

    global $_SESSION,$tableprefix;

    $digitalCount =0;

    $digital_product_exists =0;

    $select_gift_check1 = "SELECT count(crt.cart_id ) AS digitalcnt
										FROM ".$tableprefix."cart crt
										INNER JOIN ".$tableprefix."products p ON p.product_id = crt.product_id
										WHERE crt.user_id='".$user_id."'
										AND p.vdigital_product = 'Y' ";

    $result_gift_check1 = mysql_query($select_gift_check1) or die(mysql_error());

    if(mysql_num_rows($result_gift_check1) > 0) {

        $digitalObj		= mysql_fetch_object($result_gift_check1);
        $digitalCount  = $digitalObj->digitalcnt;

    }


    if($digitalCount>0) {
        $digital_product_exists =1;
    }

    return $digital_product_exists;

}


function giftProductsCartCount($user_id) {
    global $_SESSION,$tableprefix;

    $giftProducts=0;

    $select_gift_check = "SELECT crt.cart_id
						  FROM ".$tableprefix."categories ctry,".$tableprefix."cart crt,".$tableprefix."products prd
						   WHERE ctry.category_id = prd.product_category
						    AND crt.product_id = prd.product_id
							AND ctry.gift_certificate_flag = 'Y'
							AND crt.user_id='".$user_id."'
							GROUP BY crt.cart_id";

    $result_gift_check = mysql_query($select_gift_check) or die(mysql_error());

    if(mysql_num_rows($result_gift_check) > 0) {
        $giftProducts =1;

    }



    return $giftProducts;

}

function checkDigitalProductsExistsinCart($user_id) {
    global $_SESSION,$tableprefix;

    $giftProducts=false;

    $cartCount	= 0;

    $digitalCount	= 0;

    $select_gift_check = "SELECT count(*)as cartcnt
						 		 FROM ".$tableprefix."cart crt
						   WHERE
							 crt.user_id='".$user_id."' ";

    $result_gift_check = mysql_query($select_gift_check) or die(mysql_error());

    if(mysql_num_rows($result_gift_check) > 0) {

        $cartObj	= mysql_fetch_object($result_gift_check);
        $cartCount  = $cartObj->cartcnt;

    }

    $select_gift_check1 = "SELECT count(crt.cart_id ) AS digitalcnt
										FROM ".$tableprefix."cart crt
										LEFT JOIN ".$tableprefix."products p ON p.product_id = crt.product_id
										WHERE crt.user_id='".$user_id."'
										AND p.vdigital_product = 'Y' ";

    $result_gift_check1 = mysql_query($select_gift_check1) or die(mysql_error());




    if(mysql_num_rows($result_gift_check1) > 0) {

        $digitalObj		= mysql_fetch_object($result_gift_check1);
        $digitalCount  = $digitalObj->digitalcnt;

    }

    /********************/
    $select_cart_gift = "SELECT count(ct.cart_id ) AS giftcnt FROM ".$tableprefix."cart ct,".$tableprefix."products prd,".$tableprefix."categories ctry
							  WHERE ct.product_id = prd.product_id
							   AND prd.product_category = ctry.category_id
							   AND ctry.gift_certificate_flag = 'Y' AND ct.user_id='".$user_id."'";
    $result_gift = mysql_query($select_cart_gift) or die(mysql_error());
    if(mysql_num_rows($result_gift) > 0) {

        $digitalObj		= mysql_fetch_object($result_gift);
        $giftCount  = $digitalObj->giftcnt;

    }
    /********************/

    if(((int)$digitalCount+ (int)$giftCount) > 0) {
        if((int)$cartCount != ((int)$digitalCount+ (int)$giftCount)) {
            $giftProducts = true;
        }
    }

    /*if(	$cartCount>0 and $digitalCount>0)
	{
		if($cartCount !=$digitalCount)
		{
			$giftProducts = true;
		}
	else
	{
			$giftProducts	=false;
	}

	}
	else
	{
			$giftProducts	=false;
	}	*/


    return $giftProducts;


}



/*function to extract the extension of a file*/

function findexts($filename) {
    $filename = strtolower($filename) ;
    $exts = split("[/\\.]", $filename) ;
    $n = count($exts)-1;
    $exts = $exts[$n];
    return $exts;
}


/*Report to display the number of times each product viewed from the user side*/


function productViewedReport($product_id,$customer_id) {
    global $tableprefix;

    $select_product = "SELECT nreport_id,dproduct_view_date FROM ".$tableprefix."report_product
					   WHERE nreport_product_id = ".$product_id."
					    AND nreport_customerid = ".$customer_id.
            " AND dproduct_view_date != NOW()";

    $result_product = mysql_query($select_product) or die(mysql_error());

    if(mysql_num_rows($result_product) > 0) {


        $product_update = "UPDATE ".$tableprefix."report_product
						   SET nproduct_view_count = nproduct_view_count + 1,
						    dproduct_view_date = NOW()
						   WHERE nreport_product_id = ".$product_id.
                " AND nreport_customerid = ".$customer_id;
        mysql_query($product_update) or die(mysql_error());

    }
    else {

        $select_product = "SELECT nreport_id,dproduct_view_date FROM ".$tableprefix."report_product
					   	   WHERE nreport_product_id = ".$product_id.
                " AND nreport_customerid = ".$customer_id;

        $result_product = mysql_query($select_product) or die(mysql_error());

        if(mysql_num_rows($result_product) == 0) {

            $product_update = "INSERT INTO ".$tableprefix."report_product(nreport_product_id,nreport_customerid,nproduct_view_count,dproduct_view_date)
						   	   VALUES(".$product_id.",".$customer_id.",1,NOW())";
            mysql_query($product_update) or die(mysql_error());
        }

    }


}













/*displays the rating star in userside*/

function SellerRatingStar($prd_id,$units='',$static='') {
    global $tableprefix,$_SESSION;
    //echo $prd_id;

    //exit;
    //set some variables
    //$ip = $_SERVER['REMOTE_ADDR'];
    if (!$units) {
        $units = 10;
    }
    if (!$static) {
        $static = FALSE;
    }
    $rating_unitwidth = 30;

    $query = mysql_query("SELECT nrating_id,ntotal_ratings FROM ".$tableprefix."record_ratings WHERE nrseller_id = '$prd_id' AND nruser_id = ".$_SESSION['sess_userid'])or die(" Error: ".mysql_error());

    if(mysql_num_rows($query)>0) {
        $numbers=mysql_fetch_array($query);
    }

    if ($numbers['ntotal_ratings'] < 1) {
        $count = 0;
    }
    else {
        $count=$numbers['ntotal_ratings']; //how many votes total
    }
    $current_rating = $numbers['ntotal_ratings']; //total number of rating added together and stored
    $tense=($count==1) ? "vote" : "votes"; //plural form votes/vote

    // determine whether the user has voted, so we know how to draw the ul/li


    $voted = mysql_num_rows(mysql_query("SELECT nrts_id FROM ".$tableprefix."record_ratings WHERE nrseller_id = '$prd_id' AND nruser_id = ".$_SESSION['sess_userid']));

    // now draw the rating bar
    $rating_width = @number_format($numbers['nrating_id'])*$rating_unitwidth;

    $rating1 = @number_format($current_rating/$count,1);
    $rating2 = @number_format($current_rating/$count,2);


    $select_seller_rating = "SELECT nrat_id,vrating FROM ".$tableprefix."rating WHERE 1";
    $result_seller_rating = mysql_query($select_seller_rating);
    $units = mysql_num_rows($result_seller_rating);

    $rater ='';
    $rater.='<div class="ratingblock">';
    $rater.='<div id="unit_long'.$prd_id.'">';
    $rater.='<ul id="unit_ul'.$prd_id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
    $ncount = 1;

    while($rating_row = mysql_fetch_array($result_seller_rating )) {

        $rater.='<li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>';
        $rating_id = $rating_row['nrat_id'];


        if(!$voted) {

            // if the user hasn't yet voted, draw the voting stars
            $rater.='<li><a href="#?q='.$prd_id.'&amp;rating='.$rating_id.'&amp;c='.$units.'"title="'.$rating_row['vrating'].'" class="r'.$ncount.'-unit rater" rel="nofollow">'.$ncount.'</a></li>';

        }

        $ncount ++;
    }

    $select_rating_count = mysql_query("SELECT ROUND(SUM(nrating_id)/COUNT(nrating_id)) AS average_rating FROM ".$tableprefix."record_ratings WHERE nrseller_id = ".$prd_id);

    $rating_count = @mysql_fetch_array($select_rating_count);
    $type_rate=mysql_query("select vrating from ".$tableprefix."rating where nrat_id=".$rating_count['average_rating']);
    $rating_type=@mysql_fetch_array($type_rate);

    $ncount=0; // resets the count
    $rater.='  </ul>';
    $rater.='  <p';
    if($voted) {
        $rater.=' class="voted"';
    }
    $rater.='>Current Rating :'.$rating_type['vrating'];
    $rater.='  </p>';
    $rater.='  </td></tr></table>';
    $rater.='</div>';
    $rater.='</div>';
    return $rater;


}

/*function to get the site general settings*/

function getSiteGeneralSettings($field_array) {
    global $tableprefix;

    /* Example

		$check_array = array('vgooglecheck_id','vgooglecheck_key','vgooglecheck_mode');
		$settings = getSiteGeneralSettings($check_array);

    */


    $settings_array = array();
    $result_array = join($field_array,',');

    $select_settings_fields = "SELECT ".$result_array." FROM ".$tableprefix."settings WHERE 1";
    $result_settings_fields = mysql_query($select_settings_fields) or die(mysql_error());

    $settings_row = mysql_fetch_assoc($result_settings_fields);

    for($i=0;$i<count($field_array);$i++) {

        array_push($settings_array,$settings_row[$field_array[$i]]);


    }

    return $settings_array;
}


/*function to restrict the unauthorized access*/


function checkDownloadAuthorize() {
    global $_SESSION;

    if(!isset($_SESSION['SESS_download'])) {

        header('Location:digital_product_download.php');
        exit;

    }


}


/*function to activate the currency type*/


function activateCurrencyType($table_id) {
    global $tableprefix;

    if($table_id != "") {

        $update_currency_type = "UPDATE ".$tableprefix."currency_master SET vactive = 'Y' WHERE ncurrency_id = ".$table_id;
        mysql_query($update_currency_type) or die(mysql_error());

        $update_currency_type = "UPDATE ".$tableprefix."currency_master SET vactive = 'N' WHERE ncurrency_id != ".$table_id;
        mysql_query($update_currency_type) or die(mysql_error());
    }

}



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

function checkShippingEnable() {
    global $tableprefix;
    
    $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 to activate the template*/


/*function activateTemplate($table_id)
{
global $tableprefix;

	if($table_id != "")
	{

		$update_template = "UPDATE ".$tableprefix."template_master SET vactive_status = 'Y' WHERE ntemplate_id = ".$table_id;
		mysql_query($update_template) or die(mysql_error());

		$update_template = "UPDATE ".$tableprefix."template_master SET vactive_status = 'N' WHERE ntemplate_id != ".$table_id;
		mysql_query($update_template) or die(mysql_error());
	}

}*/




/*function to display the currency symbol and calculate the price based on the exchange price*/


function displayCurrencyType() {
    global $tableprefix,$_SESSION;

    $currency_array = array();

    if(isset($_SESSION['SESS_currency_type']) or $_SESSION['SESS_currency_type'] != "") {

        $select_currency_type = "SELECT vcurrency_symbol,nexchange_price,vcurrency_code FROM ".$tableprefix."currency_master
								 WHERE vcurrency_code = '".$_SESSION['SESS_currency_type'] . "'";

    }
    else {

        $admin_currency = getSettingsValue('admin_currency');

        $select_currency_type = "SELECT vcurrency_symbol,nexchange_price,vcurrency_code FROM ".$tableprefix."currency_master
								 WHERE vactive = 'Y'
                                                                 AND vcurrency_code='" . $admin_currency . "'";

    }


    $result_currency_type = mysql_query($select_currency_type) or die(mysql_error());

    $currency_row = mysql_fetch_assoc($result_currency_type);
    $currencySymbol=$currency_row['vcurrency_symbol'];

    array_push($currency_array,$currency_row['vcurrency_symbol'],$currency_row['nexchange_price'],$currency_row['vcurrency_code']);

    return $currency_array;
}


function MyUnzip($zipfile) {
    // echo $zipfile;
    global $userid;
    include('pclzip.lib.php');
    $archive = new PclZip("../products/" . $zipfile);
    if ($archive->extract(PCLZIP_OPT_PATH, "../products/zip" ) == 0) {
        // die("Error : " . $archive->errorInfo(true));
        // $message
        return false;
    }
    return true;
}
/*-------------------*/



//=============================================================

function Unzip($dir, $file, $destiny = "") {
    $dir .= DIRECTORY_SEPARATOR;
    $path_file = $dir . $file;

    $zip = zip_open($path_file);
    $_tmp = array();
    $count = 0;
    if ($zip) {
        while ($zip_entry = zip_read($zip)) {
            $_tmp[$count]["filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
            $_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
            $_tmp[$count]["mtime"] = "";
            $_tmp[$count]["comment"] = "";
            $_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
            $_tmp[$count]["index"] = $count;
            $_tmp[$count]["status"] = "ok";
            $_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

            if (zip_entry_open($zip, $zip_entry, "r")) {
                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                if ($destiny) {
                    $path_file = str_replace("/", DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
                } else {
                    $path_file = str_replace("/", DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
                }
                $new_dir = dirname($path_file);
                // Create Recursive Directory
                mkdirr($new_dir);

                $fp = fopen($dir . zip_entry_name($zip_entry), "w");
                fwrite($fp, $buf);
                fclose($fp);

                zip_entry_close($zip_entry);
            }
            echo "\n</pre>";
            $count++;
        }

        zip_close($zip);
    }
}

/*------------------*/
function delDir($dirName) {
    if (empty($dirName)) {
        return;
    }
    if (file_exists($dirName)) {
        $dir = dir($dirName);
        while ($file = $dir->read()) {
            if ($file != '.' && $file != '..') {
                if (is_dir($dirName . '/' . $file)) {
                    delDir($dirName . '/' . $file);
                } else {
                    @unlink($dirName . '/' . $file) or die('File ' . $dirName . '/' . $file . ' couldn\'t be deleted!');
                }
            }
        }
        @rmdir($dirName . '/' . $file) or die('Folder ' . $dirName . '/' . $file . ' couldn\'t be deleted!');
    } else {
        echo 'Folder "<b>' . $dirName . '</b>" doesn\'t exist.';
    }
}

function delFiles($dirName) {
    if (empty($dirName)) {
        return;
    }
    if (file_exists($dirName)) {
        $dir = dir($dirName);
        while ($file = $dir->read()) {
            if ($file != '.' && $file != '..') {
                if (is_dir($dirName . '/' . $file)) {
                    delDir($dirName . '/' . $file);
                } else {
                    @unlink($dirName . '/' . $file) or die('File ' . $dirName . '/' . $file . ' couldn\'t be deleted!');
                }
            }
        }
    } else {
        echo 'Folder "<b>' . $dirName . '</b>" doesn\'t exist.';
    }
}

/*function to display the active template*/


function displayTemplate() {
    $tableprefix = "";
    global $tableprefix,$_SESSION;


    $template_array = array();

    $select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
					    FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
    $result_template = mysql_query($select_template) or die(mysql_error());
    $template_row = mysql_fetch_assoc($result_template);

    array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);

    return $template_array;
}










/*function to get the general site settings value*/

function getSettingsValue($field_name) {
    global $tableprefix;

    $select_settings_value = "SELECT ".$field_name." FROM ".$tableprefix."settings WHERE 1";
    $result_settings_value = mysql_query($select_settings_value) or die(mysql_error());

    $settings_row = mysql_fetch_assoc($result_settings_value);

    $settings_row[$field_name];
    return $settings_row[$field_name];
}



/*function to generate a random gift coupon code*/


function randomGiftCouponKey() {
    global $tableprefix;

    $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_gift_coupon = "SELECT ngift_id FROM ".$tableprefix."giftcoupon_master WHERE vgift_coupon_code  = '".$string."'";
    $result_gift_coupon = mysql_query($select_gift_coupon);
    if(mysql_num_rows($result_gift_coupon) > 0) {
        $string = randomKey();
    }

    return($string);
}





/*function to generate a random digital product zip file name*/


function randomDigitalProduct() {
    global $tableprefix;

    $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 to display banner in the home page*/

function displayBannerHome($bannner_id) {
    global $tableprefix;

    $update_banner_display_count = "UPDATE ".$tableprefix."banners
									SET nbanner_display_count = nbanner_display_count + 1
									WHERE nbanner_id = ".$bannner_id;
    mysql_query($update_banner_display_count) or die(mysql_error());


}



function ImageTypeBanner($image) {
    list($width, $height, $type, $attr) = @getimagesize($image);
    switch ($type) {
        case 1 :
            $returntype = "gif";
            break;
        case 2 :
            $returntype = "jpg";
            break;
        case 3 :
            $returntype = "png";
            break;
        case 4 :
            $returntype = "swf";
            break;
        case 5 :
            $returntype = "psd";
            break;
        case 6 :
            $returntype = "bmp";
            break;
        case 7 :
            $returntype = "tiff";
            break;
        case 8 :
            $returntype = "tiff";
            break;
        default :
            $returntype = "notsupportted" ;
            break;
    }

    return $returntype . ":$width:$height";
}



/*----------------function to resize the image starts-----------------------*/



function generateThumbNail($src,$dest,$x,$y) {
    global $save_to_file,$image_quality,$image_type,$max_x,$max_y,$from_name,$to_name;

    // Below are default values (if parameter is not passed)


    // save to file (true) or output to browser (false)
    $save_to_file = true;

    // quality
    $image_quality = 100;

    // resulting image type (1 = GIF, 2 = JPG, 3 = PNG)
    // enter code of the image type if you want override it
    // or set it to -1 to determine automatically
    $image_type = -1;

    // maximum thumb side size
    $max_x = 100;
    $max_y = 100;


    ///////////////////////////////////////////////////
    /////////////// DO NOT EDIT BELOW
    ///////////////////////////////////////////////////

    $to_name   = '';
    $from_name = str_replace(" ","%20",$src);
    $to_name   = $dest;
    $max_x     = $x;
    $max_y     = $y;



// generate
    return GenerateThumbFile($from_name, $to_name, $max_x, $max_y);
}


function SaveImage($type, $im, $filename, $quality, $to_file = true) {

    $res = null;

    // ImageGIF is not included into some GD2 releases, so it might not work
    // output png if gifs are not supported
    if(!function_exists('imagegif')) $type = 3;

    switch ($type) {

        case 1:
            if ($to_file) {
                $res = ImageGIF($im,$filename);
            }
            else {
                header("Content-type: image/gif");
                $res = ImageGIF($im);
            }
            break;
        case 2:
            if ($to_file) {
                $res = ImageJPEG($im,$filename,$quality);
            }
            else {
                header("Content-type: image/jpeg");
                $res = ImageJPEG($im,'',$quality);
            }
            break;
        case 3:
            if ($to_file) {
                $res = ImagePNG($im,$filename);
            }
            else {
                header("Content-type: image/png");
                $res = ImagePNG($im,'',$quality);
            }
            break;
    }

    return $res;

}

function ImageCreateFromType($type,$filename) {

    $im = null;
    switch ($type) {
        case 1:
            $im = @imagecreatefromgif($filename);
            break;
        case 2:
            $im = @imagecreatefromjpeg($filename);
            break;
        case 3:
            $im = @imagecreatefrompng($filename);
            break;
    }

    //header("Content-Type: image/png");
//$img = LoadPNG("bogus.image");
    return $im;
}

// generate thumb from image and save it
function GenerateThumbFile($from_name, $to_name, $max_x, $max_y) {
    global $save_to_file, $image_type, $image_quality;


    $image_flag = 0;
    $resize_flag = 0;

    // get source image size (width/height/type)
    // orig_img_type 1 = GIF, 2 = JPG, 3 = PNG
    list($orig_x, $orig_y, $orig_img_type, $img_sizes) = GetImageSize($from_name);


    /*echo "original x =".$orig_x."<br>";
	  echo "original y =".$orig_y."<br>";
	  echo "image sizes =".$img_sizes."<br>";

	  echo "max x =".$max_x."<br>";
	  echo "max y =".$max_y."<br>";

	  exit;*/

    //$a = GetImageSize($from_name);


    // should we override thumb image type?
    $image_type = ($image_type != -1 ? $image_type : $orig_img_type);

    // check for allowed image types
    if ($orig_img_type < 1 or $orig_img_type > 3) die("Image type not supported");


    if ($orig_x < $max_x and $orig_y < $max_y) {

        $resize_flag = 1;

        //header('Location:'.$_SERVER['HTTP_REFERER']);
        // exit;

        //return $resize_flag;
    }

    if($resize_flag != 1) {


        if ($orig_x > $max_x or $orig_y > $max_y) {



            /*-------if original image size is less than the specified size to resize no need to resize------------- */



            /*$per_x = $orig_x / $max_x;
				$per_y = $orig_y / $max_y;
				if ($per_y > $per_x)
				{
				  $max_x = $orig_x / $per_y;
				}
				else
				{
				  $max_y = $orig_y / $per_x;
				}*/

        }



        else {
            // keep original sizes, i.e. just copy
            if ($save_to_file) {
                @copy($from_name, $to_name);

                // echo "testing";

                //exit;
            }
            else {

                switch ($image_type) {
                    case 1:
                        header("Content-type: image/gif");
                        include($from_name);
                        break;
                    case 2:
                        header("Content-type: image/jpeg");
                        include($from_name);
                        break;
                    case 3:
                        header("Content-type: image/png");
                        include($from_name);
                        break;
                }
            }
            return;
        }


        //if($resize_flag == 0)
        //{


        if ($image_type == 1) {
            // should use this function for gifs (gifs are palette images)
            $ni = imagecreate($max_x, $max_y);

            //echo "1ni=".$ni;

            //exit;

        }
        else {
            // Create a new true color image
            $ni = ImageCreateTrueColor($max_x,$max_y);

            //echo "2ni=".$ni;

            //exit;

        }


        // Fill image with white background (255,255,255)
        $white = imagecolorallocate($ni, 255, 255, 255);
        imagefilledrectangle( $ni, 0, 0, $max_x, $max_y, $white);
        // Create a new image from source file

        $im = ImageCreateFromType($orig_img_type,$from_name);

        if(!$im) {

            $image_flag = 1;


        }
        else {

            //imagepng($im);

            // Copy the palette from one image to another
            imagepalettecopy($ni,$im);
            // Copy and resize part of an image with resampling

            imagecopyresampled(
                    $ni, $im,             // destination, source
                    0, 0, 0, 0,           // dstX, dstY, srcX, srcY
                    $max_x, $max_y,       // dstW, dstH
                    $orig_x, $orig_y);    // srcW, srcH

            // save thumb file



            SaveImage($image_type, $ni, $to_name, $image_quality, $save_to_file);
            // }

        }

    }

    return $image_flag;


}




/*----------------function to resize the image ends-----------------------*/


function stripslashes_deep($value) {
    if (is_array($value)) {
        array_map('stripslashes_deep', $value);
    } else if (is_object($value)) {
        $value	= $value;
    } else {
        stripslashes($value);
    }
//    $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    return $value;
}
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 isValidUsername($str) {
    if (trim($str) != "") {
        if(preg_match( '/^\d*$/'  , $str) == 1) {//check whether user name is haivng just numbers
            return false;
        }
        if (eregi ("[^0-9a-zA-Z+_]", $str)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
function isValidsubdomain($str) {
    if (trim($str) != "") {
        if (eregi ("[^0-9a-zA-Z+_]", $str)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
function duplicatesubdomain($str) {
    $documentroot=str_replace("/resellers","",dirname($_SERVER['PHP_SELF']));
    $fullpath=$_SERVER['DOCUMENT_ROOT'];
    if (trim($str) != "") {
        if(is_dir($fullpath."/".$str)) {// chek folder name exists with same domain name
            return false;
        } // end if
        else {
            return true;
        }// end else

    } // end if empty check

    else {
        return false;
    }

}
function onlyChars($str) {
    if (eregi ("[^a-zA-Z]", $str)) {
        return false;
    } else {
        return true;
    }
}
function isNotNull($value) {
    if (is_array($value)) {
        if (sizeof($value) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
            return true;
        } else {
            return false;
        }
    }
}

function pageBrowser($totalrows, $numLimit, $amm, $queryStr, $numBegin, $start, $begin, $num) {
    $larrow = "&nbsp;<<&nbsp;"; //You can either have an image or text, eg. Previous
    $rarrow = "&nbsp;>>&nbsp;"; //You can either have an image or text, eg. Next
    $wholePiece = ""; //This appears in front of your page numbers
    if ($totalrows > 0) {
        $numSoFar = 1;
        $cycle = ceil($totalrows / $amm);
        if (!isset($numBegin) || $numBegin < 1) {
            $numBegin = 1;
            $num = 1;
        }
        if (!isset($start) || $start < 0) {
            $minus = $numBegin-1;
            $start = $minus * $amm;
        }
        if (!isset($begin)) {
            $begin = $start;
        }
        $preBegin = $numBegin - $numLimit;
        $preStart = $amm * $numLimit;
        $preStart = $start - $preStart;
        $preVBegin = $start - $amm;
        $preRedBegin = $numBegin-1;
        if ($start > 0 || $numBegin > 1) {
            $wholePiece .= "<a class=links href='?num=" . $preRedBegin
                    . "&start=" . $preStart
                    . "&numBegin=" . $preBegin
                    . "&begin=" . $preVBegin
                    . $queryStr . "'><font class=navigate>"
                    . $larrow . "</a></font>\n";
        }
        for ($i = $numBegin;$i <= $cycle;$i++) {
            if ($numSoFar == $numLimit + 1) {
                $piece = "<a class=links href='?numBegin=" . $i
                        . "&num=" . $i
                        . "&start=" . $start
                        . $queryStr . "'><font class=navigate>"
                        . $rarrow . "</font></a>\n";
                $wholePiece .= $piece;
                break;
            }
            $piece = "<a  class=links href='?begin=" . $start
                    . "&num=" . $i
                    . "&numBegin=" . $numBegin
                    . $queryStr
                    . "'>";
            if ($num == $i) {
                $piece .= "<b><font id=navigate class=navigate>$i</font></b>";
            } else {
                $piece .= "<font id=navigate class=navigate>$i</font>";
            }
            $piece .= "</a>\n";
            $start = $start + $amm;
            $numSoFar++;
            $wholePiece .= $piece;
        }
        $wholePiece .= "\n";
        $wheBeg = $begin + 1;
        $wheEnd = $begin + $amm;
        $wheToWhe = "<b>" . $wheBeg . "</b> - <b>";
        if ($totalrows <= $wheEnd) {
            $wheToWhe .= $totalrows . "</b>";
        } else {
            $wheToWhe .= $wheEnd . "</b>";
        }
        $sqlprod = " LIMIT " . $begin . ", " . $amm;
    } else {
        $wholePiece = "<p align=center class=text_information><font size='2'>".NO_RECORDS_DISPLAY_MSG."</font><br>&nbsp;</p>";
        $wheToWhe = "<b>0</b> - <b>0</b>";
    }

    return array($sqlprod, $wheToWhe, $wholePiece);
}
if (!function_exists('array_combine')) {
    function array_combine($a1, $a2) {
        if (count($a1) != count($a2))
            return false;
        if (count($a1) <= 0)
            return false;
        $a1 = array_values($a1);
        $a2 = array_values($a2);
        $output = array();
        for($i = 0; $i < count($a1); $i++) {
            $output[$a1[$i]] = $a2[$i];
        }
        return $output;
    }
}

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 datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
    /*
    $interval can be:
    yyyy - Number of full years
    q - Number of full quarters
    m - Number of full months
    y - Difference between day numbers
      (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
    d - Number of full days
    w - Number of full weekdays
    ww - Number of full weeks
    h - Number of full hours
    n - Number of full minutes
    s - Number of full seconds (default)
    */
    if (!$using_timestamps) {
        $datefrom = strtotime($datefrom, 0);
        $dateto = strtotime($dateto, 0);
    }
    $difference = $dateto - $datefrom; // Difference in seconds
    switch ($interval) {
        case 'yyyy': // Number of full years
            $years_difference = floor($difference / 31536000);
            if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom) + $years_difference) > $dateto) {
                $years_difference--;
            }
            if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto) - ($years_difference + 1)) > $datefrom) {
                $years_difference++;
            }
            $datediff = $years_difference;
            break;
        case "q": // Number of full quarters
            $quarters_difference = floor($difference / 8035200);
            while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($quarters_difference * 3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                $months_difference++;
            }
            $quarters_difference--;
            $datediff = $quarters_difference;
            break;
        case "m": // Number of full months
            $months_difference = floor($difference / 2678400);
            while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                $months_difference++;
            }
            $months_difference--;
            $datediff = $months_difference;
            break;
        case 'y': // Difference between day numbers
            $datediff = date("z", $dateto) - date("z", $datefrom);
            break;
        case "d": // Number of full days
            $datediff = floor($difference / 86400);
            break;
        case "w": // Number of full weekdays
            $days_difference = floor($difference / 86400);
            $weeks_difference = floor($days_difference / 7); // Complete weeks
            $first_day = date("w", $datefrom);
            $days_remainder = floor($days_difference % 7);
            $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
            if ($odd_days > 7) { // Sunday
                $days_remainder--;
            }
            if ($odd_days > 6) { // Saturday
                $days_remainder--;
            }
            $datediff = ($weeks_difference * 5) + $days_remainder;
            break;
        case "ww": // Number of full weeks
            $datediff = floor($difference / 604800);
            break;
        case "h": // Number of full hours
            $datediff = floor($difference / 3600);
            break;
        case "n": // Number of full minutes
            $datediff = floor($difference / 60);
            break;
        default: // Number of full seconds (default)
            $datediff = $difference;
            break;
    }
    return $datediff;
}
/*
function makeDropDownList($ddlname, $list, $selectedindex, $emptyrequired, $class, $properties, $behaviors)
{
    $ddl = "";
    $ddl .= "<select name=\"$ddlname\" class=\"$class\"";
    if (isNotNull($properties)) {
        $ddl .= " \"$properties\"";
    }
    if (isNotNull($behaviors)) {
        $ddl .= " $behaviors ";
    }
    $ddl .= " >";
    if ($emptyrequired) {
        $ddl .= "<option value=''";
        $ddl .= "></option>\n";
    }
    if (count($list) > 0) {
        foreach($list as $key => $value) {
            $ddl .= "<option value=\"$key\"";
            if(is_array($selectedindex)){
                if (in_array("$key", $selectedindex)) {
                    $ddl .= " selected=\"selected\"";
                }
            }else{
                if ($selectedindex == "$key") {
                    $ddl .= " selected=\"selected\"";
                }
            }

            $ddl .= ">" . htmlentities($value) . "</option>\n";
        }
    }
    $ddl .= "</select>";
    return $ddl;
}
*/
function makeDropDownList($ddlname, $list, $selectedindex, $emptyrequired, $class, $properties, $behaviors) {

    $ddl = "";
    $properties = trim($properties);
    $class = trim($class);
    $properties = trim($properties);
    $behaviors = trim($behaviors);

    $ddl .= "<select  name=\"$ddlname\" class=\"$class\" ";
    if ($properties != "") {
        $ddl .= "  $properties  ";
    }
    if ($behaviors != "") {
        $ddl .= " $behaviors ";
    }
    $ddl .= " >";
    if ($emptyrequired) {
        $ddl .= "<option value=''";
        $ddl .= "></option>\n";
    }
    if (count($list) > 0) {
        foreach($list as $key => $value) {
            $ddl .= "<option value= \"" . htmlentities($key) . "\" ";
            if (is_array($selectedindex)) {

                if (in_array($key, $selectedindex)) {
                    $ddl .= " selected=\"selected\"";
                }
            }
            else {
                if ($selectedindex ==$key) {
                    $ddl .= " selected=\"selected\"";
                }

            }
            if(strlen($value)>50)
                $value=substr($value,0,50 )."......";

            $ddl .= ">" . ($value) . "</option>\n";
        }
    }
    $ddl .= "</select>";
    return $ddl;
}


function makeCountryList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT country_iso_code_2 as val, country_name FROM " . $tableprefix . "countries ";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function makeArtistList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT artist_id,artist_name FROM " . $tableprefix . "artists  where vapproved ='Y' ORDER BY artist_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function makeSellerNameList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT artist_id, CONCAT(first_name,' ',last_name) AS artist_name FROM " . $tableprefix . "artists ORDER BY artist_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function makeUserNameList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT user_id, CONCAT(first_name,' ',last_name) AS user_name  FROM " . $tableprefix . "users ORDER BY user_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function makeUserList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT user_id,user_name  FROM " . $tableprefix . "users ORDER BY user_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function getNewslettersubscribersList($emailSubject,$emailMessage) {
    global $tableprefix;
    static $options;

    $sql = " SELECT site_url FROM " . $tableprefix . "settings";
    $res = mysql_query($sql);
    $dat_set=mysql_fetch_array($res);


    $sql = " SELECT user_id,user_name,email  FROM " . $tableprefix . "users Where newsLetter='Y'";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: ".SITE_EMAIL."<".SITE_EMAIL.">" . "\r\n";
    //$headers .= 'Bcc: ';
    //$bcc_copies = substr($bcc_copies,1);
    //$headers .= $bcc_copies;



    //Update Newsletter table before blassting the email
    $newsLetter_update = "INSERT INTO ".$tableprefix."newsletters(nl_subject, nl_message)
    VALUES(\"".addslashes($emailSubject)."\",\"".addslashes($emailMessage)."\")";
    mysql_query($newsLetter_update) or die(mysql_error());
    $newsLetterId=mysql_insert_id();

    $unSubscribeURL ="";


    $mailcontent ="";


    if ($numoptions > 0) {
        while (list($stid, $stname,$email) = mysql_fetch_row($resoptions)) {

            $siteURL      = $dat_set['site_url']."/unsubscribe.php?doIt=".base64_encode($stid);
            ;

            $mail_header  = "<p>Dear ".$stname."<p>";
            $mailcontent  = $mail_header.nl2br(stripslashes($emailMessage));
            $mailcontent .= "<br>Click the following link to unsubscribe the newsletter<br>";
            $mailcontent .= "<br><a href='".$siteURL."'>Click here to Unsubscribe</a>";
            $mail_footer  = "<p>Thanks and regards,<p>";
            $mail_footer .= "<p>Administrator,<br>".SITE_NAME."<p>";
            $mailcontent .= $mail_footer;

            $mailcontent = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="./themes/'. $active_template[4].' rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

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


</body>
</html>';


            /*$qString=base64_encode($stid);
		$unSubscribeURL="<a href='".$siteURL.$qString."'>Click here to unsubscribe</a>";
		$emailMessage.="<br><br><br>".$unSubscribeURL."<br>";*/

            $emailSubject = stripslashes($emailSubject);
            //	Pushing to email queue

            // echo  "<br>". $mailcontent;

            mail($email,$emailSubject,$mailcontent,$headers);

            // inserting subscribers to show in archives
            $newsLetter_update = "INSERT INTO ".$tableprefix."subscribers(user_id, nl_id)
		    VALUES(".$stid.",".$newsLetterId.")";
            mysql_query($newsLetter_update) or die(mysql_error());
            $message = NL_EMAIL_SUCCESS."<br>";

        }
    }else {
        $message = NL_RETRY;
        "<br>";
    }

    return $message;
}

function makeAffiliateNameList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT affiliate_id,CONCAT(first_name,' ',last_name) AS affiliate_name  FROM " . $tableprefix . "affiliates ORDER BY affiliate_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function makeAffiliateList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT affiliate_id,affiliate_name FROM " . $tableprefix . "affiliates ORDER BY affiliate_name";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

// //
// Break a word in a string if it is longer than a specified length ($len)
function break_string($string, $len, $break_char = '-') {
    $l = 0;
    $output = '';
    for ($i = 0, $n = strlen($string); $i < $n; $i++) {
        $char = substr($string, $i, 1);
        if ($char != ' ') {
            $l++;
        } else {
            $l = 0;
        }
        if ($l > $len) {
            $l = 1;
            $output .= $break_char;
        }
        $output .= $char;
    }

    return $output;
}

function sanitize_string($string) {
    $string = ereg_replace(' +', ' ', trim($string));

    return preg_replace("/[<>]/", '_', $string);
}

function replace_string($string) {
    $returnval=preg_replace("/[<>]/&.", '+', $string);

}

function getCategoryLink($baseurl, $catid) {
    global $tableprefix;
    $link = "<a class='links' href='" . $baseurl . "' class=boldtextblack>".CATEGORY."</a> ";
    if ($catid != "") {
        $link .= "<font class=\"links\">></font>";
        $sql = "SELECT * FROM `" . $tableprefix . "categories` where category_id = '" . $catid . "'";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = "<a class='links' href='" . $baseurl . "?catid=" . $currcatid . "'><b>" . (stripslashes($currcatname)) . "</b></a>";
        } else {
            $sql = "SELECT * FROM `" . $tableprefix . "categories` where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= " <a class='links' href='" . $baseurl . "?catid=" . $subcatid . "'  >" . (stripslashes($subcatname)) . "</a><font class=boldtextblack> ></font>";
                }
            }
            $link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;
    return $link;
}



function getCategoryLinkNew($baseurl, $catid) {
    global $tableprefix;
    // $link = "<a href='" . $baseurl . "'>Categories</a> ";


    if ($catid != "") {
        // $link .= " >> ";

        $sql = "SELECT * FROM " . $tableprefix . "categories where category_id = " . $catid;
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = "<a href='" . $baseurl . "?catid=" . $currcatid . "'>" . (stripslashes($currcatname)) . "</a>";
        } else {
            $sql = "SELECT * FROM " . $tableprefix . "categories where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= " <a  href='" . $baseurl . "?catid=" . $subcatid . "'>" . (stripslashes($subcatname)) . "</a>";
                }
            }
            //$link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;
    return $link;
}


function isParentCategory($catid) {
    global $tableprefix;
    $sql = "SELECT category_id FROM `" . $tableprefix . "categories` where parent_id = '" . $catid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return true;
    } else {
        return false;
    }
}

function isRootCategory($catid) {
    global $tableprefix;
    $sql = "SELECT parent_id FROM `" . $tableprefix . "categories` where category_id = '" . $catid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $row = mysql_fetch_array($result);
        $pid = $row["parent_id"];
        if (($pid == "") || ($pid == 0)) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}

function categoryHasProducts($catid) {
    global $tableprefix;
    $sql = "SELECT product_category FROM `" . $tableprefix . "products` where product_category = '" . $catid . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return true;
    }
    return false;
}
function categoryHasChildren($catid) {
    global $tableprefix;
    $sql = "SELECT category_id FROM `" . $tableprefix . "categories` where parent_id  = '" . $catid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return true;
    }
    return false;
}
function isCategoryDeletable($catid) {
    global $tableprefix;
    $sql = "SELECT parent_id FROM `" . $tableprefix . "categories` where category_id = '" . $catid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return false;
    }
    $sql = "SELECT category_id FROM `" . $tableprefix . "products` where category_id = '" . $catid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return false;
    }
    return true;
}

function make_selectlist($current_cat_id, $count) {
    global $tableprefix;
    static $option_results;
    if (!isset($current_cat_id)) {
        $current_cat_id = 0;
    }
    $count = $count + 1;
    $sql = "SELECT category_id as id, category_name as name,gift_certificate_flag
		    FROM " . $tableprefix . "categories WHERE parent_id = '" . addslashes($current_cat_id) . "' ORDER BY name ASC ";
    $get_options = mysql_query($sql);
    $num_options = mysql_num_rows($get_options);
    if ($num_options > 0) {
        while (list($cat_id, $cat_name, $gift_flag) = mysql_fetch_row($get_options)) {

            /*-------Multicart 2.0 Upgradation------------*/

            if($gift_flag == "Y") {

                $select_gift_products = "SELECT product_id FROM ".$tableprefix."products
														 WHERE product_category = ".$cat_id;

                $result_gift_products = mysql_query($select_gift_products) or die(mysql_error());

                if(mysql_num_rows($result_gift_products) > 0) {

                    if ($current_cat_id != 0) {
                        $indent_flag = "   ";
                        for ($x = 2; $x <= $count; $x++) {
                            $indent_flag .= " --> ";
                        }
                    }
                    $cat_name = $indent_flag . stripslashes($cat_name);
                    $option_results[$cat_id] = stripslashes($cat_name);
                    make_selectlist($cat_id, $count);



                }

            }
            else {

                if ($current_cat_id != 0) {
                    $indent_flag = "   ";
                    for ($x = 2; $x <= $count; $x++) {
                        $indent_flag .= " --> ";
                    }
                }
                $cat_name = $indent_flag . stripslashes($cat_name);
                $option_results[$cat_id] = stripslashes($cat_name);
                make_selectlist($cat_id, $count);

            }


        }
    }
    return $option_results;
}

function getCategoryDescendants($catid) {
    global $tableprefix;
    static $option_results;
    static $i=0;
    $option_results[$i] = $catid;
    $i++;

    /*---Mulicart 2.0 Upgradation-------*/

    $sql = "SELECT category_id FROM `" . $tableprefix . "categories` where parent_id = " . $catid;

    $result = mysql_query($sql) or die(mysql_error());

    /*---Mulicart 2.0 Upgradation-------*/

    if (mysql_num_rows($result) != 0) {
        while($row = mysql_fetch_array($result) ) {
            getCategoryDescendants($row["category_id"]);
        }
    }
    return $option_results;
}

function categoryExists($catname, $parentcatid) {
    global $tableprefix;
    $sql = "SELECT category_id FROM `" . $tableprefix . "categories` where category_name = '" . addslashes($catname) . "' AND parent_id = '" . $parentcatid . "'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        return true;
    } else {
        return false;
    }
}


function getProductStock($poId) {
    global $tableprefix;
    $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 adjustQuantities($userid) {
    global $tableprefix;


    $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++;
        }
    }
    $qtyadjusted = 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 ($qtyavailable == 0) { // soldout, so delete the item from the cart
            $sql = "DELETE FROM " . $tableprefix . "cart WHERE cart_id='" . addslashes($cartid) . "' ";
            mysql_query($sql);
            $qtyadjusted = true;
        } else if ($value > $qtyavailable) {
            $sql = "UPDATE " . $tableprefix . "cart SET quantity = '" . addslashes($qtyavailable) . "' WHERE cart_id='" . addslashes($cartid) . "' ";
            mysql_query($sql);
            $qtyadjusted = true;
            $qtyavailable = 0;
        }
    }
    return $qtyadjusted;
}
function adjustStock($userid, $mode) {

    global $tableprefix;
    $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) ;


    }



    return $stockadjusted;
}

function getCheckoutExpiredUsers() {
    global $tableprefix;
    $timenow = time();
    $oneday = 86400;

    $timeyday = $timenow - $oneday;
    $sql = "SELECT DISTINCT user_id FROM " . $tableprefix . "cart  WHERE datetime_added < '" . addslashes($timeyday) . "' AND status='1' ";
    //$sql = "SELECT DISTINCT user_id FROM " . $tableprefix . "cart  WHERE status='1' ";
    //echo $sql;
    $result = mysql_query($sql);
    $eusers = "";
    if (mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_array($result)) {
            $eusers .=",".$row["user_id"];
        }
        $eusers = substr($eusers,1);
    }
    return $eusers;
}

function getCartTotalcouponCode($userid,$couponCode) {
    global $tableprefix;
    $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;
    $currency_attributes = displayCurrencyType();

    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;
        }
    }

    $total				=	number_format($total,2,".","");
    if($couponCode['ccDiscount']<>"") {
        $total=$total-($total* $couponCode['ccDiscount'])/100;
    }

    return $total;
}


function getUserCouponcodeCartTotal($userid,$couponCode) {
    global $tableprefix;

    $currency_attributes = displayCurrencyType();

    $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;
    $currency_attributes = displayCurrencyType();
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {

            $conversionRate	= 	ConvertedCurrencyRate($currency_attributes[2]);
            $converted_price 	= 	$row['product_price'] * $conversionRate;

            $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;
        }
    }

    $total				=	number_format($total,2,".","");
    if($couponCode['ccDiscount']<>"") {
        $total=$total-($total* $couponCode['ccDiscount'])/100;
    }

    return $total;
}



function getCartTotal($userid) {
    global $tableprefix;

    $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 getUserCurrencyCartTotal($userid) {
    global $tableprefix;

    $currency_attributes = displayCurrencyType();

    $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;
    $currency_attributes = displayCurrencyType();
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {

            $conversionRate	= 	ConvertedCurrencyRate($currency_attributes[2]);
            $converted_price 	= 	$row['product_price'] * $conversionRate;

            $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 getSellerCartTotal($userid,$sellerid) {
    global $tableprefix;
    $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) . "'  and p.product_artist_id='".$sellerid."' ";
    $result = mysql_query($sql);
    $total = 0;
    $itemcount = 0;
    $currency_attributes = displayCurrencyType();
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {

            $get_convert_price = getSellerCurrency($row["product_id"]);
            $sellercurreny=getSellerCurrencySybol($row["product_artist_id"]);
            if($currency_attributes[2]!="USD" and $sellercurreny!=$currency_attributes[2]) {
                // user selected currency equllaent USD value
                // 1 USD equllaent user currency
                $get_convert_price=1/getUserCurrencyExvalue($currency_attributes[2]);
                $converted_price = ($row["product_price"]*$get_convert_price);
            } // end if
            else if($sellercurreny!="USD" and $sellercurreny!=$currency_attributes[2]) {

                if($get_convert_price != "") {
                    $converted_price = ($row["product_price"]*$get_convert_price);
                }// end if
            } // end else if
            else {
                $converted_price = $row["product_price"];
            } // end else

            $price = $row["quantity"] * $converted_price;

            if($row["discount"] !="0") {
                $price=$price- ($price*$row["discount"])/100;
            }
            $total += $price;
        }
    }
    return $total;
}
function emptyCart($userid) {
    global $tableprefix;
    $sql = "DELETE FROM " . $tableprefix . "cart  WHERE user_id = '" . addslashes($userid) . "' ";
    $result = mysql_query($sql);
    return;
}
function isCartEmpty($userid) {
    global $tableprefix;
    $sql = "SELECT cart_id FROM " . $tableprefix . "cart  WHERE user_id = '" . addslashes($userid) . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        return false;
    }
    return true;
}
function isVisitorCartEmpty($visitorid) {
    global $tableprefix;
    $sql = "SELECT cart_id FROM " . $tableprefix . "cart  WHERE visitor_cart_id = '" . addslashes($visitorid) . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        return false;
    }
    return true;
}

function mergeVisitorCartToUserCart($visitorid,$userid) {
    global $tableprefix;
    $usercart = array();
    $visitorcart = array();
    $sql = "SELECT cart_id, product_id,product_option_id,quantity FROM " . $tableprefix . "cart  WHERE visitor_cart_id = '" . addslashes($visitorid) . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $todelete = "";
        while($row = mysql_fetch_array($result)) {
            $vcartid = $row["cart_id"];
            $productid = $row["product_id"];
            $product_option_id = $row["product_option_id"];
            $quantity = $row["quantity"];
            $sql2 = "SELECT cart_id, product_id,product_option_id,quantity FROM " . $tableprefix . "cart  WHERE user_id = '" . addslashes($userid) . "'  AND product_id = '".addslashes($productid)."' AND product_option_id = '".addslashes($product_option_id)."'";
            //echo "<br>".$sql2."<br>";
            $result2 = mysql_query($sql2);
            if (mysql_num_rows($result2) > 0) {//the same product is present in usercart
                $row2 = mysql_fetch_array($result2);
                $todelete .=",".$vcartid;
                $usercartid = $row2["cart_id"];
                $userquantity =$row2["quantity"];
                $newqty = $userquantity+$quantity;
                $sql4 = "UPDATE " . $tableprefix . "cart SET visitor_cart_id='',quantity='".$newqty."'  WHERE cart_id= '".addslashes($usercartid)."' ";
                //echo $sql4."<br>";
                mysql_query($sql4);
            }else {
                $sql5 = "UPDATE " . $tableprefix . "cart SET visitor_cart_id='', user_id='".addslashes($userid)."',quantity='".$quantity."'  WHERE cart_id= '".addslashes($vcartid)."' ";
                //echo $sql5."<br>";
                mysql_query($sql5);
            }

        }
        $todelete = substr($todelete,1);
        if($todelete !="") {
            $sql6 = "DELETE FROM " . $tableprefix . "cart  WHERE cart_id IN (".addslashes($todelete).") ";
            //echo $sql6."<br>";
            mysql_query($sql6);
        }

    }

    return true;
}

function getStatusList() {
    global $tableprefix;
    static $options;
    $sql = " SELECT order_status_id, order_status FROM " . $tableprefix . "order_status ";
    $resoptions = mysql_query($sql);
    $numoptions = mysql_num_rows($resoptions);
    if ($numoptions > 0) {
        while (list($stid, $stname) = mysql_fetch_row($resoptions)) {
            $options[$stid] = $stname ;
        }
    }
    return $options;
}

function getOrderArtists($oid) {
    global $tableprefix;
    $artists = array();
    $cnt = 0;

    $sql = " SELECT artist_id FROM " . $tableprefix . "order_details WHERE order_id = '" . addslashes($oid) . "' ";
    //echo $sql;
    $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 getArtistName($sid) {
    global $tableprefix;
    $sql = "SELECT artist_name FROM `" . $tableprefix . "artists` where artist_id = '" . $sid . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $rw = mysql_fetch_array($result);
        return $rw["artist_name"];
    }
    return "";
}


function getArtistCompanyName($sid) {
    global $tableprefix;
    $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 getResellerName($sid) {
    global $tableprefix;
    $sql = "SELECT reseller_username FROM `" . $tableprefix . "resellers` where reseller_id  = '" . $sid . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $rw = mysql_fetch_array($result);
        return $rw["reseller_username"];
    }
    return "";
}
function getAffiliateName($aid) {
    global $tableprefix;
    $sql = "SELECT affiliate_name FROM `" . $tableprefix . "affiliates` where affiliate_id = '" . $aid . "' ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $rw = mysql_fetch_array($result);
        return $rw["affiliate_name"];
    }
    return "";
}
function getArtistOrderStatus($oid, $sid) {
    global $tableprefix;
    $cnt = 0;

    $sql = "SELECT s.order_status FROM " . $tableprefix . "order_details od
            INNER JOIN " . $tableprefix . "order_status s ON od.item_status = s.order_status_id
            AND od.artist_id = '" . addslashes($sid) . "'
            WHERE order_id = '" . addslashes($oid) . "' ";
    $resoptions = mysql_query($sql);
    // echo $sql;
    if (mysql_num_rows($resoptions) > 0) {
        $rw = mysql_fetch_array($resoptions);
        $status = $rw["order_status"] ;
    }
    return $status;
}

function getOrderStatus($oid) {
    global $tableprefix;
    $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 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 isValidWebImageType($mimetype) {

    if (($mimetype == "image/pjpeg") || ($mimetype == "image/jpeg") || ($mimetype == "image/x-png") || ($mimetype == "image/png") || ($mimetype == "image/gif")) {
        return true;
    } else {
        return false;
    }
}


function NewimageCreatefromtype($image) {
    list($width, $height, $type, $attr) = @getimagesize($image);
    if($type=="1") {  //gif
        $returnimage=@imagecreatefromgif($image);
    }else if($type=="2") { //jpeg
        $returnimage=@imagecreatefromjpeg($image);
    }else if($type=="3") { //png
        $returnimage=@imagecreatefrompng($image);
    }else {
        $returnimage="Not Supported";
    }
    return $returnimage;
}
function Imagetype($newImage,$newfile,$editimagefile) {
    list($width, $height, $type, $attr) = @getimagesize($editimagefile);
    $jpgCompression="60";
    if($type=="1") {  //gif
        $returnimage= @imagegif($newImage, '');
    }else if($type=="2") { //jpeg
        $returnimage=@imagejpeg($newImage, '', $jpgCompression);
        ;
    }else if($type=="3") { //png
        $returnimage= @imagepng($newImage,'');
    }else {
        $returnimage="Not Supported";
    }
    return $returnimage;
}
/*function getResizedImage($file,$img_height) {
  $img_temp = NewimageCreatefromtype($file);
  $black = @imagecolorallocate ($img_temp, 0, 0, 0);
  $white = @imagecolorallocate ($img_temp, 255, 255, 255);
  $font = 2;
  $img_width=@imagesx($img_temp)/imagesy($img_temp)*$img_height;
  $img_thumb=@imagecreatetruecolor($img_width,$img_height);
  @imagecopyresampled($img_thumb,$img_temp,0,0,0,0,$img_width,$img_height,@imagesx ($img_temp),@imagesy($img_temp));
  $originx = @imagesx($img_thumb) - 100;
  $originy = @imagesy($img_thumb) - 15;
  header ("Content-type: image/jpeg");
  imagejpeg($img_thumb, '', 60);
}*/
function getResizedImage($file, $img_height) {
    list($originalwidth, $originalheight, $originaltype) = getimagesize($file);
    $img_temp = NewimageCreatefromtype($file);
    $black = @imagecolorallocate ($img_temp, 0, 0, 0);
    $white = @imagecolorallocate ($img_temp, 255, 255, 255);
    $font = 2;
    $img_width = @imagesx($img_temp) / imagesy($img_temp) * $img_height;
    if ($originaltype == "1") { // gif
        $newwidth = $img_width;
        $newheight = $img_height;
        $tpcolor = imagecolorat($img_temp, 0, 0);
        // in the real world, you'd better test all four corners, not just one!
        $img_thumb = imagecreate($newwidth, $newheight);
        // $dest automatically has a black fill...
        imagepalettecopy($img_thumb, $img_temp);
        imagecopyresized($img_thumb, $img_temp, 0, 0, 0, 0, $newwidth, $newheight,
                @imagesx ($img_temp), @imagesy($img_temp));
        $pixel_over_black = imagecolorat($img_thumb, 0, 0);
        // ...but now make the fill white...
        $bg = imagecolorallocate($img_thumb, 255, 255, 255);
        imagefilledrectangle($img_thumb, 0, 0, $newwidth, $newheight, $bg);
        imagecopyresized($img_thumb, $img_temp, 0, 0, 0, 0, $newwidth, $newheight,
                @imagesx ($img_temp), @imagesy($img_temp));
        $pixel_over_white = imagecolorat($img_thumb, 0, 0);
        // ...to test if transparency causes the fill color to show through:
        if ($pixel_over_black != $pixel_over_white) {
            // Background IS transparent
            imagefilledrectangle($img_thumb, 0, 0, $newwidth, $newheight,
                    $tpcolor);
            imagecopyresized($img_thumb, $img_temp, 0, 0, 0, 0, $newwidth,
                    $newheight, @imagesx ($img_temp), @imagesy($img_temp));
            imagecolortransparent($img_thumb, $tpcolor);
            imagegif($img_thumb);
        } else // Background (most probably) NOT transparent
            imagegif($img_thumb);
    } else {
        $img_thumb = @imagecreatetruecolor($img_width, $img_height);
        @imagecopyresampled($img_thumb, $img_temp, 0, 0, 0, 0, $img_width, $img_height, @imagesx ($img_temp), @imagesy($img_temp));
        $originx = @imagesx($img_thumb) - 100;
        $originy = @imagesy($img_thumb) - 15;
        header ("Content-type: image/jpeg");
        imagejpeg($img_thumb, '', 60);
    }
}
function getCategory($baseurl, $catid) {
    global $tableprefix;
    $link = "";
    $append="NO";
    if ($catid != "") {
        $link .= "<font class=boldtextblack>></font>";
        $sql = "SELECT * FROM `" . $tableprefix . "categories` where category_id = '" . $catid . "'";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = "<b>" . htmlentities($currcatname) . "</b>";
        } else {
            $sql = "SELECT * FROM `" . $tableprefix . "categories` where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= "<b>" . htmlentities($subcatname) . "</b>";
                    $link =$link. "<font class=boldtextblack> ></font>";
                }
            }
            $link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;
    $link = substr($link, 37);

    return $link;
}
function makeDropDownList_search($ddlname, $list, $selectedindex, $emptyrequired, $class, $properties, $behaviors) {
    //remove ' from selected category
    $selectedindex=str_replace("'",'',$selectedindex);
    $selectedindex=trim($selectedindex);

    $ddl = "";
    $properties = trim($properties);
    $class = trim($class);
    $properties = trim($properties);
    $behaviors = trim($behaviors);

    $ddl .= "<select  name=\"$ddlname\" class=\"$class\" ";
    if ($properties != "") {
        $ddl .= "  $properties  ";
    }
    if ($behaviors != "") {
        $ddl .= " $behaviors ";
    }
    $ddl .= " >";
    if ($emptyrequired) {
        $ddl .= "<option value=''";
        $ddl .= "> ".ALL_TEXT."</option>\n";
    }
    if (count($list) > 0) {
        foreach($list as $key => $value) {
            $ddl .= "<option value= \"" . htmlentities($key) . "\" ";
            if (is_array($selectedindex)) {
                if (in_array("$key", $selectedindex)) {
                    $ddl .= " selected=\"selected\"";
                }
            } else {
                if ($selectedindex == "$key") {
                    $ddl .= " selected=\"selected\"";
                }
            }
            $title = stripslashes($value);
            if(strlen($value)>20)
                $value=substr($value,0,20 )."...";

            $ddl .= " title='".$title."'>" . stripslashes($value) . "</option>\n";
        }
    }
    $ddl .= "</select>";
    return $ddl;
}

function ReplaceArray($name) { // function for replace quotes in image
    $name=str_replace(' ','_',$name);
    $name=str_replace("'",'_',$name);
    $name=str_replace(".",'_',$name);
    return ($name);
}//end fucnction

function ReplaceArrayImage($name) { // function for replace quotes in image
    $name=str_replace(' ','_',$name);
    $name=str_replace("'",'_',$name);
    return ($name);
}//end fucnction

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

// Country data table
//
//
// To edit the list, just delete a line or add a line.  Order is important.  The order
// displayed is the order it appears on the drop down.
//
var country = '
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";

    $StateArray=split(',',$state);

    foreach ($StateArray as $val) {
        list($fist,$sName)=split($Country.':'.$cState.':',$val);
        if(trim($sName)!='') {
            return($sName);
        }//end if
    }//end if
}//end fucntion

//fucntion for remove comma from an array
function ArrayRemove($arrVal,$chkVal) {
    foreach($arrVal as $val) {
        if($val!=$chkVal) {
            $val=str_replace(",","",trim($val));
            $arrNewVal[]=$val;
        }//end if
    }//end foreach
    return($arrNewVal);
}//end function

//fucntion for remove comma from an array
function ArrayRemoveBlank($arrVal) {
    foreach($arrVal as $val) {
        if(trim($val)!='') {
            $val=$val;
            $arrNewVal[]=$val;
        }//end if
    }//end foreach
    return($arrNewVal);
}//end function

//function to reassign key
function ReassignKey($kArray,$vArray) {
    $i=0;
    foreach ($kArray as $val) {
        $name='labels'.$val;
        if(trim($_POST[$name])!='') {
            $name=$_POST[$name];
            $arrNewVal[$name]=$vArray[$i];
        }//end if
        else {
            $arrNewVal[$val]=$vArray[$i];
        }//end else
        $i++;
    }//end foreach
    return($arrNewVal);
}//end function

// function for getting user selected currency exchange valeu

function getUserCurrencyExvalue($currencyCode) {
    global $tableprefix;

    $currency = mysql_query("SELECT nexchange_price
							   from ".$tableprefix."currency_master
							   Where vcurrency_code='".$currencyCode."'") or die(mysql_error);

    if(mysql_num_rows($currency) > 0) {
        return (mysql_result($currency ,0,"nexchange_price"));
    }	// end if
    else {
        return 0;
    }	// end else

} // end function

// Function for copying  files from a folder to another folder
function copydir($source,$destination) {
    if(!is_dir($destination)) {
        $oldumask = umask(0);
        mkdir($destination, 0755); // so you get the sticky bit set
        umask($oldumask);
    }
    $dir_handle = @opendir($source);
    while ($file = @readdir($dir_handle)) {
        if($file!="." && $file!=".." && !is_dir("$source/$file"))
            copy("$source/$file","$destination/$file");
    }
    @closedir($dir_handle);
}
// End Function

function resizeImg2($imgPath, $maxWidth, $maxHeight, $directOutput = true, $quality = 90, $verbose,$imageType,$imgPath2) {
    // get image size infos (0 width and 1 height,
    //     2 is (1 = GIF, 2 = JPG, 3 = PNG)

    $size = @getimagesize($imgPath);

    // break and return false if failed to read image infos
    if(!$size) {
        if($verbose && !$directOutput)echo "<br />Not able to read image infos.<br />";
        return false;
    }

    // relation: width/height
    $relation = $size[0]/$size[1];
    // maximal size (if parameter == false, no resizing will be made)
    $maxSize = array($maxWidth?$maxWidth:$size[0],$maxHeight?$maxHeight:$size[1]);
    // declaring array for new size (initial value = original size)
    $newSize = $size;
    // width/height relation
    $relation = array($size[1]/$size[0], $size[0]/$size[1]);


    if(($newSize[0] > $maxWidth)) {
        $newSize[0]=$maxSize[0];
        $newSize[1]=$newSize[0]*$relation[0];
    }



    /*
	if(($newSize[1] > $maxHeight))
	{
		$newSize[1]=$maxSize[1];
		$newSize[0]=$newSize[1]*$relation[1];
	}
    */

    // create image

    switch($size[2]) {
        case 1:
            if(@function_exists("imagecreatefromgif")) {
                $originalImage = @imagecreatefromgif($imgPath);
            }else {
                if($verbose && !$directOutput)echo "<br />No GIF support in this php installation, sorry.<br />";
                return false;
            }
            break;
        case 2: $originalImage = @imagecreatefromjpeg($imgPath);
            break;
        case 3: $originalImage = @imagecreatefrompng($imgPath);
            break;
        default:
            if($verbose && !$directOutput)echo "<br />No valid image type.<br />";
            return false;
    }


    // create new image

    $resizedImage = @imagecreatetruecolor($newSize[0], $newSize[1]);

    @imagecopyresampled($resizedImage, $originalImage,0, 0, 0, 0,$newSize[0], $newSize[1], $size[0], $size[1]);

    $rz=$imgPath;

    // output or save
    if($directOutput) {
        @imagejpeg($resizedImage);
    }
    else {

        $rz=preg_replace("/\.([a-zA-Z]{3,4})$/","".$imageType.".jpg",$imgPath2);
        @imagejpeg($resizedImage, $rz, $quality);
    }
    // return true if successfull
    return $rz;
}

// Function for Getting Dealer Currency Symbol
function getDealerCurrencySybol($artistID) {
    global $tableprefix;

    $select_artist_currency = "SELECT currency
							   FROM ".$tableprefix."resellers
							   where reseller_id='".$artistID."' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['currency'];
} // end function

//fucntion for display file path nmae
function ClientFilePathName($PhpSelf) {
    $fpath=split("/",$PhpSelf);
    $fpath=$fpath[count($fpath)-1];
    return ($fpath);
}//end function

// Finding Domain name
function find_base_domain($url=false) {
    if($url== false) {
        $url = (@is_array($_SERVER)) ? $_SERVER['SERVER_NAME'] : ((@is_array($HTTP_SERVER_VARS)) ? $HTTP_SERVER_VARS['SERVER_NAME'] : $SERVER_NAME );
//If $_SERVER is an array, give the server name, if $HTTP_SERVER_VARS is an array, give the server name from that, if not, then just use the old old $SERVER_NAME variable;
    }
//Continue with the rest of the function;
    $url = str_replace("http://","",$url);
    $domainExt = substr($url,strrpos($url,"."));

    $domain = substr($url,0,strrpos($url,"."));

    if(strstr($domain,".")) {
        $base_domain = substr($domain,strrpos($domain,".")+1);
    }else {
        $base_domain = $domain;
    }
    return $base_domain.$domainExt;
}

// Function for Getting Dealer Currency Symbol
function getproductCount($parent_id) {
    global $tableprefix;

    $select_artist_currency = "SELECT category_id
							   FROM ".$tableprefix."categories
							   where parent_id='".$parent_id."' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);
    $catid=array();
    if(mysql_num_rows($result_artist_currency) > 0) {
        while($rs1=mysql_fetch_array($result_artist_currency)) {
            $catid[]=$rs1['category_id'];
        }
        $idstring	= implode("','", $catid);
        $sql_cnt="Select count(*) as cnt from ".$tableprefix."products where product_category   IN ('{$idstring}')";
        $rs_cnt=mysql_query($sql_cnt);
        $procount=mysql_result($rs_cnt,0,"cnt");
    }
    else {
        $procount=0;
    }
    return $procount;
} // end functio

// Resize Thumbnails

function resizeImg($imgPath, $maxWidth, $maxHeight, $directOutput = true, $quality = 90, $verbose,$imageType) {
    $size = getimagesize($imgPath);
    //print_r($size);exit;
    // break and return false if failed to read image infos
    if(!$size) {
        if($verbose && !$directOutput)echo "<br />Not able to read image infos.<br />";

        return false;
    }

    // relation: width/height
    $relation = $size[0]/$size[1];
    // maximal size (if parameter == false, no resizing will be made)
    $maxSize = array($maxWidth?$maxWidth:$size[0],$maxHeight?$maxHeight:$size[1]);
    // declaring array for new size (initial value = original size)
    $newSize = $size;
    // width/height relation
    $relation = array($size[1]/$size[0], $size[0]/$size[1]);
    //print_r($size);
    //echo "<br>";
    //print_r($relation);exit;

    if(($newSize[0] > $maxWidth)) {
        $newSize[0]=$maxSize[0];
        $newSize[1]=$newSize[0]*$relation[0];
    }




    if(($newSize[1] > $maxHeight)) {
        $newSize[1]=$maxSize[1];
        $newSize[0]=$newSize[1]*$relation[1];
    }


    // create image
    switch($size[2]) {
        case 1:
            if(function_exists("imagecreatefromgif")) {
                $originalImage = imagecreatefromgif($imgPath);
            }else {
                if($verbose && !$directOutput)echo "<br />No GIF support in this php installation, sorry.<br />";
                return false;
            }
            break;
        case 2: $originalImage = imagecreatefromjpeg($imgPath);
            break;
        case 3: $originalImage = imagecreatefrompng($imgPath);
            break;
        default:
            if($verbose && !$directOutput)echo "<br />No valid image type.<br />";
            return false;
    }

    // create new image

    $resizedImage = imagecreatetruecolor($newSize[0], $newSize[1]);

    imagecopyresampled($resizedImage, $originalImage,0, 0, 0, 0,$newSize[0], $newSize[1], $size[0], $size[1]);

    $rz=$imgPath;

    // output or save
    if($directOutput) {
        imagejpeg($resizedImage);
    }
    else {

        $exp=explode(".",$imgPath);
        $extension=$exp[count($exp)-1];
        $newimage=$imageType.".".$extension;
        $rz=preg_replace("/\.([a-zA-Z]{3,4})$/",$newimage,$imgPath);
        imagejpeg($resizedImage, $rz, $quality);
    }
    // return true if successfull
    return $rz;
} // End function Resize Image


// End function Resize Image

// check file extension of an image

function get_image_extension($filename) {
    if (@function_exists('exif_imagetype')) {
        switch (@exif_imagetype($filename)) {
            case 1:
                return 'gif';
            case 2:
                return 'jpg';
            case 3:
                return 'png';
            case 4:
                return 'swf';
            case 5:
                return 'psd';
            case 6:
                return 'bmp';
            case 7:
                return 'tiff';
            case 8:
                return 'tiff';
            case 9:
                return 'jpc';
            case 10:
                return 'jp2';
            case 11:
                return 'jpx';
            case 12:
                return 'jb2';
            case 13:
                return 'swc';
            case 14:
                return 'iff';
            case 15:
                return 'wbmp';
            case 16:
                return 'xbm';
            default:
                return false;
        }
    }
    else
        return false;
}

function GetShippingMethod($orderid,$productid) { // function for getting shipping method
    global $tableprefix;

    $select_shipping="SELECT vshipping_name
							   FROM ".$tableprefix."shipping_details
							   where norder_id='".$orderid."' AND nshp_productid='".$productid."' ";

    $result_shipping= mysql_query($select_shipping) or die(mysql_error);

    if(mysql_num_rows($result_shipping) > 0) {
        $shippingrow=mysql_fetch_assoc($result_shipping);
    }
    return $shippingrow['vshipping_name'];

} // end shipping method

function getAdminEmail() {
    global $tableprefix;
    $sql  = "SELECT site_email FROM ".$tableprefix."settings";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $var_site_email = stripslashes($row["site_email"]);
    }
    return $var_site_email;
}
function getLicense() {
    global $tableprefix;
    $sql  = "SELECT vLicenceKey FROM ".$tableprefix."settings";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $var_licencekey = stripslashes($row["vLicenceKey"]);
    }
    return $var_licencekey;
}
function getCustomerEmail($userid) {
    global $tableprefix;

    $select_artist_currency = "SELECT email
							   FROM ".$tableprefix."users
							   where user_id='".$userid."' ";

    $result_artist_currency = mysql_query($select_artist_currency) or die(mysql_error);

    if(mysql_num_rows($result_artist_currency) > 0) {
        $artist_row_currency = mysql_fetch_assoc($result_artist_currency);
    }
    return $artist_row_currency['email'];
}

function checkValiditycouponCode($couponCode) {
    global $tableprefix;
    $currentDate=date('Y-m-d');
    $sql  = "SELECT * FROM ".$tableprefix."couponcode WHERE ccCode='".trim($couponCode)."' AND ccStatus='Y' AND subscriptionStatus='Y' AND ccStartDate<='".$currentDate."' AND  ccEndDate>='".$currentDate."'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $couponCode_det['ccID']=$row['ccID'];
        $couponCode_det['ccCode']=$row['ccCode'];
        $couponCode_det['ccDiscount']=$row['ccDiscount'];
        $_SESSION['couponCode_det']=$couponCode_det;
        return $couponCode_det;
    }else {
        unset($_SESSION['couponCode_det']);
        return false;
    }

}
// end function

function validateMembership($artID) {
    global $tableprefix;
    $currentDate=date('Y-m-d');
    $sql  = "SELECT sellerPlanID FROM ".$tableprefix."artists AS art
			 LEFT JOIN ".$tableprefix."artists_membershipDetails AS artMem ON artMem.artist_id  = art.artist_id
			 WHERE art.artist_id=".$artID." AND artMem.artist_memStartDate<='".$currentDate."' AND  artMem.artist_memEndDate>='".$currentDate."'";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $_SESSION['SES_MEMPLAN']=$row['sellerPlanID'];
        return $_SESSION['SES_MEMPLAN'];
    }else {
        unset($_SESSION['SES_MEMPLAN']);
        return false;
    }
}

function checkARTPrivilege() {
    global $tableprefix;
    $sql = "SELECT enable_membership  FROM ".$tableprefix."settings ";
    $res = mysql_query($sql);
    if(mysql_num_rows($res)>0) {
        $row = mysql_fetch_array($res);
        if($row["enable_membership"]=="Y") {
            if($_SESSION['SES_MEMPLAN']<>1) {
                header("location:artistmain.php");
                exit();
            }
        }
    }
}

function showExpireMessage($artID) {
    global $tableprefix;
    unset($_SESSION['SES_PLANDET']);
    $currentDate=date('Y-m-d');
    /*	$sql  = "SELECT max(artMem.artist_memID), max( artMem.artist_memEndDate ) as artist_memEndDate,plan_Id, (To_days( max( artMem.artist_memEndDate )) - TO_DAYS('".$currentDate."')) as difference FROM ".$tableprefix."artists AS art
			 LEFT JOIN ".$tableprefix."artists_membershipDetails AS artMem ON artMem.artist_id  = art.artist_id
			 WHERE art.artist_id=".$artID."  GROUP BY art.artist_name";
    */
    $sql  = "SELECT max(artMem.artist_memID), max( artMem.artist_memEndDate ) as artist_memEndDate,plan_Id, (To_days( max( artMem.artist_memEndDate )) - TO_DAYS('".$currentDate."')) as difference
				 FROM ".$tableprefix."artists_membershipDetails AS artMem
				 WHERE artMem.artist_id=".$artID."  GROUP BY artist_memID ORDER BY `artist_memID` DESC LIMIT 0 , 1";


    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $dataArray['EndDate']=$row['artist_memEndDate'];
        $dataArray['difference']=$row['difference'];
        $dataArray['PlanID']=$row['plan_Id'];
        $DATA_getplanName=	mysql_fetch_array(mysql_query("SELECT plan_Title,plan_Period FROM ".$tableprefix."sellerPlans WHERE plan_Id=".$dataArray['PlanID']));
        $dataArray['PlanTitle']=$DATA_getplanName['plan_Title'];
        $dataArray['PlanPeriod']=$DATA_getplanName['plan_Period'];
        $_SESSION['SES_PLANDET']=$dataArray;
        return $dataArray;
    }
}

function getArtistID($userID) {
    global $tableprefix;
    $sql = "SELECT p.product_artist_id
        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;
    $currency_attributes = displayCurrencyType();
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {
            return	 $row["product_artist_id"];
        }
    }
}


//to validate cart, make sure cart holds only a single user's product
function validateCart($productid,$thisSessionID,$userid) {
    global $tableprefix;
    if($productid<>"") {
        $sql = "SELECT product_id,product_artist_id FROM ".$tableprefix."products  WHERE product_id = '".addslashes($productid)."'";
        $resultRest=mysql_query($sql) or die(mysql_error());
        $dataRest=mysql_fetch_array($resultRest);
        $upcomingProductsRestID=$dataRest['product_artist_id'];
    }
    if($thisSessionID<>"")
        $sql = "SELECT cart_id,product_id FROM ".$tableprefix."cart  WHERE visitor_cart_id = '".addslashes($thisSessionID)."' ";

    if($userid<>"")
        $sql = "SELECT cart_id,product_id FROM ".$tableprefix."cart  WHERE user_id = '".addslashes($userid)."' ";

    if($sql<>"") {
        $count=mysql_num_rows(mysql_query($sql));

        if($count>0) {
            $datacategories=mysql_fetch_array(mysql_query($sql));
            $existingProductsID=$datacategories['product_id'];
            $sql = "SELECT product_id,product_artist_id FROM ".$tableprefix."products  WHERE product_id = '".addslashes($existingProductsID)."'";
            $resultRest=mysql_query($sql) or die(mysql_error());
            $dataRest=mysql_fetch_array($resultRest);
            $existingProductsRestID=$dataRest['product_artist_id'];
            if($upcomingProductsRestID<>$existingProductsRestID) {
                //Removing existing cart values
                if($thisSessionID<>"")
                    $sql = "DELETE FROM ".$tableprefix."cart  WHERE visitor_cart_id = '".addslashes($thisSessionID)."' ";

                if($userid<>"")
                    $sql = "DELETE FROM ".$tableprefix."cart  WHERE user_id = '".addslashes($userid)."' ";
                $resultRest=mysql_query($sql) or die(mysql_error());
            }

        }
    }


}


//fucntion for disaply style array
function ShowTemplates($style) {
    $StylewArray=array();
    //create array
    foreach (showThemes() as $key=>$val) {
        $StylewArray[$val['theme_file']]=$key;
    }//end foreach

    asort($StylewArray);
    echo '<select name="style" class="textbox" onChange="showHint(this.value);">';
    foreach($StylewArray as $key=>$value) {
        ?>
<option value="<?php echo ($key)?>" <?php if($key==$style) {
            echo 'selected';
        }?>><?php echo $value?></option>
        <?php
    }//end foreach
    echo '</select>';
}//end function

//fuction for listing themes from themes folder
function showThemes() {
    $theme_root='../themes/';
    $themes_dir = @ opendir($theme_root);
    while ( ($theme_dir = readdir($themes_dir)) !== false ) {
        if ( is_dir($theme_root . '/' . $theme_dir) && is_readable($theme_root . '/' . $theme_dir) ) {
            if ( $theme_dir{0} == '.' || $theme_dir == 'CVS' )
                continue;

            $stylish_dir = @opendir($theme_root . '/' . $theme_dir);
            $found_stylesheet = false;

            while ( ($theme_file = readdir($stylish_dir)) !== false ) {
                if ( $theme_file == 'style.css' ) {
                    $theme_files[$theme_dir] = array( 'theme_file' => $theme_dir . '/' . $theme_file, 'theme_root' => $theme_root );
                    $found_stylesheet = true;
                    break;
                }//end if
            }//end while loop
            @closedir($stylish_dir);
        }//end first if
    }//end whil loop
    if ( is_dir( $theme_dir ) )
        @closedir( $theme_dir );
    return $theme_files;
}//end function


//function for template preview
function TemplatePreview($stylePath) {
    //split style path
    $styleFolder=@split("[/]",$stylePath);

    $theme_root='../themes/'.$styleFolder[0];
    $themes_dir = @ opendir($theme_root);
    while ( ($preview_file = readdir($themes_dir)) !== false ) {
        if ( $preview_file == 'preview.gif' ) {
            $preview_file=$theme_root.'/'.$preview_file;
            break;
        }//end if
        @closedir($stylish_dir);
    }//end whil loop
    if ( is_dir( $theme_dir ) )
        @closedir( $theme_dir );
    return $preview_file;
}//end functionn for listing themes from themes folder



function ProductRatingStar($pid,$units='',$static='') {
    global $tableprefix,$_SESSION;

    if($pid!='') {
        $select_rating_count = mysql_query("SELECT ROUND(SUM(nrating_id)/COUNT(nrating_id)) AS average_rating FROM ".$tableprefix."record_ratings WHERE
	   											vType='p' AND nrseller_id = ".$pid);

        $average_rating_count	=0;

        if(mysql_num_rows($select_rating_count)>0) {

            $rating_count = @mysql_fetch_array($select_rating_count);


            if($rating_count['average_rating']!='') {
                $average_rating_count	= $rating_count['average_rating'];

            }
            else {
                $average_rating_count	=0;
            }

        }


    }


    /* $type_rate=mysql_query("select vrating from ".$tableprefix."rating where nrat_id=".$rating_count['average_rating']);
	   $rating_type=@mysql_fetch_array($type_rate);

      $ncount=0; // resets the count
      $rater.='  </ul>';
      $rater.='  <p';
	  if($voted){ $rater.=' class="voted"'; }
      $rater.='>Current Rating :'.$rating_type['vrating'];
      $rater.='  </p>';
	  $rater.='  </td></tr></table>';
      $rater.='</div>';
      $rater.='</div>';*/

    return $average_rating_count;


}

// Check Selected Category is a Gift Certicate or not
function CheckGiftCertificateCategory($gcatid) {
    global $tableprefix;

    $select_gift_cat="SELECT gift_certificate_flag
							   FROM ".$tableprefix."categories
							   where category_id='".$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 sendBuyerEmail($order_id,$user_id,$usertype='user') {
    global $tableprefix,$_SESSION;

    $currency_attributes=displayCurrencyType();

    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Product Name</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);
        $couponCodeDiscount=$orderObj->couponCodeDiscount;
        $productname.= $optionStr;


        // Shipping Cost
        if($orderDetailObj->nshipping_cost!=0) {
            $totalshippingcost += $orderDetailObj->nshipping_cost;
        }
        // Shipping Cost


        $converted_price = $orderDetailObj->product_price;

        $rate = number_format(($converted_price),2 ,".","" );
        // End currency Conversion
        /*------------Multicart 2.0 Upgradation------------*/

        $qty = $orderDetailObj->product_quantity;
        $price = $qty * $rate;
        $discountstr="";
        if($orderDetailObj->product_discount !="0") {
            $price=$price- ($price*$orderDetailObj->product_discount)/100;

            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";
        }



        //$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");


        $itemTotal+=$price;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

        $inc++;

    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

    $mailContent .='<tr>
		<td>Item Price Total:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';



    // Modified ON 22-07-2010 // Asha
    if($couponCodeDiscount>0) {
        //echo "sdhjsdhasd";
        $priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        $ItemTotalPrice=$priceafterdiscount;
        $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">Coupon Code " '.$orderObj->couponCode.' " Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.($orderObj->couponCodeDiscount).' % </td>
		</tr>
		<tr>
		<td>Item Total Cost After Coupon Code Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';

    }


    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    if($totalshippingcost!=0) {
        //echo $orderObj->order_total_price;
        $mailContent .='<tr>
			<td width="40%">Shipping & Handling: </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
    }



    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$orderObj->taxrate,2,".","").'</td>
			</tr>';


    if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        $mailContent.='<tr>
		<td> Gift Certificate Code :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }


    $mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';

    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }
    if($giftCheckVal=="") {
        if($orderObj->shipping_address2) {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }else {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
    }

    if($usertype=="guest") {
        $sql_usrObj="SELECT user_name,email from ".$tableprefix."users where user_id='".$orderObj->user_id."' ";
        $rs_Order	=mysql_query($sql_usrObj) or die(mysql_error());
        if(mysql_num_rows($rs_Order)>0) {
            $rs_Order_obj=mysql_fetch_object($rs_Order);

            $guest_user_name=$rs_Order_obj->user_name;

            $guest_user_password=$_SESSION["sess_guest_password"];

            $mailContent .='<tr><td>&nbsp;</td></tr>';

            $mailContent .='<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> <I>NOTE : </I> You can login to '.$orderObj->storename.' ( '.SITE_URL.') using  following details to check the order status.</td></tr>';

            $mailContent .='<tr><td>User Name : &nbsp;<b>'.$guest_user_name.'</b></td></tr>';

            $mailContent .='<tr><td>Password  : &nbsp;<b>'.$guest_user_password.'</b></td></tr>';

            $mailContent .='<tr><td>&nbsp;</td></tr></table>';
        }
    }

    $mailContent .='</table>';

    $mailcontent_buyer=readEmailTemplate('order_notification_buyer');

    if(stristr($mailcontent_buyer,"[buyer_first_name")) {
        $mailcontent_buyer=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_buyer);
    }
    if(stristr($mailcontent_buyer,"[buyer_last_name")) {
        $mailcontent_buyer=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_buyer);
    }


    $mailcontent_buyer=str_replace('[order_details]',$mailContent,$mailcontent_buyer);


    $mail_send_details_buyer ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_buyer.'</p>
                  </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_buyer;

    $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  = "New Order placed at ".SITE_NAME;

    //echo $mail_send_details_buyer;


    $mailsent = mail($orderObj->billing_email,$ordersubject,$mail_send_details_buyer,$headers);

    // echo $mailContent;
}

function sendSellerEmail($order_id,$user_id) {
    global $tableprefix;

    $adminCurrency	= GetAdminCurrency();

    $currencySymbol	=	$adminCurrency['currency_symbol'];

    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);

    $queryOrderDetail_seller	 = "SELECT DISTINCT od.artist_id,s.*
  										FROM ".$tableprefix."order_details od
										INNER JOIN ".$tableprefix."artists s ON s.artist_id=od.artist_id
										WHERE od.order_id =".$order_id;
    $orderDetailQ_seller     = mysql_query($queryOrderDetail_seller);

    while($orderobjseller=mysql_fetch_object($orderDetailQ_seller)) {

        $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Product Name</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';


        $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id." AND od.artist_id=".$orderobjseller->artist_id." ";
        $orderDetailQ     = mysql_query($queryOrderDetail);
        $itemTotal =0;
        $inc = 1;
        $totalshippingcost=0;
        $taxTotal =0;
        $productlist_fillstock=array();
        while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
            $optionStr="";


            if($giftCheckVal) {
                $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
            }
            $productname=stripslashes($orderDetailObj->product_name);
            $couponCodeDiscount=$orderObj->couponCodeDiscount;
            $productname.= $optionStr;


            // Shipping Cost
            if($orderDetailObj->nshipping_cost!=0) {
                $totalshippingcost += $orderDetailObj->nshipping_cost;
            }
            // Shipping Cost


            $converted_price = $orderDetailObj->product_price;

            $rate = number_format(($converted_price),2 ,".","" );
            // End currency Conversion
            /*------------Multicart 2.0 Upgradation------------*/

            $qty = $orderDetailObj->product_quantity;
            $price = $qty * $rate;
            $discountstr="";
            if($orderDetailObj->product_discount !="0") {
                $price=$price- ($price*$orderDetailObj->product_discount)/100;

                $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";
            }



            //$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");


            $itemTotal+=$price;

            $taxTotal+=$orderDetailObj->product_tax;

            $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currencySymbol.'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currencySymbol.'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';
            $inc++;

        }
        $mailContent.='</table>
		</td>
		</tr>';

        $ItemTotalPrice=0;
        //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
        $ItemTotalPrice=$itemTotal;
        $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

        $mailContent .='<tr>
		<td>Item Price Total:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp;'.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';

        // Modified ON 22-07-2010 // Asha
        /*if($couponCodeDiscount>0)
	{
		//echo "sdhjsdhasd";
		$priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
		$totalprice=$priceafterdiscount+$orderObj->transportation_amount+$orderObj->taxrate;
		$mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">Coupon Code " '.$orderObj->couponCode.' " Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.($orderObj->couponCodeDiscount).' % </td>
		</tr>
		<tr>
		<td>Item Total Cost After Coupon Code Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">$ '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';

	}

	if($giftCertificate_Code!='' &&  $giftCertificate_Amount>0)
	{
		$mailContent.='<tr>
		<td> Gift Certificate Code :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$giftCertificate_Code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">$ '.number_format($giftCertificate_Amount,2,".","").' </td>
		</tr>';
	}*/

        $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.$taxTotal.'</td>
		</tr>';

        if($totalshippingcost!=0) {
            //echo $orderObj->order_total_price;
            $mailContent .='<tr>
			<td width="40%">Shipping & Handling: </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
        }

        $mailContent .='<tr>
			<td>Order Total Price:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$taxTotal,2,".","").'</td>
			</tr>';


        if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
            $mailContent.='<tr>
		<td> Gift Certificate Code :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';

            $mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';
        }

        if($orderObj->billing_address2) {
            $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
        }else {
            $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
        if($giftCheckVal=="") {
            if($orderObj->shipping_address2) {
                $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
            }else {
                $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
            }
        }

        $mailContent .='</table>';

        $mailcontent_seller = readEmailTemplate('order_notification_mail_seller');

        //  echo $mailcontent_seller;

        $mailcontent_seller=str_replace('[order_details]',$mailContent,$mailcontent_seller);

        $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="103%" 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"> Dear '.$orderobjseller->first_name.'&nbsp;'.$orderobjseller->last_name.', </td>
			<tr>
			<tr>
			<td align="left">A new order has been placed  in '.SITE_NAME.' .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_seller.'</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 "<br>".$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  = "New Order placed at ".SITE_NAME;

        //$orderobjseller->email='asha.s@armiasystems.com';

        //echo $ordersubject,$mail_send_details_seller;

        $mailsent = mail($orderobjseller->email,$ordersubject,$mail_send_details_seller,$headers);

        // Send Stock reorder Mail

    } // end while loop of artists

    // echo $mailContent;
}

function checkSellerStock($product_option_id,$quantity=0) {
    global $tableprefix;

    $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 sendStockreordermail($product_option_id,$quantity=0) {
    global $tableprefix;

    $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">
		Product Restocking Information
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailcontent .= '<tr>
		<td >Product Name</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.stripslashes($productObj->product_name)." ".$optionVal.'</td>
		</tr>
		<tr>
		<tr>
		<td >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>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="103%" 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"> Dear '.$productObj->first_name.'&nbsp;'.$productObj->last_name.', </td>
			<tr>
			<tr>
			<td align="left">Stock reorder level information - '.SITE_NAME.' .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 = "Stock Reorder at ".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 sendgiftCertificateMail_Buyer($order_id,$user_id,$usertype='') {
    global $tableprefix,$_SESSION;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Gift Certificate Name</td>
		<td align="left" valign="top">Gift Certificate Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>

		</tr>';
    $queryOrderDetail = "SELECT od.*,gc.vgift_coupon_code
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."giftcertificates gc ON gc.ngift_product_id=od.product_id AND gc.ngift_order_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);


        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

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


        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->vgift_coupon_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';
        $enable_seller_friendly ='Y';
        if($enable_seller_friendly == "Y") {

            $select_seller_name = "SELECT artist_name FROM ".$tableprefix."artists WHERE artist_id = ".$orderDetailObj->artist_id;
            $result_seller_name = mysql_query($select_seller_name) or die(mysql_error());

            if(mysql_num_rows($result_seller_name) > 0) {

                $seller_name_row = mysql_fetch_assoc($result_seller_name);
                $txtSellerName = $seller_name_row['artist_name'];
            }

            $friendly_url = SITE_URL."/store/".$txtSellerName;

        }  //end of if User Friendly URL checking condition

        else {
            $friendly_url = SITE_URL."/showportfolio.php?artistid=".$orderDetailObj->artist_id;
        }


        $mailContent .='<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6">
		<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 align="left" valign="top">
			You can purchase products using this Gift Certificate from the seller store below
		</td>
		</tr>';
        $mailContent .='<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			'.$friendly_url.'
		</td>
		</tr></table></td></tr>';

        $inc++;

    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

    $mailContent .='<tr>
			<td>Gift Certificate Amount:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';
    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$orderObj->taxrate,2,".","").'</td>
			</tr>';

    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }

    if($usertype=="guest") {
        $sql_usrObj="SELECT user_name,email from ".$tableprefix."users where user_id='".$orderObj->user_id."' ";
        $rs_Order	=mysql_query($sql_usrObj) or die(mysql_error());
        if(mysql_num_rows($rs_Order)>0) {
            $rs_Order_obj=mysql_fetch_object($rs_Order);

            $guest_user_name=$rs_Order_obj->user_name;

            $guest_user_password=$_SESSION["sess_guest_password"];

            $mailContent .='<tr><td>&nbsp;</td></tr>';

            $mailContent .='<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> <I>NOTE : </I> You can login to '.$orderObj->storename.' ( '.SITE_URL.') using  following details to check the order status.</td></tr>';

            $mailContent .='<tr><td>User Name : &nbsp;<b>'.$guest_user_name.'</b></td></tr>';

            $mailContent .='<tr><td>Password  : &nbsp;<b>'.$guest_user_password.'</b></td></tr>';

            $mailContent .='<tr><td>&nbsp;</td></tr></table> </TD></TR>';
        }
    }


    $mailContent .='</table>';


    $mailcontent_buyer= readEmailTemplate('gift_coupon');

    if(stristr($mailcontent_buyer,"[buyer_first_name")) {
        $mailcontent_buyer=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_buyer);
    }
    if(stristr($mailcontent_buyer,"[buyer_last_name")) {
        $mailcontent_buyer=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_buyer);
    }

    $mailcontent_buyer = str_replace('[coupon_details]',$mailContent,$mailcontent_buyer);


    $mail_send_details_buyer ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_buyer.'</p>
                  </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_buyer;

    $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 = "Gift Certificate Order placed at ".SITE_NAME;

    $mailsent = mail($orderObj->billing_email,$ordersubject,$mail_send_details_buyer,$headers);


}
function sendAdminEmail($order_id,$user_id) {
    global $tableprefix;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];



    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Product Name</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);
        $couponCodeDiscount=$orderObj->couponCodeDiscount;
        $productname.= $optionStr;

        // Shipping Cost
        if($orderDetailObj->nshipping_cost!=0) {
            $totalshippingcost += $orderDetailObj->nshipping_cost;
        }
        // Shipping Cost

        $converted_price = $orderDetailObj->product_price;

        $rate = number_format(($converted_price),2 ,".","" );
        // End currency Conversion
        /*------------Multicart 2.0 Upgradation------------*/

        $qty = $orderDetailObj->product_quantity;
        $price = $qty * $rate;
        $discountstr="";
        if($orderDetailObj->product_discount !="0") {
            $price=$price- ($price*$orderDetailObj->product_discount)/100;

            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";
        }



        //$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");


        $itemTotal+=$price;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

        $inc++;

    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

    $mailContent .='<tr>
		<td>Item Price Total:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';



    // Modified ON 22-07-2010 // Asha
    if($couponCodeDiscount>0) {
        //echo "sdhjsdhasd";
        $priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        $ItemTotalPrice=$priceafterdiscount;
        $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">Coupon Code " '.$orderObj->couponCode.' " Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.($orderObj->couponCodeDiscount).' % </td>
		</tr>
		<tr>
		<td>Item Total Cost After Coupon Code Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';

    }


    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    if($totalshippingcost!=0) {
        //echo $orderObj->order_total_price;
        $mailContent .='<tr>
			<td width="40%">Shipping & Handling: </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
    }


    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$orderObj->taxrate,2,".","").'</td>
			</tr>';


    if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        $mailContent.='<tr>
		<td> Gift Certificate Code :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }


    $mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';


    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }
    if($giftCheckVal=="") {
        if($orderObj->shipping_address2) {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }else {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Shipping Address:
		</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 align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		Phone: '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
    }

    $mailContent .='</table>';

    $mailcontent_admin=readEmailTemplate('order_notification_admin');

    //echo $orderObj->billing_first_name.$orderObj->billing_last_name;

    //echo "<br>";

    $mailcontent_admin=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[order_details]',$mailContent,$mailcontent_admin);


    $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </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_buyer;

    $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  = "New Order placed at ".SITE_NAME;

    //$orderObj->billing_email='asha.s@armiasystems.com';

    //echo $mail_send_details_admin;

    $adminemail	=getSettingsValue('site_email');



    $mailsent = mail($adminemail,$ordersubject,$mail_send_details_admin,$headers);

    // echo $mailContent;
}

//***************************************************function for paging
function dopaging($sql,$numrecords=0,$limit=15) {


    global $clspg;
    global $pages;
    global $num;
    $clspg = new Pager;
    $temp = mysql_query($sql) or die(mysql_error());
    $numrows = mysql_num_rows($temp);
    $start = $clspg->findStart($limit,$numrows);
    if ($numrecords == 0)
        $pages = $clspg->findPages($numrows, $limit);
    else {
        if ($numrows > $numrecords)
            $pages = $clspg->findPages($numrecords, $limit);
        else
            $pages = $clspg->findPages($numrows, $limit);
    }
    if ($numrecords == 0)
        $sql1 = $sql . " LIMIT " . $start. ", ". $limit ;
    else {
        if (($start + $limit) > $numrecords)
            $sql1 = $sql . " LIMIT " . $start. ", ". ($numrecords - $start);
        else
            $sql1 = $sql . " LIMIT " . $start. ", ". $limit ;
    }


    return $sql1;


}
function leftpaging() {
    global $clspg;
    global $pages;
    $pagelist = "";
//checking version
    $version = substr(phpversion(), 0, 1);

    if($version<5) {
        if (trim($clspg) != "")

            if ($pages > 1)
                $pagelist = $clspg->pageList($_GET['page'], $pages);
    }
    else {
        if ($clspg!= "")
            if ($pages > 1)
                $pagelist = $clspg->pageList($_GET['page'], $pages);
    }
    return $pagelist;
}

function rightpaging() {

    global $clspg;
    global $pages;
    $pagelist = "";
//checking version
    $version = substr(phpversion(), 0, 1);

    if($version<5) {

        if (trim($clspg) != "")
            if ($pages > 1)
                $pagelist = $clspg->pageList($_GET['page'], $pages);
    }
    else {
        if ($clspg!= "")
            if ($pages > 1)
                $pagelist = $clspg->pageList($_GET['page'], $pages);
    }

    return $pagelist;
}
///************************************************************end of paging

function formatPrice($price) {
    //$price=ceil($price);
    $price=number_format($price, 2, '.', '');
    return $price;
}

// Function To Get Count of Cart Items of a Particular User
function GetUserCartCount($userid) {
    global $tableprefix;

    $sql_cart="SELECT count(c.cart_id) as cartCount
	 			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='".$userid."' ";
    $rs_cart=mysql_query($sql_cart) or die(mysql_error());
    $cartObj = mysql_fetch_object($rs_cart);
    $cartCount=$cartObj->cartCount;
    if(!$cartCount) {
        $cartCount=0;
    }
    return $cartCount;

}

// Function To Get Count of Cart Items of a Particular Visitor User
function GetVisitorCartCount($visitorid) {
    global $tableprefix;

    $sql_cart="SELECT count(c.cart_id) as cartCount
			   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.visitor_cart_id='".$visitorid."' ";

    $rs_cart=mysql_query($sql_cart) or die(mysql_error());
    $cartObj = mysql_fetch_object($rs_cart);
    $cartCount=$cartObj->cartCount;
    if(!$cartCount) {
        $cartCount=0;
    }
    return $cartCount;

}

function generatePassword($length=6,$level=2) {

    list($usec, $sec) = explode(' ', microtime());
    srand((float) $sec + ((float) $usec * 100000));

    $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
    $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $validchars[3] = "abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    $password  = "";
    $counter   = 0;

    while ($counter < $length) {
        $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

        // All character must be different
        if (!strstr($password, $actChar)) {
            $password .= $actChar;
            $counter++;
        }
    }

    return $password;

}

function generateUsername($length=6,$level=2) {

    list($usec, $sec) = explode(' ', microtime());
    srand((float) $sec + ((float) $usec * 100000));

    $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
    $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyz";
    $validchars[3] = "abcdfghjkmnpqrstvwxyz";

    $username  = "";
    $counter   = 0;

    while ($counter < $length) {
        $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

        // All character must be different
        if (!strstr($password, $actChar)) {
            $username .= $actChar;
            $counter++;
        }
    }

    return $username;

}





function sendBulkUploadSellerEmail($sellerid,$productDetails) {

    global $tableprefix;




    $queryOrder="SELECT a.* from ".$tableprefix."artists a where a.artist_id=".$sellerid." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $current_date=date('m-d-Y');

    $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">
		Bulk Product Upload Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '
		<tr>
		<td >Upload  Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$current_date.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Product Name</td>
		<td align="left" valign="top">Category Name</td>
		<td align="left" valign="top">Stock</td>
		<td align="left" valign="top">Price</td>
		</tr>';


    $adminCurrency	= GetAdminCurrency();

    $sellerCurrency=	$adminCurrency['currency_symbol'];


    $inc = 1;
    foreach($productDetails as $row) {


        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'. stripslashes($row['product_code']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['product_name']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['category_name']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['product_stock']) .'</td>
		<td align="left" valign="top">'.$sellerCurrency.'&nbsp;'.number_format($row['product_price'],2,".","").'&nbsp;&nbsp;</td>
		</tr>';
        $inc ++;
    }

    $mailContent.='</table></td></tr></table>';


    $mailcontent_data=readEmailTemplate('bulkproduct_uploadnotification_seller');

    $mailcontent_data=str_replace('[seller_first_name]',$orderObj->first_name,$mailcontent_data);

    $mailcontent_data=str_replace('[seller_last_name]',$orderObj->last_name,$mailcontent_data);

    $mailcontent_data=str_replace('[product_details]',$mailContent,$mailcontent_data);


    $mail_send_details ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_data.'</p>
                  </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_buyer;

    $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  = "Bulk Product Upload Information with  ".SITE_NAME;


    //$orderObj->email='asha.s@armiasystems.com';

    $mailsent = mail($orderObj->email,$ordersubject,$mail_send_details,$headers);



}


function sendBulkUploadAdminEmail($sellerid,$productDetails) {

    global $tableprefix;

    $queryOrder="SELECT a.* from ".$tableprefix."artists a where a.artist_id=".$sellerid." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $current_date=date('m-d-Y');

    $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">
		Bulk Product Upload Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '
		<tr>
		<td >Upload  Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$current_date.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Product Name</td>
		<td align="left" valign="top">Category Name</td>
		<td align="left" valign="top">Stock</td>
		<td align="left" valign="top">Price</td>
		</tr>';


    $adminCurrency	= GetAdminCurrency();

    $sellerCurrency	=	$adminCurrency['currency_symbol'];



    $inc = 1;
    foreach($productDetails as $row) {


        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'. stripslashes($row['product_code']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['product_name']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['category_name']) .'</td>
		<td align="left" valign="top">'. stripslashes($row['product_stock']) .'</td>
		<td align="left" valign="top">'.$sellerCurrency.'&nbsp;'.number_format($row['product_price'],2,".","").'&nbsp;&nbsp;</td>
		</tr>';
        $inc ++;
    }

    $mailContent.='</table></td></tr></table>';


    $mailcontent_data=readEmailTemplate('bulkproduct_uploadnotification_admin');

    $mailcontent_data=str_replace('[seller_first_name]',$orderObj->first_name,$mailcontent_data);

    $mailcontent_data=str_replace('[seller_last_name]',$orderObj->last_name,$mailcontent_data);

    $mailcontent_data=str_replace('[product_details]',$mailContent,$mailcontent_data);


    $mail_send_details ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_data.'</p>
                  </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_buyer;

    $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  = "Bulk Product Upload Information with  ".SITE_NAME;

    $adminemail	=getSettingsValue('site_email');

    //$adminemail='asha.s@armiasystems.com';

    $mailsent = mail($adminemail,$ordersubject,$mail_send_details,$headers);



}


function getAdminMenus($parentid) {
    global $tableprefix;
    $arr1=array();
    $qry = "select b.* from ". $tableprefix ."admin_menu b where  ";
    $qry .=" b.parent_id=".$parentid." and b.status ='ACTIVE' ORDER BY b.display_order";

    // echo $qry;die();
    $res=mysql_query($qry) or die(mysql_error());
    if (mysql_num_rows($res) != 0) {
        $i=0;
        while($rws= mysql_fetch_assoc($res)) {
            $arr1[$i]["menu_id"]= $rws["menu_id"];
            $arr1[$i]["page_name"]= $rws["page_name"];
            $arr1[$i]["link"]= SITE_URL."/admin/".$rws["link"];
            $arr1[$i]["divname"]= $rws["divname"];
            $arr1[$i]["title"]= $rws["title"];
            $ChildNodeExists	=	whetherAdminChildNodeExist($rws["menu_id"]);
            if($ChildNodeExists === TRUE) {
                $arr1[$i]['subpage']=getAdminMenus($rws["menu_id"]);
                $i++;
            }
            else {
                $i++;
            }
        }
    }
    return $arr1;
}

function whetherAdminChildNodeExist($pageId) {
    global $tableprefix;
    $Qry		=	"SELECT COUNT(*) AS TotCount FROM ". $tableprefix ."admin_menu WHERE parent_id = '$pageId' and status='ACTIVE'";
    //$Row		=	$this->db->get_row($Qry, ARRAY_A);
    $res=mysql_query($Qry) or die(mysql_error());
    if(mysql_num_rows($res) != 0) {
        $rws= mysql_fetch_assoc($res);
    }
    $TotCount	=	$rws['TotCount'];
    if($TotCount > 0)
        return TRUE;
    else
        return FALSE;
}

function sendgiftCertificateMail_Seller($order_id,$user_id) {

    global $tableprefix;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];



    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);

    $queryOrderDetail_seller	 = "SELECT DISTINCT od.artist_id,s.*
  										FROM ".$tableprefix."order_details od
										INNER JOIN ".$tableprefix."artists s ON s.artist_id=od.artist_id
										WHERE od.order_id =".$order_id;
    $orderDetailQ_seller     = mysql_query($queryOrderDetail_seller);

    while($orderobjseller=mysql_fetch_object($orderDetailQ_seller)) {

        $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Gift Certificate Name</td>
		<td align="left" valign="top">Gift Certificate Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';

        $queryOrderDetail = "SELECT od.*,gc.vgift_coupon_code
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."giftcertificates gc ON gc.ngift_product_id=od.product_id AND gc.ngift_order_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id." AND od.artist_id=".$orderobjseller->artist_id." ";

        $orderDetailQ     = mysql_query($queryOrderDetail);
        $itemTotal =0;
        $inc = 1;
        $totalshippingcost=0;
        $productlist_fillstock=array();
        while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
            $optionStr="";

            if($giftCheckVal) {
                $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
            }
            $productname=stripslashes($orderDetailObj->product_name);


            $productRate	=	$orderDetailObj->product_price;
            $productPrice	=	$productRate*$orderDetailObj->product_quantity;
            $discountstr="";
            if($orderDetailObj->product_discount!=0) {
                $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
                $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

            }


            $converted_price = $productPrice;

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


            $itemTotal+=$productPrice;

            $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->vgift_coupon_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';


            $inc++;

        }


        $ItemTotalPrice=0;
        //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
        $ItemTotalPrice=$itemTotal;

        $mailContent.='</table>
		</td>
		</tr>';

        $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

        $mailContent .='<tr>
			<td>Gift Certificate Amount:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';
        $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

        $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$orderObj->taxrate,2,".","").'</td>
			</tr>';
        if($orderObj->billing_address2) {
            $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
        }else {
            $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }

        $mailContent .='</table>';

        $mailcontent_seller = readEmailTemplate('gift_couponmail_seller');

        //  echo $mailcontent_seller;
        $mailcontent_seller=str_replace('[coupon_details]',$mailContent,$mailcontent_seller);

        $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="103%" 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"> Dear '.$orderobjseller->first_name.'&nbsp;'.$orderobjseller->last_name.', </td>
			<tr>
			<tr>
			<td align="left">A new order has been placed  in '.SITE_NAME.' .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_seller.'</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 "<br>".$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  = "New Gift Certificate Order placed at ".SITE_NAME;

        //echo  "<br>".$mail_send_details_seller;
        //echo $ordersubject,$mail_send_details_seller;

        $mailsent = mail($orderobjseller->email,$ordersubject,$mail_send_details_seller,$headers);

        // Send Stock reorder Mail

    } // end while loop of artists

}

function sendgiftCertificateMail_Admin($order_id,$user_id) {

    global $tableprefix;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Gift Certificate Name</td>
		<td align="left" valign="top">Gift Certificate Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>

		</tr>';
    $queryOrderDetail = "SELECT od.*,gc.vgift_coupon_code
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."giftcertificates gc ON gc.ngift_product_id=od.product_id AND gc.ngift_order_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>Gift Coupon Code : ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);


        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

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


        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->vgift_coupon_code.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';
        $enable_seller_friendly ='Y';
        if($enable_seller_friendly == "Y") {

            $select_seller_name = "SELECT artist_name FROM ".$tableprefix."artists WHERE artist_id = ".$orderDetailObj->artist_id;
            $result_seller_name = mysql_query($select_seller_name) or die(mysql_error());

            if(mysql_num_rows($result_seller_name) > 0) {

                $seller_name_row = mysql_fetch_assoc($result_seller_name);
                $txtSellerName = $seller_name_row['artist_name'];
            }

            $friendly_url = SITE_URL."/store/".$txtSellerName;

        }  //end of if User Friendly URL checking condition

        else {
            $friendly_url = SITE_URL."/showportfolio.php?artistid=".$orderDetailObj->artist_id;
        }


        $mailContent .='<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6">
		<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 align="left" valign="top">
			Buyer can purchase products using this Gift Certificate from the seller store below
		</td>
		</tr>';
        $mailContent .='<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			'.$friendly_url.'
		</td>
		</tr></table></td></tr>';

        $inc++;

    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

    $mailContent .='<tr>
			<td>Gift Certificate Amount:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">$ '.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$orderObj->taxrate,2,".","").'</td>
			</tr>';

    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }


    $mailContent .='</table>';


    $mailcontent_admin= readEmailTemplate('gift_couponmail_admin');


    $mailcontent_admin=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_admin);

    $mailcontent_admin = str_replace('[coupon_details]',$mailContent,$mailcontent_admin);


    $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </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_buyer;

    $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  = "New Gift Certificate Order placed at ".SITE_NAME;

    //$orderObj->billing_email='asha.s@armiasystems.com';

    //echo $mail_send_details_admin;

    $adminemail	=getSettingsValue('site_email');


    $mailsent = mail($adminemail,$ordersubject,$mail_send_details_admin,$headers);


}

function GetAdminCurrency() {
    global $tableprefix;

    $sql = "SELECT admin_currency FROM `" . $tableprefix . "settings` ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result)>0) {

        $rsCurrencyObj	= mysql_fetch_object($result);

        switch($rsCurrencyObj->admin_currency) {
            case "USD": {
                    $adminCurrencySymbol	= '&#36;';
                    break;
                }
            case "EUR": {
                    $adminCurrencySymbol	= '€';
                    break;
                }
            case "GBP": {
                    $adminCurrencySymbol	= '£';
                    break;
                }
            default :
                $adminCurrencySymbol	= '&#36;';
                break;

        }

        $admin_currency= array("currency_code"=>$rsCurrencyObj->admin_currency,
                "currency_symbol"=>$adminCurrencySymbol);

        return  $admin_currency;

    }
}

function GetAdminLanguage() {
    global $tableprefix;

    $sql = "SELECT admin_language FROM `" . $tableprefix . "settings` ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result)>0) {

        $rsLanguageObj	= mysql_fetch_object($result);

        /*switch($rsLanguageObj->admin_language)
			{
				case "USD":
				{
					$adminCurrencySymbol	= '&#36;';
					break;
				}
				case "EUR":
				{
					$adminCurrencySymbol	= '€';
					break;
				}
				case "GBP":
				{
					$adminCurrencySymbol	= '£';
					break;
				}
				default :
				$adminCurrencySymbol	= '&#36;';
				break;

			}

			  $admin_currency= array("currency_code"=>$rsCurrencyObj->admin_currency,
											 	"currency_symbol"=>$adminCurrencySymbol);
        */
        return  $rsLanguageObj->admin_language;

    }
}


function ConvertedCurrencyRate($currenyCode) {

    global $tableprefix;

    $sql = "SELECT nexchange_price FROM `" . $tableprefix . "currency_master`  where vcurrency_code='".$currenyCode."' ";
    $result = mysql_query($sql);
    if(mysql_num_rows($result)>0) {
        $currencyObj	=mysql_fetch_object($result);

        $userCurrencyRate =$currencyObj->nexchange_price;
    }
    else {
        $userCurrencyRate = 1;
    }

    $convertedRate=$userCurrencyRate;

    return $convertedRate;

}

function USDollarConversionRate($currencyCode) {
    global $tableprefix;
    $adminCurrency	= GetAdminCurrency();

    if($currencyCode!='USD') {

        $sql = "SELECT usdollar_rate FROM `" . $tableprefix . "currency_master`  where vcurrency_code='".$currencyCode."' ";
        $result = mysql_query($sql);
        if(mysql_num_rows($result)>0) {
            $currencyObj	=mysql_fetch_object($result);

            $userCurrencyRate =$currencyObj->usdollar_rate;
        }

        $convertedRate=$userCurrencyRate;
    }
    else {
        $convertedRate =1;
    }

    return $convertedRate;

}


function ConvertUSDollorToUserCurrency($currencyCode) {
    global $tableprefix;

    $adminCurrency	= GetAdminCurrency();

    if($currencyCode!='USD') {

        $sql = "SELECT usdollar_rate FROM `" . $tableprefix . "currency_master`  where vcurrency_code='".$currencyCode."' ";
        $result = mysql_query($sql);
        if(mysql_num_rows($result)>0) {
            $currencyObj	=mysql_fetch_object($result);

            $userCurrencyRate =($currencyObj->usdollar_rate);
        }

        $convertedRate=$userCurrencyRate;
    }
    else {
        $convertedRate =1;
    }

    return $convertedRate;

}

function UserCurrencyToUSDollar($currencyCode) {
    global $tableprefix;
    $adminCurrency	= GetAdminCurrency();

    if($currencyCode!='USD') {

        $sql = "SELECT usdollar_rate FROM `" . $tableprefix . "currency_master`  where vcurrency_code='".$currencyCode."' ";
        $result = mysql_query($sql);
        if(mysql_num_rows($result)>0) {
            $currencyObj	=mysql_fetch_object($result);

            $userCurrencyRate =$currencyObj->usdollar_rate;
        }

        $convertedRate=$userCurrencyRate;
    }
    else {
        $convertedRate =1;
    }

    return $convertedRate;

}

function sendDigitalCertificateMail_Buyer($order_id,$user_id,$usertype='') {
    global $tableprefix,$_SESSION;
    $mailContent ="";

    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>';

    $product_download_details ="";

    $product_download_details = "<font color='#FF0000'>Note: If you do not have pop-ups enabled on your browser, the product download may not work properly.So please enable pop-ups before downloading !!</font>";


    $mailContent .='<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 align="left" valign="top">
					'.$product_download_details.'
				</td>
				</tr>
				<tr><td><b> <br>Click on  each  Link to Download Products.</b></td></tr>

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

    $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Digital Product  Name</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,DATE_FORMAT(gc.ndownload_expiry,'%m-%d-%Y') as ndownload_expiry,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON od.product_id = gc.ndigital_productid AND od.order_id=gc.ndigital_orderid
						WHERE od.order_id =".$order_id." GROUP BY gc.ndigital_productid ";


    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        $productname=stripslashes($orderDetailObj->product_name);
        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

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


        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

        $product_download_try = $orderDetailObj->ndownload_try;

        $download_expiry_date = $orderDetailObj->ndownload_expiry;


        /*if($orderDetailObj->ndownload_expiry!='')
					{
						$download_expiry_date  	= dateFormat($orderDetailObj->ndownload_expiry, "Y-m-d", "m-d-Y");
					}

					$download_expiry_date  	= $orderDetailObj->ndownload_expiry;*/
        $expiry_days = 	$orderDetailObj->ndownload_expiry_days;

        /*if($orderDetailObj->ndownload_expiry_days!='')
			{
				   $expiry_days = 	dateFormat($orderDetailObj->ndownload_expiry_days, "Y-m-d", "m-d-Y");
			}*/

        $product_download_trydetails ="";


        $product_download_trydetails .= "<br><br>Product Download Try - $product_download_try Time(s)\r\n";
        $product_download_trydetails .= "<br><br>Download Expiry Date - $download_expiry_date\r\n";

        $valid_date_upto = date("Y-m-d H:s:m",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$expiry_days,date("Y")));

        $mailContent .='<tr>
				<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6" width="100%">
				<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 align="left" valign="top">
					'.$product_download_trydetails.'
				</td>
				</tr>

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


        $queryOrderDetail_digital = "SELECT gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM  ".$tableprefix."digital_product gc where gc.ndigital_productid='".$orderDetailObj->product_id."' AND gc.ndigital_orderid='".addslashes($order_id)."' ";
        $rs_digital					=mysql_query($queryOrderDetail_digital)	or die(mysql_error());

        $product_download_details ="";



        if(mysql_num_rows($rs_digital)>0) {
            $product_download_details_link = "";
            $download_link = "";

            $cnt	=1 ;

            while($orderDetailObjdigital=mysql_fetch_object($rs_digital)) {

                $download_link = " <br><br>Download Link  ".$cnt." - ".SITE_URL."/digital_product_download.php?download_code=$orderDetailObjdigital->vdigital_product_code\r\n";
                $product_download_details_link = $download_link;

                $mailContent .='<tr>
				<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6">
				<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 align="left" valign="top">
					'.$product_download_details_link.'
				</td>
				</tr></table></td></tr>';

                $cnt++;

            }



        }




        $inc++;




    }


    $mailContent .='</table></td></tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " width="100%">
		<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; ">';

    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr>';
    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }


    if($usertype=="guest") {
        $sql_usrObj="SELECT user_name,email from ".$tableprefix."users where user_id='".$orderObj->user_id."' ";
        $rs_Order	=mysql_query($sql_usrObj) or die(mysql_error());
        if(mysql_num_rows($rs_Order)>0) {
            $rs_Order_obj=mysql_fetch_object($rs_Order);

            $guest_user_name=$rs_Order_obj->user_name;

            $guest_user_password=$_SESSION["sess_guest_password"];

            $mailContent .='<tr><td>&nbsp;</td></tr>';

            $mailContent .='<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> <I>NOTE : </I> You can login to '.$orderObj->storename.' ( '.SITE_URL.') using  following details to check the order status.</td></tr>';

            $mailContent .='<tr><td>User Name : &nbsp;<b>'.$guest_user_name.'</b></td></tr>';

            $mailContent .='<tr><td>Password  : &nbsp;<b>'.$guest_user_password.'</b></td></tr>';

            $mailContent .='<tr><td>&nbsp;</td></tr></table> </TD></TR>';
        }
    }


    $mailContent .='</table>';


    $mailcontent_buyer= readEmailTemplate('digital_product');

    $mailcontent_buyer=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_buyer);

    $mailcontent_buyer=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_buyer);

    $mailcontent_buyer=str_replace('[order_details]',$mailContent,$mailcontent_buyer);

    $mail_send_details_buyer ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_buyer.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>

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

     </td>
   </tr>
</table>
</body>
</html>';
    $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 = "Digital Product Order placed at ".SITE_NAME;

    $mailsent = mail($orderObj->billing_email,$ordersubject,$mail_send_details_buyer,$headers);

}


function sendDigitalCertificateMail_Seller($order_id,$user_id) {

    global $tableprefix;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];



    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);

    $queryOrderDetail_seller	 = "SELECT DISTINCT od.artist_id,s.*
  										FROM ".$tableprefix."order_details od
										INNER JOIN ".$tableprefix."artists s ON s.artist_id=od.artist_id
										WHERE od.order_id =".$order_id;
    $orderDetailQ_seller     = mysql_query($queryOrderDetail_seller);

    while($orderobjseller=mysql_fetch_object($orderDetailQ_seller)) {

        $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Digital Product  Name</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';


        $queryOrderDetail = "SELECT od.*,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON gc.ndigital_productid=od.product_id  AND od.order_id=gc.ndigital_orderid
						WHERE od.order_id =".$order_id." AND od.artist_id=".$orderobjseller->artist_id." GROUP BY gc.ndigital_productid ";

        $orderDetailQ     = mysql_query($queryOrderDetail);
        $itemTotal =0;
        $taxTotal =0;
        $inc = 1;
        while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
            $optionStr="";


            $productname=stripslashes($orderDetailObj->product_name);
            $productRate	=	$orderDetailObj->product_price;
            $productPrice	=	$productRate*$orderDetailObj->product_quantity;
            $discountstr="";
            if($orderDetailObj->product_discount!=0) {
                $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
                $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

            }



            $converted_price = $productPrice;

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

            $taxTotal+=$orderDetailObj->product_tax;

            $itemTotal+=$productPrice;

            $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

            $inc++;
        }

        $mailContent.='</table>
		</td>
		</tr>';



        $ItemTotalPrice=0;
        //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
        $ItemTotalPrice=$itemTotal;



        $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</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; ">';

        $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$taxTotal.'</td>
		</tr>';

        $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice+$taxTotal,2,".","").'</td>
			</tr>';

        /*$mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';*/
        $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
        if($orderObj->billing_address2) {
            $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
        }else {
            $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }

        $mailContent .='</table>';

        $mailcontent_seller= readEmailTemplate('digital_product_seller');

        $mailcontent_seller=str_replace('[first_name]',$orderObj->billing_first_name,$mailcontent_seller);

        $mailcontent_seller=str_replace('[last_name]',$orderObj->billing_last_name,$mailcontent_seller);

        $mailcontent_seller=str_replace('[order_details]',$mailContent,$mailcontent_seller);


        $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="103%" 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"> Dear '.$orderobjseller->first_name.'&nbsp;'.$orderobjseller->last_name.', </td>
			<tr>

			<tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left">'.$mailcontent_seller.'</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 "<br>".$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 = "New Digital Product Order placed at ".SITE_NAME;

        //echo  "<br>".$mail_send_details_seller;
        //echo $ordersubject,$mail_send_details_seller;

        $mailsent = mail($orderobjseller->email,$ordersubject,$mail_send_details_seller,$headers);

        // Send Stock reorder Mail

    } // end while loop of artists

}


function sendDigitalCertificateMail_Admin($order_id,$user_id) {
    global $tableprefix;


    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $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">
		Order Details:
		</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%">Store Name</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >Order Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Products:
		</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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>
		<td align="left" valign="top">Digital Product  Name</td>
		<td align="left" valign="top">Product Code</td>
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>

		</tr>';
    $queryOrderDetail = "SELECT od.*,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON gc.ndigital_productid=od.product_id AND gc.ndigital_orderid='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id." GROUP BY gc.ndigital_productid ";


    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        $productname=stripslashes($orderDetailObj->product_name);
        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>discount(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

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

        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';


        $inc++;



    }

    $mailContent .='</table></td></tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Charges:
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " width="100%">
		<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; ">';

    $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    $mailContent .='<tr>
			<td>Order Total :</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td>Amount Paid:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			Billing Address:
			</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 align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			Phone: '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		Billing Address:
		</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 align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		Phone: '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }


    $mailContent .='</table>';


    $mailcontent_admin= readEmailTemplate('digital_product_admin');

    $mailcontent_admin=str_replace('[first_name]',$orderObj->billing_first_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[last_name]',$orderObj->billing_last_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[order_details]',$mailContent,$mailcontent_admin);


    $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </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_buyer;

    $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 = "Digital Product Order placed at ".SITE_NAME;

    $adminemail	=getSettingsValue('site_email');

    $mailsent = mail($adminemail,$ordersubject,$mail_send_details_admin,$headers);


}


function getCurrPagename($url) {
    global $tableprefix;

    $curr_page_url_sql = "SELECT page_name
							 FROM ".$tableprefix."admin_menu
							WHERE link='$url'";
    $curr_page_url_result = mysql_query($curr_page_url_sql);
    while($curr_page_url_row = mysql_fetch_array($curr_page_url_result)) {
        $curr_page_name =  $curr_page_url_row['page_name'];
    }
    return $curr_page_name;
}

function getFilenameWithoutExt($file) {
    $file_name = rtrim($file, strrchr($file, '.'));
    return $file_name;
}

function get_file_extension($file_name) {
    return substr(strrchr($file_name,'.'),1);
}


function GetSellerPlanDetails($sellerid) {
    global $tableprefix;

    $seller_plan_details	=array();

    $sql_date_check = "SELECT ar . * , am . *,s.*
							FROM ".$tableprefix."artists_membershipDetails am
							INNER JOIN ".$tableprefix."artists ar ON ar.artist_id = am.artist_id
							INNER JOIN ".$tableprefix."sellerPlans s ON s.plan_Id = ar.sellerPlanID AND  s.plan_Id = am.plan_Id
							WHERE  ar.artist_id=".$sellerid." ORDER BY am.artist_memEndDate  DESC LIMIT 1";
    $rs_date_check	=mysql_query($sql_date_check) or die(mysql_error());
    if(mysql_num_rows($rs_date_check)>0) {
        $sellerObj=mysql_fetch_object($rs_date_check);

        $seller_plan_details=array("Plan_name"=>$sellerObj->plan_Title,
                "Plan_description"=>$sellerObj->plan_Description,
                "Plan_amount"=>$sellerObj->plan_SubscriptionCharge,
                "Plan_startDate"=>$sellerObj->artist_memStartDate,
                "Plan_expiry"=>$sellerObj->artist_memEndDate);


    }

    return  $seller_plan_details;
}


function checkSkuQuantity($order_id,$productid) {
    global $tableprefix;
    $refundQ="SELECT * FROM ".$tableprefix."refunds WHERE  order_id  = ".$order_id." AND   product_id  =".$productid." ";
    $refundmQ = mysql_query($refundQ);
    $refundRows=mysql_num_rows($refundmQ);

    if(mysql_num_rows($refundmQ)>0) {
        while($refundObj=mysql_fetch_array($refundmQ)) {
            $txtQty+=$refundObj['quantity'];
        }
        // Refund sku found
    }
    else {
        $txtQty=0;
    }


    return $txtQty;

}// end function

function checkRefundStatus($order_id,$productid) {
    global $tableprefix;

    $refundQ="SELECT * FROM ".$tableprefix."refunds WHERE  order_id   = ".$order_id." AND  product_id  =".$productid."  ";
    $refundmQ = mysql_query($refundQ);

    if(mysql_num_rows($refundmQ)>0) {
        $chekRefundStatus=1;
        // Refund sku found
    }
    else {
        $chekRefundStatus=0;
    }


    return $chekRefundStatus;

}// end function

function getRefundOrderStatus($orderid) {
    global $tableprefix;

    $sql_date="SELECT item_status FROM " . $tableprefix . "order_details
				 	  WHERE order_id = '" . addslashes($orderid) . "' AND item_status='4' AND DATE_ADD(item_delivery_date,INTERVAL 48 HOUR)>=now()";
    $rs_date=mysql_query($sql_date) or die(mysql_error());

    if(mysql_num_rows($rs_date)>0) {
        $refund_flag=1; // Delivred Products Exists for Refund
    }else {

        $refund_flag=0;  // No Products for Refund
    }

    return 	$refund_flag;

}


function checkAllProductsRefunded($orderid) {


    global $tableprefix;

    $allproductsRefunded =false;

    $sql = "SELECT  sum(od.product_quantity) as productqty
			      FROM ".$tableprefix."order_details od
			     WHERE od.order_id=".$orderid." AND od.item_status=4  ";

    $rs	  =mysql_query($sql)or die(mysql_error());

    $totalProductCount =0;


    if(mysql_num_rows($rs)>0) {

        $rsObj	= mysql_fetch_object($rs);

        $totalProductCount	= $rsObj->productqty;

    }


    $sql1 = "SELECT sum(r.quantity) as refundqty
			      			FROM ".$tableprefix."refunds r
			     	WHERE r.order_id=".$orderid."   ";

    $rs1  =mysql_query($sql1)or die(mysql_error());

    $totalRefundCount =0;


    if(mysql_num_rows($rs1)>0) {

        $rsObj1	= mysql_fetch_object($rs1);

        $totalRefundCount	= $rsObj1->refundqty;

    }



    if($totalProductCount ==$totalRefundCount) {
        $allproductsRefunded	= true;
    }

    return $allproductsRefunded;

}


function checkProductRatingStatus($userid,$productid) {

    global $tableprefix;

    $ratingCount	= 0;



    $productCount  = 0;


    $RatingStatus	= 1;



    if($productid!='') {
        $prodStatus=mysql_query("select od.product_name from ".$tableprefix."orders o left join ".$tableprefix."order_details od
							on o.order_id=od.order_id where user_id='".$userid."' and
							product_id='".$productid."'") or die(mysql_error());


        if(mysql_num_rows($prodStatus)>0) {
            $productCount =1;
        }


        $select_rating = "SELECT ntotal_ratings FROM ".$tableprefix."record_ratings WHERE nrseller_id = '$productid' AND vType='p'
												AND nruser_id = ".$userid;


        $result_rating = mysql_query($select_rating);

        if(mysql_num_rows($result_rating)>0) {

            $ratingCount =1;
        }


        if($productCount == 1 && $ratingCount==0) {
            $RatingStatus = 0;
        }


    }

    return $RatingStatus;

}


function checkSellerRatingStatus($sellerid,$userid,$productid) {

    global $tableprefix;

    $productCount  = 0;

    $sellerRatingStatus	 = 0;

    // Check Product Alreday purchsed by the user

    if($productid!='') {
        $prodStatus=mysql_query("select od.product_name from ".$tableprefix."orders o left join ".$tableprefix."order_details od
							on o.order_id=od.order_id where user_id='".$userid."' and
							product_id='".$productid."'") or die(mysql_error());


        if(mysql_num_rows($prodStatus)>0) {
            $productCount =1;
        }
    }



    if($sellerid !='' && $userid!='') {
        $select_seller_rating = "SELECT rating  FROM ".$tableprefix."artist_feedbacks WHERE artist_id = '$sellerid'
                                                                                                        AND user_id = ".$userid;


        $result_seller_rating = mysql_query($select_seller_rating);

        if(mysql_num_rows($result_seller_rating)>0) {
            $sellerRatingStatus =1;
        }
        else {
            if($productCount==1) {
                $sellerRatingStatus =0;
            }else {
                $sellerRatingStatus =1;
            }
        }



    }





    return $sellerRatingStatus;


}


function GetSellerRatingStar($feedback_id) {
    global $tableprefix,$_SESSION;
    //echo $prd_id;

    //exit;
    //set some variables
    //$ip = $_SERVER['REMOTE_ADDR'];

    $sellerRating	= 0;

    $select_rating_count = mysql_query("SELECT rating FROM ".$tableprefix."artist_feedbacks WHERE artist_feedback_id=".$feedback_id." ");

    if(mysql_num_rows($select_rating_count)>0) {

        $rating_count 	= 		@mysql_fetch_array($select_rating_count);

        $sellerRating	= 		$rating_count['rating'];

    }

    return $sellerRating;


}


function digitalCart($user_id) {


    global $tableprefix,$_SESSION;

    $digital_cart_count	= 0;

    $select_gift_check1 = "SELECT *
										FROM ".$tableprefix."cart crt
										INNER JOIN ".$tableprefix."products p ON p.product_id = crt.product_id
										WHERE crt.user_id='".$user_id."'
										AND p.vdigital_product = 'Y' ";

    $result_gift_check1 = mysql_query($select_gift_check1) or die(mysql_error());

    if(mysql_num_rows($result_gift_check1)>0) {
        $digital_cart_count =1;
    }

    return $digital_cart_count;

}


function getCartTotalcouponCodeDicountamount($userid,$couponCode) {
    global $tableprefix;
    $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;
    $currency_attributes = displayCurrencyType();

    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;
        }
    }

    $total				=	number_format($total,2,".","");
    if($couponCode['ccDiscount']<>"") {
        $total=($total* $couponCode['ccDiscount'])/100;
    }

    return $total;
}

/*------------------------New Functions for Seller Profile, Metatags, Product Details Breadcrumb Page------------------*/
function getSellerProfileLink($baseurl,$sellerid,$catid) {
    global $tableprefix;

    $baseurl.="?artistid=".$sellerid;

    $link = "<a href='" . $baseurl . "'>".STORE_HOME_TEXT."</a> ";

    if ($catid != "") {

        $sql = "SELECT * FROM " . $tableprefix . "categories where category_id = " . $catid;
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = "<a href='" . $baseurl . "&catid=" . $currcatid . "'>" . (stripslashes($currcatname)) . "</a>";
        } else {
            $sql = "SELECT * FROM " . $tableprefix . "categories where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= " <a  href='" . $baseurl . "&catid=" . $subcatid . "' >" . (stripslashes($subcatname)) . "</a>";
                }
            }
            // $link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;
    return $link;
}

//Function to check Subcategories Exists for a categfory
function checkSubCategoryCount($catid) {
    global $tableprefix;

    $select_parent_category = "SELECT count(category_id) as pcount
							   FROM ".$tableprefix."categories
							   where parent_id='".$catid."'";
    $result_parent_category = mysql_query($select_parent_category) or die(mysql_error);
    $count= 0;
    if (mysql_num_rows($result_parent_category) != 0) {
        $rw_parent_category = mysql_fetch_array($result_parent_category);
        $count=$rw_parent_category['pcount'];
    }

    return  $count;
} // end function


// Get Seller Average Rating

function GetSellerAverageRating($sellerid) {
    global $tableprefix,$_SESSION;
    //echo $prd_id;

    //exit;
    //set some variables
    //$ip = $_SERVER['REMOTE_ADDR'];

    $sellerRating	= 0;

    $select_rating_count="SELECT (SUM(rating)/ count(artist_feedback_id)) as rating,count(artist_feedback_id) as countrate  from ".$tableprefix."artist_feedbacks where artist_id='".$sellerid."'  AND published='Y' ";

    $rs_rating			=mysql_query($select_rating_count) or die(mysql_error());

    if(mysql_num_rows($rs_rating)>0) {

        $rating_count 	= 		@mysql_fetch_array($rs_rating);

        $sellerRating	= 		$rating_count['rating'];

        $sellerRating	= 		round($sellerRating);

    }

    return $sellerRating;


}

function GetSeoTags($pagename) {
    global $tableprefix;

    if($pagename!='') {

        $sql_meta		= "SELECT * from ".$tableprefix."metatags where vPageName='".$pagename."'  ";

        $rs_meta_tags   = mysql_query($sql_meta) or die(mysql_error());

        if(mysql_num_rows($rs_meta_tags)>0) {
            $metaObj	= mysql_fetch_object($rs_meta_tags);

            $page_title	 = stripslashes($metaObj->vTitle);

            $page_keywords	 = stripslashes($metaObj->vKeywords);

            $page_description	 = stripslashes($metaObj->vDescription);
        }


        switch($pagename) {
            case "productdetails.php":

                $product_id		= $_REQUEST['productid'];

                $seo_product_page=GetCategory_productName($product_id);

                $page_title 		= 		html_entity_decode($seo_product_page['product_title']);

                $page_keywords	 	=  		html_entity_decode($seo_product_page['product_keyword']);

                $page_description	= 		$seo_product_page['product_description'];

                break;


            case "categorydetail.php":

                if($_REQUEST['catid']!='') {

                    $category_id			= $_REQUEST['catid'];

                    $seo_product_page		= GetCategory_metaName($category_id);

                    $page_title 		= 		html_entity_decode($seo_product_page['product_title']);

                    $page_keywords	 	=  		html_entity_decode($seo_product_page['product_keyword']);

                    $page_description	= 		$seo_product_page['product_description'];
                }

                break;


        }


        $page_meta_tags= array("meta_title"=>$page_title,
                "meta_keywords"=>$page_keywords,
                "meta_description"=>$page_description);

        return $page_meta_tags;


    }


}



function GetCategory_productName($productid) {
    global $tableprefix;


    $sql_meta_product		= "SELECT p.product_name,c.category_name,c.category_id,p.product_description,p.product_price  from ".$tableprefix."products p INNER JOIN ".$tableprefix."categories c
	 								ON c.category_id=p.product_category  where p.product_id='".$productid."'  ";

    $rs_meta_prodcuct   	= mysql_query($sql_meta_product) or die(mysql_error());

    if(mysql_num_rows($rs_meta_prodcuct)>0) {
        $productObj			= mysql_fetch_object($rs_meta_prodcuct);

        $product_name		= stripslashes($productObj->product_name);

        $category_name		= stripslashes($productObj->category_name);

        $category_id		= $productObj->category_id;

        // Item Description
        if(strlen($productObj->product_description) > 200) {
            $description = substr($productObj->product_description,0,200);
        }
        else {
            $description =$productObj->product_description;
        }
// End Item Description

        $price			    =  $productObj->product_price;

        $adminCurrency	= GetAdminCurrency();

        $description		= strip_tags($description);

        $description.= "  Price :: ".$adminCurrency['currency_symbol']." ".number_format($price,2,".","");


    }

    $keywordTag			= 	$product_name .", " .getCategorynames($category_id) . SITE_NAME;

    $titleTag			= 	$product_name . ", " .getCategorynames($category_id). SITE_NAME;

    $descriptionTag		= 	$description ;


    $product_description= array("product_title"=>$titleTag,
            "product_keyword"=>$keywordTag,
            "product_description"=>$descriptionTag);

    return $product_description;


}


function GetCategory_metaName($categoryid) {
    global $tableprefix;


    $sql_meta_category		= "SELECT c.category_name  from  ".$tableprefix."categories c
	 								 where c.category_id='".$categoryid."'  ";

    $rs_meta_category   	= mysql_query($sql_meta_category) or die(mysql_error());

    if(mysql_num_rows($rs_meta_category)>0) {
        $productObj			= mysql_fetch_object($rs_meta_category);

        $category_name		= stripslashes($productObj->category_name);
    }

    $keywordTag			= 	$category_name . "  -  ".SITE_NAME;

    $titleTag			= 	$category_name . "  -  ".SITE_NAME;

    $descriptionTag		= 	$category_name . "  -  ".SITE_NAME;


    $product_description= array("product_title"=>$titleTag,
            "product_keyword"=>$keywordTag,
            "product_description"=>$descriptionTag);

    return $product_description;


}


function getProductPageLink($baseurl,$catid,$productname) {
    global $tableprefix;

    $link = "<a href='index.php'> ".HOME_LINK." </a> ";

    if ($catid != "") {

        $sql = "SELECT * FROM " . $tableprefix . "categories where category_id = " . $catid;
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = "<a href='" . $baseurl . "?catid=" . $currcatid . "'>" . (stripslashes($currcatname)) . "</a>";
        } else {
            $sql = "SELECT * FROM " . $tableprefix . "categories where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= " <a  href='" . $baseurl . "?catid=" . $subcatid . "' >" . (stripslashes($subcatname)) . "</a>";
                }
            }
            // $link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;

    $prodctlink .= " <a  href='#' >" . $productname . "</a>";
    $newlink= $link . $prodctlink;
    return $newlink;
}


function getCategorynames($catid) {
    global $tableprefix;

    $link = "";

    if ($catid != "") {

        $sql = "SELECT * FROM " . $tableprefix . "categories where category_id = " . $catid;
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $row = mysql_fetch_array($result);
            $currcatid = $row["category_id"];
            $currcatname = stripslashes($row["category_name"]);
            $subcats = $row["route"];
        }
        if ($subcats == "") {
            $lastcat = htmlentities(stripslashes($currcatname));
        } else {
            $sql = "SELECT * FROM " . $tableprefix . "categories where category_id in ($subcats) ";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) != 0) {
                while ($row = mysql_fetch_array($result)) {
                    $subcatname = stripslashes($row["category_name"]);
                    $subcatid = $row["category_id"];
                    $link .= htmlentities(stripslashes($subcatname))." :: ";
                }
            }
            // $link = substr($link, 0, -35);
        }
    }

    $link .= $lastcat;

    return $link;
}
//function to get Product Options -written by Santhosh Thomas Alexander
function getProductOptions($productId,$selectedOption='',$arr=array(),$selectBoxname, $class='',$i=0) {
    global $tableprefix;
    $query_product_more_options = "SELECT product_option_id FROM ".$tableprefix."product_options WHERE product_id = '{$productId}'";
    $query_product_more_optionsQ = mysql_query($query_product_more_options);
    $product_more_options_count = mysql_num_rows($query_product_more_optionsQ);

    if($product_more_options_count>1) {
//checking what all options are available for the default Option
        $option .= "<select name='".$selectBoxname."' class='".$class."' onChange='changeOption(this);' id='".$selectBoxname."'>";

        while($product_options_obj = mysql_fetch_object($query_product_more_optionsQ)) {
            $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 = ".$product_options_obj->product_option_id." ORDER BY o.option_name";
            $query_available_optionsQ = mysql_query($query_available_options);

            while($product_options_val_obj = mysql_fetch_object($query_available_optionsQ)) {
                $sel = '';
                if($selectedOption==$product_options_obj->product_option_id) {
                    $sel = 'SELECTED';
                }
                $option .= "<option value=".$product_options_obj->product_option_id." ".$sel.">".$product_options_val_obj->option_val."</option>";

            }

        }
        $option .= "</select>";

    }else {
        $product_options_obj = mysql_fetch_object($query_product_more_optionsQ);
        $option .= "<input type='hidden' name='".$selectBoxname."'  id='".$selectBoxname."' value='".$product_options_obj->product_option_id."'>";
        $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 = ".$product_options_obj->product_option_id." 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 .= "<div style='width:150px;' class='selectbox'>";
            $option .= $product_options_val_obj->option_val;
            $option .= "</div>";
        }

    }
    return $option;
}
function getOptionsFromCategory($catid) {
    $options_arr = array();
    global $tableprefix;
    if($catid !="") {
        $query_cat_options = "SELECT o.option_id,o.option_name
                            FROM ".$tableprefix."options o
                                INNER JOIN ".$tableprefix."category_options co ON co.option_id = o.option_id AND co.category_id = '".$catid."' ORDER BY o.option_name";
        $cat_optionsQ = mysql_query($query_cat_options);

        while($optionsObj = mysql_fetch_object($cat_optionsQ)) {
            $options_arr[] = array("option_id"=>$optionsObj->option_id,"option_name"=>$optionsObj->option_name);

        }
    }
    return $options_arr;
}
function getProductOptionsName($productOptionId,$arr=array()) {
    global $tableprefix;
    $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;
}

// Paypal Parallel Payment Data Retrievel
function decodePayPalIPN($raw_post) {
    if (empty($raw_post)) {
        return array();
    } # else:
    $post = array();
    $pairs = explode('&', $raw_post);
    foreach ($pairs as $pair) {
        list($key, $value) = explode('=', $pair, 2);
        $key = urldecode($key);
        $value = urldecode($value);
        # This is look for a key as simple as 'return_url' or as complex as 'somekey[x].property'
        preg_match('/(\w+)(?:\[(\d+)\])?(?:\.(\w+))?/', $key, $key_parts);
        switch (count($key_parts)) {
            case 4:
            # Original key format: somekey[x].property
            # Converting to $post[somekey][x][property]
                if (!isset($post[$key_parts[1]])) {
                    $post[$key_parts[1]] = array($key_parts[2] => array($key_parts[3] => $value));
                } else if (!isset($post[$key_parts[1]][$key_parts[2]])) {
                    $post[$key_parts[1]][$key_parts[2]] = array($key_parts[3] => $value);
                } else {
                    $post[$key_parts[1]][$key_parts[2]][$key_parts[3]] = $value;
                }
                break;
            case 3:
            # Original key format: somekey[x]
            # Converting to $post[somkey][x]
                if (!isset($post[$key_parts[1]])) {
                    $post[$key_parts[1]] = array();
                }
                $post[$key_parts[1]][$key_parts[2]] = $value;
                break;
            default:
            # No special format
                $post[$key] = $value;
                break;
        }#switch
    }#foreach

    return $post;
}#decodePayPalIPN()


//Function to check Subcategories Exists for a categfory
function checkProductStock($productid) {
    global $tableprefix;

    $product_count=0;

    $select_product_stock = "SELECT sum(product_stock ) AS product_stock
							   FROM ".$tableprefix."product_options
							   where product_id='".$productid."'";
    $result_product_stock = mysql_query($select_product_stock) or die(mysql_error);

    if (mysql_num_rows($result_product_stock) != 0) {
        $rw_product_count = mysql_fetch_array($result_product_stock);
        $product_count=$rw_product_count['product_stock'];
    }

    return  $product_count;
} // end function


//Function to check Digital Product Order
function checkDigitalOrder($orderid) {
    global $tableprefix;

    $digital_count=false;

    $select_digital_count = "SELECT d.ndigital_id  FROM ".$tableprefix."digital_product d
                                                       INNER JOIN ".$tableprefix."orders o  ON o.order_id=d.ndigital_orderid
							 where d.ndigital_orderid='".$orderid."'";
    $result_digital_count = mysql_query($select_digital_count) or die(mysql_error);

    if (mysql_num_rows($result_digital_count) != 0) {
        //$rw_product_count = mysql_fetch_array($result_digital_count);
        //$digital_count=$rw_product_count['product_stock'];
        $digital_count =true;
    }

    return  $digital_count;
} // end function

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


    $txtArray=array("product_name" => TXT_PD_NAME,
            "product_category" => TXT_PD_CAT,
            "product_code" => TXT_PD_CODE,
            "product_description" => TXT_PD_DESC,
            "product_price" => TXT_PD_PRICE,
            "options" => TXT_PD_OPT,
            "additional_price" => TXT_PD_PRICE,
            "product_stock" => TXT_PD_STOCK,
            "reorder_level" => TXT_PD_LEVEL,
            "small_image" => TXT_PD_SMALLIMG,
            "big_image" => TXT_PD_BIGIMG,
            "more_images" => TXT_PD_IMG,
            "discount" => TXT_PD_DISCOUNT,
            "discount_description" => TXT_PD_DESC,
            "shipping_weight" => TXT_PD_WEIGHT,
            "product_length" => TXT_PD_LENGTH,
            "product_width" => TXT_PD_WIDTH,
            "product_height" => TXT_PD_HEIGHT);
    return  $txtArray;
}

/********************** Copy a Folder & its Contents *************************/
function recurse_copy($src,$dst) {

    $dir = opendir($src);

    @mkdir($dst);

    while(false !== ( $file = readdir($dir)) ) {

        if (( $file != '.' ) && ( $file != '..' )) {

            if ( is_dir($src . '/' . $file) ) {

                recurse_copy($src . '/' . $file,$dst . '/' . $file);

            }

            else {

                copy($src . '/' . $file,$dst . '/' . $file);

            }

        }

    }

    closedir($dir);

}

function getStoreAlias($storename,$storenameOrig, $artistid=NULL) {
    global $tableprefix;

    if(empty($artistid)) {
        $sql = "select storename from  " . $tableprefix . "artists where storename='" . addslashes($storename) . "'";
    } else {
        $sql = "select storename from  " . $tableprefix . "artists where storename='" . addslashes($storename) . "' AND artist_id <> '".addslashes($artistid)."' ";
    }

    $result = mysql_query($sql);
    if (mysql_num_rows($result) > 0) {
        $storename = $storenameOrig."-".rand_str(4);
        $storename = getStoreAlias($storename,$storenameOrig, $artistid);
    } 
    return $storename;
}

function rand_str($length = 32, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890') {
    // Length of character list
    $chars_length = (strlen($chars) - 1);

    // Start our string
    $string = $chars{rand(0, $chars_length)};

    // Generate random string
    for ($i = 1; $i < $length; $i = strlen($string)) {
        // Grab a random character from our list
        $r = $chars{rand(0, $chars_length)};

        // Make sure the same two characters don't appear next to each other
        if ($r != $string{$i - 1}) $string .=  $r;
    }

    // Return the string
    return $string;
}


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{

	$link = mysql_connect($host,$user,$pass);
	mysql_select_db($name,$link);

	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}

	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);

		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";

		for ($i = 0; $i < $num_fields; $i++)
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++)
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}

	//save file


        $filename = 'db'.time().'.sql';
	$handle = fopen('../dbbackups/'.$filename,'w+');
	fwrite($handle,$return);
	fclose($handle);

        return $filename;
}

function remove_comments(&$output)
{
   $lines = explode("\n", $output);
   $output = "";

   // try to keep mem. use down
   $linecount = count($lines);

   $in_comment = false;
   for($i = 0; $i < $linecount; $i++)
   {
      if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
      {
         $in_comment = true;
      }

      if( !$in_comment )
      {
         $output .= $lines[$i] . "\n";
      }

      if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
      {
         $in_comment = false;
      }
   }

   unset($lines);
   return $output;
}

//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
   $lines = explode("\n", $sql);

   // try to keep mem. use down
   $sql = "";

   $linecount = count($lines);
   $output = "";

   for ($i = 0; $i < $linecount; $i++)
   {
      if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
      {
         if (isset($lines[$i][0]) && $lines[$i][0] != "#")
         {
            $output .= $lines[$i] . "\n";
         }
         else
         {
            $output .= "\n";
         }
         // Trading a bit of speed for lower mem. use here.
         $lines[$i] = "";
      }
   }

   return $output;

}

function splitsqlfile($sql, $delimiter) {
// Split up our string into "possible" SQL statements.
$tokens = explode($delimiter, $sql);
// try to save mem.
$sql = "";
$output = array();
// we don't actually care about the matches preg gives us.
$matches = array();
// this is faster than calling count($oktens) every time thru the loop.
$token_count = count($tokens);
for ($i = 0; $i < $token_count; $i++) {
// Don't wanna add an empty string as the last thing in the array.
if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

$unescaped_quotes = $total_quotes - $escaped_quotes;
// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
if (($unescaped_quotes % 2) == 0) {
// It's a complete sql statement.
$output[] = $tokens[$i];
// save memory.
$tokens[$i] = "";
} else {
// incomplete sql statement. keep adding tokens until we have a complete one.
// $temp will hold what we have so far.
$temp = $tokens[$i] . $delimiter;
// save memory..
$tokens[$i] = "";
// Do we have a complete statement yet?
$complete_stmt = false;

for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++) {
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

$unescaped_quotes = $total_quotes - $escaped_quotes;

if (($unescaped_quotes % 2) == 1) {
// odd number of unescaped quotes. In combination with the previous incomplete
// statement(s), we now have a complete statement. (2 odds always make an even)
$output[] = $temp . $tokens[$j];
// save memory.
$tokens[$j] = "";
$temp = "";
// exit the loop.
$complete_stmt = true;
// make sure the outer loop continues at the right point.
$i = $j;
} else {
// even number of unescaped quotes. We still don't have a complete statement.
// (1 odd and 1 even always make an odd)
$temp .= $tokens[$j] . $delimiter;
// save memory.
$tokens[$j] = "";
}
} // for..
} // else
}
}
return $output;
}


//Check Product is Digital Or Not 

function isDigital($productid)
{
    global $tableprefix;
    
    $digitalFlag    =   'N';
      
        if(!empty($productid)) {
            $resSet = "SELECT vdigital_product from ".$tableprefix."products p where p.product_id='".mysql_real_escape_string($productid)."' ";
            $data   = mysql_query($resSet);
            if(mysql_num_rows($data)>0)
            {
                $rsObj          =   mysql_fetch_object($data);
                
                $digitalFlag    =   $rsObj->vdigital_product;
            }
            
        }
        return $digitalFlag;
}


function isSellerApproved($txtEmail)
{
     global $tableprefix;
    
    $approvalFlag    =   'Y';
      
        if(!empty($txtEmail)) {
            $sql = "SELECT vapproved, artist_id FROM ".$tableprefix."artists WHERE email = '".addslashes($txtEmail)."' ";
            $res = mysql_query($sql);
            if(mysql_num_rows($res)>0)
            {
                $rsObj          =   mysql_fetch_object($res);
                
                $approvalFlag    =   $rsObj->vapproved;
            }
            
        }
        return $approvalFlag;
}


 //Send Order Staus Change Mail To Buyer 
  
  function sendOrderStatusChangeMailToBuyer($order_id,$artistid,$orderstatus,$from='A')
{
	 global $tableprefix;
	 
	
          $adminCurrency	= GetAdminCurrency();
	 
	  $currency_attributes[0]	=	$adminCurrency['currency_symbol']; 


          if($from=='S')
          {
              $senderName               =   SELLER_CAPTION. getorderSellerName($artistid);
              
              $sellerCaption            =   'The '.$senderName.' '. ORDER_STATUS_CHANGE_CAPTION .'<span style="font-size:12px; color:#991818; font-weight:bold; "> '.$orderstatus.'  </span> '. ORDER_STATUS_CHANGE_TEXT .'  '.SITE_NAME.'  ('.SITE_URL.')';
              
             
              
             
          }else{
                
                $senderName             =   SITE_NAME ;
                
                
                
                $sellerCaption            =   'The '.$senderName.' '. ORDER_STATUS_CHANGE_CAPTION .'  <span style="font-size:12px; color:#991818; font-weight:bold; "> '.$orderstatus.'  </span>  '.ORDER_STATUS_CHANGE_SELLER_TEXT.'  '.getorderSellerName($artistid).' '.ORDER_STATUS_CHANGE_ORDER_TEXT.' '.SITE_NAME.'  ('.SITE_URL.') ';
          
          }
	 
          $currentDate                  =   date('m-d-Y :H:i:s');
          
	$queryOrder="SELECT o.* ,concat(o.billing_first_name,' ',billing_last_name) AS buyername , o.billing_email as buyeremail , DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
	 	 $orderQ      = mysql_query($queryOrder); 
  		 $orderObj    = mysql_fetch_object($orderQ);
		  $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  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; ">';
                 $mailContent .= '<tr>
		<td colspan="2">Dear  '.$orderObj->buyername.' , </td>
		</tr><tr>
		<td colspan="2"> '.$sellerCaption.' </td>
		</tr>
		<tr>
		<tr>';
		
		$mailContent .= '<tr>
		<td >Order ID</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<td >Status Change  Date</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currentDate.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.PRODUCT_DETAILS_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 style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">Sl No.</td>      
		<td align="left" valign="top">Product Code</td>                  
		<td align="left" valign="top">Product Name</td>                 
		<td align="left" valign="top">Rate</td>
		<td align="left" valign="top">Quantity</td>
		<td align="left" valign="top">Price</td>
		</tr>';		

  $queryOrderDetail = "SELECT od.* FROM ".$tableprefix."order_details od 
                                                WHERE od.order_id =".$order_id." AND od.artist_id='".mysql_real_escape_string($artistid)."' ";
  	
  $orderDetailQ     = mysql_query($queryOrderDetail);	
  $itemTotal =0;
  $inc = 1;
  while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
  $optionStr="";
		
         
	$productname=stripslashes($orderDetailObj->product_name);
	$couponCodeDiscount=$orderObj->couponCodeDiscount;
	$productname.= $optionStr;
	
	
		
				$converted_price = $orderDetailObj->product_price;
			
				$rate = number_format(($converted_price),2 ,".","" );
						
							
				$qty = $orderDetailObj->product_quantity;
				$price = $qty * $rate;
				$discountstr="";
				if($orderDetailObj->product_discount !="0"){
				$price=$price- ($price*$orderDetailObj->product_discount)/100; 
					
					$discountstr="<br>discount(".$orderDetailObj->product_discount."%)";
				}
			
		
			
		//$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");
					
					
		$itemTotal+=$price;	
	
	 $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>            
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>              
		<td align="left" valign="top">'.$productname.'</td>                    
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($rate,2,".","").'</td>                    
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
	         </tr>';
         
		
		 $inc++;

	}
		$mailContent.='<tr><td colspan="6">&nbsp;</td></tr></table>
		</td>
		</tr>';
		
	 
	  $mailContent .='</table>';
	  
	  $mailcontent_admin=readEmailTemplate('order_statuschange_buyer_seller');
	  
	  //echo $orderObj->billing_first_name.$orderObj->billing_last_name;
	  //echo "<br>";
	  
	 
	  
	  $mailcontent_admin=str_replace('[order_details]',$mailContent,$mailcontent_admin);

	
  $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Online reservation</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="95%" 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="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </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_buyer;

		$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  = "Your order status in ".SITE_NAME. " has been changed ";
		
		//$orderObj->billing_email='asha.s@armiasystems.com';
		
		//echo $mail_send_details_admin;
		
		$buyeremail	=$orderObj->buyeremail;
		
                
		//$buyeremail     =   'armiatester@gmail.com';

		$mailsent = mail($buyeremail,$ordersubject,$mail_send_details_admin,$headers);
	  
	 // echo $mailContent;
}
  
    

function getorderSellerName($sellerid)
{
     global $tableprefix;
     
     
                 $seller_sql    = "select concat(first_name,' ',last_name) AS name from ".$tableprefix."artists where artist_id=$sellerid";
		 $seller_rs     = mysql_query($seller_sql) or die(mysql_error());
		 $seller_rw     = mysql_fetch_array($seller_rs); 
		 $seller_name   = ucwords($seller_rw["name"]);
                 
                 return $seller_name;
}
?>