/**
* 2007-2020 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2020 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

var isCallAjax = false;
$(document).ready(function(e){
 /******start init*******/
    function getUrlVars(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++){
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
      }
      return vars;
    }//function getUrlVars()

    var storage = $.localStorage;
    var cssPath = prestashop.urls.css_url;
    var demo_theme = getUrlVars()["demo-theme"];
    var demo_theme_mode = getUrlVars()["demo-theme-mode"];
    var cssDataResult = '';
    if(demo_theme != '' && demo_theme != undefined)//FOR REQUEST
      gettvcmsthemeoptions();

    function setRequestTheme(demo_theme){
      if(demo_theme == "box-width"){
        storage.set("box-layout",true);  
      }else if(demo_theme != '' && demo_theme != undefined){
        storage.set("theme",demo_theme);
        $('.tvselect-theme #select_theme option[value="' + storage.get("theme") + '"]').prop('selected', true);
        var themeColorVal = $('option:selected', $('#select_theme')).attr('data-color');
        var themeColorVal2 = $('option:selected', $('#select_theme')).attr('data-color-two');
        storage.set("theme_color", themeColorVal);//save localStorage
        storage.set("theme_color2", themeColorVal2);//save localStorage
        setCustomeTheme();
        setTimeout(function(){$('.tvtheme-control-icon').trigger('click')},500);
      }
      if(demo_theme_mode == 'dark'){
        storage.set("theme-dark-mode", 1);
      }else if(demo_theme != '' && demo_theme != undefined){
        storage.set("theme-dark-mode", 0);
      }
    }
  
  /******end init*******/
  
  function gettvcmsthemeoptions(){
    if(!isCallAjax){
      isCallAjax = true;
      $.ajax({
          type: 'POST',
          url: getThemeOptionsLink,
          success: function(data){
            $('body').prepend(data);
            $('#themecolor1').minicolors();
            $('#themecolor2').minicolors();
            $('#themebgcolor2').minicolors();
            $('#themebodybgcolor').minicolors();
            $('#themeCustomTitleColor').minicolors();
            loadJs();
            setRequestTheme(demo_theme);
            getCustomSetting();
            getCustomFontSettingOnPageLoad();
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
          }
      });
    }
    
  }
  //setTimeout(function(){gettvcmsthemeoptions()},1000);
  //document.addEventListener('scroll', function(e) {
  $(document).on('scroll', function() {
    gettvcmsthemeoptions();
  });
  
  function escapeRegExp(string){
      return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }
  function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
  }
  function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";   
  }

  function getRGBComponents(color) {       

      var r = color.substring(1, 3);
      var g = color.substring(3, 5);
      var b = color.substring(5, 7);

      return {
         R: parseInt(r, 16),
         G: parseInt(g, 16),
         B: parseInt(b, 16)
      };
  }
  
  function setCustomeTheme(){ 
    if ((storage.get("theme_color") != undefined &&  storage.get("theme_color") != '') || (storage.get("theme_color2") != undefined &&  storage.get("theme_color2") != '')) {
      $('#themecolor1').val(storage.get("theme_color"));
      $('#themecolor2').val(storage.get("theme_color2"));

      if(cssDataResult == ""){
        $.get( cssPath+"theme-custom.css", function( dataResult ) {
      console.log(cssPath+"theme-custom.css");
          cssDataResult = dataResult;
          setCustomCssValues(cssDataResult);
        });
      }else{
        setCustomCssValues(cssDataResult);
      }
    }
  }
  function setCustomCssValues(dataResult){
    var TextColor1 = idealTextColor(storage.get("theme_color"));
    var TextColor2 = idealTextColor(storage.get("theme_color2"));
    dataResult = replaceAll(dataResult,'#maincolor1',storage.get("theme_color"));
    dataResult = replaceAll(dataResult,'#maincolor2',storage.get("theme_color2"));
    dataResult = replaceAll(dataResult,'#maincolortext1',TextColor1);
    dataResult = replaceAll(dataResult,'#maincolortext2',TextColor2);
    $('.tvcms-custom-theme .custom-css').remove('');
    $(".tvcms-custom-theme").append("<div class='custom-css'><style>"+dataResult+"</style><div>");
  }
  $(document).on("change",'input[name="TVCMSCUSTOMSETTING_DARK_MODE_INPUT"]',function(){
    $('.tvcheck-popup').hide();
    $(this).parent().find('.tvcheck-popup').show();
    storage.set("theme-dark-mode", $(this).val());
    setDarkMode();
  });

  function setDarkMode(){
    if(storage.get("theme-dark-mode")==0){
      $('.tvtheme-theme-mode .lightModeWrapper .tvcheck-popup').show();
      $('.tvtheme-theme-mode .lightModeWrapper input').prop('checked', true);
      $('.tvcms-custom-theme .dark-mode-css').remove('');
    }else{
      $('.tvtheme-theme-mode .darkModeWrapper .tvcheck-popup').show();
      $('.tvtheme-theme-mode .darkModeWrapper input').prop('checked', true);
      $.get( cssPath+"dark-theme.css", function( data ) {
            $('.tvcms-custom-theme .dark-mode-css').remove('');
            data = replaceAll(data,'url(..\/img\/','url('+prestashop.urls.img_url);
            $(".tvcms-custom-theme").append("<div class='dark-mode-css'><style>"+data+"</style><div>");
      });
    }
  }
  function setBoxLayout(obj){
      // if($(obj).find('.toggle.btn.btn-default').hasClass('off')){
      if($(obj).prop("checked") == true){
        $('.tv-main-div').addClass('tv-box-layout container');
        $('.tv-main-div').removeClass('tv-full-layout');

        $('.tvtheme-background-patten, .tvtheme-background-color').show();
        if(storage.get("theme-bg-status")){
          $('body').css('background-image',storage.get("theme-bg-pattern"));
          $('body').css('background-color','');
        }else{
          $('body').css('background-color', storage.get("theme-bg-color"));
          $('body').css('background-image', "");
        } 
        storage.set("box-layout", true);//save localStorage
      }else{
        $('.tv-main-div').addClass('tvcms-full-layout');
        $('.tv-main-div').removeClass('tv-box-layout container');

        $('.tvtheme-background-patten, .tvtheme-background-color').hide();
        storage.set("box-layout", false);//save localStorage
      }
    }
    function getPattenSetting(obj){
        $(obj).addClass('active');
        $('.tvtheme-pattern-image').removeClass("active");
        $('.tvtheme-pattern-image').each(function(){
          if ("url("+$(this).attr('data-background-image-url')+")" == storage.get("theme-bg-pattern")) {
            $(this).addClass('active');
          }
        });
        $('body').css('background-image',"url("+storage.get("theme-bg-pattern")+")");
        $('body').css('background-color','');
    }
    function getBgColorSetting(obj){
    $('body').css('background-color', storage.get("theme-bg-color"));
        $('body').css('background-image', "");
        obj.parent().find('.minicolors-swatch-color').css('background-color',storage.get("theme-bg-color"));
    }
  function getCustomSetting(){
    if(!storage.get("themeControl")){
          resetCustomSetting();
      }
      $('.tvselect-theme #select_theme option[value="' + storage.get("theme") + '"]').prop('selected', true);
      setCustomeTheme();
    if(($('.tvselect-theme #select_theme').val()).match(/theme_custom/g)){
      $('.tvtheme-color-one').show();
      $('.tvtheme-color-two').show();
      $('#themecolor1').parent().find('.minicolors-swatch-color').css('background-color',storage.get("theme_color"));
      $('#themecolor2').parent().find('.minicolors-swatch-color').css('background-color',storage.get("theme_color2"));
    }else{
      $('.tvtheme-color-one').hide();
      $('.tvtheme-color-two').hide();
    }
    setDarkMode();

      if(storage.get("box-layout")){
        var obj = $(".tvtheme-box-layout-option");
        setBoxLayout(obj);
        if(storage.get("theme-bg-status")){
          getPattenSetting($('.tvtheme-pattern-image'));
        }else{
          getBgColorSetting($('#themebgcolor2'));
        }
        obj.trigger('click');
      }else{
        $('.tvtheme-background-patten, .tvtheme-background-color').hide();
      }

      if(storage.get("menu-sticky")){
        $('.tvtheme-menu-sticky-option').trigger('click');
      }
     
  }
  function resetCustomSetting(){
    storage.removeAll();
      storage.set("themeControl", true);
      storage.set("theme", "");
      storage.set("theme_color", "");
      storage.set("theme_color2", "");
      storage.set("box-layout", false);
      storage.set("menu-sticky", true);
      storage.set("themeColor1", '#fff');//default color1
      storage.set("themeColor2", '#ededed');//default color1
      storage.set("theme-bg-pattern", "url("+prestashop.urls.img_url+"pattern/pattern14.png)");//save storage
      storage.set("theme-bg-color", '#000');//default color2
      storage.set("theme-bg-status", true);//patten bg dafault on box layout on*/
      storage.set("theme-body-bgcolor-status", false);
      storage.set("theme-body-bgcolor-effect", '');
      storage.set("theme-body-bgcolor", "");
      storage.set("theme-body-bgimage", "");
      storage.set("theme-custom-font-1", "");
      storage.set("theme-custom-font-link-1", "");
      storage.set("theme-custom-font-2", "");
      storage.set("theme-custom-font-link-2", "");
      storage.set("theme-title-color", "");
      storage.set("theme-dark-mode", 0);
  }

    function getCustomFontSettingOnPageLoad(){
      
      if (storage.get("theme-body-bgcolor-status") == true) {
        $('.tvtheme-body-background-option').trigger('click');
        $('.tvtheme-body-bgcolor').show();
        $('.tvtheme-body-background-patten').show();

        if (storage.get("theme-body-bgcolor-effect").trim() == 'color') {

          $('.tv-main-div').css('background-color', storage.get("theme-body-bgcolor"));
          $('#themebodybgcolor').val(storage.get("theme-body-bgcolor"));
          $('#themebodybgcolor').parent().find('.minicolors-swatch-color').css('background-color',storage.get("theme-body-bgcolor"));

        } else{
          $('.tv-main-div').css('background-image',storage.get('theme-body-bgimage'));
          storage.get('theme-body-bgimage');
        }
      } else {
        $('.tvtheme-body-bgcolor').hide();
        $('.tvtheme-body-background-patten').hide();
      }

      setCustomeFontTheme(1);//title font 1
      setCustomeFontTheme(2);//body font 2
      setCustomeFontTheme(3);//title color 3
      
    }

 function setCustomeFontTheme($dataCall){
  var returnData ="";
      /******************Title Font********************/
      if (storage.get("theme-custom-font-1") != undefined && storage.get("theme-custom-font-1") != '' && $dataCall == 1) {
        $('.tvselect-title-font-1-select').val(storage.get("theme-custom-font-1"));
        $.get( cssPath+"theme-custom-title-font.css", function( data ) {
          var link_1 = '';
          data = replaceAll(data,'#fontFamily1', storage.get("theme-custom-font-1"));
          link_1 = '@import url(\''+storage.get("theme-custom-font-link-1")+'\');';
          returnData += link_1+' '+data;
          // $(".tvcms-custom-font").html($(".tvcms-custom-font").html()+"<style>"+returnData+"</style>");
          $('.tvcms-custom-font-1').html("<style>"+returnData+"</style>");
        });
      } else if (storage.get("theme-custom-font-1") == '') {
        $('.tvcms-custom-font-1').html('');
      }
      /******************title color********************/
      if (storage.get("theme-title-color") != undefined &&  storage.get("theme-title-color") != ''  && $dataCall == 3) {
        $.get( cssPath+"theme-custom-title-color.css", function( data ) {
          data = replaceAll(data,'#customTitleColor',storage.get("theme-title-color"));
          returnData = data;
          $('#themeCustomTitleColor').val(storage.get("theme-title-color"));
          $('#themeCustomTitleColor').parent().find('.minicolors-swatch-color').css('background-color',storage.get("theme-title-color"));
          // $(".tvcms-custom-font").html($(".tvcms-custom-font").html()+"<style>"+returnData+"</style>");
          $('.tvcms-custom-color').html('<style>'+returnData+'</style>');
        });
      } else if (storage.get("theme-title-color") == '') {
          $('.tvcms-custom-color').html('');
      }
      /******************Body Font********************/
      if (storage.get("theme-custom-font-2") != undefined && storage.get("theme-custom-font-2") != '' && $dataCall == 2) {
        $('.tvselect-title-font-2-select').val(storage.get("theme-custom-font-2"));
        $.get( cssPath+"theme-custom-body-font.css", function( data ) {
          var link_2 = '';
          data = replaceAll(data,'#fontFamily2',storage.get("theme-custom-font-2"));
          link_2 = '@import url(\''+storage.get("theme-custom-font-link-2")+'\');';
          returnData = link_2+' '+data;
          // $(".tvcms-custom-font").html($(".tvcms-custom-font").html()+"<style>"+returnData+"</style>");
          $('.tvcms-custom-font-2').html('<style>'+returnData+'</style>');
        });
      } else if (storage.get("theme-custom-font-2") == '') {
        $('.tvcms-custom-font-2').html('');
      }
    }

  function loadJs(){
    $(".tvcms-custom-font-1").html('');
    $(".tvcms-custom-font-2").html('');
    $(".tvcms-custom-color").html('');

    $(document).on('click','.tvtheme-menu-sticky-option',function(e){
      if($(this).prop("checked") == true){
        storage.set("menu-sticky", true);//save localStorage
      } else {
        storage.set("menu-sticky", false);//save localStorage  
      }
    });

    $(document).on('click','.tvcmstheme-control .tvtheme-control-icon',function(e){
      var themeOptionWrapper = $('.tvcmstheme-control .tvtheme-control-wrapper');
      if(themeOptionWrapper.hasClass('open')){
        themeOptionWrapper.removeClass('open');
        $('.tvcmstheme-control').removeClass('open');
      }else{
        themeOptionWrapper.addClass('open');
        $('.tvcmstheme-control').addClass('open');
      }
    });

    $(document).on('change','.tvselect-theme #select_theme',function(e){
      e.preventDefault();
      var themeVal = $(this).val();
      var themeColorVal = $('option:selected', this).attr('data-color');
      var themeColorVal2 = $('option:selected', this).attr('data-color-two');
      storage.set("theme", themeVal);//save localStorage
      storage.set("theme_color", themeColorVal);//save localStorage
      storage.set("theme_color2", themeColorVal2);//save localStorage
      $('.tvtheme-color-one').hide();
      $('.tvtheme-color-two').hide();
      if(themeVal == ""){
        $('.tvcms-custom-theme .custom-css').remove();
        $('.minicolors .themecolor1').hide();
        $('.minicolors .themecolor2').hide();
      }else if(themeVal.match(/theme_custom/g)){
          $('.tvtheme-color-one').show();
          $('.tvtheme-color-two').show();
          var theme_color = $('#themecolor1').val();
          var theme_color2 = $('#themecolor2').val();
          storage.set("theme_color", theme_color);
          storage.set("theme_color2", theme_color2);
          setCustomeTheme();
      }else{
          setCustomeTheme();
      }
    });
    
    $(document).on('change','#themecolor1',function(e){      
      var theme_color = $(this).val();
      storage.set("theme_color", theme_color);
       setCustomeTheme();
    });

    $(document).on('change','#themecolor2',function(e){
      var theme_color2 = $(this).val();
      storage.set("theme_color2", theme_color2);
      setCustomeTheme();
    });
   
    $(document).on('click','.tvtheme-box-layout-option',function(e){
      setBoxLayout(this);
    });

    $(document).on('click','.tvtheme-pattern-image',function(e){
      $('.tvtheme-pattern-image').removeClass('active');
        $(this).addClass('active');
        $('body').css('background-image',"url("+$(this).attr('data-background-image-url')+")");
        storage.set("theme-bg-pattern", "url("+$(this).attr('data-background-image-url')+")");//save localStorage
        $('body').css('background-color','');
        storage.set("theme-bg-status",true);
    });
     $(document).on('change','#themebgcolor2',function(e){
        $('body').css('background-color', $(this).val());
        $('body').css('background-image', "");     
        storage.set("theme-bg-status", false);
        storage.set("theme-bg-color", $(this).val());
    });

    $(document).on('click','.tvtheme-body-background', function(){
      if ($('.tvtheme-body-background-option').prop("checked") == true) {
        $('.tvtheme-body-bgcolor').hide();
        $('.tvtheme-body-background-patten').hide();
        $('.tv-main-div').removeAttr('style');
        storage.set("theme-body-bgcolor-status", false);
      } else {
        $('.tvtheme-body-bgcolor').show();
        $('.tvtheme-body-background-patten').show();
        var val = storage.get("theme-body-bgcolor");
        $('.tv-main-div').css('background-color', val);
        storage.set("theme-body-bgcolor-status", true);
      }
    });

    $(document).on('change','#themebodybgcolor',function(e){
      $('.tv-main-div').removeAttr('style');
        $('.tv-main-div').css('background-color', $(this).val());
        storage.set("theme-body-bgcolor", $(this).val());
        storage.set("theme-body-bgcolor-effect", 'color');
    });

    $(document).on('click','.tvtheme-body-pattern-image',function(e){
      $('.tvtheme-body-pattern-image').removeClass('active');
        $('.tv-main-div').removeAttr('style');
        $(this).addClass('active');
        // $(this).css('background-image')
        var tmp = $(this).attr('data-background-image-url');
        $('.tv-main-div').css('background-image','url('+tmp+')');
        storage.set("theme-body-bgimage", 'url('+tmp+')');//save localStorage
        storage.set("theme-body-bgcolor-effect", 'image');
    });    

    $(document).on('change','.tvselect-title-font-1 #select_title_font_1',function(e){
      var font_title = $(this).val();
      var font_link = $(this).find('option:selected').attr('data-font-link');
      storage.set("theme-custom-font-1", font_title);
      storage.set("theme-custom-font-link-1", font_link);
      setCustomeFontTheme(1);
    });

    $(document).on('change','.tvselect-title-font-2 #select_title_font_2',function(e){
      var font_title = $(this).val();
      var font_link = $(this).find('option:selected').attr('data-font-link');
      storage.set("theme-custom-font-2", font_title);
      storage.set("theme-custom-font-link-2", font_link);
      setCustomeFontTheme(2);
    });

    $(document).on('change','#themeCustomTitleColor',function(e){
      storage.set("theme-title-color", $(this).val());
      setCustomeFontTheme(3);
    });

    $(document).on('click','.tvtheme-control-reset',function(e){
      console.log("reset");
      resetCustomSetting();
      location.reload(); 
    });
  }
});
//==========================================