/**
* 2007-2020 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@buy-addons.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author    Buy-addons    <contact@buy-addons.com>
* @copyright 2007-2020 Buy-addons
* @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
"use strict";
function baquote_showProducts(products){
	if (products.length == 0) {
		return false;
	}
    var html_new = '';
    html_new += '';
    html_new +=     '';
    html_new +=     '<div class="col-lg-6">';
    html_new +=         '<select id="td_id_product" name="id_product_new" onchange="baquote_requestCombination(this);">';
    html_new += '<option value="-1">Select Product</option>';
	var item, i;
	for (i=0; i< products.length; i++) {
		item = products[i];
		html_new += '<option  value="'+ item.id_product + '">'+item.name_formatted+'</option>';
	}
    html_new += '</select>';;
    window.parent.$("#td_list_product").html(html_new);
}
$(document).ready(function(){
    $(".td_search_product").keyup(function(){
		searchproduct('keyup');
    });
});
$(document).ready(function(){
    $( ".td_new_quote" ).click(function() {
        $("#td_add_new").toggle();
    });
});
function searchproduct(check = '') {
	window.parent.$("#quote_err").css("display", "none");
	var td_id_quote = jQuery('.td_id_quote').val();
	setTimeout(function(){
		var search = jQuery('.td_search_product').val();
		var baseurl = window.location.hostname;
		if(search.length >= '3' || check == ''){
			window.parent.$(".td_show_attr_price").css("display", "none");
			jQuery.ajax({
				type: 'POST',//phương thức gửi
				jscrossDomain: window.location.hostname,
				crossDomain: true,
				dataType: "json",
				url: '../index.php?controller=addnewproduct&fc=module&module=askforaquotemodul',
				data: 'search_product=' + search 
					+ '&jsshopid=' + jsshopid 
					+ '&quote_token=' + token_askaquotemodule 
					+ '&id_currency='+ td_id_currency 
					+ '&id_quote='+ td_id_quote 
					+ '&ajax=1',      
				beforeSend: function() {
					window.parent.$("#td_list_product").css("display", "none");
					window.parent.$("#img_loading_gif").css("display", "block");
					window.parent.$(".img_loading").css("display", "block");
					window.parent.$(".loadicon").css("display", "inline-block");
					window.parent.$(".td_quanity_max").css("display", "none");
					window.parent.$(".td_add_new_product").css("display", "none");
				},
				success: function(jsonData,textStatus,jqXHR)
				{
					baquote_showProducts(jsonData.products);
					if(jsonData.products.length == 0){
						window.parent.$("#products_found").css("display", "none");
						window.parent.$("#products_err").css("display", "block");
					} else {					
						window.parent.$("#products_found").css("display", "block");
						window.parent.$("#products_err").css("display", "none");
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					window.parent.$("#products_found").css("display", "none");
					window.parent.$("#products_err").css("display", "block");
				},
				complete: function(jsonData,textStatus,jqXHR) {
					window.parent.$(".img_loading").css("display", "none");
					window.parent.$("#td_list_product").css("display", "block");
					window.parent.$(".loadicon").css("display", "none");
				}		
			});
		}
		else
		{
			jQuery(".dp_include_product").css("display", "none");
			var html1 = '';
			html1 += '<div style="float: left; width: 100%">';
			html1 += '<input type="text" id="search_include_product" name="0" value="'+name+'" autocomplete="off" onkeyup="seach_product()" class="search_include_product_class">';
			html1 += '<span class="input-group-addon" style="width: 9% !important;"><i class="icon-search"></i></span>';
			html1 += '</div>';
			jQuery(".name_product").html(html1);
		}
	}, 1000);
}
function baquote_requestCombination(idproduct)
{
    var idproduct = idproduct.value;
    var baseurl = window.location.hostname;
    var id_select = 1;
	$('.combiornot').text('');
    window.parent.$("#img_loading_gif_attr").css("display", "block");
    window.parent.$(".td_show_attr_price").css("display", "block");
    window.parent.$("#td_attributes_list").css("display", "none");
        jQuery.ajax({
            type: 'POST',
            jscrossDomain: window.location.hostname,
            crossDomain: true,
            url: '../index.php?controller=attrbute&fc=module&module=askforaquotemodul',
            data: '&idproduct=' + idproduct + '&id_select=' + id_select + '&jsshopid=' + jsshopid + '&quote_token=' + token_askaquotemodule + '&ajax=1' + '&id_currency='+ td_id_currency,
            beforeSend: function() {
                window.parent.$("#img_loading_gif_attr").css("display", "block");
            },
            success: function(jsonData1,textStatus,jqXHR)
            {
                jsonData1 = JSON.parse(jsonData1);
				if (idproduct != "-1") {
					baquote_displayCombination(jsonData1);
				} else {
					jQuery(".td_show_attr_price").css("display", "none");
				}
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
            },
            complete: function(jsonData1,textStatus,jqXHR) {
				window.parent.$("#td_attributes_list").css("display", "block");
                window.parent.$("#img_loading_gif_attr").css("display", "none");
            }
            
        });
}
function baquote_displayCombination(data){
    var html = '', i;
    if(data.combi_product != "0"){
		$('.combiornot').text(textcombination);
        html += '<div class="col-lg-6" style="width: 50%;">';
        html += '<select id="id_pro_attribute" name="id_attrbute_pro" id="combi_product" value="" class="id_product_attribute" onchange="baquote_displayQty(this);">';
        html += '<option value="-1">Select Combination</option>';
        for(i=0;i<data.combi_product.length;i++){    
            html += '<option  value="'+ data.id_attr_product[i] +'">'+ data.combi_product[i] +'</option>';
        }
        html += '</select><input type="hidden" class="id_pro_have_select" value="' + data.id_product + '">';
        html += '</div>';
        jQuery("#td_attributes_list").html(html);
    } else {
		$('.combiornot').text(textproduct);
        html +=  '<div class="col-lg-6" style="width: 50%;" id="id_pro_attribute" value="-1">'+ data.price_product +'</div>';
        jQuery("#td_attributes_list").html(html);
		baquote_displayQty();
    }
}
function baquote_displayQty(id_attr_product = '')
{
	if (id_attr_product != '') {
		var id_attr_product = id_attr_product.value;
	}
	var result;
    var baseurl = window.location.hostname;
    var id_pro_have_select = jQuery('#td_id_product').val();
	jQuery.ajax({
		type: 'POST',//phương thức gửi
		jscrossDomain: window.location.hostname,
		crossDomain: true,
		url: '../index.php?controller=quantitymax&fc=module&module=askforaquotemodul', // lấy link của controller mới
		data: '&id_attr_product=' + id_attr_product + '&id_pro_have_select=' + id_pro_have_select + '&jsshopid=' + jsshopid + '&quote_token=' + token_askaquotemodule + '&ajax=1',  // lấy dữ liệu từ id product ở trên định nghĩa
		beforeSend: function() {
			window.parent.$(".td_quanity_max").css("display", "block");
			window.parent.$(".td_add_new_product").css("display", "none");
			jQuery(".td_quanity_max").html('<div id="img_loading_gif_attr" style="margin-left: 265px;"><img class = "img_loading2" width="15px;" src="../modules/askforaquotemodul/views/img/ajax_loadding.gif"/></div>');
		},
		success: function(jsonData,textStatus,jqXHR)
		{
			jsonData = JSON.parse(jsonData);
			baquote_displayQtyBox(jsonData);
		},
		complete: function(jsonData,textStatus,jqXHR) {
			result = JSON.parse(jsonData['responseText']);
			window.parent.$(".td_add_new_product").css("display", "inline-block");
		}
		
	});
}
function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}
function baquote_displayQtyBox(jsonData){
    var html = '';
	html += '<div class="form-group">';
	html += '<label class="control-label col-lg-3" for="qty">Quantity</label>';
	html += '<div class="col-lg-9">';
	html += '<input type="text" name="product_qty" onkeypress="validate(event)"  id="qty_product" class="form-control fixed-width-sm" value="1" style="position:relative;">';
	html += '<span class="alert_max_qty"><i class="icon-warning-sign"></i></span>';
	html += '<p class="help-block">In stock <span id="qty_in_stock">' + jsonData.quantity + '</span></p>';
	html += '<span class="notice_max_qty"><p class="help-block">You have exceeded the number of existing products</p></span>';
	html += '<input type="hidden" id="td_check_qty_add_pro" value="' + jsonData.quantity + '"></div></div>';
	jQuery(".td_quanity_max").html(html);
}
