<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta name="csrf_token" content="{{ csrf_token() }}" />
        <title>Designer</title>

        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    
        <!-- ---- Include the above in your HEAD tag -------- -->
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
        
        <link href="{{asset('/public/designer/css/custom-style.css')}}" rel="stylesheet">
        <link href="{{asset('/public/designer/css/tab-styles.css')}}" rel="stylesheet">
        <link href="{{asset('/public/designer/css/input-range-style.css')}}" rel="stylesheet">
        <link href="{{asset('/public/designer/css/spectrum.css')}}" rel="stylesheet">
        <link href="{{asset('/public/designer/css/one-by-one-slider.css')}}" rel="stylesheet">
        <link href="{{asset('/public/designer/custom-fonts/custom-fonts.php')}}" rel='stylesheet' type='text/css'>
        <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
        
        <style>
            .carousel-indicators > li,
            .carousel-indicators > li.active{
                width: 100px;
                height: 25px;
                border-radius: 0;
                border: solid 1px grey;
                background:white ;
                text-indent: 0;
            }
            .carousel-indicators > li.active {
                background: lightgrey;
            }
            
            .custom-navbar-brand>img {
                display: block;
                height: 36px;
                margin-top: -9px;
            }
            .body-spacer{
                padding: 20px;
            }
            .visualizer-container{
                height: 520px; 
                width: 100%; 
                margin: auto;
            }
            .panel-default{
                font-size: 12px;
            }

            .nav-pills>li.active>a, .nav-pills>li.active>a:focus, .nav-pills>li.active>a:hover{
				color: #000;
    			background-color: #f5f5f5;
			}
			.nav-pills>li>a{
				border-radius: 2px;
            }
            #wrapper{
				width: 1300px;
				overflow: hidden;
				margin: 0 auto;
            }
            #btn-body-gradient{
				/*	background: black; For browsers that do not support gradients */
				background: -webkit-linear-gradient(black, white); /* For Safari 5.1 to 6.0 */
				background: -o-linear-gradient(black, white); /* For Opera 11.1 to 12.0 */
				background: -moz-linear-gradient(black, white); /* For Firefox 3.6 to 15 */
				background: linear-gradient(black, white); /* Standard syntax */
				-webkit-text-stroke-width: 1px;
   				-webkit-text-stroke-color: white;
				border-radius: 0px;
				border-color: #000000;
				width: 45px;
				height: 45px;
				padding:5px;
            }

            #btn-body-pattern-gradient{
				background: -webkit-linear-gradient(black, white); /* For Safari 5.1 to 6.0 */
				background: -o-linear-gradient(black, white); /* For Opera 11.1 to 12.0 */
				background: -moz-linear-gradient(black, white); /* For Firefox 3.6 to 15 */
				background: linear-gradient(black, white); /* Standard syntax */
				-webkit-text-stroke-width: 1px;
   				-webkit-text-stroke-color: white;
				border-radius: 0px;
				border-color: #000000;
				width: 45px;
				height: 45px;
				padding:5px;
			}

            .patternThumbs, .patternTrimThumbs {
				width: 45px;
				height: 45px;
				padding:5px;
				border-radius: 0px;
				border-color: #000000;
            }
            
            .patternBox{
				margin-left: 8px;
				margin-right: 8px;
            }
            
            .row-trim-gradient{
				display:none;
				margin-top: 20px;
            }
            
            #row-body-gradient{
                display:none;
                margin-top: 20px;
            }

            #addNewTextId{
				display: none;
            }

            .canvas-container{
				margin:auto;
            }
            
            .addMarginLeft{
                margin-left:5px;
                margin-bottom: 5px;
            }

            #textProperties{
				display: none;
            }
            
            .font-name-bottom{
				background-color: #f3f3f3;
				padding: 5px;
				margin-top: 14px;
				font-size: 10px
			}
			.custom-font-td:hover{
				background-color: #f2f2f2; !important;
				cursor: pointer;
			}
            .carousel-inner>.item>a>img, .carousel-inner>.item>img, .img-responsive, .clipart-thumnail a>img, .clipart-thumnail>img{
				height: 100px;
			}
			.clipart-thumnail {
				border: none;
			}

            .sendSelectedObjectToFront{
				height: 45px;
				width: 45px;
				background-image: url("{{asset('/public/images/bring_forward.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
			}
			.sendSelectedObjectBack{
				height: 45px;
				width: 45px;
                background-image: url("{{asset('/public/images/send_backward.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
			}

            .btn-send-middle{
                height: 45px;
				width: 45px;
                background-image: url("{{asset('/public/images/send_to_middle.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
            }

            .team-name-standard{
                height: 45px;
				width: 45px;
				background-image: url("{{asset('/public/images/bring_forward.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
            }
            .center-vertical{
                height: 45px;
				width: 45px;
				background-image: url("{{asset('/public/images/align-v1.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
            }

            .center-horizontal{
                height: 45px;
				width: 45px;
				background-image: url("{{asset('/public/images/align-h1.png')}}");
				background-repeat: no-repeat;
				background-size: cover;
            }
            .clipart-thumnail img {
                border: 1px #e2e2e2 solid;
                padding: 2px;
            }
        </style>

        <!-- Global site tag (gtag.js) - Google Analytics -->
		<script async src="https://www.googletagmanager.com/gtag/js?id=UA-136108155-1"></script>
		<script>
		  window.dataLayer = window.dataLayer || [];
		  function gtag(){dataLayer.push(arguments);}
		  gtag('js', new Date());

		  gtag('config', 'UA-136108155-1');
		</script>
    </head>
    <body>
        <div class="navbar-holder">
            @include('layout.navbar')
        </div>
        <div class="body-spacer"></div>
        <div id="wrapper">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-7 col-md-7  col-sm-12">
                        <div  class="panel with-nav-tabs panel-default " style="min-height:300px; height: 602px;">
                            <div class="panel-heading">
                                <ul class="nav nav-tabs nav-justified" id="uniform_sides">
                                    @foreach($templatepaths_arrays as $k => $template)
                                        <li class="@if ($template->Side == 'Front') active @endif" data-tab="li_{{  $template->Side }}_{{  $template->Type }}" data-object-svg="objSVG_{{  $template->Type }}_{{  $template->Side }}" data-canvas-id="canvas_{{  $template->Type }}_{{  $template->Side }}" >
                                            <a i href="#a_{{  $template->Side }}_{{  $template->Type }}" data-toggle="tab" class="svg">
                                                <span style="text-transform:uppercase; font-weight: bold;">{{  $template->Side }}</span>
                                            </a>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                            <div class="panel-body">
                                <div class="tab-content">
                                    @foreach($templatepaths_arrays as $k => $template)
                                        <div class="tab-pane @if ($template->Side == 'Front') active @endif" id="a_{{  $template->Side }}_{{  $template->Type }}">
                                            <div class="col-md-12" style="overflow: auto;">
                                                <div class="visualizer-container divName">
                                                    <div id="objSVG_{{  $template->Type }}_{{  $template->Side }}" style="position:absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);">
                                                    </div>
                                                    
                                                    <!-- Basketball Uniform -->
                                                    @if($template->Type == "Jersey" && $template->Side == "Front")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="222px" height="380px" style="margin-top:47px; margin-left: 0px;"></canvas>
                                                    @endif                                                    
                                                    @if($template->Type == "Jersey" && $template->Side == "Back")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="221.107px" height="379.04px" style="margin-top:22px; margin-left:0px;"></canvas>
                                                    @endif
                                                    @if($template->Type == "Shorts" && $template->Side == "Right")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="157.933px" height="315.863px" style="margin-top:180px; margin-left: 0px;" ></canvas>
                                                    @endif

                                                    @if($template->Type == "Shorts" && $template->Side == "Left")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="157.933px" height="315.863px" style="margin-top:180px; margin-left: 0px;" ></canvas>
                                                    @endif

                                                    <!-- Shirts  -->
                                                    @if($template->Type == "Shirts" && $template->Side == "Front" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="222px" height="380px" style="margin-top:59px; margin-left: 0px;"></canvas>
                                                    @endif
                                                    @if($template->Type == "Shirts" && $template->Side == "Back" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="221.107px" height="379.04px" style="margin-top:23px; margin-left:-1px;"></canvas>
                                                    @endif
                                                    
                                                    @if($template->Type == "Shirts" && $template->Side == "Right" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="96px" height="112px" style="margin-top:257px; margin-left: -17px;" ></canvas>
                                                    @endif

                                                    @if($template->Type == "Shirts" && $template->Side == "Left" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}"  width="96px" height="112px" style="margin-top:257px; margin-left: 17px;" ></canvas>
                                                    @endif

                                                    <!-- Shirts All over Print  -->
                                                    @if($template->Type == "Shirts" && $template->Side == "Front" && $template->TemplateFormat == "png")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="512px" height="512px" style="position:absolute;  top: 50%; left: 50%;"></canvas>
                                                    @endif
                                                    @if($template->Type == "Shirts" && $template->Side == "Back" && $template->TemplateFormat == "png")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="512px" height="512px" style="position:absolute;  top: 50%; left: 50%;"></canvas>
                                                    @endif

                                                    <!-- Hoodie  -->
                                                    @if($template->Type == "Hoodie" && $template->Side == "Front" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="158px" height="174px" style="margin-top:193px; margin-left: 0px;"></canvas>
                                                    @endif
                                                    @if($template->Type == "Hoodie" && $template->Side == "Back" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="158px" height="174px" style="margin-top:171px; margin-left:0xp;"></canvas>
                                                    @endif
													
													<!-- Hoodie All over Print  -->
                                                    @if($template->Type == "Hoodie" && $template->Side == "Front" && $template->TemplateFormat == "png")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="512px" height="512px" style="position:absolute;  top: 50%; left: 50%;"></canvas>
                                                    @endif
                                                    @if($template->Type == "Hoodie" && $template->Side == "Back" && $template->TemplateFormat == "png")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="512px" height="512px" style="position:absolute;  top: 50%; left: 50%;"></canvas>
                                                    @endif


                                                     <!-- Cake  -->
                                                     @if($template->Type == "Cake" && $template->Side == "Front" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="400px" height="400px" style="margin-top:60px; margin-left: -5px;"></canvas>
                                                    @endif
													
                                                    @if($template->Type == "Cake" && $template->Side == "Back" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="400px" height="400px" style="margin-top:60px; margin-left: -5px;"></canvas>
                                                    @endif
													
													<!-- Mask All over Print  -->
                                                    @if($template->Type == "Mask" && $template->Side == "Front" && $template->TemplateFormat == "png")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="572px" height="502px" style="position:absolute;  top: 50%; left: 50%;"></canvas>
                                                    @endif
													
													@if($template->Type == "Mask" && $template->Side == "Front" && $template->TemplateFormat == "svg")
                                                        <canvas id="canvas_{{  $template->Type }}_{{  $template->Side }}" width="451.006px" height="250.56px" style="position:absolute; left: 50%; margin-top: 132px;"></canvas>
                                                    @endif

                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-5 col-md-5 col-sm-12">
                        <div class="panel with-nav-tabs panel-default">
                            <div class="panel-heading">
                                <ul class="nav nav-tabs nav-justified" id="side-controls">

                                @if($template->Type != "Shirts")
                                    <li class="active"><a href="#tab-change-color" id="tab-change-color1" data-toggle="tab"><b style="color:red;">Step 1</b><br>Uniform Color</a></li>
                                    <li><a href="#tab-add-text" id="tab-add-text1" data-toggle="tab"><b style="color:red;">Step 2</b><br>Team Name</a></li>
                                    <li><a href="#tab-add-number" id="tab-add-number1" data-toggle="tab"><b style="color:red;">Step 3</b><br>Name / Number</a></li>
                            
                                @elseif($template->Type == "Shirts")
                                    <li class="active"><a href="#tab-change-color" id="tab-change-color1" data-toggle="tab"><br><br>Body Color</a></li>
                                    <li><a href="#tab-add-text" id="tab-add-text1" data-toggle="tab"><i class="fa fa-font"></i><br><br>Text</a></li>
                                @endif
                                    <li><a href="#tab-clipart" id="tab-clipart1" data-toggle="tab"><i class="fa fa-shirtsinbulk" aria-hidden="true"></i><br>Add<br>Clipart(s)</a></li>
                                    <li><a href="#tab-upload-image" id="tab-upload-image1" data-toggle="tab"><i class="fa fa-image" aria-hidden="true"></i><br>Add<br>Image(s)</a></li>
                                </ul>
                            </div>
                            <div class="panel-body" style="height: 441px; overflow:auto;">
                                <!-- <div class="row"> -->
                                    <!-- <div class="col-sm-12"> -->
                                    <div class="well">
                                        <div class="form-inline">
                                            <div class="form-group">
                                                <div class="checkbox">
                                                    <input type="checkbox" id="grid_lines" data-toggle="toggle" style="width:75px;" data-width="100px" data-on="<i class='fa fa-check-circle'></i> Grid" data-off="<i class='fa fa-ban'></i> Grid" data-size="small">
                                                </div>
                                            </div> 
                                            <div class="form-group">
                                                <div style="margin-right:10px;"></div>
                                            </div>
                                            <div class="form-group upper-buttons">
                                                <button id="copy" class="btn btn-default btn-sm" title="Copy"><i class="fa fa-clone"></i></button>
                                                <button id="paste" class="btn btn-default btn-sm" title="Paste" disabled="disabled"><i class="fa fa-clipboard"></i></button>
                                                <button class="btn btn-default btn-sm remove" title="Delete" disabled="disabled"><i class="fa fa-trash" aria-hidden="true"></i></button>
                                                <button class="btn btn-default btn-sm btn-lock-object" data-status="unlock" title="Lock" disabled="disabled"><i class="fa fa-unlock-alt"></i></button>
                                                
                                                <!-- <button type="button" class="btn btn-default btn-sm remove" title="Remove object"><i class="fa fa-trash" aria-hidden="true"></i></button> -->
                                                <!-- <button id="flip_x">flip X</button>
                                                <button id="flip_y">flip Y</button> -->
                                            </div>
                                        </div>
                                    </div>
                                    <!-- </div>
                                </div> -->
                                <div class="tab-content">
                                    <div class="tab-pane fade in active" id="tab-change-color">
                                        <h4>Body Color</h4>

                                        <ul class="nav nav-pills nav-stacked col-md-4">
                                            <li class="active"><a href="#tab_basecolor" data-toggle="pill">Solid Color</a></li>
                                            @if($template_arrays[0]->WithGradient != 'no')
                                            <li><a href="#tab_gradient" data-toggle="pill">Gradient</a></li>
                                            @endif
                                            <li><a href="#tab_bodypattern" data-toggle="pill">Pattern</a></li>
                                        </ul>
                                        <div class="tab-content col-md-8">
                                            
                                            <div class="tab-pane active" id="tab_basecolor">
                                                <input type="hidden" id="body-color-type" value="Solid">
                                                <table class="table table-custom" >
                                                    <tr>
                                                        <td>Solid Color</td>
                                                    </tr>	
                                                    <tr>
                                                        <td>
                                                            <input type="hidden" name="mainColor" id="mainColor"/>
                                                            <br><small><i>* Click on box to Choose Color</i></small>
                                                        </td>
                                                    </tr>	
                                                </table>
                                            </div>
                                            
                                            <div class="tab-pane" id="tab_gradient">
                                                <table class="table table-custom" >
                                                    <tr>
                                                        <td>Choose Gradient Color</td>
                                                    </tr>	
                                                    <tr>
                                                        <td>
                                                            <button type="button" class="btn" id="btn-body-gradient" title="Gradient Color"></button>
                                                            <br><small><i>* Click on box to choose Gradient Color</i></small>
                                                        </td>
                                                    </tr>	
                                                </table>

                                                <div id="row-body-gradient">
                                                    <div class="row">
                                                        <div class="form-group col-md-12 col-sm-12 col-xs-12">
                                                            Gradient Color:
                                                        </div>
                                                    </div>
                                                    <div class="row">						
                                                        <div class="form-group col-md-2 col-sm-2 col-xs-2">
                                                            <input type="hidden" class="gradientColor pull-right" name="Body_Gradient_Color1" id="Body_Gradient_Color1" data-gradient-type="Body" value="rgb(0, 0, 0)" />
                                                        </div>
                                                        <div class="form-group col-md-10 col-sm-10 col-xs-10">
                                                            <input type="range" id="Offset_Body_Gradient_Color1" data-gradient-id="Body_Gradient_Color1" class="offsetGradientColor form-control input-sm" value="100" min="0" max="10" />
                                                        </div>
                                                    </div>
                                                    <div class="row">
                                                        <div class="form-group col-md-2 col-sm-2 col-xs-2">
                                                            <input type="hidden" class="gradientColor pull-right" name="Body_Gradient_Color2" id="Body_Gradient_Color2" data-gradient-type="Body" value="rgb(255, 255, 255)" />
                                                        </div>
                                                        <div class="form-group col-md-10 col-sm-10 col-xs-10">
                                                            <input type="range" id="Offset_Body_Gradient_Color2" data-gradient-id="Body_Gradient_Color2" class="offsetGradientColor form-control input-sm" value="0" min="0" max="10" />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="tab-pane" id="tab_bodypattern">
                                                <input type="hidden" id="body-pattern-color-type" value="Solid" />
                                                <table class="table table-custom">
                                                    <tr>
                                                        <td>
                                                            Select Pattern
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="text-center">
                                                            <div class="carousel slide multi-item-carousel" id="theCarousel" data-interval="false">
                                                                <div class="carousel-inner">
                                                                    @foreach ($pattern_arrays as $i => $val)
                                                                        <div class="item @if ($i == 0) active @endif">
                                                                            <div class="btn-group patternBox ">
                                                                                <button type="button" data-pattern-path="{{ $val[0]->SVGPath }}" class="patternThumbs btn" data-id="{{ $val[0]->PatternId }}" style="background-image:url('{{ minio_url($val[0]->PatternThumbnail) }}'); background-size:cover; background-repeat: no-repeat;" @if ($i == 0) disabled @endif> @if ($i == 0) <i class="fa fa-2 fa-check" aria-hidden="true"></i> @endif</button>	
                                                                            </div>
                                                                        </div>
                                                                    @endforeach
                                                                </div> 
                                                                <a class="left carousel-control" href="#theCarousel" data-slide="prev" style="width:50px"><i class="fa fa-chevron-left custom-chevron-left"></i></a>
                                                                <a class="right carousel-control" href="#theCarousel" data-slide="next" style="width:50px"><i class="fa fa-chevron-right custom-chevron-right"></i></a>
                                                            </div> 
                                                        </td>
                                                    </tr>
                                                </table>
                                                <div class="row">
                                                    <div id="patternColorChoices">
                                                        <input type="hidden"  name="body-pattern-name" id="body-pattern-name" value="noPattern,0">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        @for($i = 1; $i <=  $template_arrays[0]->Trim; $i++)
                                           <div class="row">
                                                <div class="form-group col-md-12 col-sm-12 col-xs-12">
                                                    <hr style="margin-top: 10px; margin-bottom: 1px;">
                                                </div>
                                            </div>

                                            <!-- @if($template->Type == "Shirts")
                                                @if($i == 1)
                                                    <h4>Right Sleeve</h4>	
                                                @endif

                                                @if($i == 2)
                                                    <h4>Left Sleeve</h4>		
                                                @endif

                                                @if($i == 3)
                                                    <h4>Neck Line</h4>	
                                                @endif

                                            @else
                                                <h4>Trim {{ $i }}</h4>	
                                            @endif -->

                                            <h4 id="h4_Trim_{{ $i }}">Trim {{ $i }}</h4>				
                                            <ul class="nav nav-pills nav-stacked col-md-4">
                                                <li class="active"><a href="#tab_trim_basecolor{{ $i }}" data-toggle="pill">Base Color</a></li>
                                                <li><a href="#tab_trimpattern{{ $i }}" data-toggle="pill">Pattern</a></li>
                                            </ul>

                                            <div class="tab-content col-md-8">
                                                <div class="tab-pane active" id="tab_trim_basecolor{{ $i }}">
                                                    <input type="hidden" id="trim-{{ $i }}-color-type" value="Solid">
                                                    <table class="table table-custom">
                                                        <tr>
                                                            <td>Solid Color</td>
                                                            <!-- <td>Gradient Color</td> -->
                                                        </tr>	
                                                        <tr>
                                                            <td>
                                                                <input type="hidden" class="trimColor" data-trim-num="{{ $i }}" name="trim{{ $i }}" id="Trim_{{ $i }}" value="rgb(204, 204, 204)" />
                                                                <br><small><i>* Click on box to Choose Color</i></small>
                                                            </td>
                                                        </tr>	
                                                    </table>
                                                    <div class="row-trim-gradient" id="row-trim-{{ $i }}-gradient">
                                                        <b>Gradient Color:</b>		
                                                        <div class="row">						
                                                            <div class="form-group col-md-2 col-sm-2 col-xs-2">
                                                                <input type="hidden" class="gradientColor pull-right" name="Trim_{{ $i }}_Gradient_Color1" id="Trim_{{ $i }}_Gradient_Color1" data-gradient-type="Trim" data-trim-num="{{ $i }}" value="rgb(0, 0, 0)" />
                                                            </div>
                                                            <div class="form-group col-md-10 col-sm-10 col-xs-10">
                                                                <input type="range" id="Offset_Trim_{{ $i }}_Gradient_Color1" data-gradient-id="Trim_{{ $i }}_Gradient_Color1" class="offsetGradientColor form-control input-sm" value="100" min="0" max="10" />
                                                            </div>
                                                        </div>
                                                        <div class="row">
                                                            <div class="form-group col-md-2 col-sm-2 col-xs-2">
                                                                    <input type="hidden" class="gradientColor pull-right" name="Trim_{{ $i }}_Gradient_Color2" id="Trim_{{ $i }}_Gradient_Color2" data-gradient-type="Trim" data-trim-num="{{ $i }}" value="rgb(255, 255, 255)" />
                                                            </div>
                                                            <div class="form-group col-md-10 col-sm-10 col-xs-10">
                                                                <input type="range" id="Offset_Trim_{{ $i }}_Gradient_Color2" data-gradient-id="Trim_{{ $i }}_Gradient_Color2" class="offsetGradientColor form-control input-sm" value="0" min="0" max="10" />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="tab-pane" id="tab_trimpattern{{ $i }}">
                                                    <input type="hidden" id="trim-{{ $i }}-pattern-color-type" value="Solid">
                                                    <table class="table table-custom">
                                                        <tr>
                                                            <td>
                                                                Select Pattern
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td class="text-center">
                                                                <div class="carousel slide multi-item-carousel" id="theCarousel{{ $i }}" data-interval="false">
                                                                    <div class="carousel-inner">
                                                                        @foreach ($pattern_arrays as $r => $val)
                                                                            <div class="item @if ($r == 0) active @endif">
                                                                                <div class="btn-group patternBox ">
                                                                                    <button type="button" data-pattern-path="{{ $val[0]->SVGPath }}" class="patternTrimThumbs patternTrim{{ $i }} btn" data-id="{{ $val[0]->PatternId }}"  data-trim="{{ $i }}" style="background-image:url('{{ minio_url($val[0]->PatternThumbnail) }}'); background-size:cover; background-repeat: no-repeat;" @if ($r == 0) disabled @endif> @if ($r == 0) <i class="fa fa-2 fa-check" aria-hidden="true"></i> @endif</button>	
                                                                                </div>
                                                                            </div>
                                                                        @endforeach
                                                                    </div> 
                                                                        <a class="left carousel-control" href="#theCarousel{{ $i }}" data-slide="prev" style="width:50px"><i class="fa fa-chevron-left custom-chevron-left"></i></a>
                                                                        <a class="right carousel-control" href="#theCarousel{{ $i }}" data-slide="next" style="width:50px"><i class="fa fa-chevron-right custom-chevron-right"></i></a>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                    <div class="row">
                                                        <div id="trim-{{ $i }}-pattern-color-choices">
                                                            <input type="hidden"  name="Trim_{{ $i }}_patternName" id="Trim_{{ $i }}_patternName" value="noPattern,0" />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endfor

                                    </div>
                                    <div class="tab-pane fade" id="tab-add-text">
																			<div id="addNewTextId">
																				<div class="row">
																					<div class="form-group col-sm-12">
																						<!-- <button type="button" class="btn btn-danger pull-right btn-sm remove addMarginLeft" title="Remove object"><i class="fa fa-trash" aria-hidden="true"></i></button> -->
																						<button type="button" onclick="addNewText();" class="btn btn-primary pull-right btn-sm"><i class="fa fa-plus" aria-hidden="true"></i> New Text</button>
																					</div>
																				</div>
																				<div class="row">
																					<div class="form-group col-sm-12">
																						<label>Enter team name here</label>
																						<textarea name="editedTextInput" id="editedTextInput" class="form-control" placeholder="Enter team name here"></textarea>

																					</div>
																				</div>
																			</div>
																			<div id="enterTextId">
																				<div class="row">
																					<div class="form-group col-sm-12">
																						<label>Enter team name here</label>
																						<textarea name="textInput" id="textInput" class="form-control" placeholder="Enter team name here"></textarea>
																						<!--span id="errfirstName" style="color: #dd4b39"></span> !-->
																					</div>

																					<div class="form-group col-sm-12">
																						<button type="button" id="okBtn" onclick="addText();" class="btn btn-primary btn-block btn-sm">OK</button>
																					</div>
																				</div>
																			</div>
																			<div id="textProperties">
																					@include('designer.text_properties')
																			</div>
                                    </div>

                                    <div class="tab-pane fade" id="tab-add-number">
                                        <input type="hidden" id="countbtn" value="0" />
                                        <div id="addNumberId" style="display:none;">
                                            <div class="row">
                                                <div class="form-group col-sm-12">
                                                    <button type="button" class="btn btn-danger pull-right btn-sm removeNameNumber addMarginLeft" title="Remove object"><i class="fa fa-trash" aria-hidden="true"></i></button>
                                                    <div id="NameNumberId"></div>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="form-group col-sm-12">
                                                    <label>Edit Name / Number</label>
                                                    <textarea name="editedNumberInput" id="editedNumberInput" class="form-control" placeholder="Enter number here"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="enterNumberId">
                                            <div class="row">
                                                <div class="form-group col-sm-12">
                                                    <button type="button" id="btnNumber" class="btn btn-warning btn-block btn-lg" onclick="addNameNumber();"><i class="fa fa-plus" aria-hidden="true"></i> Add Name and Number</button>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="numberProperties" style="display:none;">
                                            @include('designer.text_properties')
                                        </div>
                                    </div>

                                    <div class="tab-pane fade" id="tab-clipart">
																			<div id="tab-clipart-content">
																			</div>
																		</div>

                                    <div class="tab-pane fade" id="tab-upload-image">
										<!-- <div class="row">
											<div class="form-group col-md-12">
												<button id="img-remove-btn" type="button" class="btn btn-danger pull-right btn-sm remove addMarginLeft" title="Remove object"><i class="fa fa-trash" aria-hidden="true"></i></button>
											</div>
										</div> -->
										<div class="row">
											<div class="form-group col-md-12">
												<h4>Add Image(s)</h4>
												<hr>
												<input type="file" id="upload-images" class="form-control" placeholder="Choose Image">
											</div>
										</div>
										<!-- <hr> -->
										<div id="image-properties">
										    
											<div class="row">
												<div class="col-md-6">
													<h4>Image Properties</h4>
												</div>
												<div class="col-md-6">
													<button class="btn btn-sm btn-default pull-right addMarginLeft" id="btn-close-clipart-properties" title="Close Clipart Properties"><i class="fa fa-remove" aria-hidden="true"></i> Close</button>
													<!-- <button id="img-remove-btn" type="button" class="btn btn-danger pull-right btn-sm remove addMarginLeft" title="Remove object"><i class="fa fa-trash" aria-hidden="true"></i></button> -->
                                                    <!-- <button type="button" class="btn btn-danger pull-right btn-sm addMarginLeft copyObject" title="Duplicate object"><i class="fa fa-copy" aria-hidden="true"></i></button>  -->
												</div>
											</div>
											<div class="row">
												<div class="form-group col-md-3 col-sm-3 col-xs-3">
													<label>Opacity</label>
												</div>
												<div class="form-group col-md-6 col-sm-6 col-xs-6">

													<input type="range"  class="form-control input-sm opacityTextSlider" value="1" min="0" max="10"  />
												</div>
												<div class="form-group col-md-3 col-sm-3 col-xs-3">
													<input type="text" style="margin-top:5px;" class="form-control input-sm  text-center opacityTextValue" />
												</div>
											</div>
											<div class="row">
												<div class="form-group col-md-3 col-sm-3 col-xs-3">
													<label>Rotate</label>
												</div>
												<div class="form-group col-md-6 col-sm-6 col-xs-6">

													<input type="range" class="form-control input-sm rotateTextSlider" value="0" min="-180" max="180"  />
												</div>
												<div class="form-group col-md-3 col-sm-3 col-xs-3">
													<input type="text" style="margin-top:5px;" class="form-control input-sm text-center rotateTextValue"/>
												</div>
											</div>
											<div class="row">
												<div class="form-group col-md-5 col-sm-6 col-xs-6">
													<label>Layer Order</label><br>
													<button class="btn btn-sm btn-default sendSelectedObjectToFront" title="Bring Forward"></button>
													<button class="btn btn-sm btn-default sendSelectedObjectBack"  title="Send Backward"></button>
												</div>
												<div class="form-group col-md-7 col-sm-6 col-xs-6">
													<label>Position</label><br>
													<!-- <button class="btn btn-sm btn-default btn-send-middle" style="margin:2px;" onclick="centerOnly();"></button>
													<button class="btn btn-sm btn-default center-horizontal" style="margin:2px;" onclick="centerVer();"></button>
													<button class="btn btn-sm btn-default center-horizontal" style="margin:2px;"  onclick="centerHor();" ></button> -->
                                                    <button class="btn btn-sm btn-default" style="min-width:35px;" title="Center Vertical" onclick="centerVer();"><i class="fa fa-arrows-v"></i></button>
                                                    <button class="btn btn-sm btn-default" style="min-width:35px;" title="Center Horizontal" onclick="centerHor();" ><i class="fa fa-arrows-h"></i></button>
                                                    <button class="btn btn-sm btn-default flip-vertically" style="min-width:35px;" title="Flip Vertically"><i class="fa fa-angle-double-up"></i></button>
                                                    <button class="btn btn-sm btn-default flip-horizontally" style="min-width:35px;" title="Flip Horizontally"><i class="fa fa-angle-double-right"></i></button>
												</div>
											</div>
											<hr>
										
										</div>
									</div>
                                    
                                </div>
                            </div>
                            <div class="panel-footer">
								<div class="row">
									<div class="form-group col-md-12">
                                    @if (Auth::guest())
                                        <div class="btn-save-design">
                                            <button type="button" class="btn btn-lg btn-primary pull-right" data-toggle="modal" data-target="#modalLogin"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save Design</button>
                                        </div>
                                    @else
                                        <button type="button" class="btn btn-lg btn-primary pull-right" data-toggle="modal" data-target="#modalDesignName"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save Design</button>
                                       
                                    @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        
        <!-- modals -->
            <div class="modal fade" id="fontsModal" role="dialog">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Fonts</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-12">
                                    <table class="table table-bordered">
                                        @define $columns = 4
                                        @define $i = 0
                                       
                                        @foreach($fonts_array as $fonts)

                                         @define $i++
                                            @if ($i % $columns == 1) 
                                                <tr>
                                            @endif

                                            <td class="custom-font-td col-md-3 text-center" style="padding: 0px;" data-font-size="{{ $fonts->additionalSize }}" data-font-style="{{ $fonts->fontFamily }}" data-font-display="{{ $fonts->fontNameDisplay }}">
                                                <div style="font-family:'{{ $fonts->fontFamily }}'; font-size:1.5em; padding: 5px;" class="add-text-content"></div>
                                                <div class="font-name-bottom">{{ $fonts->fontNameDisplay }} <i class=""></i></div>
                                            </td>
                                        
                                            <!-- //if this is last value in row, end row -->
                                            @if ($i % $columns == 0) 
                                                </tr>
                                            @endif
                                        @endforeach

                                        @define $spacercells = $columns - ($i % $columns)

                                        @if ($spacercells < $columns) 
                                            @define $j
                                            @for($j=1; $j<=$spacercells; $j++)
                                                <td></td>
                                            @endfor
                                            </tr>
                                        @endif

                                       
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="modalDesignName" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                            <h4 class="modal-title">Design Name</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-xs-12">
                                    <label>Name your design</label>
                                        <textarea class="form-control" id="design_name"></textarea>
                                        <br>
                                        <button type="button" id="btn_submitDesignName" class="btn btn-lg btn-primary btn-block">Submit</button>
                                        <br><br>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="modalLogin" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                            <!-- <h4 class="modal-title">Design Name</h4> -->
                        </div>
                        <div class="modal-body">
                            <div class="row">
                            <div class="col-md-10 col-md-offset-1">
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <h3>Login</h3>
                                    </div>
                                    <div class="panel-body">
                                        <div class="row">
                                            <div class="col-xs-6">
                                                <div class="well">
                                                    <div id="login-response-msg"></div>
                                                    <form  role="form" id="frm-login">
                                                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                                        <input type="hidden" name="redirect" value="{{ Request::get('redirectUrl')  }}">
                                                        <div class="form-group">
                                                            <label for="username" class="control-label">Username</label>
                                                            <input type="email" class="form-control" name="email"  value="{{ old('email') }}"  title="Please enter your email address" placeholder="example@gmail.com">
                                                            <span class="help-block"></span>
                                                        </div>
                                                        <div class="form-group">
                                                            <label for="password" class="control-label">Password</label>
                                                            <input type="password" class="form-control" name="password"  title="Please enter your password">
                                                            <span class="help-block"></span>
                                                        </div>
                                                        <div class="checkbox">
                                                            <label>
                                                                <input type="checkbox" name="remember"> Remember login
                                                            </label>
                                                            <p class="help-block">(if this is a private computer)</p>
                                                        </div>
                                                        <button type="submit" id="btn-login" class="btn btn-success btn-block"><span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign in</button>
                                                        <a href="{{ url('/password/email') }}" class="btn btn-link btn-block">Forgot Your Password?</a>
                                                    </form>
                                                </div>
                                            </div>
                                            <div class="col-xs-6">
                                                <p class="lead">Register now for <span class="text-success">FREE</span></p>
                                                <ul class="list-unstyled" style="line-height: 2">
                                                    <li><span class="fa fa-check text-success"></span> See all your orders</li>
                                                    <li><span class="fa fa-check text-success"></span> Fast re-order</li>
                                                    <li><span class="fa fa-check text-success"></span> Save your favorites</li>
                                                    <li><span class="fa fa-check text-success"></span> Fast checkout</li>
                                                    <li><span class="fa fa-check text-success"></span> Get a gift <small>(only new customers)</small></li>
                                                    <!-- <li><a href="/read-more/"><u>Read more</u></a></li> -->
                                                </ul>
                                                <p><a href="{{ url('auth/register') }}" class="btn btn-info btn-block">Yes please, register now!</a></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <!-- end modals -->

        <!-- Footer -->
        <!-- End Footer -->
        
        <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.15/fabric.min.js"></script>
        <!-- <script src="https://rawgit.com/EffEPi/fabric.curvedText/master/fabric.curvedText.js"></script>  -->
        <script src="{{asset('/public/designer/js/spectrum.js')}}"></script>

        <script src="{{asset('/public/designer/js/custom-script.js')}}"></script>
        <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
        <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
        <script src="https://rawgit.com/fabricjs/fabric.js/master/lib/centering_guidelines.js"></script>
        <script src="https://rawgit.com/fabricjs/fabric.js/master/lib/aligning_guidelines.js"></script>
        <script>
            
            $(document).ready(function() {
              
                $.getJSON("{{asset('/public/designer/palette.json') }}", callbackFuncWithData);

                function callbackFuncWithData(data){
                    console.log(data)
                }
                
                $('#toTop').click(function() {
                    $('body,html').animate({scrollTop:0},800);
                });

                $('#grid_lines').change(function() {

                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];
                        
                        try{
                            if($(this).prop('checked')){
                                document.getElementById(sideName + '_Grid_Lines').setAttribute("display", "");
                            }else{
                                document.getElementById(sideName + '_Grid_Lines').setAttribute("display", "none");
                            }
                        }catch(e){

                        }
                    }

                    
                });

                $("#copy").click(function(){
                    copy();
                });
                $("#paste").click(function(){
                    paste();
                });

                $(".btn-lock-object").click(function(){
                    if($(this).data('status') == 'unlock'){
                        lockObject();
                    }else{
                        unLockObject();
                    }
                    
                });

                $(document).on('button click', '.flip-horizontally', function(){
                    // console.log('flipx');
                    var object = canvas.getActiveObject();
                    object.toggle('flipX');
                    canvas.renderAll();  
                });

                $(document).on('button click', '.flip-vertically', function(){
                    var object = canvas.getActiveObject();
                    object.toggle('flipY');
                    canvas.renderAll();  
                });

                $(document).keyup(function(e) {
                    if (e.key === "Escape") { // escape key maps to keycode `27`
                        //console.log('escape');
                        onDeSelected();
                    }
                });
        
                var copiedObject,
                copiedObjects = new Array();
                function copy(){
                    copiedObjects = new Array();
                    if(canvas.getActiveGroup()){
                        //console.log(canvas.getActiveGroup().getObjects());
                        canvas.getActiveGroup().getObjects().forEach(function(o){
                            var object = fabric.util.object.clone(o);
                            copiedObjects.push(object);
                        });
                        $('#paste').attr("disabled", false);             
                    }
                    else if(canvas.getActiveObject()){
                        
                        // var object = fabric.util.object.clone(canvas.getActiveObject());
                        var object = canvas.getActiveObject().toObject(['id']);
                        copiedObject = object;
                        copiedObjects = new Array();
                        $('#paste').attr("disabled", false);
                        
                    }
                }

                function paste(){

                    if(copiedObjects.length > 0){
                        for(var i in copiedObjects){
                            copiedObjects[i]=fabric.util.object.clone(copiedObjects[i]);
                            
                            //copiedObjects[i].set("top", copiedObjects[i].top+100);
                            //copiedObjects[i].set("left", copiedObjects[i].left+100);
                            
                            canvas.add(copiedObjects[i]);
                            canvas.item(canvas.size() - 1).hasControls = true;
                        }                
                    }

                    else if(copiedObject){
                        // copiedObject= fabric.util.object.clone(copiedObject);
                        // copiedObject.set("top", 150);
                        // copiedObject.set("left", 150);
                        // canvas.add(copiedObject);
                        // canvas.item(canvas.size() - 1).hasControls = true;
                        fabric.util.enlivenObjects([copiedObject], function(objects) {
                            objects.forEach(function(o) {
                                o.set({
                                    // top: o.top + 1,
                                    // left: o.left + 1,
                                    borderColor: '#71b7f3',
                                    cornerColor: '#71b7f3',
                                    cornerSize: 10,
                                    transparentCorners: false
                                });
                                canvas.add(o);
                                canvas.setActiveObject(o);
                            });
                            canvas.renderAll();
                        });
                    }
                    canvas.renderAll();  
                }

                $("#frm-login").validate({
                    rules: {
                        email: {
                            required: true,
                            email: true
                        },
                        password: {
                            required: true
                            //minlength: 6  // <-- removed underscore
                        }
                    },
                    messages: {},
                    errorPlacement: function(error, element) {
                        var placement = $(element).data('error');
                        if (placement) {
                            $(placement).append(error);
                        }else {
                            error.insertAfter(element);
                        }
                    },
                    submitHandler: submitLoginForm
                });

                // calling functions 
                changeData();
                colorPickerCustom();
                templateColors('{{ $template_arrays[0]->TemplateCode }}');
                loadClipartContent();
                
                var get_template_type = "{{ $template->Type }}";

                // if((get_template_type  != "Shirts")  || (get_template_type  != "Hoodie")){
                if(get_template_type  != "Hoodie" && get_template_type  != "Shirts"  && get_template_type  != "Cake" && get_template_type  != "Mask" ){    
                    addDefaultTeamText();
                    addNameNumber();
                }

                // onDeSelected();
                //  end call
                
                $('.multi-item-carousel .item').each(function(){
                    var next = $(this).next();
                        if (!next.length) {
                            next = $(this).siblings(':first');
                        }

                        next.children(':first-child').clone().appendTo($(this));
                        

                    for (var i=0; i<2; i++){
                        
                        next=next.next(); 
                        
                        if (!next.length){ 
                            next=$(this).siblings(':first');
                        }
                        next.children(':first-child').clone().appendTo($(this));
                    }

                });

                // initCanvas();
                // onSelected(canvas_Shirts_Front);
            });
            
            // design saving 
            $(document).on('button click', '#btn_submitDesignName', function(){
                
                var design_name = $('#design_name').val();
                if(design_name != ""){
                    submitSaveDesign(design_name);
                }else{
                    alert("Please enter your design name.");
                    $('#design_name').focus();
                }
                
            });

            function submitSaveDesign(design_name){
                newformSaveDesign			=	document.createElement('form');
                newformSaveDesign.name		=	'formSaveDesign';
                newformSaveDesign.method	=	'POST';
                newformSaveDesign.action	=	"{{url('designer/a/save-design')}}";

                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];

                    var contentName = "content_" + sideName;
                    var objects = window['canvas_' + type + '_' + sideName].getObjects();
                    try {
                        objects.forEach((obj, index) => {
                        var newUrl =  saveImages(obj._originalElement.currentSrc, sideName, index);
                        obj._originalElement.src  = newUrl;
                    });
                    } catch (error) {
                        console.log(error);
                    }
                    // objects.forEach((obj, index) => {
                    //     var newUrl =  saveImages(obj._originalElement.currentSrc, sideName, index);
                    //     obj._originalElement.src  = newUrl;
                    // });
                    window['canvas_' + type + '_' + sideName].renderAll();

                    contentName = JSON.stringify(window['canvas_' + type + '_' + sideName].toObject(['idNumber', 'id'])); // = new fabric.Canvas(canvasName);
            

                    var inputName = "json_" +  sideName;
                    var hiddenFieldContentDesign = "field_" + sideName;

                    hiddenFieldContentDesign = document.createElement("input");
                    hiddenFieldContentDesign.setAttribute("type", "hidden");
                    hiddenFieldContentDesign.setAttribute("name", inputName);
                    hiddenFieldContentDesign.setAttribute("value", contentName);
                    newformSaveDesign.appendChild(hiddenFieldContentDesign);
                }
                
                var hiddenFieldTemplateDetails = document.createElement("input");
                hiddenFieldTemplateDetails.setAttribute("type", "hidden");
                hiddenFieldTemplateDetails.setAttribute("name", "templateDetails");
                hiddenFieldTemplateDetails.setAttribute("value",  exportSVG());
                newformSaveDesign.appendChild(hiddenFieldTemplateDetails);

                var hiddenField_design_name = document.createElement("input");
                hiddenField_design_name.setAttribute("type", "hidden");
                hiddenField_design_name.setAttribute("name", "design_name");
                hiddenField_design_name.setAttribute("value", design_name);
                newformSaveDesign.appendChild(hiddenField_design_name);

                var hiddenField_token = document.createElement("input");
                hiddenField_token.setAttribute("type", "hidden");
                hiddenField_token.setAttribute("name", "_token");
                hiddenField_token.setAttribute("value", "<?= csrf_token(); ?>");
                newformSaveDesign.appendChild(hiddenField_token);

                document.body.appendChild(newformSaveDesign);
                // console.log(exportSVG());
                newformSaveDesign.submit();
            }

            function exportSVG(){

                var finalJSON = [];
                var arrayMainColor = [];
                var arrayTrim = [];
                var arrpatternColors = [];
                var temp;

                var arrayPatternColors = [];
                var value = $('#body-pattern-name').val();
                var p = value.split(',');
                patternId  = p[0];
                patternNoOFColors = p[1];

                if(patternNoOFColors > 0){
                    arrayPatternColors.push({
                        patternId : patternId,
                        patternColorType : $('#body-pattern-color-type').val(),
                        patternGradientColor1 : $('#Body_Pattern_Gradient_Color1').val(),
                        patternGradientColor2 : $('#Body_Pattern_Gradient_Color2').val(),
                        patternGradientOffset1 : $('#Offset_Body_Pattern_Gradient_Color1').val() * 10 + "%",
                        patternGradientOffset2 : $('#Offset_Body_Pattern_Gradient_Color2').val() * 10 + "%",
                        patternOpacity: $('#opacityPatternValue').val() / 10,
                        patternColors : arrpatternColors

                    });
                    for (i = 1; i <=  patternNoOFColors; i++){
                        temp = {};
                            temp['PatternColor' + i] = $('#PatternColor'+i).val();
                        arrpatternColors.push(temp);
                    }
                }

                arrayMainColor.push({
                    type : $('#body-color-type').val(),
                    solidColor: $('#mainColor').val(),
                    // gradientColorId: 'gradientColor',
                    gradientColor1: $('#Body_Gradient_Color1').val(),
                    gradientColor2: $('#Body_Gradient_Color2').val(),
                    gradientColorOffset1: $('#Offset_Body_Gradient_Color1').val() * 10 + "%",
                    gradientColorOffset2: $('#Offset_Body_Gradient_Color2').val() * 10 + "%",

                });

                var numberOfTrimi = '{{ $template_arrays[0]->Trim }}';

                for(var i = 0; i < numberOfTrimi; i++){
                    var trimCount = i + 1;
                    var SVGTrimId = "Trim_"+trimCount;
                    var TrimVar = "Trim"+trimCount;
                    var TrimPattern = "Trim"+trimCount+"_Pattern";
                    // Trim_2_PatternColor1
                    var getPatternValue = $('#Trim_'+trimCount+'_patternName').val();
                    var res = getPatternValue.split(',');
                    Trim_patternId  = res[0];
                    Trim_patternNoOFColors = res[1];
                    
                    var trimpatterncolor = "Trim"+trimCount+"_patternColor";
                    // console.log(Trim_patternId);
                    var patterncolor = getTrimPatternColor(Trim_patternNoOFColors, trimCount);
                    arrayTrim.push({
                        [TrimVar] : {
                            // color : $('#Trim_'+trimCount).val(),
                            type : $('#trim-'+trimCount+'-color-type').val(),
                            solidColor: $('#Trim_'+trimCount).val(),
                            // gradientColorId: 'gradientColor',
                            gradientColor1: $('#Trim_'+trimCount+'_Gradient_Color1').val(),
                            gradientColor2: $('#Trim_'+trimCount+'_Gradient_Color2').val(),
                            gradientColorOffset1: $('#Offset_Trim_'+trimCount+'_Gradient_Color1').val() * 10 + "%",
                            gradientColorOffset2: $('#Offset_Trim_'+trimCount+'_Gradient_Color2').val() * 10 + "%",
                        },
                        [TrimPattern] :{
                            patternId : Trim_patternId,
                            patternColorType : $('#trim-'+trimCount+'-pattern-color-type').val(),
                            // patternGradientId : 'gradientPattern',
                            patternGradientColor1 : $('#Trim_'+trimCount+'_Pattern_Gradient_Color1').val(),
                            patternGradientColor2 : $('#Trim_'+trimCount+'_Pattern_Gradient_Color2').val(),
                            patternGradientOffset1 : $('#Offset_Trim_'+trimCount+'_Pattern_Gradient_Color1').val() * 10 + "%",
                            patternGradientOffset2 : $('#Offset_Trim_'+trimCount+'_Pattern_Gradient_Color2').val() * 10 + "%",
                            // patternOpacity: $('#opacityPatternValue').val() / 10,
                            patternColors : patterncolor
                        },
                        
                        //  [trimpatterncolor] : {
                        // 	patterncolor
                        //  }

                    });
                }

                finalJSON.push({
                    templateCode : '{{ $template_arrays[0]->TemplateCode }}',
                    mainColor : arrayMainColor,
                    patternColors : arrayPatternColors,
                    Trims: arrayTrim,
                    //contents: consolidatedContents,
                });

                // then to get the JSON string
                var jsonString = JSON.stringify(finalJSON);
                return jsonString;

                // console.log(jsonString);
            }
            
            function getTrimPatternColor(patternColor, trimCount){
                var trimcolor;
                var Trim_Pattern_Color_Array = [];
                for (k = 1; k <=  patternColor; k++){
                    trimcolor = {};
                        trimcolor['PatternColor' + k] = $('#Trim_'+trimCount+'_PatternColor'+k).val();
                    Trim_Pattern_Color_Array.push(trimcolor);
                    // Trim_Pattern_Color_Array.push($('#Trim_'+trimCount+'_PatternColor'+k).val());
                
                }
                return Trim_Pattern_Color_Array;
                // return false;
            }


            function saveImages(base64Image, sideName, image_count){
                var newUrl;
                $.ajax({    //create an ajax request to load_page.php
                    type: "POST",
                    url: "{{url('designer/a/save-images')}}",
                    async: false,
                    dataType : 'json',
                    data: {
                        base64_image : base64Image,
                        side: sideName,
                        image_count: image_count
                    },
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response){
                        if(response.success){
                            newUrl =  response.url;
                        }
                    } 
                });

                return newUrl;
            }

            // end design saving

            // 1ST TAB <---####################################
            $('#btn-body-gradient').on("click", function() {
				
				$('#row-body-gradient').css({
					'display':'block'
				});
				
				$(this).html('<i class="fa fa-2 fa-check" aria-hidden="true"></i>');
				
				$('#body-color-type').val('Gradient');
				
				var gradientId = $(this).attr('id');
				
                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];
                    var pathLocation = SideAndPath[i]['Path'];

					var objectId = "objSVG_" + type + "_" + sideName;
					var SVGColorId = type +"_"+sideName+"_"+"Color";
					var getGradientId = sideName + "_" + type + "_Body_Gradient";
					try{
						document.getElementById(SVGColorId).setAttribute("fill", "url(#"+getGradientId+")");
					}catch(e){
						// error here
					}
				}
			});
            
            $(document).on('button click', '.patternThumbs', function(){

                var patternSVGPath = $(this).attr('data-pattern-path');

                var patternPath =  "{{ minio_url('') }}" + patternSVGPath; 

                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];

                    var mainColorId = type + "_" + sideName + "_" + "Color";
                    var urlClippath = "url(#"+ mainColorId +"_Clippath_URL)"; 
                    var objectId = "objSVG_" + type + "_" + sideName;
                    var svgpatternidVal = mainColorId + "_Pattern";
                    var TypeAndSide =  type + "_" + sideName;

                    if(patternSVGPath == ""){
                        var a = document.getElementById(objectId);
                        var svgDoc = a.contentDocument;
                        try{
                            document.getElementById(svgpatternidVal).innerHTML = "";
                        }catch(e){
                            //console.log(e);
                        }
                    }else{
                        loadPattern(patternPath, urlClippath, svgpatternidVal, objectId, TypeAndSide);
                    }
                    
                    
                }

                var getId = $(this).attr('data-id');

                $.ajax({    //create an ajax request to load_page.php

                    type: "POST",
                    url: "{{url('designer/a/set-pattern')}}",
                    dataType: "html",   //expect html to be returned
                    data: {
                        patternId : getId
                    },
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response){

                        if(getId != 'noPattern'){

                            $("#patternColorChoices").hide().html(response).fadeIn("slow");

                                loadPatternColor();
                                colorPickerCustom();


                        }else{
                                $("#patternColorChoices").html(response);
                                //backToNoPattern();

                        }
                    }
                });

                $(".patternThumbs").attr("disabled", false);
                $(".patternThumbs").html('').fadeIn("slow");
                $(this).attr("disabled", true);
                $(this).html('<i class="fa fa-2 fa-check" aria-hidden="true"></i>');

                $("#body-pattern-color-type").val("Solid");

            });
            
            $(document).on('button click', '.patternTrimThumbs', function(){

                var patternSVGPath = $(this).attr('data-pattern-path');
                var patternPath =  "{{ minio_url('') }}" + patternSVGPath; 
                var getTrimId = $(this).attr('data-trim');
               
                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];

                    var mainColorId = type + "_" + sideName + "_" + "Color";
                    var urlClippath = "url(#"+type + "_" + sideName +"_Trim_"+ getTrimId +"_Clippath_URL)"; 
                    var objectId = "objSVG_" + type + "_" + sideName;
                    var svgpatternidVal = type + "_" + sideName + "_Trim_" + getTrimId + "_Pattern";
                    var TypeAndSide =  type + "_" + sideName + "_Trim_" + getTrimId;

                    if(patternSVGPath == ""){
                        var a = document.getElementById(objectId);
                        var svgDoc = a.contentDocument;
                        try{
                            document.getElementById(svgpatternidVal).innerHTML = "";
                        }catch(e){
                            //console.log(e);
                        }
                    }else{
                        loadPattern(patternPath, urlClippath, svgpatternidVal, objectId, TypeAndSide);
                    }
                }

                var getPatternId = $(this).attr('data-id');

                $.ajax({    //create an ajax request to load_page.php

                    type: "POST",
                    url: "{{url('designer/a/set-trim-pattern')}}",
                    dataType: "html",   //expect html to be returned
                    data: {
                        patternId : getPatternId,
                        trim : getTrimId,
                    },
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response){

                        if(getPatternId != 'noPattern'){
                            $("#trim-"+getTrimId+"-pattern-color-choices").hide().html(response).fadeIn("slow");
                            loadPatternColor();
                            colorPickerCustom();
                        }else{
                                $("#trim-"+getTrimId+"-pattern-color-choices").hide().html(response).fadeIn("slow");
                    
                        }
                    } 
                });

                $(".patternTrim"+getTrimId).attr("disabled", false);
                $(".patternTrim"+getTrimId).html('').fadeIn("slow");
                $(this).attr("disabled", true);
                $(this).html('<i class="fa fa-2 fa-check" aria-hidden="true"></i>');
                $('#trim-'+getTrimId+'-pattern-color-type').val('Solid');

            });

            $(document).on('select click', '#btn-body-pattern-gradient', function() {
				var gradientId = $(this).attr('id');
				$('#body-pattern-color-type').val('Gradient');

				$("#row-body-pattern-gradient").css('display', 'block');
				$(this).html('<i class="fa fa-2 fa-check" aria-hidden="true"></i>');
                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];
                    var pathLocation = SideAndPath[i]['Path'];

					var objectId = "objSVG_" + type + "_" + sideName;
					var patternColorId = type + "_" + sideName + "_PatternColor1";
					// patternColorId = type + "_" + sideName + "_" + patternId;
					var getGradientId = sideName + "_" + type + "_Body_Pattern_Gradient";
					// Front_Jersey_PatternColor1
					try{
						document.getElementById(patternColorId).setAttribute("fill", "url(#"+getGradientId+")");
						// document.getElementById(patternColorId).setAttribute("fill", onMoveColor);
					}catch(e){
						// error here
					}
				}

			});

            function colorPickerCustom(){
                $('.sp-replacer').css({
                    'padding':'0px',
                    'height':'45px',
                    'width':'45px',
                    'radius': '2px'
                });

                $('.sp-preview').css({
                    'width':'45px',
                    'height':'45px',
                    'border':'none'
                });
                $('.sp-dd').css({
                    'display':'none'
                });

                $('.sp-input-container').css({
                    'float': 'left',
                    'width':'100%'
                });
                
                $('.sp-palette-button-container').css({
                    'padding-top': '10px',
                });

                $('.sp-button-container').css({
                    'padding-top': '10px',
                });
                
            }

            function changeData() {

                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                var canvas;
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];
                    var pathLocation = SideAndPath[i]['Path'];
                    var templateFormat = SideAndPath[i]['TemplateFormat'];

                    var objectId = "objSVG_" + type + "_" + sideName;
                    var SVGColorId = type +"_"+sideName+"_Color";
                    var gradientIds = sideName+"_"+type+"_Gradients";
                    var gradientPrefix = sideName+"_"+type+"_";
                
                    var tempPath = "{{ minio_url('') }}" + pathLocation;
                    console.log(tempPath)
                    if(!document.getElementById(objectId))
                        return false;

                    if(templateFormat == 'png'){
                        var canvasName = "canvas_" + type + "_" + sideName;
                    }

                    if(templateFormat == 'svg'){
                        loadTemplate(tempPath, objectId, gradientIds, gradientPrefix);
                    }
                   
                    
                } 
            }

            function loadTemplate(tempPath, objectId, gradientIds, gradientPrefix){
                $.get(tempPath, null, function(data){
                    var svgNode = $("svg", data);
                    
                    var docNode = document.adoptNode(svgNode[0]);
                    // console.log(docNode);
                    $('#'+objectId).html(docNode);
                }, 'xml');
                
                setTimeout(function() {

                    var template_array = {!! json_encode($template_arrays) !!};
                    var TrimCount  = template_array[0]['Trim'];
                    var ListGradient = document.getElementById(gradientIds);
                   
                    $.ajax({ //create an ajax request to load_page.php

                        type: "POST",
                        url: "{{url('designer/a/gradient-append')}}",
                        data : {
                            gradientPrefix: gradientPrefix, 
                            TrimCount: TrimCount 
                        },
                        beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                        },
                        success: function(response) {
                            ListGradient.innerHTML = response;
                        }
                    });
                       
                }, 2000);
            }

            function loadPattern(svgpath, clipathval, svgpatternid, visualizerObject, TypeAndSide){
                $.get(svgpath, null, function(data){
                    var svgNode = $("svg", data);
                    var arrPath = [];
                    
                    var docNode = document.adoptNode(svgNode[0]);
                    // console.log(docNode);
                        for(var i = 0 ; i < docNode.querySelectorAll("path")['length'] ; i++){
                            j = i + 1;
                            k = "PatternColor" + j;

                            var pathPatterns = docNode.querySelectorAll("path")[i];
                        
                            // for setting clippath
                            var att = document.createAttribute("clip-path");      
                            att.value = clipathval;
                            pathPatterns.setAttributeNode(att);

                            // for set Pattern Id
                            var getPatternIdFromSVG = TypeAndSide +"_"+ pathPatterns.getAttributeNode('id').value
                            var att1 = document.createAttribute("id");      
                            att1.value = getPatternIdFromSVG;
                            pathPatterns.setAttributeNode(att1);

                            // for PatternColor
                            // var patterColor  = document.createAttribute("fill");      
                            // patterColor.value = getPatternColor[i][k];
                            // pathPatterns.setAttributeNode(patterColor);

                            var s = new XMLSerializer();	
                            var str = s.serializeToString(pathPatterns);
                            
                            arrPath.push(str);
                        }
                        
                        try{

                            var contents = JSON.stringify(arrPath);
                            var con = jQuery.parseJSON(contents);
                            
                            var countContents = con.length;
                            if(countContents != 0){ // check if content
                                var jContent = $.map(con, function(value) {
                                    return(value);
                                });
                                var patternHolder = document.getElementById(svgpatternid);
                                $(patternHolder).html(jContent.join(""));

                            }
                        }catch (e){
                            //no errpr
                        }
                    
                }, 'xml');
            }

            function templateColors(tc){
                $.ajax({ //create an ajax request to load_page.php
                    type: "POST",
                    url: "{{url('designer/a/get-template-default-colors')}}",
                    data : { 
                        templateCode : tc
                    },
                    // dataType: "JSON", //expect JSON to be returned
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response) {
                        // console.log(response.default_template_color_array);

                        // for (var [key, value] of Object.entries(response.default_template_color_array)) {
                            console.log(response.default_template_color_array);
                            response.default_template_color_array.forEach(function(value, key){
                                var colors_array = value;
                                console.log(colors_array);
                                if(key == 0){
                                    // console.log(colors_array['default_mainColor'])
                                    $("#mainColor").spectrum("set", colors_array['default_mainColor']);
                                }else{
                                    if(colors_array['h4_Trim_'+key] != null){
                                        $('#h4_Trim_'+key).html(colors_array['h4_Trim_'+key]);
                                    }else{
                                        $('#h4_Trim_'+key).html(colors_array['Trim '+ key]);
                                    }

                                }
                                // console.log(colors_array['h4_Trim_'+key])
                                // colors_array.forEach(function(v){
                                //     console.log(v, k);
                                // })
                                
                            });
                        // }
                        // var objColor = jQuery.parseJSON(response);
                        // for (var i = 0; i < objColor.length; i++){
                        // 	for (var key in objColor[i]) {
                        // 		if(key == "default_mainColor"){
                        // 			$("#mainColor").spectrum("set", objColor[i][key]);
                        // 		}else{
                                    
                        // 			$("input#Trim_"+key+".trimColor").spectrum("set", objColor[i][key]);
                        // 			colorPickerCustom();
                        // 		}
                        // 	}
                        // }
                    }
                    
                });
            }
            
            function activaTab(tab){
                $('.nav-tabs a[href="#' + tab + '"]').tab('show');
            };
            //END 1ST TAB <---####################################
            
            // FABRIC JS 
            var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
            for (var i = 0; i < SideAndPath.length; i++) {
                var sideName = SideAndPath[i]['Side'];
                var type = SideAndPath[i]['Type'];
                var pathLocation = SideAndPath[i]['Path'];
                var canvasName = "canvas_" + type + "_" + sideName;
                var tempPath = "{{ minio_url('') }}" + pathLocation;

                window['canvas_' + type + '_' + sideName] = new fabric.Canvas(canvasName);
                var templateFormat = SideAndPath[i]['TemplateFormat'];
                initCanvas(window['canvas_' + type + '_' + sideName]);
                if(templateFormat == 'png'){
                    window['canvas_' + type + '_' + sideName].setOverlayImage(tempPath, window['canvas_' + type + '_' + sideName].renderAll.bind(window['canvas_' + type + '_' + sideName]), {
                        width:  window['canvas_' + type + '_' + sideName].width,
                        height:  window['canvas_' + type + '_' + sideName].height
                     });
                }
            }

            /* ############################ */
            var canvas = window['canvas_' + SideAndPath[0]['Type'] + '_' + SideAndPath[0]['Side']]; //canvas_Jersey_Front;
            var canvasID = 'canvas_' + SideAndPath[0]['Type'] + '_' + SideAndPath[0]['Side'];
            /* ############################ */ 
            initCenteringGuidelines(canvas);
            initAligningGuidelines(canvas);
            canvas.selection = false;
            canvas.controlsAboveOverlay = true;

           
            // canvas.dispose();
            $('#side-controls a').click(function (e) {
                onDeSelected();
            });
                
            $("#uniform_sides li").click(function() {
                onDeSelected();
                canvas =  window[$(this).attr('data-canvas-id')];
                canvasID = $(this).attr('data-canvas-id');
                canvas.calcOffset();
                // initCanvas();
                // canvas.on('object:moving', function(options) {
                   
                    // console.log('asdasd')
                // });
                // canvas.on('selection:cleared', onDeSelected);
                // canvas.on('object:selected', onSelected);
                initCenteringGuidelines(canvas);
                initAligningGuidelines(canvas);
                
                canvas.selection = false;
                canvas.controlsAboveOverlay = true;
            });
            //trigger enter ######################################################################

			$(document).on('input keyup', '.rotateTextValue', function(e) {
				if (e.keyCode == 13) {
					var obj = canvas.getActiveObject();

					if(this.value <= 180 && this.value >= -180){

						if(obj){
							obj.setAngle(this.value);
						}
						$('.rotateTextSlider').val(this.value);
					}else{

						if(obj){
							obj.setAngle(0);
						}
						$('.rotateTextValue').val(0);
						$('.rotateTextSlider').val(0);
					}
					canvas.renderAll();
				}
			});
			
			$(document).on('input keyup', '.spacingTextValue', function(e) {
				if (e.keyCode == 13) {
					var obj = canvas.getActiveObject();

					if(this.value <= 100 && this.value >= -100){
						if(obj){
							obj.setCharSpacing(this.value * 2);
						}
						$('.spacingTextSlider').val(this.value);
					}else{

						if(obj){
							obj.setCharSpacing(0);
						}
						$('.spacingTextValue').val(0);
						$('.spacingTextSlider').val(0);


					}
					canvas.renderAll();
				}
			});
			
			$(document).on('input keyup', '.opacityTextValue', function(e) {
				if (e.keyCode == 13) {
					var obj = canvas.getActiveObject();

					if(this.value <= 10 && this.value >= 0){
						if(obj){
							obj.setOpacity(this.value / 10);
						}
						//console.log(this.value / 10);
						$('.opacityTextSlider').val(this.value);
					}else{

						if(obj){
							obj.setOpacity(10);
						}
						$('.opacityTextValue').val(10);
						$('.opacityTextSlider').val(10);
					}
					canvas.renderAll();
				}
			});

			$("#textInput").keypress(function (e) {
				if(e.which == 13 && !e.shiftKey) {
					$( "#okBtn" ).click();
					e.preventDefault();
					return false;
				}
			});

			$("#font_size").keypress(function (e) {
				if(e.which == 13 && !e.shiftKey) {
					// $( "#okBtn" ).click();
					e.preventDefault();
					return false;
				}
			});
			//End Trigger enter ######################################################################


            function initCanvas(canvas){
                canvas.on('selection:cleared', onDeSelected);
                canvas.on('object:selected', onSelected);
                // canvas.on('object:scaling', onScaling);
                // canvas.on('object:modified', onModified);
                var snapZone = 4;
                canvas.on('object:moving', function(options) {
                    // var objectMiddle = options.target.left + options.target.getWidth() / 2;
                    // if (objectMiddle > canvas.width / 2 - snapZone &&
                    //     objectMiddle < canvas.width / 2 + snapZone) {
                    //     options.target.set({
                    //     left: canvas.width / 2 - options.target.getWidth() / 2,
                    //     }).setCoords();
                    
                    //     // $("#"+canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").css({ "display" : "" });
                    //     document.getElementById(canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").setAttribute("display", "");

                    // }
                    // console.log('asdasd')
                });
                
                canvas.on('object:rotating', onRotating);

                var _isDragging = false;
                var _isMouseDown = false;

                canvas.on('mouse:down', function () {
                    _isMouseDown = true;
                    // other stuff
                });

                canvas.on('mouse:move', function () {
                    _isDragging = _isMouseDown;
                    // other stuff
                });

                canvas.on('mouse:up', function(element) {
                    
                    try{
                        document.getElementById(canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").setAttribute("display", "none");
                    }catch(e){

                    }
                    
                    
                    
                    _isMouseDown = false;
                    var isDragEnd = _isDragging;
                    _isDragging = false;
                    if (isDragEnd) {
                        try{
                            default_canvas_width = canvas.width;
                            default_canvas_height = canvas.height;

                            var obj = canvas.getActiveObject();
                            getWidth = obj.getWidth();
                            makeWidthToNegative = ~getWidth + 1;

                            getHeight = obj.getHeight();
                            makeHeightToNegative = ~getHeight + 1;

                            if(obj.left >=  default_canvas_width){
                                obj.setLeft(default_canvas_width - getWidth);
                                obj.setCoords()
                                canvas.renderAll();
                            }
                            if(obj.left <= makeWidthToNegative){
                                obj.setLeft(1);
                                obj.setCoords()
                                canvas.renderAll();	
                            }

                            if(obj.top >=  default_canvas_height){
                                obj.setTop(default_canvas_height - getHeight);
                                obj.setCoords()
                                canvas.renderAll();
                            }
                            
                            if(obj.top <= makeHeightToNegative){
                                obj.setTop(1);
                                obj.setCoords()
                                canvas.renderAll();
                            }
                        }catch(e){

                        }

                    } else {
                        // code for no drag mouse up
                    }
                    // code for both
                });

                canvas.on('object:scaling', function(event) {
                    if (event.target && event.target.type == "text") {
                        try{
                            var inFont = $('.btn-show-fonts').attr('data-font-size');
                            $(".text-font-size").val(((event.target.fontSize * event.target.scaleX) / inFont ).toFixed(2));
                            event.target._clearCache();
                            event.target.setCoords();
                            canvas.renderAll();
                        }catch(e){
                            // error
                        }
                    }
                });

                canvas.on('object:modified', function(event) {
                    if (event.target && event.target.type == "text") {
                        event.target.fontSize *= event.target.scaleX;
                        event.target.fontSize = event.target.fontSize.toFixed(2);
                        event.target.scaleX = 1;
                        event.target.scaleY = 1;
                        event.target._clearCache();
                        var inFont = $('.btn-show-fonts').attr('data-font-size');
                        $(".text-font-size").val(((event.target.fontSize * event.target.scaleX) / inFont ).toFixed(2));
                        event.target.setCoords();
                        canvas.renderAll();
                    }
                });
            }
            
            function addNewText(){
                onDeSelected();
            }

            function lockObject(){
                
                var obj = canvas.getActiveObject();
                obj.set({
                    'lockStatus' : true,
                    'lockMovementX': true,
                    'lockMovementY': true,
                    'lockScalingX': true,
                    'lockScalingY': true,
                    'lockRotation': true,

                });
                $('.btn-lock-object').html('<i class="fa fa-lock"></i>');
                $('.btn-lock-object').attr('title', 'Unlock');
                $('.btn-lock-object').addClass('active');
                $('.btn-lock-object').data('status', 'lock');
                
                canvas.renderAll();

            }
            
            function unLockObject(){
                
                var obj = canvas.getActiveObject();
                obj.set({
                    'lockStatus' : false,
                    'lockMovementX': false,
                    'lockMovementY': false,
                    'lockScalingX': false,
                    'lockScalingY': false,
                    'lockRotation': false,

                });

                $('.btn-lock-object').html('<i class="fa fa-unlock"></i>');
                $('.btn-lock-object').attr('title', 'Lock');
                $('.btn-lock-object').removeClass('active');
                $('.btn-lock-object').data('status', 'unlock');
                canvas.renderAll();

            }
		    function onSelected(){
                // console.log(canvas);
                try{
                    var obj = canvas.getActiveObject();
                    // console.log("Height =", (obj.getScaleY() * obj.getHeight()).toFixed(2));
                    // console.log("Width = ", (obj.getScaleX() * obj.getWidth()).toFixed(2));
                    $('.remove').attr("disabled", false);
                    var getLockStatus = canvas.getActiveObject().get('lockStatus');
                    // console.log(getLockStatus);
                    $('.btn-lock-object').attr("disabled", false);
                    if(getLockStatus == true){
                        $('.btn-lock-object').html('<i class="fa fa-lock"></i>');
                        $('.btn-lock-object').attr('title', 'Unlock');
                        $('.btn-lock-object').addClass('active');
                        $('.btn-lock-object').data('status', 'lock');
                    }else{
                        $('.btn-lock-object').html('<i class="fa fa-unlock"></i>');
                        $('.btn-lock-object').attr('title', 'Lock');
                        $('.btn-lock-object').data('status', 'unlock');
                        // $('.btn-lock-object').addClass('active');
                    }
                    // console.log('left-', obj.left, 'top-', obj.top);
                    // console.log('font-', obj.fontSize);

                    if(obj != null){
                        
                        var objType = canvas.getActiveObject().get('type');
                        var id = canvas.getActiveObject().get('idNumber');
                        // console.log(obj.type);

                        if(objType == "curvedText"){
                            if(obj.effect == "curved"){
                                $('#teamname_text_shape').html('Text Shape: <br><img src="{{ minio_url('text-shapes-logo/curve-logo.png') }}" height="30px">');
                            }else if(obj.effect == "arc"){
                                $('#teamname_text_shape').html('Text Shape: <br><img src="{{ minio_url('text-shapes-logo/arch-logo.png') }}" height="30px">');
                            }else{
                                $('#teamname_text_shape').html('Add text Shape');
                            }
                        }else{
                            $('#teamname_text_shape').html('Add text Shape');
                        }

                        if(objType == "i-text" || objType == "curvedText" || objType == "text"){

                            if(id){
                                $("#numberProperties").css({ "display" : "block" });
                                $('#tab-add-number1').tab('show');

                                $("#addNumberId").css({ "display" : "block" });
                                $("#enterNumberId").css({ "display" : "none" });

                                $('#editedNumberInput').val(obj.getText());
                            }else{

                                $("#textProperties").css({ "display" : "block" });
                                $('#tab-add-text1').tab('show');

                                $("#addNewTextId").css({ "display" : "block" });
                                $("#enterTextId").css({ "display" : "none" });

                                $('#editedTextInput').val(obj.getText());
                            }

                            var fontprop = getFontDisplay(obj.fontFamily);
                            console.log(fontprop)
                            $('.btn-show-fonts').html(fontprop.fontNameDisplay);
                            $('.btn-show-fonts').css('font-family', obj.fontFamily);
                            $('.btn-show-fonts').attr('data-font-size', fontprop.additionalSize);
                            $(".text-font-size").val((obj.fontSize / $(".btn-show-fonts").attr('data-font-size')).toFixed(2));

                            // $('#reverse').prop('checked', obj.get('reverse'));
                            // $('#radius').val(obj.get('radius'));
                            // $('#spacing').val(obj.get('spacing'));
                            //$('#fill').val(obj.getFill());
                            //$('#effect').val(obj.getEffect());

                            $(".fontColor").spectrum("set", obj.getFill());
                            $(".strokeColor").spectrum("set", obj.getStroke());
                            $(".outlineThickness").val(obj.getStrokeWidth());
                            $('#font_size').val(obj.getFontSize() + " in");
                            $('.rotateTextSlider, .rotateTextValue').val(Math.round(obj.getAngle()));
                            $('.spacingTextSlider, .spacingTextValue').val(obj.getCharSpacing() / 2);
                            $('.opacityTextSlider, .opacityTextValue').val(obj.getOpacity() * 10);

                            /* if($('#strokeColor').val() == ""){
                                console.log("null");
                            }else{
                            console.log($('#strokeColor').val());
                            } */
                        }

                        if(objType == "image"){
                            $('#tab-upload-image1').tab('show');
                            $('.rotateTextSlider, .rotateTextValue').val(Math.round(obj.getAngle()));
                            $('.opacityTextSlider, .opacityTextValue').val(obj.getOpacity() * 10);

                            $("#img-remove-btn").css({ "display" : "block" });
                            $("#image-properties").css({ "display" : "block" });
                        }

                        if(objType == "path-group"){
                            
                            $('.clipartColor').blur();
                            var obj = "";
                            var arrayPathId = [];
                            var k = 0;
                            
                            $('#tab-clipart1').tab('show');
                            obj = canvas.getActiveObject();
                            $('#clipartProperties').html('');
                            var randomNumbers = Math.random();
                            for (var j in obj.paths) {
                                k = k + 1;
                                var id = obj.paths[j].get('id');
                                var fill = obj.paths[j].get('fill');
                                // console.log(id);
                                arrayPathId.push({
                                    'id' : id,
                                    'fill' : fill,
                                    'ran_num' : randomNumbers
                                });
                            }
                            
                            setTimeout(function() {
                                // event.preventDefault();
                                getClipartProperties(arrayPathId, randomNumbers); 
                            }, 500);
                            
                            setTimeout(function() {
                                $('.rotateTextSlider, .rotateTextValue').val(Math.round(obj.getAngle()));
                                $('.opacityTextSlider, .opacityTextValue').val(obj.getOpacity() * 10);
                            }, 1000);
                            
                            return false;
                        }

                        try{
                            document.getElementById(canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").setAttribute("display", "");
                        }catch(e){

                        }
                    
                    }
                }catch(e){

                }
               
            }

            function onDeSelected(){
                var obj = canvas.getActiveObject();
                $('.remove').attr("disabled", true);
                
                $('.btn-lock-object').attr("disabled", true);
                $('.btn-lock-object').html('<i class="fa fa-unlock-alt"></i>');
                $('.btn-lock-object').attr('title', 'Lock');
                $('.btn-lock-object').removeClass('active');
                $('.btn-lock-object').data('status', 'unlock');

                $("#textProperties").css({ "display" : "none" });
                $("#addNewTextId").css({ "display" : "none" });
                $("#enterTextId").css({ "display" : "block" })
                $("#textShapeProperties").css({ "display" : "none" })

                /* $("#numberProperties").css({ "display" : "none" });
                $("#addNumberId").css({ "display" : "none" });
                $("#enterNumberId").css({ "display" : "block" }) */


                $("#btnNumber").attr('disabled', false);
                $("#btnNumber").html('<i class="fa fa-2 fa-plus" aria-hidden="true"></i> Add Name and Number');

                $("#img-remove-btn").css({ "display" : "none" });
                $("#image-properties").css({ "display" : "none" });

                $("#okBtn").html("OK");
                $("#okBtn").attr('disabled', false);

                $('#textInput').val('');
                $('#numberInput').val('');
                
                loadClipartContent();

                canvas.discardActiveObject();
                canvas.renderAll();

                try{
                    document.getElementById(canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").setAttribute("display", "none");
                }catch(e){

                }

            }

            function onRotating(){
                var obj = canvas.getActiveObject();
                /* obj.getAngle().toFixed(0);
                canvas.renderAll(); */
                var angleValue = obj.getAngle().toFixed(0);
                if(angleValue > 180){
                    angleValue = 180 - angleValue;
                }
                $('.rotateTextValue, .rotateTextSlider').val(angleValue);

            }

            // arrow keys navigations
			var processKeys = function (evt) {
				evt = evt || window.event;

				var movementDelta = 1;

				var activeObject = canvas.getActiveObject();
				var activeGroup = canvas.getActiveGroup();

				if (evt.keyCode === 37) {
					evt.preventDefault(); // Prevent the default action
					if (activeObject) {
						var a = activeObject.get('left') - movementDelta;
						activeObject.set('left', a);
					}
					else if (activeGroup) {
						var a = activeGroup.get('left') - movementDelta;
						activeGroup.set('left', a);
					}

				} else if (evt.keyCode === 39) {
					evt.preventDefault(); // Prevent the default action
					if (activeObject) {
						var a = activeObject.get('left') + movementDelta;
						activeObject.set('left', a);
					}
					else if (activeGroup) {
						var a = activeGroup.get('left') + movementDelta;
						activeGroup.set('left', a);
					}

				} else if (evt.keyCode === 38) {
					evt.preventDefault(); // Prevent the default action
					if (activeObject) {
						var a = activeObject.get('top') - movementDelta;
						activeObject.set('top', a);
					}
					else if (activeGroup) {
						var a = activeGroup.get('top') - movementDelta;
						activeGroup.set('top', a);
					}

				} else if (evt.keyCode === 40) {
					evt.preventDefault(); // Prevent the default action
					if (activeObject) {
						var a = activeObject.get('top') + movementDelta;
						activeObject.set('top', a);
					}
					else if (activeGroup) {
						var a = activeGroup.get('top') + movementDelta;
						activeGroup.set('top', a);
					}
				}

				if (activeObject) {
					activeObject.setCoords();
					canvas.renderAll();
				} else if (activeGroup) {
					activeGroup.setCoords();
					canvas.renderAll();
                }
                
                try{
                    document.getElementById(canvasID.split("_")[2] + "_" +canvasID.split("_")[1] + "_Border").setAttribute("display", "");
                }catch(e){

                }
                
			};
            
			window.addEventListener("keydown", processKeys, false);
             // end arrow keys navigations

            // window.addEventListener("mousemove", myFunction, false);


            // function myFunction(){
            //     console.log('asda')
            // }

            //remove object
            $(document).on('button click', '.remove', function() {
                var object = canvas.getActiveObject();
                if (!object){
                    alert('Please select the element to remove');
                    return '';
                }
                canvas.remove(object);
            });

            $(document).on('button click', '.copyObject', function(event){
				event.preventDefault();
                var copyData = canvas.getActiveObject().toObject(['id']);
                
				fabric.util.enlivenObjects([copyData], function(objects) {
					objects.forEach(function(o) {
						o.set({
							top: o.top + 10,
							left: o.left + 10,
							borderColor: '#71b7f3',
							cornerColor: '#71b7f3',
							cornerSize: 10,
							transparentCorners: false
						});
						canvas.add(o);
						canvas.setActiveObject(o);
					});
					canvas.renderAll();
				});
			});

            function numberStandardPos(){
                var obj = canvas.getActiveObject();

                var id = canvas.getActiveObject().get('idNumber');

                if(id == "NumberFront"){
                    obj.set({
                        top: 114.85 // default position for number
                    });
                }else if(id == "NumberBack"){
                    obj.set({
                        top: 175.00 // default position for number
                    });
                }else if(id == "LastNameBack"){
                    obj.set({
                        top: 50.28 // default position for number
                    });
                }else if(id == "NumberLeftShorts"){
                    obj.set({
                        top: 278.35 // default position for number
                    });
                }else if(id == "NumberRightShorts"){
                    obj.set({
                        top:  278.35, // default position for number
                    });
                }
                

                obj.centerH();
                obj.setCoords();
                canvas.renderAll();
            }

            function centerHor(){
                var obj = canvas.getActiveObject();
                obj.centerH();
                obj.setCoords();
                canvas.renderAll();
            }

            function centerVer(){
                var obj = canvas.getActiveObject();
                obj.centerV();
                obj.setCoords();
                canvas.renderAll();
            }

            //DROP DOWN STROKE
            $(document).on('select change', '.outlineThickness', function() {
                var strokeId = $(this).attr('data-outline');

                //$('#fontSizeValue').val($(this).val());
                var obj = canvas.getActiveObject();
                if(obj){

                    if($('#'+strokeId).val() == ""){
                        alert("Choose outline color first.");
                        //$('strokeColor').focus();
                        $('.outlineThickness').val(0);
                        //return false;
                    }else{
                        if($(this).val() == 0){
                            obj.setStrokeWidth($(this).val());
                            obj.setStroke(null);
                        }else{
                            obj.setStrokeWidth($(this).val());
                        }
                        
                    }

                }
                canvas.renderAll();
            });

            /// GRADIENT SLIDER
            $(document).on('input change', '.offsetGradientColor', function() {
                
                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                var templateType = "{{ $template->Type }}";
                // console.log(templateType);
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];

                    var objectId = "objSVG_" + type + "_" + sideName;

                    try {
                        if(templateType == "Shirts" && (sideName == "Right" || sideName == "Left")) {
                            document.getElementById(sideName + "_" + type +"_" + $(this).attr('data-gradient-id')).setAttribute("offset", ($(this).val() * 10) - 40 + "%");
                        }else{
                            document.getElementById(sideName + "_" + type +"_" + $(this).attr('data-gradient-id')).setAttribute("offset", $(this).val() * 10 + "%");
                        }
                        
                    }
                    catch (e) {
                    //console.log(e);
                    }
                }
            });
            
            // OFFSETE GRADIENT PATTERN SLIDER
            $(document).on('input change', '.offsetGradientPattern', function(){

                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];

                    var mainColorId = type + "_" + sideName + "_" + "Color";

                    var objectId = "objSVG_" + type + "_" + sideName;

                    try {
                        document.getElementById(sideName + "_" + type +"_" + $(this).attr('data-gradient-id')).setAttribute("offset", $(this).val() * 10 + "%");
                    }
                    catch (e) {
                    //console.log(e);
                    }
                }
            });

            //PATTERN OPACITY SLIDER
            $(document).on('input change', '#opacityPattern', function(){
                //console.log($(this).val() * 1);

                var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                for (var i = 0; i < SideAndPath.length; i++) {
                    var sideName = SideAndPath[i]['Side'];
                    var type = SideAndPath[i]['Type'];


                    var mainColorId = type + "_" + sideName + "_" + "Color";

                    var objectId = "objSVG_" + type + "_" + sideName;

                    try {
                    document.getElementById(objectId).contentDocument.getElementById("patternColor1").setAttribute("opacity", $(this).val() / 10);

                    $('#opacityPatternValue').val($(this).val() * 1);
                    }
                    catch (e) {
                    //console.log(e);
                    }
                }
            });

            //OPACITY SLIDER
            $(document).on('input change', '.opacityTextSlider', function(){
                //console.log($(this).val() / 10);
                $('.opacityTextValue').val($(this).val());
                var obj = canvas.getActiveObject();
                if(obj){
                    obj.set({
                        opacity: $(this).val() / 10
                    });
                }
                canvas.renderAll();
            });
            
            //SPACING SLIDER
            $(document).on('input change', '.spacingTextSlider', function() {
                //console.log($(this).val());
                $('.spacingTextValue').val($(this).val());
                var obj = canvas.getActiveObject();
                if(obj){
                    
                        if(obj.type == "text"){
                            obj.set({
                                charSpacing: $(this).val() * 2
                            });
                        }else{
                            obj.set({
                                spacing: $(this).val() * 2
                            });
                        }
                        
                }
                canvas.renderAll();
            });

            //RADIUS SLIDER
            $(document).on('input change', '.radiusSlider', function() {
                $('.radiusTextValue').val($(this).val());
                var obj = canvas.getActiveObject();
                if(obj){
                    obj.set({
                        radius: $(this).val()
                    });
                }
                canvas.renderAll();
            });

            //ROTATE SLIDER
            $(document).on('input change', '.rotateTextSlider', function() {
                //console.log($(this).val());
                $('.rotateTextValue').val($(this).val());
                var obj = canvas.getActiveObject();
                if(obj){
                    obj.setAngle($(this).val());
                }
                canvas.renderAll();
            });

            $('.text-font-size').keyup(function() {
                var inFont =  $('.btn-show-fonts').attr('data-font-size');
                var val = $(this).val() * inFont;
                if (isNaN(val)) {
                    alert('please enter number');
                    $(this).val(20);
                    return false;
                }
                var activeObject = canvas.getActiveObject();
                activeObject.fontSize = val;
                activeObject._clearCache();
                activeObject.setCoords();
                canvas.renderAll();
            });

            $('#editedTextInput').keyup(function(){
                var obj = canvas.getActiveObject();
                if(obj){
                    obj.setText(this.value);
                    canvas.renderAll();
                }
            });

            $('#editedNumberInput').keyup(function(){
                var obj = canvas.getActiveObject();
                if(obj){
                    obj.setText(this.value);
                    canvas.renderAll();
                }
            });

            // front back function //
            $(document).on('button click', '.sendSelectedObjectBack', function(){

                var object = canvas.getActiveObject();
                if (!object){

                    alert('Please select object.');
                    return
                }
                canvas.sendToBack(object);
                object.setCoords();
                canvas.renderAll();

            });

            $(document).on('button click', '.sendSelectedObjectToFront', function(){

                var object = canvas.getActiveObject();
                if (!object){
                    alert('Please select object.');
                    return '';
                }
                canvas.bringToFront(object);
                object.setCoords();
                canvas.renderAll();

            });
            //END FABRIC JS <---####################################
            
            // 2ND TABS <---####################################
            function addText() {
                var userTextInput = $('#textInput').val();

                if(userTextInput == "" || userTextInput == null){
                    $('#textInput').focus();
                    return false;

                }

                var oText = new fabric.Text(userTextInput, {
                    top: 94.35 , // 94.35 for the default
                    fontSize: 71.25, // 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    //fontFamily: 'Academic M54',
                    textAlign: 'center',
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true,
                    objectCaching : false
                });

                // var div_textProperties = document.getElementById('wait-msg-jfront');
                //     div_textProperties.style.display = 'block';

                $("#okBtn").html("Please Wait");
                $("#okBtn").attr('disabled', true);
                canvas.centerObject(oText);
                canvas.add(oText);
                setTimeout(function() {
                    //canvas.add(oText);
                    canvas.setActiveObject(oText);
                    oText.bringToFront();
                    oText.setCoords();

                    //var div_textProperties = document.getElementById('wait-msg-jfront');
                        // div_textProperties.style.display = 'none';
                    canvas.renderAll();
                }, 1000);

            }

            function getFontDisplay(ff){
                var data;
                $.ajax({    //create an ajax request to load_page.php
                    type: "POST",
                    url :  "{{url('designer/a/get-font-display')}}",
                    data : {
                        fontFamily : ff
                    },
                    async: false,
                    dataType : 'json',
                    cache: true,
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                        xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response){
                        data = response;
                    }
                    
                });

                return data;
            }

            $(document).on('button click', '.btn-show-fonts', function() {
				var obj = canvas.getActiveObject();
				$('.add-text-content').html(obj.getText());
				$('#fontsModal').modal('show'); 
			});
            
            $(document).on('button click', '.custom-font-td', function() {
				
				$('.btn-show-fonts').css('font-family', $(this).attr('data-font-style'));
				$('.btn-show-fonts').html($(this).attr('data-font-display'));
				$('.btn-show-fonts').attr('data-font-style', $(this).attr('data-font-style'));
				$('.btn-show-fonts').attr('data-font-size',  $(this).attr('data-font-size'));
				var data_font_size = $(this).attr('data-font-size');
				// var current_font = $('.text-font-size').val();
				
				var obj = canvas.getActiveObject();
				
				if(obj){
					obj.set({
							fontFamily: $(this).attr('data-font-style')
						});

					default_text = obj.getText();
					props = obj.toObject(['idNumber']);
					delete props['type'];
					props['borderColor'] =  '#71b7f3',
					props['cornerColor'] =  '#71b7f3',
					props['cornerSize'] =  10,
					props['transparentCorners'] = false,
					props['centeredScaling'] =  true,
					props['hasControls'] =  true,
					props['lockScalingFlip'] =  true,
					props['lockUniScaling'] =  true,
					props['objectCaching'] =  false
					
					setTimeout(function() {
						obj.setCoords();
						canvas.renderAll();
						canvas.setActiveObject(obj);
						
					}, 1000);
						// return false;
				}
				$('#fontsModal').modal('hide'); 
			});
            //END 2ND TAB <---####################################

            // 3RD TAB
            
            function addFrontNumber(){
               
                var defaultNumber  = "00";
                var currentCount = +$("#countbtn").val() + 1;
                $('#countbtn').val(currentCount);
                var defNumberFront = new fabric.Text(defaultNumber, {
                    idNumber:"NumberFront",
                    top: 114.85 , // 94.35 for the default
                    fontSize: 75.00, // 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                activaTab('a_Front_Jersey');
                canvas = canvas_Jersey_Front;
                canvasID = "canvas_Jersey_Front";

                setTimeout(function() {
                    canvas.add(defNumberFront);
                    canvas.setActiveObject(defNumberFront);

                    defNumberFront.bringToFront();
                    defNumberFront.centerH();
                    defNumberFront.setCoords();
                    $('#addFrontNumber').remove();
                }, 1000);
                canvas.renderAll();
            }

            function addBackNumber(){

                var defaultNumber  = "00";
                var currentCount = +$("#countbtn").val() + 1;
                $('#countbtn').val(currentCount);

                var defNumberBack = new fabric.Text(defaultNumber, {
                    idNumber:"NumberBack",
                    top: 84.35, // 94.35 for the default
                    fontSize: 175.00,
                    fill: '#000000',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                activaTab('a_Back_Jersey');
                canvas = canvas_Jersey_Back;
                canvasID = "canvas_Jersey_Back";

                setTimeout(function() {
                    canvas.add(defNumberBack);
                    canvas.setActiveObject(defNumberBack);

                    defNumberBack.bringToFront();
                    defNumberBack.centerH();
                    defNumberBack.setCoords();
                    $('#addBackNumber').remove();
                }, 1000);
                canvas.renderAll();

            }

            function addLastName(){

                var defaultName = "PLAYER";
                var currentCount = +$("#countbtn").val() + 1;
                $('#countbtn').val(currentCount);

                var defNameBack = new fabric.Text(defaultName, {
                    idNumber:"LastNameBack",
                    top: 50.28 , // 94.35 for the default
                    fontSize: 32.50,// 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                activaTab('a_Back_Jersey');
                canvas = canvas_Jersey_Back;
                canvasID = "canvas_Jersey_Back";

                setTimeout(function() {
                    canvas.add(defNameBack);
                    canvas.setActiveObject(defNameBack);

                    defNameBack.bringToFront();
                    defNameBack.centerH();
                    defNameBack.setCoords();
                    $('#addLastName').remove();


                }, 1000);
                canvas.renderAll();

            }

            function addShortsNumberLeft(){

                var defaultNumber  = "00";
                var currentCount = +$("#countbtn").val() + 1;
                $('#countbtn').val(currentCount);

                var defNameShortLeft = new fabric.Text(defaultNumber, {
                    idNumber:"NumberLeftShorts",
                    top: 278.35,
                    fontSize: 62.50,
                    fill: '#000000',
                    textAlign: 'center',
                    padding: 0,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                activaTab('a_Left_Shorts');
                canvas = canvas_Shorts_Left;
                canvasID = "canvas_Shorts_Left";

                setTimeout(function() {
                    canvas.add(defNameShortLeft);
                    canvas.setActiveObject(defNameShortLeft);

                    defNameShortLeft.bringToFront();
                    defNameShortLeft.centerH();
                    defNameShortLeft.setCoords();
                    $('#addShortsNumberLeft').remove();


                }, 1000);
                canvas.renderAll();
            }

            function addShortsNumberRight(){

                var defaultNumber  = "00";
                var currentCount = +$("#countbtn").val() + 1;
                $('#countbtn').val(currentCount);

                var defNameShortRight = new fabric.Text(defaultNumber, {
                    idNumber:"NumberRightShorts",
                    top: 278.35,
                    fontSize: 62.50,
                    fill: '#000000',
                    textAlign: 'center',
                    padding: 0,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                activaTab('a_Right_Shorts');
                canvas = canvas_Shorts_Right;
                canvasID = "canvas_Shorts_Right";

                setTimeout(function() {
                    canvas.add(defNameShortRight);
                    canvas.setActiveObject(defNameShortRight);

                    defNameShortRight.bringToFront();
                    defNameShortRight.centerH();
                    defNameShortRight.setCoords();
                    $('#addShortsNumberRight').remove();

                }, 1000);
                canvas.renderAll();

            }
            
            function addNameNumber() {
                var defaultNumber  = "00";
                var defaultName = "PLAYER";

                $('#countbtn').val("5");
                $('#NameNumberId').html('');

                var defNumberFront = new fabric.Text(defaultNumber, {
                    idNumber:"NumberFront",
                    top: 114.85 , // 94.35 for the default
                    fontSize: 75.00, // 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    fontFamily: 'Athletic Regular',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                var defNumberBack = new fabric.Text(defaultNumber, {
                    idNumber:"NumberBack",
                    top: 84.35, // 94.35 for the default
                    fontSize: 175.00, // 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    fontFamily: 'Athletic Regular',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                var defNameBack = new fabric.Text(defaultName, {
                    idNumber:"LastNameBack",
                    top: 50.28 , // 94.35 for the default
                    fontSize: 32.50, // 71.25 for default font size. equivalent 2.5"
                    fill: '#000000',
                    fontFamily: 'Athletic Regular',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                var defNameShortLeft = new fabric.Text(defaultNumber, {
                    idNumber:"NumberLeftShorts",
                    top: 235.35,
                    fontSize: 62.50, // 71.25 for default font size. equivalent 2.5"
                    //height:  fabric.util.parseUnit('1in'),
                    fill: '#000000',
                    fontFamily: 'Athletic Regular',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                 var defNameShortRight = new fabric.Text(defaultNumber, {
                    idNumber:"NumberRightShorts",
                    top: 235.35,
                    fontSize: 62.50, // 71.25 for default font size. equivalent 2.5"
                    //height:  fabric.util.parseUnit('1in'),
                    fill: '#000000',
                    textAlign: 'center',
                    fontFamily: 'Athletic Regular',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                // $("#btnNumber").html("Please Wait");
                $("#btnNumber").attr('disabled', true);
                activaTab('a_Front_Jersey');
                canvas = canvas_Jersey_Front;
                canvasID = "canvas_Jersey_Front";

                setTimeout(function() {
                    canvas_Jersey_Front.add(defNumberFront);
                    canvas_Jersey_Front.setActiveObject(defNumberFront);
                    canvas_Jersey_Back.add(defNumberBack, defNameBack);
                    canvas_Shorts_Right.add(defNameShortRight);
                    canvas_Shorts_Left.add(defNameShortLeft);

                    /// FRONT JERSEY
                    defNumberFront.bringToFront();
                    defNumberFront.centerH();
                    defNumberFront.setCoords();

                    /// BACK JERSEY
                    defNumberBack.bringToFront();
                    defNumberBack.centerH();
                    defNumberBack.setCoords();

                    defNameBack.bringToFront();
                    defNameBack.centerH();
                    defNameBack.setCoords();

                    /// LEFT SHORTS
                    defNameShortLeft.bringToFront();
                    defNameShortLeft.centerH();
                    defNameShortLeft.setCoords();

                    /// RIGHT SHORTS
                    defNameShortRight.bringToFront();
                    defNameShortRight.centerH();
                    defNameShortRight.setCoords();


                }, 1000);
                canvas_Jersey_Front.renderAll();
                canvas_Jersey_Back.renderAll();
                canvas_Shorts_Right.renderAll();
                canvas_Shorts_Left.renderAll();
            }

            function addDefaultTeamText() {
                var defaultName = "TEAM";
                var defTeamName = new fabric.Text(defaultName, {
                    top: 58.35,
                    fontSize: 50.00, // 71.25 for default font size. equivalent 2.5"
                    //height:  fabric.util.parseUnit('1in'),
                    fill: '#000000',
                    fontFamily: 'Athletic Regular',
                    textAlign: 'center',
                    padding: 0,
                    //spacing: 20,
                    stroke: null,
                    strokeWidth: 0,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    //hasRotatingPoint: false,
                    centeredScaling: true,
                    hasControls: true,
                    lockScalingFlip: true,
                    lockUniScaling: true
                });

                canvas = canvas_Jersey_Front;
                canvasID = "canvas_Jersey_Front";

                setTimeout(function() {
                    canvas_Jersey_Front.add(defTeamName);
                    /// FRONT JERSEY
                    defTeamName.bringToFront();
                    defTeamName.centerH();
                    defTeamName.setCoords();
                    // canvas_Jersey_Front.discardActiveObject();
                    // activaTab('tab-change-color');
                }, 1000);
                
                canvas_Jersey_Front.renderAll();
            }

            function submitLoginForm (){
                // method="POST" action="{{ url('/auth/login') }}"
                var data = $("#frm-login").serialize();
                // console.log(data)
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('/custom/auth') }}",
                    data : data,
                    dataType : 'json',
                    beforeSend: function() { 
                        $("#login-response-msg").fadeOut();
                        $("#btn-login").html('Signing in &nbsp; <i class="fa fa-spinner fa-spin"></i>');
                    },
                    success :  function(response){ 
                        $("#login-response-msg").html("");
                        $("#login-response-msg").fadeIn(1000, function(){
                            
                            if(response.success){

                                $(".navbar-holder").html(response.navbar);
                                $(".btn-save-design").html(response.save_design_button);
                               
                                setTimeout(function() {
                                    $('#modalLogin').modal('hide');
                                    $('#modalDesignName').modal('show');
                                }, 500);
                                
                            }else{
                                $("#login-response-msg").html(response.message);
                            }
                            //

                            // console.log(response.success);
                            $("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign In');
                        });
                    }
                });
                return false;
            }/* login submit */

            $('.removeNameNumber').click(function(){
                var obj = canvas.getActiveObject();
                if (!obj){
                    alert('Please select the element to remove');
                    return '';
                }

                var id = canvas.getActiveObject().get('idNumber');

                if(id == "NumberFront"){
                    $('#NameNumberId').append('<button type="button" id="addFrontNumber" onclick="addFrontNumber();" class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Front Number</button>');
                    canvas.remove(obj);
                    var currentCount = $('#countbtn').val();
                    $('#countbtn').val(currentCount - 1)
                }else if(id == "NumberBack"){
                    $('#NameNumberId').append('<button type="button" id="addBackNumber" onclick="addBackNumber();" class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Back Number</button>');
                    canvas.remove(obj);
                    var currentCount = $('#countbtn').val();
                    $('#countbtn').val(currentCount - 1)
                }else if(id == "LastNameBack"){
                    $('#NameNumberId').append('<button type="button" id="addLastName"  onclick="addLastName();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Lastname</button>');
                    canvas.remove(obj);
                    var currentCount = $('#countbtn').val();
                    $('#countbtn').val(currentCount - 1)
                }else if(id == "NumberLeftShorts"){
                    $('#NameNumberId').append('<button type="button" id="addShortsNumberLeft"  onclick="addShortsNumberLeft();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Left Shorts Number</button>');
                    canvas.remove(obj);
                    var currentCount = $('#countbtn').val();
                    $('#countbtn').val(currentCount - 1)
                }else if(id == "NumberRightShorts"){
                    $('#NameNumberId').append('<button type="button" id="addShortsNumberRight"  onclick="addShortsNumberRight();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Right Shorts Number</button>');
                    canvas.remove(obj);
                    var currentCount = $('#countbtn').val();
                    $('#countbtn').val(currentCount - 1)
                }

                var currentCount = $('#countbtn').val();

                if(currentCount == 0){
                    $("#numberProperties").css({ "display" : "none" });
                    $("#addNumberId").css({ "display" : "none" });
                    $("#enterNumberId").css({ "display" : "block" })
                }
            });

            document.onkeydown = function(e) {
                if (46 === e.keyCode) {
                // 46 is Delete key
                // do stuff to delete selected elements
                    var object = canvas.getActiveObject();
                    if (!object){
                        alert('Please select the element to remove');
                        return '';
                    }
                    
                    var id = canvas.getActiveObject().get('idNumber');

                    if(id == "NumberFront"){
                        $('#NameNumberId').append('<button type="button" id="addFrontNumber" onclick="addFrontNumber();" class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Front Number</button>');
                        canvas.remove(obj);
                        var currentCount = $('#countbtn').val();
                        $('#countbtn').val(currentCount - 1)
                    }else if(id == "NumberBack"){
                        $('#NameNumberId').append('<button type="button" id="addBackNumber" onclick="addBackNumber();" class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Back Number</button>');
                        canvas.remove(obj);
                        var currentCount = $('#countbtn').val();
                        $('#countbtn').val(currentCount - 1)
                    }else if(id == "LastNameBack"){
                        $('#NameNumberId').append('<button type="button" id="addLastName"  onclick="addLastName();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Lastname</button>');
                        canvas.remove(obj);
                        var currentCount = $('#countbtn').val();
                        $('#countbtn').val(currentCount - 1)
                    }else if(id == "NumberLeftShorts"){
                        $('#NameNumberId').append('<button type="button" id="addShortsNumberLeft"  onclick="addShortsNumberLeft();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Left Shorts Number</button>');
                        canvas.remove(obj);
                        var currentCount = $('#countbtn').val();
                        $('#countbtn').val(currentCount - 1)
                    }else if(id == "NumberRightShorts"){
                        $('#NameNumberId').append('<button type="button" id="addShortsNumberRight"  onclick="addShortsNumberRight();"  class="btn btn-primary pull-right btn-sm addMarginLeft"><i class="fa fa-plus" aria-hidden="true"></i> Right Shorts Number</button>');
                        canvas.remove(obj);
                        var currentCount = $('#countbtn').val();
                        $('#countbtn').val(currentCount - 1)
                    }else{
                        canvas.remove(object);
                    }

                    var currentCount = $('#countbtn').val();

                    if(currentCount == 0){
                        $("#numberProperties").css({ "display" : "none" });
                        $("#addNumberId").css({ "display" : "none" });
                        $("#enterNumberId").css({ "display" : "block" })
                    }
                }
            }
            // END 3RD TAB
            
            // 4TH TAB
            function loadClipartContent(){
                $.ajax({ //create an ajax request to load_page.php
                    type: "GET",
                    url: "{{url('designer/a/tab-clipart-content')}}",
                    dataType: "html", //expect html to be returned
                    success: function(response) {
                        // console.log(response);
                        $('#tab-clipart-content').html('');
                        
                        $('#tab-clipart-content').html(response);
                        $(".clipartColor").blur();
                        
                        // getFeaturedCliparts();
                    }
                });
            }

            $(document).on('a click', '.clipart-category', function(){
				getCliparts($(this).attr('data-id'), $(this).attr('data-type'), $(this).attr('data-title'));
				return false;
			});

            function getCliparts(categoryId, req_type, cat_name){
                $.ajax({ //create an ajax request to load_page.php

                    type: "POST",
                    url: "{{url('designer/a/get-cliparts')}}",
                    data: {
                        'categoryId' : categoryId,
                        'req_type' : req_type,
                        'cat_name' : cat_name
                    },
                    dataType: "html", //expect html to be returned
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response) {
                        $('#show-clipart-content').html(response).hide().fadeIn('slow');
                    }
                });
            }

            $(document).on('button click', '#btn-close-clipart-properties', function(){
				loadClipartContent();
				onDeSelected();
			});

            $(document).on('a click', '.img-clipart', function() {
				
				var getClipartLink = $(this).attr('data-link');
				// alert($(this).attr('data-link'));
				loadSVGClipart(getClipartLink);
				return false;
			});

            function loadSVGClipart(dataUrl){
                var k = 0;
                var arrayPathId = [];
                var svgUrl = "{{ minio_url('cliparts/') }}" + dataUrl;
                fabric.loadSVGFromURL(svgUrl, function(objects, options) {
                var clipart = fabric.util.groupSVGElements(objects, options );
                clipart.set({
                    svgPath: svgUrl,
                    width: clipart.width,
                    height: clipart.height,
                    borderColor: '#71b7f3',
                    cornerColor: '#71b7f3',
                    cornerSize: 10,
                    transparentCorners: false,
                    noScaleCache: false
                    //hasRotatingPoint: false,
                // });
                }).scaleToWidth(100);
                    canvas.centerObject(clipart);
                    canvas.add(clipart);
                    canvas.setActiveObject(clipart);
                    canvas.renderAll();
                    var obj = canvas.getActiveObject();
                    $('#clipartProperties').html('');
                    for (var j in obj.paths) {
                        k = k + 1;
                        var id = obj.paths[j].get('id');
                        var fill = obj.paths[j].get('fill');
                        arrayPathId.push({
                            'id' : id,
                            'fill' : fill
                        });
                        
                    }
                    // getClipartProperties(arrayPathId); 
                });
            }

            function getClipartProperties(arrayPathId, randomNumbers) {
                // console.log(arrayPathId);
                $.ajax({ //create an ajax request to load_page.php

                    type: "POST",
                    url: "{{ url('designer/a/clipart-properties') }}",
                    data: {
                        PathId : arrayPathId
                    },
                    dataType: "html", //expect html to be returned
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success: function(response) {
                    //    console.log(response);
                        $('#tab-clipart-content').html('');
                        $('#tab-clipart-content').html(response).hide().fadeIn("slow");
                            
                        loadClipartColor(randomNumbers);
                        colorPickerCustom();
                    }

                });
            }
            // END 4TH TAB
            
            // 5TH TAB
            // for upload image
		    document.getElementById('upload-images').onchange = function handleImage(e) {
                // console.log(event);
                var reader = new FileReader();
                reader.onload = function (event) {
                    
                    var imgObj = new Image();
                    
                    imgObj.src = event.target.result;
                    // console.log(event.target.result);
                    imgObj.onload = function () {
                        // start fabricJS stuff
                        var image = new fabric.Image(imgObj);
                        // console.log(image);
                        image.set({
                            top:0,
                            left:0,
                            borderColor: '#71b7f3',
                            cornerColor: '#71b7f3',
                            opacity: 10,
                            cornerSize: 10,
                            transparentCorners: false,
                            hasControls: true,
                            lockScalingFlip: true,
                            cache: false,
                            crossOrigin : 'anonymous'
                            // width: 15.6

                        }).scale(0.1);
                        //image.scale(getRandomNum(0.1, 0.25)).setCoords();

                        canvas.centerObject(image);
                        canvas.add(image);
                        canvas.renderAll(image);
                        canvas.setActiveObject(image);
                        image.bringToFront();
                        image.center();
                        image.setCoords();
                        $('#upload-images').val("");
                    }

                }

                //console.log(e.target.files[0]);
                reader.readAsDataURL(e.target.files[0]);

            }
            // end upload image
            // END 5TH TAB


            //################### C O L O R  P A L E T T E S #######################///
            $("#mainColor").spectrum({
                color: "rgb(255, 255, 255)",
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                showSelectionPalette: true,
                maxSelectionSize: 4,
                preferredFormat: "rgb",
                localStorageKey: "spectrum.demo",
                
                move: function(color) {

                    var onMoveColor =  color.toHexString(); // #ff0000
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                   
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];
                            var templateFormat = SideAndPath[i]['TemplateFormat'];
                            
                            if(templateFormat == "png"){
                                window['canvas_' + type + '_' + sideName].backgroundColor = onMoveColor;
                                window['canvas_' + type + '_' + sideName].renderAll();
                            }

                            var mainColorId = type + "_" + sideName + "_" + "Color";
                            var objectId = "objSVG_" + type + "_" + sideName;
                            
                            var y = 0.2126*color._r + 0.7152*color._g + 0.0722*color._b;
                            // var c = y < 128 ? 'white' : 'black';
                           
                            try{
                                document.getElementById(mainColorId).setAttribute("fill", onMoveColor);
                                if(y < 128){
                                    document.getElementById(sideName+'_Grid_Lines_Path').setAttribute("stroke", "white");

                                    var border_stroke = document.getElementById(sideName + '_' + type + '_Border');
                                    $(border_stroke).children("path").attr("fill", "yellow");

                                }else{
                                    document.getElementById(sideName+'_Grid_Lines_Path').setAttribute("stroke", "black");
                                    var border_stroke = document.getElementById(sideName + '_' + type + '_Border');
                                    $(border_stroke).children("path").attr("fill", "rgb(106, 77, 169)");
                                }

                                // console.log(border_stroke)

                               
                            }catch(e){

                            }
                         
                            
                        }
                    
                    

                    $('#row-body-gradient').css({
                        'display':'none'
                    });

                    $('#btn-body-gradient').html('');

                    $('#body-color-type').val('Solid');
                },
                
                show: function () {
                    // alert("dadas");
                    // console.log();
                },
                
                beforeShow: function () {
                    
                },
                
                hide: function (color) {
                    var onHideColor = color.toHexString(); // #ff0000
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                    
                    try{
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            //document.getElementById(objectId).contentDocument.getElementById(mainColorId).setAttribute("fill", onHideColor);
                            document.getElementById(mainColorId).setAttribute("fill", onHideColor);
                            
                        }
                    }catch(e){

                    }
                   

                    $('#row-body-gradient').css({
                        'display':'none'
                    });
                    $('#btn-body-gradient').html('');
                    $('#body-color-type').val('Solid');


                },
                
                change: function(color) {

                    var onChangeColor =  color.toHexString(); // #ff0000

                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                    
                    try{
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            //document.getElementById(objectId).contentDocument.getElementById(mainColorId).setAttribute("fill", onChangeColor);
                            document.getElementById(mainColorId).setAttribute("fill", onChangeColor);
                            
                            
                        }
                    }catch(e){

                    }
                    

                    $('#row-body-gradient').css({
                        'display':'none'
                    });
                    $('#btn-body-gradient').html('');
                    $('#body-color-type').val('Solid');

                },
                
                "palette": [
                    ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                    ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                    ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                    ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                    ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                    ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                ]
            });

            $(".gradientColor").spectrum({
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                //allowEmpty: true,
                showSelectionPalette: true,
                maxSelectionSize: 4,
                preferredFormat: "rgb",
                localStorageKey: "spectrum.demo",

                move: function(color) {
                    var onMoveColor = color.toHexString(); // #ff0000

                    var gradientId = $(this).attr('id');
                    var dataGradientType = $(this).attr('data-gradient-type');
                    
                    if(dataGradientType == "Body"){
                        var top_gradient_color = $('#Body_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Body_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-body-gradient";
                    }else{
                        var dataTrimNum = $(this).attr('data-trim-num');
                        var top_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-trim-"+dataTrimNum+"-gradient";
                    }
                    
                    document.getElementById(btnGradientId).style.background = "linear-gradient("+bot_gradient_color+","+top_gradient_color+")";
                    

                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        // btn-trim-1-gradient
                        document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onMoveColor);
                    }

                },
                
                show: function () {
                    

                },
                beforeShow: function () {

                },
                hide: function (color) {
                    var onHideColor = color.toHexString(); // #ff0000

                    var gradientId = $(this).attr('id');

                    var dataGradientType = $(this).attr('data-gradient-type');
                    
                    if(dataGradientType == "Body"){
                        var top_gradient_color = $('#Body_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Body_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-body-gradient";
                    }else{
                        var dataTrimNum = $(this).attr('data-trim-num');
                        var top_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-trim-"+dataTrimNum+"-gradient";
                    }
                    
                    document.getElementById(btnGradientId).style.background = "linear-gradient("+bot_gradient_color+","+top_gradient_color+")";
                   
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onHideColor);
                    }


                },
                
                change: function(color) {

                    var onChangeColor =  color.toHexString(); // #ff0000


                    var gradientId = $(this).attr('id');
                    var dataGradientType = $(this).attr('data-gradient-type');
                    
                    if(dataGradientType == "Body"){
                        var top_gradient_color = $('#Body_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Body_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-body-gradient";
                    }else{
                        var dataTrimNum = $(this).attr('data-trim-num');
                        var top_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color2').val(); // top color
                        var bot_gradient_color = $('#Trim_'+dataTrimNum+'_Gradient_Color1').val(); // bottom color 
                        var btnGradientId = "btn-trim-"+dataTrimNum+"-gradient";
                    }
                    
                    document.getElementById(btnGradientId).style.background = "linear-gradient("+bot_gradient_color+","+top_gradient_color+")";

                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onChangeColor);
                    }

                },
                palette: [
                    ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                    ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                    ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                    ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                    ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                    ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                ]
            });

            $(".trimColor").spectrum({
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                showSelectionPalette: true,
                maxSelectionSize: 4,
                preferredFormat: "rgb",
                localStorageKey: "spectrum.demo",
                move: function(color) {
                    var onMoveColor = color.toHexString(); // #ff0000

                    var trimId = $(this).attr('id');
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        try{
                            document.getElementById(type + "_" + sideName + "_" + trimId).setAttribute("fill", onMoveColor);
                        } catch(e){

                        }
                        

                    }

                    var trimCount =  $(this).attr('data-trim-num');
                    $('#row-trim-'+trimCount+'-gradient').css({
                        'display':'none'
                    });
                    $('#btn-trim-'+trimCount+'-gradient').html('');
                    $('#trim-'+trimCount+'-color-type').val('Solid');

                },
                show: function () {

                },
                beforeShow: function () {

                },
                hide: function (color) {
                    var onHideColor = color.toHexString(); // #ff0000

                    var trimId = $(this).attr('id');
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        
                        try{
                            document.getElementById(type + "_" + sideName + "_" + trimId).setAttribute("fill", onHideColor);
                        } catch(e){

                        }
                    }

                    var trimCount =  $(this).attr('data-trim-num');
                    $('#row-trim-'+trimCount+'-gradient').css({
                        'display':'none'
                    });
                    $('#btn-trim-'+trimCount+'-gradient').html('');
                    $('#trim-'+trimCount+'-color-type').val('Solid');

                },
                change: function(color) {

                    var onChangeColor =  color.toHexString(); // #ff0000

                    var trimId = $(this).attr('id');
                    var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                    for (var i = 0; i < SideAndPath.length; i++) {
                        var sideName = SideAndPath[i]['Side'];
                        var type = SideAndPath[i]['Type'];

                        var objectId = "objSVG_" + type + "_" + sideName;
                        //document.getElementById(objectId).contentDocument.getElementById(trimId).setAttribute("fill", onChangeColor);
                    
                        try{
                            document.getElementById(type + "_" + sideName + "_" + trimId).setAttribute("fill", onChangeColor);
                        } catch(e){

                        }
                    }

                    var trimCount =  $(this).attr('data-trim-num');
                    $('#row-trim-'+trimCount+'-gradient').css({
                        'display':'none'
                    });
                    $('#btn-trim-'+trimCount+'-gradient').html('');
                    $('#trim-'+trimCount+'-color-type').val('Solid');
                },
                palette: [
                    ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                    ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                    ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                    ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                    ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                    ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                ]
            });
            
            $(".fontColor").spectrum({
                color: "#3a53a4",
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                //allowEmpty: true,
                showSelectionPalette: true,
                maxSelectionSize: 4,
                preferredFormat: "rgb",
                localStorageKey: "spectrum.demo",
                move: function(color) {
                    //console.log(color);
                    //var onMoveColor = color.toHexString(); // #ff0000
                    var onMoveColor = color;
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setFill(onMoveColor);
                    }
                    canvas.renderAll();
                },
                show: function () {


                },
                beforeShow: function () {

                },
                hide: function (color) {
                    var onHideColor = color.toHexString(); // #ff0000
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setFill(onHideColor);
                    }
                    canvas.renderAll();


                },
                change: function(color) {

                    var onChangeColor =  color.toHexString(); // #ff0000
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setFill(onChangeColor);
                    }
                    canvas.renderAll();

                },
                palette: [
                    ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                    ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                    ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                    ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                    ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                    ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                ]
            });

            $(".strokeColor").spectrum({
                color: null,
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                //allowEmpty: true,
                showSelectionPalette: true,
                maxSelectionSize: 4,
                preferredFormat: "rgb",
                localStorageKey: "spectrum.demo",
                move: function(color) {
                    //console.log(color);
                    var onMoveColor = color.toHexString(); // #ff0000
                    //var onMoveColor = color;
                    //console.log(onMoveColor);
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setStroke(onMoveColor);
                    }
                    canvas.renderAll();
                },
                show: function () {


                },
                beforeShow: function () {

                },
                hide: function (color) {
                    var onHideColor = color.toHexString(); // #ff0000
                    //var onHideColor = color;
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setStroke(onHideColor);

                        if(onHideColor == ""){
                            $('.outlineThickness').val(0);
                        }
                    }
                    canvas.renderAll();


                },
                change: function(color) {

                    //var onChangeColor =  color.toHexString(); // #ff0000
                    var onChangeColor =  color;
                    var obj = canvas.getActiveObject();
                    if(obj){
                        obj.setStroke(onChangeColor);
                        if($('.outlineThickness').val() == 0){
                            obj.setStrokeWidth(1);
                            $('.outlineThickness').val(1);
                        }

                        if(onChangeColor == null){
                            $('.outlineThickness').val(0);
                        }
                    }
                    //console.log(color);
                    canvas.renderAll();

                },
                palette: [
                    ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                    ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                    ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                    ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                    ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                    ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                ]
            });

            function loadPatternColor(){
                $(".patternColor").spectrum({
                    showInput: true,
                    className: "full-spectrum",
                    showInitial: true,
                    showPalette: true,
                    //allowEmpty: true,
                    showSelectionPalette: true,
                    maxSelectionSize: 4,
                    preferredFormat: "rgb",
                    localStorageKey: "spectrum.demo",

                    move: function(color) {
                        var onMoveColor = color.toHexString(); // #ff0000
                        var patternId = $(this).attr('id');
                       
                        var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];
                            
                            var patternColorId = type + "_" + sideName + "_" + patternId;
                            var objectId = "objSVG_" + type + "_" + sideName;
                            try {

                            document.getElementById(patternColorId).setAttribute("fill", onMoveColor);
                            }
                            catch (e) {
                            //console.log(e);
                            }


                        }
                        // $("#gPattern").css('display', 'none');

                        var getDataTrim = $(this).attr('data-trim-num');
                    
                        if(typeof getDataTrim == 'undefined'){
                            $('#body-pattern-color-type').val('Solid');
                            $('#row-body-pattern-gradient').css('display', 'none');
                            $('#btn-body-pattern-gradient').html('');
                        }else{
                            $('#trim-'+getDataTrim+'-pattern-color-type').val('Solid');
                            $('#row-trim-'+getDataTrim+'-pattern-gradient').css('display', 'none');
                            $('#btn-trim-'+getDataTrim+'-pattern-gradient').html('');
                            // btn-trim-1-pattern-grandient
                        }
                        

                    },
                    show: function () {
                        
                    },
                    beforeShow: function () {

                    },
                    hide: function (color) {
                        var onHideColor = color.toHexString(); // #ff0000
                        var patternId = $(this).attr('id');
                        var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                    
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var patternColorId = type + "_" + sideName + "_" + patternId;
                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            try {
                            //   document.getElementById(objectId).contentDocument.getElementById(patternId).setAttribute("fill", onHideColor);
                            document.getElementById(patternColorId).setAttribute("fill", onHideColor);
                            }
                            catch (e) {
                            //console.log(e);
                            }


                        }
                        // $("#gPattern").css('display', 'none');
                        var getDataTrim = $(this).attr('data-trim-num');
                    
                        if(typeof getDataTrim == 'undefined'){
                            $('#body-pattern-color-type').val('Solid');
                        }else{
                            $('#trim-'+getDataTrim+'-pattern-color-type').val('Solid');
                        }
                        
                    },
                    change: function(color) {

                        var onChangeColor =  color.toHexString(); // #ff0000

                        var patternId = $(this).attr('id');

                        var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var patternColorId = type + "_" + sideName + "_" + patternId;
                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            try {
                            //  document.getElementById(objectId).contentDocument.getElementById(patternId).setAttribute("fill", onChangeColor);
                                document.getElementById(patternColorId).setAttribute("fill", onChangeColor);
                            }
                            catch (e) {
                            //console.log(e);
                            }
                        }
                        // $("#gPattern").css('display', 'none');
                        var getDataTrim = $(this).attr('data-trim-num');
                    
                        if(typeof getDataTrim == 'undefined'){
                            $('#body-pattern-color-type').val('Solid');
                        }else{
                            $('#trim-'+getDataTrim+'-pattern-color-type').val('Solid');
                        }
                        

                    },
                    palette: [
                        ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                        ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                        ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                        ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                        ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                        ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                    ]
                });

                $(".patternGradientColor").spectrum({
                    showInput: true,
                    className: "full-spectrum",
                    showInitial: true,
                    showPalette: true,
                    //allowEmpty: true,
                    showSelectionPalette: true,
                    maxSelectionSize: 4,
                    preferredFormat: "rgb",
                    localStorageKey: "spectrum.demo",

                    move: function(color) {
                        var onMoveColor = color.toHexString(); // #ff0000
                        var gradientId = $(this).attr('id');
                        // console.log(gradientId);
                        var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var objectId = "objSVG_" + type + "_" + sideName;
                            // btn-trim-1-gradient
                            document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onMoveColor);
                        }

                    },
                    show: function () {


                    },
                    beforeShow: function () {

                    },
                    hide: function (color) {
                        var onHideColor = color.toHexString(); // #ff0000
                        var gradientId = $(this).attr('id');
                        var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onHideColor);

                        }
                    },
                    change: function(color) {

                        var onChangeColor =  color.toHexString(); // #ff0000

                        var gradientId = $(this).attr('id');

                         var SideAndPath = {!! json_encode($templatepaths_arrays) !!};
                
                        for (var i = 0; i < SideAndPath.length; i++) {
                            var sideName = SideAndPath[i]['Side'];
                            var type = SideAndPath[i]['Type'];

                            var mainColorId = type + "_" + sideName + "_" + "Color";

                            var objectId = "objSVG_" + type + "_" + sideName;
                            document.getElementById(sideName + "_" + type + "_" + gradientId).setAttribute("stop-color", onChangeColor);
                        }

                    },
                    palette: [
                        ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                        ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                        ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                        ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                        ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                        ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                    ]
                });
            }

            function loadClipartColor(randomNumber){
                // console.log(randomNumber);
                $(".clipartColor").spectrum({
                    showInput: true,
                    className: "full-spectrum",
                    showInitial: true,
                    showPalette: true,
                    //allowEmpty: true,
                    showSelectionPalette: true,
                    maxSelectionSize: 4,
                    preferredFormat: "rgb",
                    localStorageKey: "spectrum.demo",

                    move: function(color) {
                        try{
                            var onMoveColor = color.toHexString(); // #ff0000
                            var pathid = $(this).attr('data-id');
                            var getRandomNumber = $(this).attr('data-number');
                            // console.log(getRandomNumber);
                            var obj = canvas.getActiveObject();
                            for (var j in obj.paths) {
                                
                                var id = obj.paths[j].get('id');
                                
                                if(pathid == id && randomNumber == getRandomNumber){
                                    obj.paths[j].setFill(onMoveColor);
                                    canvas.renderAll();
                                }
                            }
                        }catch(e){
                            $('.clipartColor').blur();
                        }

                    },
                    
                    show: function () {
                        

                    },
                    beforeShow: function () {

                    },
                    
                    hide: function (color) {	
                        try{
                            var onHideColor = color.toHexString(); // #ff0000
                            var pathid = $(this).attr('data-id');
                            var getRandomNumber = $(this).attr('data-number');
                            var obj = canvas.getActiveObject();
                            for (var j in obj.paths) {
                                
                                var id = obj.paths[j].get('id');
                                // console.log(onHideColor);
                                if(pathid == id && randomNumber == getRandomNumber){
                                    obj.paths[j].setFill(onHideColor);
                                    // console.log("random number true - hide");

                                    canvas.renderAll();
                                }
                            }
                        }catch(e){
                            $('.clipartColor').blur();
                        }
                        
                    },
                    
                    change: function(color) {
                        try{
                            var onChangeColor =  color.toHexString(); // #ff0000
                            var pathid = $(this).attr('data-id');
                            var getRandomNumber = $(this).attr('data-number');
                            var obj = canvas.getActiveObject();
                            
                            for (var j in obj.paths) {
                                
                                var id = obj.paths[j].get('id');
                                // console.log(onChangeColor);
                                if(pathid == id && randomNumber == getRandomNumber){
                                    obj.paths[j].setFill(onChangeColor);
                                    // console.log("random number true - change");
                                    canvas.renderAll();
                                }
                            }

                        }catch(e){
                            $('.clipartColor').blur();
                        }
                    },
                    palette: [
                        ["rgb(38, 38, 38)", "rgb(102, 102, 102)", "rgb(68, 69, 79)", "rgb(255, 255, 255)"],
                        ["rgb(77, 20, 8)", "rgb(0, 75, 43)", "rgb(0, 135, 81)", "rgb(0, 111, 175)"],
                        ["rgb(0, 95, 111)", "rgb(16, 34, 64)", "rgb(66, 128, 206)", "rgb(17, 43, 155)"],
                        ["rgb(64, 18, 129)", "rgb(116, 0, 36)", "rgb(169, 30, 54)", "rgb(221, 117, 174)"],
                        ["rgb(214, 0, 2)", "rgb(51, 0, 0)", "rgb(255, 224, 27)", "rgb(255, 186, 0)"],
                        ["rgb(211, 198, 120)", "rgb(158, 64, 0)", "rgb(255, 64, 0)", "rgb(255, 112, 10)"]
                    ]
                });
            }
            //###################	E N D  C O L O R  P A L E T T E S #######################//
        </script>
    </body>

</html>