<?php
session_start();
include("../include/config.php");
include("../include/simpleimage.php");
include("../include/functions.php"); 
validate_admin();

//$BASE_URL = 'https://www.dev.goquicklly.com';
$BASE_URL ='https://www.quicklly.com';
if (isset($_POST['ajax']) && isset($_POST['action'])) {
    $json = json_decode($_POST['data']);

    if($_POST['action'] == "getProds") {
        $prodArr=$obj->query("  SELECT 	p.id, CONCAT(p.product_name, ' - ', pp.size, pp.size_type) product_name, p.photo 
                                FROM 	tbl_product p
                                        INNER JOIN tbl_productprice pp ON pp.product_id = p.id
                                WHERE 	p.storeid = " . $json->{'sid'} . " AND p.status = 1  
                                ORDER BY p.product_name");
        
        $arrProds = array();

        while($prod=$obj->fetchNextObject($prodArr)){
            array_push($arrProds, array(   
                "id" => $prod->id,
                "name"  => $prod->product_name,
                "img"  => $prod->photo
            ));
        }

        $response = array(
            "lstProds" => $arrProds
        );

        header('Content-Type: application/json');
        echo json_encode($response);  
        exit;
    }
}

// Save Data
if($_REQUEST['submitForm']=='yes'){
    //cards
    if($_REQUEST["hdnTmpIDs"] != ''){
        $stores_arr = explode (",", $_REQUEST["hdnTmpIDs"]);
        $home_section=$_POST['home_section'];
        foreach($stores_arr as $indx) {
            $img = $_REQUEST["hdnOldImg-" . $indx];
            $id = $_REQUEST["hdnID-" . $indx];
            $order = $_REQUEST["hdnOrderNo-" . $indx];
            $sec = $_REQUEST["ddlSec-" . $indx];
            $store = $_REQUEST["ddlStore-" . $indx];
            $prod = $_REQUEST["ddlProd-" . $indx];
            $title = $_REQUEST["txtTitle-" . $indx];

            if($store == '') $store = "NULL";
            if($prod == '') $prod = "NULL";

            if($_FILES['fileImg-' . $indx]['size']>0 && $_FILES['fileImg-' . $indx]['error']==''){
                $Image= new SimpleImage();
                $filename = $_FILES['fileImg-' . $indx]['name'];
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                
                $img=time()."-".$filename;

                // Upload to main website FTP
                $url =SITE_URL;

                if($url ==MAINSITE_URL || $url==DEVSITE_URL ||
                   $url==UATSITE_URL){

                    if($url ==MAINSITE_URL){
                        $conn_id = ftp_connect("quicklly.com") or die("Error in FTP connection - Live");
                        $login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login - Live");
                    }
                    else {
                        $conn_id = ftp_connect("92.204.135.155") or die("Error in FTP connection");
                        ftp_pasv($conn_id, true);
                        
                        if($url==UATSITE_URL)
                            $login_status = ftp_login($conn_id, "devgoquicklly", "7ZcS58nmn_MH31") or die("Error in FTP login");
                        else
                            $login_status = ftp_login($conn_id, "devpuneet@dev.goquicklly.com", "*dyMZIYm[[PT") or die("Error in FTP login");
                    }
    
                    $destination_file = "upload_images/prods-deals/".$img;
                    $upload_status = ftp_put($conn_id, $destination_file, $_FILES['fileImg-' . $indx]['tmp_name'], FTP_BINARY);
                        
                    if (!$upload_status)
                        echo "Something went wrong, Contact to site administrator.";
                        
                    ftp_close($conn_id);
                //}
                
                // Upload locally to admin
                move_uploaded_file($_FILES['fileImg-' . $indx]['tmp_name'],"../upload_images/prods-deals/".$img);
                
                //$Image->load("../upload_images/prods-deals/".$img);	  
                //$Image->resize(300,300);	  
                //$Image->save("../upload_images/prods-deals/".$img);	 
                //CompressImage('../upload_images/prods-deals/'.$img, '../upload_images/prods-deals/'.$img, 50);

                $img = 'upload_images/prods-deals/' . $img;
            }
		}
            if($id == "0") {
                $obj->query("   INSERT INTO home_page_prods (home_section, title, img, order_no, sec_id, store_id, prod_id, last_update_datetime)
                                VALUES ('$home_section','$title', '@$img', $order, $sec, $store, $prod, now())"); 
            }
            else {
                $obj->query("   UPDATE  home_page_prods 
                                SET    home_section='$home_section', title = '$title', img = '@$img',
                                        order_no = $order, sec_id = $sec,
                                        store_id = $store, prod_id = $prod,
                                        last_update_datetime = now()
                                WHERE   id = $id"); 
            }
       // }
    }

    //Delete
    if($_REQUEST["hdnDelIDs"] != ''){
        $obj->query("   DELETE FROM home_page_prods 
                        WHERE  id IN (" . $_REQUEST["hdnDelIDs"] . ")"); 
    }
}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo SITE_TITLE; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/admin.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.2.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js" defer></script>
<style>
    .clsTemplate {
        display: none;
    }

    .clsFP_Stores {
        padding: 10px;
        margin: 0;
        padding-left: 15px;
        display: inline-block;
    }

        .clsFP_Stores .clsFP_Store {
            border: 1px solid #c8c8c8;
            padding: 7px;
            background-color: #f3f4f6;
            display: inline-table;
            vertical-align: top;
            margin: 0 10px 10px 0;
        }

        .ui-state-highlight {
            display: inline-table;
            vertical-align: top;
            margin: 0 10px 10px 0;
            min-width: 380px;
            min-height: 230px;
            border: 1px dashed #e5d262 !important;
        }

        .clsFP_Stores .clsFP_Store > div {
            display: inline-block;
        }

        .clsFP_Stores .clsFP_Store:not(:last-child) {
            margin-bottom: 10px;
        }

            .clsFP_Stores .clsFP_Store img.clsCardImg {
                display: inline-table;
                vertical-align: top;
                width: 100px;
                height: 100px;
                background-size: contain;
                background-repeat: no-repeat;
                background-position: center center;
                border: 1px solid #c8c8c8;
            }

            .clsFP_Stores .clsFP_Store .cntrls {
                margin-left: 5px;
                display: inline-table;
                vertical-align: top;
            }

                .clsFP_Stores .clsFP_Store .cntrls input, .select2 {
                    display: block;
                    width: 100% !important;
                    box-sizing: border-box;
                }

                .clsFP_Stores .clsFP_Store .cntrls span:not(:first-child):not('.select2-selection__arrow') {
                    margin-top: 5px;
                    display: block;
                }

                .clsFP_Stores .clsFP_Store .cntrls input[type=file]{
                    display: block;
                    margin-top: 5px;
                }

                .clsFP_Stores .clsFP_Store .cntrls a.clsRemoveBtn {
                    margin-top: 5px;
                    display: inline-block;
                }

                .clsFP_Stores .clsFP_Store .cntrls a.clsRemoveBtn img {
                    height: 15px;
                    width: 15px;
                    display: inline-table;
                    vertical-align: middle;
                }

    .clsAddBtn, a.clsAddBtn {
        border: none;
        background-color: #0971a2;
        color: #FFFFFF;
        font-family: Verdana, Arial, Helvetica, sans-serif;
        font-size: 12px;
        border-radius: 5px;
        text-decoration: none;
        outline: none;
        display: inline-block;
        padding: 7px 12px;
        font: 12px/1.5em Arial, Helvetica, sans-serif;
        cursor: pointer;
    }   

    .clsPgLoader {
        display: none;
        position: fixed;
        left: 0;right: 0;
        top: 0;bottom: 0;
        background-color: rgba(255, 255, 255, 0.6);
        z-index: 9999;
    }    

        .clsPgLoader img {
            display: inline-block;
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%,-50%);
        }    
</style>
</head>
<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<?php include("header.php") ?>
<tr>
	<td align="right" class="paddRtLt70" valign="top">
		<table width="99%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<?php
				$cardsname = $obj->query("SELECT * FROM home_page_setting where id='".$_GET['id']."'");
                            $cardrow = $obj->fetchNextObject($cardsname)               
				?>
				<td align="right" valign="top">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td align="left" valign="middle" class="headingbg bodr text14">
                                <em><img src="images/arrow2.gif" width="21" height="21" hspace="10" align="absmiddle" /></em>Admin: <?=$cardrow->title?>
                            </td>
						</tr>
						
						<tr>
							<td height="100" align="left" valign="top" bgcolor="#f3f4f6" class="bodr">
                                <form name="frm" method="POST" enctype="multipart/form-data" action="" onsubmit="return validate(this)">
                                    <input type="hidden" name="submitForm" value="yes" />
                                    <input type="hidden" name="home_section" value="<?=@$_GET['id']?>">
                                    <input type="hidden" name="hdnDelIDs" id="hdnDelIDs" value="">    
                                    <input type="hidden" name="hdnDelImgs" id="hdnDelImgs" value=""> 
                                    <input type="hidden" name="hdnTmpIDs" id="hdnTmpIDs" value="">

                                    <p style="padding: 10px;margin: 0;">Drag cards to arrange display order. Image resolution 500x500 px</p>

                                    <div class="clsFP_Stores">
                                        <?php
                                            $cards = $obj->query("SELECT home_section, id, title, img, sec_id, store_id, prod_id FROM home_page_prods where home_section='".$_GET['id']."' ORDER by order_no");
                                            $TmpID = 1;

                                            while($card = $obj->fetchNextObject($cards)){
                                        ?>   
                                            <div class="clsFP_Store" id="store-<?php echo $TmpID ?>">
                                                <div>
                                                    <input type="hidden" name="hdnOrderNo-<?php echo $TmpID ?>" id="hdnOrderNo-<?php echo $TmpID ?>" value="<?php echo $TmpID ?>" class="order">
                                                    <input type="hidden" name="hdnID-<?php echo $TmpID ?>" id="hdnID-<?php echo $TmpID ?>" value="<?php echo $card->id ?>" class="id">
                                                    <input type="hidden" name="hdnOldImg-<?php echo $TmpID ?>" id="hdnOldImg-<?php echo $TmpID ?>" value="<?php echo $card->img ?>" class="old">
                                                    <input type="hidden" name="hdnTmpID-<?php echo $TmpID ?>" id="hdnTmpID-<?php echo $TmpID ?>" value="<?php echo $TmpID ?>" class="tmpid">

                                                    <img class="clsCardImg" style="background-image: none, url('<?php echo $BASE_URL . '/' . $card->img ?>');">

                                                    <div class="cntrls">
                                                        <span>Section*</span>
                                                        <select name="ddlSec-<?php echo $TmpID ?>" class="js-dll-sec js-search-dropdown" onchange="getStores(this);" title="Section*">
                                                            <option value="">Select Section*</option>
                                                            <?php
                                                                $secs = $obj->query("SELECT id, section_name FROM tbl_section ORDER by section_name");
                                                                while($sec = $obj->fetchNextObject($secs)){
                                                                    $selected = '';

                                                                    if($sec->id == $card->sec_id)
                                                                        $selected = ' selected';

                                                                    echo '<option value="' . $sec->id . '"' . $selected . '>' . $sec->section_name . '</option>';
                                                                }
                                                            ?>   
                                                        </select>

                                                        <span>Store</span>
                                                        <select name="ddlStore-<?php echo $TmpID ?>" class="js-dll-store js-search-dropdown" onchange="getProds(this);" title="Store">
                                                            <option value="">Select Store</option>
                                                            <?php
                                                                $stores = $obj->query("SELECT storeid, storename, photo FROM stores WHERE sectionid = " . $card->sec_id . " ORDER BY storename");
                                                                while($store = $obj->fetchNextObject($stores)){
                                                                    $selected = '';

                                                                    if($store->storeid == $card->store_id)
                                                                        $selected = ' selected';

                                                                    echo '<option value="' . $store->storeid . '" data-img="' . $store->photo . '"' . $selected . '>' . $store->storename . '</option>';
                                                                }
                                                            ?>
                                                        </select>

                                                        <span>Product</span>
                                                        <select name="ddlProd-<?php echo $TmpID ?>" class="js-dll-prod js-search-dropdown" onchange="setProdTitle(this);" title="Product*">
                                                            <option value="">Select Product</option>
                                                            <?php
                                                                if($card->store_id != null){
                                                                    $prods = $obj->query("  SELECT 	p.id, CONCAT(p.product_name, ' - ', pp.size, pp.size_type) product_name, p.photo 
                                                                                            FROM 	tbl_product p
                                                                                                    INNER JOIN tbl_productprice pp ON pp.product_id = p.id
                                                                                            WHERE 	p.storeid = " . $card->store_id . " AND p.status = 1  
                                                                                            ORDER BY p.product_name");
                                                                                            
                                                                    while($prod = $obj->fetchNextObject($prods)){
                                                                        $selected = '';
    
                                                                        if($prod->id == $card->prod_id)
                                                                            $selected = 'selected';
    
                                                                        echo '<option value="' . $prod->id . '" data-img="' . $prod->photo . '" ' . $selected . '>' . $prod->product_name . '</option>';
                                                                    }
                                                                }
                                                            ?>
                                                        </select>

                                                        <span>Title*</span>
                                                        <input name="txtTitle-<?php echo $TmpID ?>" class="js-txt-title" type="text" value="<?php echo $card->title ?>" placeholder="Enter title*" maxlength="100" title="Title*">

                                                        <input type="file" name="fileImg-<?php echo $TmpID ?>" onchange="setImg(this)" accept="image/jpeg, image/jpg, image/png">

                                                        <a href="javascript:void(0);" class="clsRemoveBtn" onclick="removeStore(this);">
                                                            <img src="../images/close-icon1.png" alt="">
                                                            Remove
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php
                                            $TmpID = $TmpID + 1;
                                        }
                                        ?>
                                    </div>

                                    <br><br>
                                    <div style="padding: 10px;">
                                        <a href="javascript:void(0);" class="clsAddBtn" onclick="addStore();">+ Add Card</a>
                                        <input type="submit" name="submit" value="Update"  class="clsAddBtn" onclick="return setData();"/>
                                    </div>
                                </form>
							</td>
						</tr>
						
					</table>
				</td>
			</tr>
		</table>
	</td>
</tr>
<?php include('footer.php'); ?>
</table>

<div class="clsTemplate">
    <div id="tempStore">
        <div class="clsFP_Store" id="{li_id}">
            <div>
                <input type="hidden" name="{0}" id="{1}" value="0" class="order">
                <input type="hidden" name="{2}" id="{3}" value="0" class="id">
                <input type="hidden" name="{4}" id="{5}" value="" class="old">
                <input type="hidden" name="{6}" id="{7}" value="{8}" class="tmpid">

                <img class="clsCardImg" style="background-image: none, url('https://www.quicklly.com/images/no-img.jpg');">

                <div class="cntrls">
                    <span>Section*</span>
                    <select name="{sel_sec}" class="js-dll-sec" onchange="getStores(this);" title="Section*">
                        <option value="">Select Section*</option>
                    </select>

                    <span>Store</span>
                    <select name="{sel_store}" class="js-dll-store" onchange="getProds(this);" title="Store">
                        <option value="">Select Store</option>
                    </select>

                    <span>Product</span>
                    <select name="{sel_prod}" class="js-dll-prod" onchange="setProdTitle(this);" title="Product*">
                        <option value="">Select Product</option>
                    </select>

                    <span>Title*</span>
                    <input name="{title}" class="js-txt-title" type="text" placeholder="Enter title*" maxlength="100" title="Title*">

                    <input type="file" name="{file_img}" onchange="setImg(this)" accept="image/jpeg, image/jpg, image/png">

                    <a href="javascript:void(0);" class="clsRemoveBtn" onclick="removeStore(this);">
                        <img src="../images/close-icon1.png" alt="">
                        Remove
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="clsPgLoader">
    <img src="../images/ajax-loader1.gif" alt="">
</div>

<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
    const BASE_URL = '<?php echo $BASE_URL ?>';

    var lstSec = [
        <?php
            $secArr=$obj->query("SELECT id, section_name FROM tbl_section ORDER by section_name");
            while($sec=$obj->fetchNextObject($secArr)){
        ?>
                {
                    id:'<?php echo$sec->id ?>',
                    name:'<?php echo$sec->section_name ?>'
                },
        <?php }?>
    ];

    var lstStores = [
        <?php
            $storesArr=$obj->query("SELECT storeid, sectionid, storename, photo FROM stores ORDER BY sectionid, storename");
            while($store=$obj->fetchNextObject($storesArr)){
        ?>
                {
                    sid:'<?php echo$store->storeid ?>',
                    sname:'<?php echo$store->storename ?>',
                    section:[<?php echo$store->sectionid ?>],
                    img:'<?php echo$store->photo ?>'
                },
        <?php }?>
    ];

    var lstProds = [];

    function addStore(){
        var id = 1;

        var stores = $('.clsFP_Stores .clsFP_Store');
        if(stores.length > 0)
            id = parseInt(stores[stores.length - 1].id.substr(6)) + 1;

        var template = $('#tempStore').html();
        template = template.replace('{li_id}', 'store-' + id);
        template = template.replace('{0}', 'hdnOrderNo-' + id);
        template = template.replace('{1}', 'hdnOrderNo-' + id);
        template = template.replace('{2}', 'hdnID-' + id);
        template = template.replace('{3}', 'hdnID-' + id);
        template = template.replace('{4}', 'hdnOldImg-' + id);
        template = template.replace('{5}', 'hdnOldImg-' + id);
        template = template.replace('{6}', 'hdnTmpID-' + id);
        template = template.replace('{7}', 'hdnTmpID-' + id);
        template = template.replace('{8}', id);
        template = template.replace('{sel_sec}', 'ddlSec-' + id);
        template = template.replace('{sel_store}', 'ddlStore-' + id);
        template = template.replace('{sel_prod}', 'ddlProd-' + id);
        template = template.replace('{title}', 'txtTitle-' + id);
        template = template.replace('{file_img}', 'fileImg-' + id);
        $('.clsFP_Stores').append(template);

        var dvLast = $('.clsFP_Stores .clsFP_Store:last-child');
        $(dvLast).find('select')[0].focus();

        var ddlSec = $(dvLast).find('select')[0];

        for (i = 0; i < lstSec.length; i++) {
            var option = document.createElement('option');
            option.value = lstSec[i].id;
            option.innerText = lstSec[i].name;
            $(ddlSec).append(option);
        }

        var ddlSec = $(dvLast).find('select')[0];
        var ddlStore = $(dvLast).find('select')[1];
        var ddlProd = $(dvLast).find('select')[2];

        $(ddlSec).select2();
        $(ddlStore).select2();
        $(ddlProd).select2();
    }

    function getStores(ddl){
        var ddlStore = $(ddl).parent().find('.js-dll-store');
        $(ddlStore).find('option:not(:first-child)').remove();
        
        if(ddl.value != ''){
            $(ddl).parent().find('input[type=text]').val($(ddl).find('option:selected')[0].innerText);
            var lstTmpStores = lstStores.filter(function (el) {return el.section.includes(parseInt(ddl.value));});

            if(lstTmpStores != null && lstTmpStores.length > 0){
                for (i = 0; i < lstTmpStores.length; i++) {
                    var option = document.createElement('option');
                    option.innerText = lstTmpStores[i].sname;
                    option.value = lstTmpStores[i].sid;
                    option.dataset.img = lstTmpStores[i].img;
                    $(ddlStore).append(option);
                }
            }
        }
    }

    function getProds(ddl){
        var ddlProd = $(ddl).parent().find('.js-dll-prod');
        $(ddlProd).find('option:not(:first-child)').remove();

        if(ddl.value != ''){
            $('.clsPgLoader').fadeIn();

            var selOption = $(ddl).find('option:selected')[0];
            var img = $(ddl).closest('.clsFP_Store').find('img')[0];
            var hdnImg = $(ddl).closest('.clsFP_Store').find('input[type=hidden]')[2];

            $(ddl).parent().find('input[type=text]').val(selOption.innerText);
            img.src = BASE_URL + '/seller/upload_images/store/thumb/' + selOption.dataset.img;
            hdnImg.value = 'seller/upload_images/store/thumb/' + selOption.dataset.img;
            $(img).css('background-image','none');

            var lstTmpProds = lstProds.filter(function (el) {return el.sid == ddl.value });

            if(lstTmpProds != null && lstTmpProds.length > 0){
                for (i = 0; i < lstTmpProds[0].lstProds.length; i++) {
                    var option = document.createElement('option');
                    option.value = lstTmpProds[0].lstProds[i].id;
                    option.innerText = lstTmpProds[0].lstProds[i].name;
                    option.dataset.img = lstTmpProds[0].lstProds[i].img;
                    $(ddlProd).append(option);
                }

                $('.clsPgLoader').fadeOut();
            }
            else {
                var req = {
                    'sid': ddl.value
                };

                $.ajax({
                    data: {ajax: 1, action: 'getProds', data: JSON.stringify(req)},
                    type: "POST",
                    success: function (data) {
                        if(data.lstProds != null && data.lstProds.length > 0){
                            lstProds.push({
                                sid: ddl.value,
                                lstProds: data.lstProds
                            });

                            for (i = 0; i < data.lstProds.length; i++) {
                                var option = document.createElement('option');
                                option.value = data.lstProds[i].id;
                                option.innerText = data.lstProds[i].name;
                                option.dataset.img = data.lstProds[i].img;
                                $(ddlProd).append(option);
                            }
                        }

                        $('.clsPgLoader').fadeOut();
                    },
                    error: function (jqXHR, exception) {
                        $('.clsPgLoader').fadeOut();

                        var msg = '';
                        if (jqXHR.status === 0) {
                            msg = 'Not connect.\n Verify Network.';
                        } else if (jqXHR.status == 404) {
                            msg = 'Requested page not found. [404]';
                        } else if (jqXHR.status == 500) {
                            msg = 'Internal Server Error [500].';
                        } else if (exception === 'parsererror') {
                            msg = 'Requested JSON parse failed.';
                        } else if (exception === 'timeout') {
                            msg = 'Time out error.';
                        } else if (exception === 'abort') {
                            msg = 'Ajax request aborted.';
                        } else {
                            msg = 'Uncaught Error.\n' + jqXHR.responseText;
                        }

                        console.error(msg);
                    }
                });
            }
        }
    }

    function setProdTitle(ddl){
        var selOption = $(ddl).find('option:selected')[0];
        var img = $(ddl).closest('.clsFP_Store').find('img')[0];
        var hdnImg = $(ddl).closest('.clsFP_Store').find('input[type=hidden]')[2];

        $(ddl).parent().find('input[type=text]').val(selOption.innerText);
        img.src = BASE_URL + '/upload_images/product/thumb/' + selOption.dataset.img;
        hdnImg.value = 'upload_images/product/thumb/' + selOption.dataset.img;
        $(img).css('background-image','none');
    }

    function removeStore(lnk){
        if(confirm('Remove card?')){
            var parent = $(lnk).closest('.clsFP_Store');

            var hdnID = $(parent).find('input[type=hidden]')[1];
            if (hdnID != undefined && hdnID.value != '0')
                $('#hdnDelIDs')[0].value += hdnID.value + ",";

            var hdnID = $(parent).find('input[type=hidden]')[2];
            if (hdnID != undefined && hdnID.value != '0')
                $('#hdnDelImgs')[0].value += hdnID.value + ",";

            $(lnk).closest('.clsFP_Store').remove();
        }
    }

    function setImg(fu){
        var dvImg = $(fu).parent().parent().find('.clsCardImg')[0];

        if (fu.files && fu.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                dvImg.src = null;
                dvImg.style.backgroundImage = "url(" + e.target.result + ")";
            }

            reader.readAsDataURL(fu.files[0]);
        }
        else
            dvImg.style.backgroundImage = "none, url('https://www.quicklly.com/images/no-img.jpg')";
    }

    function validateData(){
        try{
            var ErrMsg = ''

            var stores = $('.clsFP_Stores .clsFP_Store');
            if(stores.length > 0) {
                var flgSec = false, flgStore = false, flgProd = false, flgTitle = false, flgImg = false;
                for (var i = 0; i < stores.length; i++) {
                    var id = $(stores[i]).find('input[type=hidden]')[1];
                    var ddlSec = $(stores[i]).find('select')[0];
                    var ddlStore = $(stores[i]).find('select')[1];
                    var ddlProd = $(stores[i]).find('select')[2];
                    var txtTitle = $(stores[i]).find('input[type=text]')[0];
                    var hdnImg = $(stores[i]).find('input[type=hidden]')[2];
                    var fileImg = $(stores[i]).find('input[type=file]')[0];

                    if (ddlSec.value == '') {
                        if (!flgSec) {
                            flgSec = true;
                            ErrMsg += '- Select section!\n';
                        }
                        $(ddlSec)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(ddlSec)[0].style.backgroundColor = 'transparent';

                    if (ddlStore.value == '') {
                        if (!flgStore) {
                            flgStore = true;
                            ErrMsg += '- Select store!\n';
                        }
                        $(ddlStore)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(ddlStore)[0].style.backgroundColor = 'transparent';

                    if (ddlProd.value == '') {
                        if (!flgProd) {
                            flgProd = true;
                            ErrMsg += '- Select product!\n';
                        }
                        $(ddlProd)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(ddlProd)[0].style.backgroundColor = 'transparent';

                    if (txtTitle.value == '') {
                        if (!flgTitle) {
                            flgTitle = true;
                            ErrMsg += '- Enter title!\n';
                        }
                        $(txtTitle)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(txtTitle)[0].style.backgroundColor = 'transparent';

                    //if (id.value == '0'){
                        if (hdnImg.value == '' && fileImg.value == '') {
                            if (!flgImg) {
                                flgImg = true;
                                ErrMsg += '- Select image!\n';
                            }
                        }
                    //}
                }
            }

            if (ErrMsg != '') {
                alert('Validation Error!\n' + ErrMsg);
                return false;
            }
            else
                return true;
        } catch (e) {
            alert('Validation Failed!\n');
            console.error(e.message);
            return false;
        }
    }

    function setData() {
        if(validateData()){
            $('#hdnTmpIDs')[0].value = '';

            var items = $(".clsFP_Stores .clsFP_Store")

            for (var i = 0; i < items.length; i++) {
                var hdnOrderNo = $(items[i]).find('input[type=hidden]')[0];
                hdnOrderNo.value = (i + 1);

                var hdnTmpID = $(items[i]).find('input[type=hidden]')[3];
                $('#hdnTmpIDs')[0].value += hdnTmpID.value + ',';
            }

            if(hdnTmpIDs.value != '')
                $('#hdnTmpIDs')[0].value =  $('#hdnTmpIDs').val().substr(0, $('#hdnTmpIDs').val().length - 1);

            if($('#hdnDelIDs').val() != '')
                $('#hdnDelIDs')[0].value =  $('#hdnDelIDs').val().substr(0, $('#hdnDelIDs').val().length - 1);

            return true;
        }
        else
            return false;
    }   

    $(document).ready(function() {
        $(".clsFP_Stores").sortable({
            placeholder: "ui-state-highlight"
        });
        
        $(".clsFP_Stores").disableSelection();

        $('.js-search-dropdown').select2();
	 });
</script>

</body>
</html>
