$versions{'template_manager-ext_lib.pl'} = '06.6.00.0000';

# Contains all sub routines (functions) for the templates and skins that wrap
# around the store pages that are dynamically generated (parsed).

#######################################################################
#
# AgoraCart and all associated files, except where noted, are
# Copyright 2001 to Present jointly by K-Factor Technologies, Inc.
# and by C E Mayo (aka Mister Ed) at AgoraCart.com & K-Factor.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This copyright notice may not be removed or altered in any way.
#
#######################################################################

# Misc Variables
$sm_templatelinks  = q{};
$sm_old_templateName  = q{};
$installTemplateMessage  = q{};

# Begin - loaded when lib read into manager.cgi. Sets up menu options.
{
    local ($modname) = 'template_manager';
    if ( $mc_change_main_settings_ok eq '' ) {
        $mc_change_main_settings_ok = 'yes';
    }
    register_extension( $modname, 'Store Template Manager', $versions{$modname} );
    register_menu( 'show_template_mgr_screen', 'show_template_mgr_screen',
        $modname, "Display Template Manager" );
    register_menu( 'ChangeTemplateSettings', 'action_input_template_settings',
        $modname, "Write Template Selection Settings" );
    register_menu( 'ChangeTempSocialSettings', 'action_template_social_settings',
        $modname, "Write Template Social Settings" );
    register_menu( 'SaveTemplateJSfile', 'save_template_js_file',
        $modname, 'Write - Save Template JS File' );
    register_menu( 'ChangeTemplateHTMLwidgets', 'save_template_htmlwidget_file',
          $modname, 'Write - Save Template HTML Widget File' );
    register_menu( 'ChangeTemplateCSSfile', 'save_template_css_file',
        $modname, 'Write - Save Template CSS File' );
    register_menu( 'ChangeTemplateManifest', 'save_template_manifest_file',
        $modname, 'Write - Save Template Manifest File' );
    register_menu( 'CopyAtemplate', 'copy_and_rename_template',
        $modname, 'Write - Copy and Rename a Template' );
    register_menu( 'DeleteAtemplate', 'delete_unused_template',
        $modname, 'Write - Delete an Unused Template' );
    register_menu( 'ChangeLangOverrideFile', 'save_user_language_override_file',
        $modname, 'Write - Save User Language Override File' );
    register_menu( 'ChangeTemplateZoneHomeWidgets', 'save_template_zonehome_file',
        $modname, 'Write - Save Template ZoneHome File' );
    register_menu( 'InstallTemplate', 'save_install_community_template_set',
        $modname, 'Write - Download and Extract Community Version Template Set' );


    add_settings_choice(
        'Store Template Manager',
        'Store Template Manager',
        'show_template_mgr_screen'
    );
    add_merchtools_settings_choice(
        'Store Template Manager',
        'Store Template Manager',
        'show_template_mgr_screen'
    );


}

#######################################################################

sub action_input_template_settings {

    local ( $temp1, $temp2 );
    local $mgr_is_manifest_loaded = q{};
    my ( $myset ) = q{};

    # template headers and footers
    $sc_headerTemplateRoot = $in{'sc_headerTemplateRoot'};
    $sc_headerTemplateRoot =~ /([\w\-\_]+)/;  # untaint
    $sc_headerTemplateRoot = $1;
    require_supporting_libraries( __FILE__, __LINE__,
        "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/$sc_hedfut_template_manifest" );
    $mgr_is_manifest_loaded = 'yes';
    $myset .= "\$sc_headerTemplateRoot = '$sc_headerTemplateRoot';\n";

    $sc_template_dir_for_URL = $sc_hedfut_templates_dir . '/' . $sc_headerTemplateRoot;
    $sc_template_dir_for_URL =~ s/\.\///; # strip off relative path: ./

    $sc_store_header_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/store_header.tpl";
    $sc_store_footer_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/store_footer.tpl";
    $sc_checkout_store_header_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/store_checkout_header.tpl";
    $sc_checkout_store_footer_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/store_checkout_footer.tpl";
    $myset .= "\$sc_template_dir_for_URL = '$sc_template_dir_for_URL';\n";
    $myset .= "\$sc_store_header_file = '$sc_store_header_file';\n";
    $myset .= "\$sc_store_footer_file = '$sc_store_footer_file';\n";
    $myset .= "\$sc_checkout_store_header_file = '$sc_checkout_store_header_file';\n";
    $myset .= "\$sc_checkout_store_footer_file = '$sc_checkout_store_footer_file';\n";
    $myset .= "\$sc_cssframework_dir_for_URL = '$mgr_template_framework';\n";

    $sc_agoracolors_css_enabled = $in{'sc_agoracolors_css_enabled'};
    $myset .= "\$sc_agoracolors_css_enabled = '$sc_agoracolors_css_enabled';\n";

    # template specific files - CSS
    $sc_template_css_enabled = $in{'sc_template_css_enabled'};
    $myset .= "\$sc_template_css_enabled = '$sc_template_css_enabled';\n";
    $sc_template_css_file = '';
    if ( $sc_template_css_enabled eq 'yes' ) {
      $sc_template_css_file = "$sc_template_dir_for_URL/template.css";
    }
    $myset .= "\$sc_template_css_file = q|$sc_template_css_file|;\n";

    $sc_template_advanced_tabs_enabled = $in{'sc_template_advanced_tabs_enabled'};
    $myset .= "\$sc_template_advanced_tabs_enabled = '$sc_template_advanced_tabs_enabled';\n";

    # template specific files - HTML widgets
    $sc_template_widgets_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/template_widgets.inc";
    $myset .= "\$sc_template_widgets_file = \"$sc_template_widgets_file\";\n";
    $sc_template_homezone_file = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/template_homezone.inc";
    $myset .= "\$sc_template_homezone_file = q|$sc_template_homezone_file|;\n";

    # template specific files - JS
    $sc_template_js_enabled = $in{'sc_template_js_enabled'};
    $myset .= "\$sc_template_js_enabled = '$sc_template_js_enabled';\n";
    $sc_template_js_file = '';
    if ( $sc_template_js_enabled eq 'yes' ) {
      $sc_template_js_file = "$sc_template_dir_for_URL/template.js";
    }
    $myset .= "\$sc_template_js_file = q|$sc_template_js_file|;\n";

    # set custom productPage.inc directory within chosen template.
    $myset .= "\$sc_prod_cat_templates_dir = qq|$sc_hedfut_templates_dir/$sc_headerTemplateRoot|;\n";

    # Misc Layout/Design/Template settings
    $myset .= "\$sc_displayDynamicCategories = \"$in{'sc_displayDynamicCategories'}\";\n";
    $myset .= "\$sc_headerStoreTitle = qq|$in{'sc_headerStoreTitle'}|;\n";

    update_store_settings( 'TEMPLATE', $myset );   # template settings
    require_supporting_libraries( __FILE__, __LINE__, "$mgr_user_settings_path" );
    write_html_css_js_includes();
    show_template_mgr_screen();
}

#######################################################################

sub action_template_social_settings {

  local ($myset) = q{};
  require_supporting_libraries( __FILE__, __LINE__,
      "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/$sc_hedfut_template_manifest" );
  $mgr_is_manifest_loaded = 'yes';

  $sc_social_facebook_url = $in{'sc_social_facebook_url'};
  $sc_social_twitter_url = $in{'sc_social_twitter_url'};
  $sc_social_linkedin_url = $in{'sc_social_linkedin_url'};
  $sc_social_instagram_url = $in{'sc_social_instagram_url'};
  $sc_social_gab_url = $in{'sc_social_gab_url'};
  $sc_social_youtube_url = $in{'sc_social_youtube_url'};

  # Social Media links for template - left blank/skipped if URL blank.
  if ( $in{'sc_social_facebook_url'} && $mgr_social_facebook{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_facebook_url = q|$sc_social_facebook_url|;\n";
    $mgr_social_facebook{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaFacebook\]\]/$in{'sc_social_facebook_url'}/;
    $myset .= "\$sc_template_social_facebook = q|$mgr_social_facebook{$sc_headerTemplateRoot}|;\n";
  }
  if ( $in{'sc_social_twitter_url'} && $mgr_social_twitter{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_twitter_url = q|$sc_social_twitter_url|;\n";
    $mgr_social_twitter{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaTwitter\]\]/$in{'sc_social_twitter_url'}/;
    $myset .= "\$sc_template_social_twitter = q|$mgr_social_twitter{$sc_headerTemplateRoot}|;\n";
  }
  if ( $in{'sc_social_linkedin_url'} && $mgr_social_linkedin{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_linkedin_url = q|$sc_social_linkedin_url|;\n";
    $mgr_social_linkedin{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaLinkedIn\]\]/$in{'sc_social_linkedin_url'}/;
    $myset .= "\$sc_template_social_linkedin = q|$mgr_social_linkedin{$sc_headerTemplateRoot}|;\n";
  }
  if ( $in{'sc_social_instagram_url'} && $mgr_social_instagram{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_instagram_url = q|$sc_social_instagram_url|;\n";
    $mgr_social_instagram{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaInstagram\]\]/$in{'sc_social_instagram_url'}/;
    $myset .= "\$sc_template_social_instagram = q|$mgr_social_instagram{$sc_headerTemplateRoot}|;\n";
  }
  if ( $in{'sc_social_gab_url'} && $mgr_social_gab{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_gab_url = q|$sc_social_gab_url|;\n";
    $mgr_social_gab{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaGab\]\]/$in{'sc_social_gab_url'}/;
    $myset .= "\$sc_template_social_gab = q|$mgr_social_gab{$sc_headerTemplateRoot}|;\n";
  }
  if ( $in{'sc_social_youtube_url'} && $mgr_social_youtube{$sc_headerTemplateRoot} ) {
    $myset .= "\$sc_social_youtube_url = q|$sc_social_youtube_url|;\n";
    $mgr_social_youtube{$sc_headerTemplateRoot} =~ s/\[\[SocialMediaYoutube\]\]/$in{'sc_social_youtube_url'}/;
    $myset .= "\$sc_template_social_youtube = q|$mgr_social_youtube{$sc_headerTemplateRoot}|;\n";
  }

  update_store_settings( 'TEMPLATESOCIAL', $myset );   #save template social settings
  require_supporting_libraries( __FILE__, __LINE__, "$mgr_user_settings_path" );
  show_template_mgr_screen();

}

#######################################################################

sub save_template_zonehome_file {

    my $temp2backup = "./$sc_template_homezone_file";
    my $new_homezone_file = "$in{'changed_template_homezone_widgets_file'}";
    open( NEWHOMEZONEFILE, '>', "$temp2backup" );
    print NEWHOMEZONEFILE $new_homezone_file;
    close( NEWHOMEZONEFILE );

    show_template_mgr_screen();
}

#######################################################################

sub save_template_css_file {

    # create backup of CSS file
    my $temp_time = time();
    my $temp2backup = "./$sc_template_css_file";
    my $newbackupfile = "./$sc_template_dir_for_URL" . '/template_CSSedit_backup_' . $temp_time . '.css';
    copy( $temp2backup, $newbackupfile );

    # update the CSS file
    my $new_css_file = "$in{'changed_template_CSS_file'}";
    open( NEWCSSFILE, '>', "$temp2backup" );
    print NEWCSSFILE $new_css_file;
    close( NEWCSSFILE );

    show_template_mgr_screen();
}

#######################################################################

sub save_template_js_file {

    # create backup of JS file
    my $temp_time = time();
    my $temp2backup = "./$sc_template_js_file";
    my $newbackupfile = "./$sc_template_dir_for_URL" . '/template_JSedit_backup_' . $temp_time . '.js';
    copy( $temp2backup, $newbackupfile );

    # update the JS file
    my $new_js_file = "$in{'changed_template_JS_file'}";
    open( NEWJSFILE, '>', "$temp2backup" );
    print NEWJSFILE $new_js_file;
    close( NEWJSFILE );

    show_template_mgr_screen();
}

#######################################################################

sub save_template_htmlwidget_file {

    # create backup of HTML Widgets file
    my $temp_time = time();
    my $temp2backup = "./$sc_template_widgets_file";
    my $newbackupfile = "./$sc_template_dir_for_URL" . '/template_WIDGETSedit_backup_' . $temp_time . '.inc';
    copy( $temp2backup, $newbackupfile );

    # update the HTML Widget file
    my $new_widget_file = "$in{'changed_template_widgets_file'}";
    open( NEWWIDGETFILE, '>', "$temp2backup" );
    print NEWWIDGETFILE $new_widget_file;
    close( NEWWIDGETFILE );

    show_template_mgr_screen();
}

#######################################################################

sub save_template_manifest_file {

    # create backup of manifest file
    my $temp_time = time();
    my $temp2backup = "./$sc_template_dir_for_URL/$sc_hedfut_template_manifest";
    my $newbackupfile = "./$sc_template_dir_for_URL" . '/template_MANIFESTedit_backup_' . $temp_time . '.inc';
    copy( $temp2backup, $newbackupfile );

    # update the manifest file
    my $new_manifest_file = "$in{'changed_template_manifest_file'}";
    open( NEWMANIFESTFILE, '>', "$temp2backup" );
    print NEWMANIFESTFILE $new_manifest_file;
    close( NEWMANIFESTFILE );

    show_template_mgr_screen();
}

#######################################################################

sub save_user_language_override_file {

    my $temp2backup = "$sc_lang_dir/$sc_lang_path/user_changes_to_language.pl";
    my $new_file = "$in{'changed_user_language_override_file'}";
    open( NEWLANGOVERRIDE, '>', "$temp2backup" );
    print NEWLANGOVERRIDE $new_file;
    close( NEWLANGOVERRIDE );

    show_template_mgr_screen();
}

#######################################################################

sub copy_and_rename_template {

    my (@lines) = q{};
    my $x = "File::Copy::Recursive qw(fcopy rcopy dircopy fmove rmove dirmove)";
    my $sm_template_to_change_id = "$in{'sm_template_to_change_id'}";
    my $new_template_name = "$in{'sm_template_new_name'}";
    my $new_template_id = "$in{'sm_template_new_id'}";
    my $datestring = localtime();
    my $skip = 0;

    $sm_template_to_change_id =~ /^([\w\._\-]+)$/;  # untaint
    $sm_template_to_change_id = $1;

    $new_template_name =~ /([\w\. \-]+)/;  # untaint
    $new_template_name = $1;
    $new_template_id =~ /([\w\._ \-]+)/;  # untaint
    $new_template_id = $1;
    $new_template_id =~ s/ +/_/g;
    $new_template_id =~ s/\.+/dot/g;

    my $new_template_manifest = "$sc_hedfut_templates_dir/$new_template_id/$sc_hedfut_template_manifest";
    my $new_template_mgr_lang_file = "$sc_hedfut_templates_dir/$new_template_id/$sc_lang_path" . '-mgr_lang.inc';
    my $new_display_manifest = "$new_template_id/$sc_hedfut_template_manifest";
    my $new_display_mgr_lang_file = "$new_template_id/$sc_lang_path" . '-mgr_lang.inc';

    my $page_output = &$manager_page_header( 'Store Template Manager', '', '', '', '' );

    $page_output .= "<p><br><br><br></p>";

    eval("use $x"); # use in non-fatal way
    if ($@) {
        # just in case we can't use it, but it is a core perl module
        $page_output .=  qq|
        <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
                <h4 class="text-danger mgr-center">Error:: $result &amp; $@</h4>
            </div>
        </div>|;
        $skip = 1;
    }
    else {
        local $File::Copy::Recursive::SkipFlop = 1; # continue if error
        my $orig = "$sc_hedfut_templates_dir/$sm_template_to_change_id";
        my $new = "$sc_hedfut_templates_dir/$new_template_id";
        my($num_of_files_and_dirs) = dircopy($orig,$new);

        if ( -e $new ) {
            $page_output .= qq|
            <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
                    <h4 class="text-primary mgr-center">Success: Template was Copied</h4>
                </div>
            </div>|;
        }
        else {
            # directory does not exist
            $page_output .= qq|
            <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
                    <h4 class="text-danger mgr-center">Oops: Something went wrong! The selected template was not copied</h4>
                </div>
            </div>|;
            $skip = 1;
        }

        $page_output .= "<p><br><br><br></p>";
        $page_output .= "<p>Copy attempted from original directory at: <b>$orig</b></p>";
        $page_output .= "<p>To new directory at: <b>$new</b></p>";
        $page_output .=  "<p>Total files to be copied: <b>$num_of_files_and_dirs</b></p>";

        if ( $skip < 1 ) {
            # replace template ID and name in template's manifest & mgr language files.
            open( OLDMANIFEST, "$new_template_manifest" ) || my_die("Can't Open $new_template_manifest");
            @lines = <OLDMANIFEST>;
            close(OLDMANIFEST);
            open( NEWMANIFEST, ">$new_template_manifest" ) || my_die("Can't Open $new_template_manifest");
            foreach $file_line (@lines) {
                if ( $file_line =~ /^\$mgr_template_thumbnail_URL\{/ ) {
                $file_line = qq|\$mgr_template_thumbnail_URL{'$new_template_id'} = 'images/template_copy_image.png';|;

                }
                $file_line =~ s/$sm_template_to_change_id/$new_template_id/g;

                print NEWMANIFEST $file_line;
            }
            close(NEWMANIFEST);

            $page_output .= "<p><b>Updated:</b> $new_display_manifest" .'</p>';

            @lines = q{};

            open( OLDMGRLANG, "$new_template_mgr_lang_file" ) || my_die("Can't Open $new_template_mgr_lang_file");
            @lines = <OLDMGRLANG>;
            close(OLDMGRLANG);
            open( NEWMGRLANG, ">$new_template_mgr_lang_file" ) || my_die("Can't Open $new_template_mgr_lang_file");
            foreach $file_line (@lines) {
                if ( $file_line =~ /^\$mgr_template_name\{/ ) {
                    $file_line = qq|\$mgr_template_name{'$new_template_id'} = '$new_template_name';|;
                }
                $file_line =~ s/$sm_template_to_change_id/$new_template_id/g;
                print NEWMGRLANG $file_line;
            }

            $file_line = qq|\$mgr_template_copied_from{'$new_template_id'} .= "<p>Copied from: $sm_template_to_change_id, on: $datestring (server time)</p>";|;
            print NEWMGRLANG $file_line;

            $page_output .= "<p><p><b>Updated:</b> $new_display_mgr_lang_file" .'</p>';
            close(NEWMGRLANG);

            (@mgrlines, @manlines) = q{};
        }

    }

  # show link to template manager
    $page_output .= qq|<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12"><p><br><br><br></p><p><a type="button" class="btn btn-lrg btn-success mgr-center" style="display: block;" href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&show_template_mgr_screen=yes">Return to Store Template Manager</a></p></div>|;

    $page_output .= &$manager_page_footer;
    print $page_output;
}

#######################################################################

sub delete_unused_template {

    my $x = "File::Path qw(rmtree)"; # remove_tree for newer versions
    my $sm_template_to_delete_id = "$in{'sm_template_to_delete_id'}";
    my $current_template_id = "$in{'current_template_id'}";
    $sm_template_to_delete_id =~ /^([\w\._\-]+)$/;  # untaint
    $sm_template_to_delete_id = $1;

    my $page_output = &$manager_page_header( 'Store Template Manager', '', '', '', '' );

    $page_output .= "<p><br><br><br></p>";

    eval("use $x"); # use in non-fatal way
    if ($@) {
        # just in case we can't use it, but it is a core perl module
        $page_output .=  qq|
        <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
                <h4 class="text-danger mgr-center">Error:: $result &amp; $@</h4>
            </div>
        </div>|;
    }
    elsif ( $current_template_id ) {
        my $target = "$sc_hedfut_templates_dir/$sm_template_to_delete_id";

        $page_output .= "<p>Attempting to delete template directory at: <b>$target</b></p><p><br></p>";

        rmtree($target); # remove_tree for newer versions

        if(-e $target) {
            # directory still exists
            $page_output .= qq|
            <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
                    <h4 class="text-danger mgr-center">Oops: Something went wrong! The selected template was not deleted</h4>
                </div>
            </div>|;

        }
        else {
            $page_output .= qq|
            <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
                    <h4 class="text-primary mgr-center">Success: Template was deleted</h4>
                </div>
            </div>|;
        }

    }
    else {
        # no current template ID provided
        $page_output .=  qq|
        <div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
                <h4 class="text-danger mgr-center">Oops: Something went wrong! Action Not Allowed</h4>
            </div>
        </div>|;
    }

  # show link to template manager
    $page_output .= qq|<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12"><p><br><br><br></p><p><a type="button" class="btn btn-lrg btn-success mgr-center" style="display: block;" href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&show_template_mgr_screen=yes">Return to Store Template Manager</a></p></div>|;

    $page_output .= &$manager_page_footer;
    print $page_output;
}

#######################################################################

sub save_install_community_template_set {

    my $filename = $in{'template_key'};
    $filename =~ /([\w\-\/]+)/;
    $filename = "$1";
    my $local_dir = "$sc_hedfut_templates_dir/$filename";
    my $local_tarball = "$sc_hedfut_templates_dir/$filename.tar";
    my $moduleTest = 'OK'; # default

    # make sure not installed already

    # global to pass URL
    $mgr_install_source_file_path = "downloadupdates/Route66/templates/$filename.tar";

    # get the .tar file
    if ( $moduleTest eq 'OK' ) {
        &get_file_to_install_pro_file($local_tarball);
    }

    # is tarball there?
    if (-e $local_tarball ) {
        eval("use Archive::Extract;");
        eval("use Archive::Tar;");
        my $install_me = "$filename.tar";

        # Now extract AgoraCart install file
        chdir("$sc_hedfut_templates_dir");
        $Archive::Tar::CHMOD = 0; # PRESERVE PERMISSIONS!
        my $artar = Archive::Tar->new();
        $artar->read( $install_me );
        $artar->extract();
        unlink("$install_me");

        # check if a couple contents exist
        if ( (-e "$filename" ) && ( -e "$filename/template_manifest.inc" ) && ( -e "$filename/store_header.tpl" ) ) {
            $installTemplateMessage .= "Template Successfully Downloaded and Extracted";
        }
        else {
            $installTemplateMessage .= "ERROR: Template Was Not Downloaded and Extracted";
        }

        chdir("../../../"); # up from ./view66/templates/headers_footers/

    }
    else {
        # we didn't get the file for some reason
        $installTemplateMessage .= "ERROR: Template Archive not Found";
    }

    &show_template_mgr_screen();

}

#######################################################################

sub show_template_mgr_screen {

    my $page_output = &$manager_page_header( 'Store Template Manager', '', '', '', '' );
    my ( $err_code, $sm_template_id, $sm_template_name ) = q{};
    my ( $full_template_js_file, $full_template_css_file, $full_template_widgets_file ) = q{};
    my ( $full_language_file, $full_language_override_file, $full_template_homezone_file ) = q{};
    my ( $sm_templateSelectedOption, $sm_templateOptions, $memtempl_output ) = q{};
    local ( $socialbuttons ) = q{};
    my (@templline, @paidtemplline);

    opendir( TEMPLATES, "$sc_hedfut_templates_dir" );
    @myfiles = readdir(TEMPLATES);
    closedir(TEMPLATES);
    foreach $zfile (@myfiles) {
      if ( !( $zfile =~ /\./ ) ) {
        $zfile =~ /([\w\-\_]+)/;  # untaint
        $zfile = $1;
        #$mgr_template_id = ''; # reset, just in case
        $mgr_template_language_location = "$sc_hedfut_templates_dir/$zfile/$sc_lang_path" . '-mgr_lang.inc';
        require_supporting_libraries( __FILE__, __LINE__, "$sc_hedfut_templates_dir/$zfile/$sc_hedfut_template_manifest" );

        if ( ( $zfile eq $sc_headerTemplateRoot ) && ( $mgr_template_id  eq '' ) ) {
            $mgr_template_id = $zfile;
        }

        if ( $mgr_template_id ) {

          require_supporting_libraries( __FILE__, __LINE__, "$mgr_template_language_location");

          if ( $sc_headerTemplateRoot eq $mgr_template_id ) {
            $sm_template_id = $mgr_template_id;
            $sm_template_name = $mgr_template_name{"$mgr_template_id"};
            $sm_templateSelectedOption = qq|<option value="$mgr_template_id">$mgr_template_name{"$mgr_template_id"}</option>|;
            $sm_templatelinks .= qq~<div class="row"><div class="radio">
  <div class="col-md-4"><label>
    <input type="radio" name="sc_headerTemplateRoot" value="$mgr_template_id" checked>
    <img class='img-responsive' style="padding-left:28px" src="$mgr_template_thumbnail_URL{$mgr_template_id}">
  </label></div></div>
  <div class="col-md-8"><p class="text-left"><h3>$mgr_template_name{"$mgr_template_id"}</h3> &nbsp; <a data-toggle="collapse" href="#select$mgr_template_id" aria-expanded="false" aria-controls="select$mgr_template_id"><i class="fa fa-info-circle"></i> Template Details</a></p></div>
</div><div class="collapse" id="select$mgr_template_id">
    <div class="well">
        <p><b>Column Layout/Structure: </b>$mgr_template_column_layout{"$mgr_template_id"}</p>
        <p><b>Color/Scheme: </b>$mgr_template_color_scheme{"$mgr_template_id"}</p>
        <p><b>Target uses: </b>$mgr_template_target{"$mgr_template_id"}</p>
        <p><b>Style/Design Framework: </b>$mgr_template_framework{"$mgr_template_id"}</p>
        <p><b>Loads jQuery: </b> $mgr_template_jquery_details{"$mgr_template_id"}</p>
        $mgr_template_copied_from{"$mgr_template_id"}
    </div>
</div><p><hr></p>\n~;
          }
          else {
            $sm_templateOptions .= qq|<option value="$mgr_template_id">$mgr_template_name{"$mgr_template_id"}</option>|;
            $sm_templatelinks .= qq~<div class="row"><div class="radio">
  <div class="col-md-4"><label>
    <input type="radio" name="sc_headerTemplateRoot" value="$mgr_template_id">
    <img class='img-responsive' style="padding-left:28px" src="$mgr_template_thumbnail_URL{$mgr_template_id}">
  </label></div></div>
  <div class="col-md-8"><p class="text-left"><h3>$mgr_template_name{"$mgr_template_id"}</h3> &nbsp; <a data-toggle="collapse" href="#select$mgr_template_id" aria-expanded="false" aria-controls="select$mgr_template_id"><i class="fa fa-info-circle"></i> Template Details</a></p></div>
</div><div class="collapse" id="select$mgr_template_id">
    <div class="well">
        <p><b>Column Layout/Structure: </b>$mgr_template_column_layout{"$mgr_template_id"}</p>
        <p><b>Color/Scheme: </b>$mgr_template_color_scheme{"$mgr_template_id"}</p>
        <p><b>Target uses: </b>$mgr_template_target{"$mgr_template_id"}</p>
        <p><b>Style/Design Framework: </b>$mgr_template_framework{"$mgr_template_id"}</p>
        <p><b>Loads jQuery: </b> $mgr_template_jquery_details{"$mgr_template_id"}</p>
        $mgr_template_copied_from{"$mgr_template_id"}
    </div>
</div><p><hr></p>\n~;
          }
        }
        $mgr_template_id = '';
      }
    }

    if ( $mgr_social_facebook{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-facebook-square fa-2x"></i> &nbsp;&nbsp; Facebook URL:</b><input name="sc_social_facebook_url" type="url" class="form-control" maxlength="80" value="$sc_social_facebook_url"></p>\n|;
    }
    if ( $mgr_social_twitter{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-twitter-square fa-2x"></i> &nbsp;&nbsp; Twitter URL:</b><input name="sc_social_twitter_url" type="url" class="form-control" maxlength="80" value="$sc_social_twitter_url"></p>\n|;
    }
    if ( $mgr_social_linkedin{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-linkedin-square fa-2x"></i> &nbsp;&nbsp; LinkedIn URL:</b><input name="sc_social_linkedin_url" type="url" class="form-control" maxlength="80" value="$sc_social_linkedin_url"> </p>\n|;
    }
    if ( $mgr_social_instagram{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-instagram fa-2x"></i> &nbsp;&nbsp; Instagram URL:</b><input name="sc_social_instagram_url" type="url" class="form-control" maxlength="80" value="$sc_social_instagram_url"></p>\n|;
    }
    if ( $mgr_social_gab{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-user-circle fa-2x"></i> &nbsp;&nbsp; Gab URL:</b><input name="sc_social_gab_url" type="url" class="form-control" maxlength="80" value="$sc_social_gab_url"></p>\n|;
    }
    if ( $mgr_social_youtube{$sc_headerTemplateRoot} ) {
      $socialbuttons .= qq|<p><br></p><p><b><i class="fa fa-youtube-square fa-2x"></i> &nbsp;&nbsp; Youtube URL:</b><input name="sc_social_youtube_url" type="url" class="form-control" maxlength="80" value="$sc_social_youtube_url"></p>\n|;
    }

    open( TEMPLATEWIDGETS, "<$sc_template_widgets_file" ) || file_open_error(
        "$sc_template_widgets_file", 'Could not find file', __FILE__, __LINE__ );
    while (<TEMPLATEWIDGETS>) {
        $full_template_widgets_file .= $_;
    }
    close(TEMPLATEWIDGETS);

    if ( $sc_template_css_enabled eq '' ) {
      $sc_template_css_enabled = 'yes';
    }
    if ( $sc_template_js_enabled ne 'yes' ) {
      $sc_template_js_enabled = 'no';
    }

    $page_output .= <<ENDOFTEXT;
<h1 class='mgr-page-title'>Store Template Manager</h1>
<p><br></p>

<p class="well">This manager allows you to change the store header &amp; footer templates that your store will use by default. First select the template name you wish to use in the <b>Template</b> tab. You may only change the settings within a single tab at a time. Press the <b><i>submit</i></b> button at the very bottom of the tab after you are finished making any desired changes. Click on the <i class="fa fa-info-circle"></i> icon next to any setting for more information on the setting.
<br><br>See the <a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&show_edit_hdrftr_screen=yes">Template Header &amp; Footer Editor</a> to make changes to the actual selected template headers and footers (aka store content wrappers) used for your store.
<br><br>If you need to customize a template extensively or make your own based on a template you have installed, please copy the existing template using the "Copy Template" tab below before editing the template. Also make sure to selected it and saved the settings after you have copied a template so that the new template will be used in the file editors. This will allow you to upgrade standard templates without overwriting your extensive changes.
<br><br>Also see the <a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&change_store_layout_screen=yes">Layout & Design Settings - Misc</a> Manager for other misc layout items.</p>
<p><br></p>

ENDOFTEXT

    if ( $in{'system_edit_success'} ) {
        $page_output .= qq|
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
    <h4 class="text-primary mgr-center">Template settings (or files) have been successfully updated</h4>
    <p>$installTemplateMessage</p>
    </div>
</div>
<p><br><br><br><br><br></p>
|;
    }

    $page_output .= <<ENDOFTEXT;

<ul class="nav nav-tabs" id="tabs2" role="tablist">
    <li role="presentation" class="active"><a href="#tabs-1" aria-controls="tabs-1" role="tab" data-toggle="tab">Template</a></li>
    <li role="presentation"><a href="#tabs-2" aria-controls="tabs-2" role="tab" data-toggle="tab">Social Media</a></li>
ENDOFTEXT

    if ( $sc_template_css_enabled eq 'yes' ) {
      open( TEMPLATECSS, "<$sc_template_css_file" ) || file_open_error(
          "$sc_template_css_file", 'Could not find file', __FILE__, __LINE__ );
      while (<TEMPLATECSS>) {
          $full_template_css_file .= $_;
      }
      close(TEMPLATECSS);
      $css_output = &javascr_color_picker_display;
      $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-3" aria-controls="tabs-3" role="tab" data-toggle="tab">CSS</a></li>
ENDOFTEXT
    }

    if ( $sc_template_js_enabled eq 'yes' ) {
      open( TEMPLATEJS, "<$sc_template_js_file" ) || file_open_error(
          "$sc_template_js_file", 'Could not find file', __FILE__, __LINE__ );
      while (<TEMPLATEJS>) {
          $full_template_js_file .= $_;
      }
      close(TEMPLATEJS);
      $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-4" aria-controls="tabs-4" role="tab" data-toggle="tab">Javascript</a></li>
ENDOFTEXT
    }

    if ( $sc_template_advanced_tabs_enabled eq 'yes' ) {
      my $temp_manifest_location = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/$sc_hedfut_template_manifest";
      my $lang_file_location = "$sc_lang_dir/$sc_lang_path/agora_messages.pl";
      my $lang_override_location = "$sc_lang_dir/$sc_lang_path/user_changes_to_language.pl";
      open( TEMPLATEMANI, "<$temp_manifest_location" ) || file_open_error(
          "$temp_manifest_location", 'Could not find file', __FILE__, __LINE__ );
      while (<TEMPLATEMANI>) {
          $full_template_manifest_file .= $_;
      }
      close(TEMPLATEMANI);

      open( LANGOVERRIDE, "<$lang_override_location" ) || file_open_error(
          "$lang_override_location", 'Could not find file', __FILE__, __LINE__ );
      while (<LANGOVERRIDE>) {
          $full_language_override_file .= $_;
      }
      close(LANGOVERRIDE);

      open( LANGFILE, "<$lang_file_location" ) || file_open_error(
          "$lang_file_location", 'Could not find file', __FILE__, __LINE__ );
      while (<LANGFILE>) {
          $full_language_file .= $_;
      }
      close(LANGFILE);

      open( HOMEZONEFILE, "<$sc_template_homezone_file" ) || file_open_error(
          "$sc_template_homezone_file", 'Could not find file', __FILE__, __LINE__ );
      while (<HOMEZONEFILE>) {
          $full_template_homezone_file .= $_;
      }
      close(HOMEZONEFILE);

      $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-5" aria-controls="tabs-5" role="tab" data-toggle="tab">HTML &amp; Widgets</a></li>
ENDOFTEXT
    }
    $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-6" aria-controls="tabs-6" role="tab" data-toggle="tab">HomePage Widget File</a></li>
ENDOFTEXT
    if ( $sc_template_advanced_tabs_enabled eq 'yes' ) {
          $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-8" aria-controls="tabs-8" role="tab" data-toggle="tab">Manifest File</a></li>
<li role="presentation"><a href="#tabs-9" aria-controls="tabs-9" role="tab" data-toggle="tab">Language Override</a></li>
ENDOFTEXT
    }

    $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-11" aria-controls="tabs-11" role="tab" data-toggle="tab">Copy</a></li>
ENDOFTEXT

    if ( $sm_templateOptions ) {
        $page_output .= <<ENDOFTEXT;
<li role="presentation"><a href="#tabs-12" aria-controls="tabs-12" role="tab" data-toggle="tab">Delete</a></li>
ENDOFTEXT
    }
    $page_output .= <<ENDOFTEXT;
    <li role="presentation"><a href="#tabs-14" aria-controls="tabs-14" role="tab" data-toggle="tab">Install</a></li>
</ul>

<div class="tab-content">

<div class="tab-pane active" id="tabs-1">
<form class="form-horizontal" action="manager.cgi" method="post">
<input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">

<p><br></p>

    <p>This area allows you to chose a header and footer template, from those currently installed, that will be used by default in the design/look of your store -- the default design applied store wide unless customized pages or templates are found per each product or category.  Creating Using your own headers/footers is fairly easy for those with HTML editing skills/experience. For easier setup, use a template already available.</p>

    <p><hr></p>
    <p><br></p>
    $sm_templatelinks
    <p><br><br></p>

    <p><b>Enable Template's CSS file? &nbsp; <a data-toggle="collapse" href="#templateCSSfile" aria-expanded="false" aria-controls="templateCSSfile"><i class="fa fa-info-circle"></i></a></b> <span style="padding-left: 25px;"></span><select name="sc_template_css_enabled">
    <option>$sc_template_css_enabled</option>
    <option>yes</option>
    <option>no</option>
    </select></p>
    <div class="collapse" id="templateCSSfile">
         <div class="well">
             <p>This allows you to load a template specific CSS file with rules/code you add manually to override any CSS rules from the CSS frameworks used by your template. This file will load after all the other CSS files are loaded.</p>
             <p>Default is YES, disable by setting to NO. If enabled, an editor tab will appear after these settings are saved.</p>
         </div>
     </div>
     <p><hr></p>

     <p><b>Do you wish to use a custom Javascript file? &nbsp; <a data-toggle="collapse" href="#templateJSfile" aria-expanded="false" aria-controls="templateJSfile"><i class="fa fa-info-circle"></i></a></b> <span style="padding-left: 25px;"></span><select name="sc_template_js_enabled">
     <option>$sc_template_js_enabled</option>
     <option>no</option>
     <option>yes</option>
     </select></p>
     <div class="collapse" id="templateJSfile">
          <div class="well">
              <p>This allows you to load a custom JS (javascript) file with rules/code you add manually for any additional template specific javascript you need. This file will load after all the other javascript files are loaded.</p>
              <p>Default is NO, enable by setting to YES. If enabled, an editor tab will appear after these settings are saved.</p>
              <p>TIP: for speed considerations, do not enable unless you need to add javascript code that cannot be added elsewhere.</p>
          </div>
      </div>
      <p><hr></p>

      <p><b>Do you wish to display advanced template features? &nbsp; <a data-toggle="collapse" href="#templateAdvancedTabs" aria-expanded="false" aria-controls="templateAdvancedTabs"><i class="fa fa-info-circle"></i></a></b> <span style="padding-left: 25px;"></span><select name="sc_template_advanced_tabs_enabled">
      <option>$sc_template_advanced_tabs_enabled</option>
      <option>no</option>
      <option>yes</option>
      </select></p>
      <div class="collapse" id="templateAdvancedTabs">
           <div class="well">
               <p>This allows you to display the advanced features of this template manager.</p>
               <p>Default is NO, enable by setting to YES. If enabled, an advanced tabs will appear after these settings are saved.</p>
               <p>TIP: Only enable if you need to edit the template's manifest file (supplied by the template's creator) OR you need to copy the template to create a new template or make substantial edits you do not want overwritten by a template upgrade.</p>
           </div>
       </div>
       <p><hr></p>

       <p><b>Display Categories (and sub categories if enabed): &nbsp; <a data-toggle="collapse" href="#dispCats" aria-expanded="false" aria-controls="dispCats"><i class="fa fa-info-circle"></i></a></b><span style="padding-left: 20px;"></span><select name="sc_displayDynamicCategories">
       <option selected>$sc_displayDynamicCategories</option>
       <option>yes</option>
       <option>no</option>
       </select></p>
       <div class="collapse" id="dispCats">
           <div class="well">
               <p>This will enable or disable the displaying of your product category lists.</p>
               <p>NOTE: This is legacy feature as these lists can be enabled and disabled by assigning of widgets displaying category lists to a template, so make sure it has the intended effects if you enable or disble it here.</p>
           </div>
       </div>
       <p><hr></p>

    <p><b>Store Name / Title: &nbsp; <a data-toggle="collapse" href="#storeTitle" aria-expanded="false" aria-controls="storeTitle"><i class="fa fa-info-circle"></i></a></b><span style="padding-left: 25px;"></span><input name="sc_headerStoreTitle" type="text" class="form-control" maxlength="45" value="$sc_headerStoreTitle"></p>
    <div class="collapse" id="storeTitle">
        <div class="well">
              <p>This is the store name/title diplayed to your customers in the heading of suported templates. 45 characters max. The shorter the better to ensure the store template does not get distorted due to the long text line. Leave blank if you do not want this line to show.</p>
              <p>Do not use special metacharacters (\$,%,&,\@ etc) nor double quotes.</p>
        </div>
    </div>
    <p><hr></p>

    <p><b>Store Tag Line: &nbsp; <a data-toggle="collapse" href="#storeTagLine" aria-expanded="false" aria-controls="storeTagLine"><i class="fa fa-info-circle"></i></a></b><span style="padding-left: 25px;"></span><input name="sc_headerStoreTagLine" type="text" class="form-control" maxlength="60" value="$sc_headerStoreTagLine"></p>
    <div class="collapse" id="storeTagLine">
        <div class="well">
              <p>This is located just beneath the Store title listed above. 60 characters max.  The shorter the better to ensure the store template does not get distorted due to the long text line. Leave blank if you do not want this line to show.</p>
              <p>Do not use special metacharacters (\$,%,&,\@ etc) nor double quotes.</p>
        </div>
    </div>

    <p><hr></p>

    <p>Button Set images have been deprecated and removed as of the Route 66 version.  All button coloring, styling, etc is handled via CSS3 in each template. The default for buttons are based on the Bootstrap framework.</p>

    <p>NOTE: You can use your own templates if you wish, but this will require you to create your own header and footer .tpl files and upload them to the store's <i>$sc_hedfut_templates_dir/TemplateNameHere</i> sub-directory of your chosing along with the .css and template_manifest.inc files for your customized template.</p>


    <!--<p>If you wish to use custom header and/or footer files by category name, you will need to create those files separately and place them in the <i>$sc_hedfut_templates_dir/TemplateNameHere</i> sub-directory of your store (using the formats of header-CATEGORY-NAME-HERE.inc and/or footer-CATEGORY-NAME-HERE.inc, which is detected automatically if enabled in the <a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&change_store_layout_screen=yes">Layout & Design Settings: Misc</a> Manager).  <i>Make sure to upload all HTML and CSS files in ASCII (text only) mode.</i></p>-->


    <p><br><br></p>
    <input type="hidden" name="system_edit_success" value="yes">
    <input name="ChangeTemplateSettings" type="hidden" value="Submit">
    <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template Choice</button>
    <p><br><br><br></p>

    </form>
	</div>


        <!-- End of tab 1 -->


    <div class="tab-pane" id="tabs-2">
    <form class="form-horizontal" action="manager.cgi" method="post">
    <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">

    <p><br></p>
    <h2 class="mgr-page-title"><b>Social Media Buttons</b></h2>

    <p>This area allows you to enable social media icons in you template. Enter the URL for each platform to enable. Leave blank to disable. If the social media platform you wish to use is not shown below, then it is not supported automatically by your selected template.</p>

    <p><hr></p>

    $socialbuttons

          <p><br></p>
          <input type="hidden" name="system_edit_success" value="yes">
          <input name="ChangeTempSocialSettings" type="hidden" value="Submit">
          <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Social Media Buttons</button>
          <p><br><br><br></p>

          </form>
	</div>


        <!-- End of tab 2 -->



	<div class="tab-pane" id="tabs-3">
        <p><br></p>
        <h2 class="mgr-page-title"><b>CSS File Editor</b></h2>
        <p><br></p>

        <p class="well">This manager allows you to edit the your selected template's CSS (cascading style sheet).</p>
        <p><br></p>


        <p><b>HEX Color Picker - for use in your CSS file: &nbsp; <a data-toggle="collapse" href="#HEXcolorPicker" aria-expanded="false" aria-controls="HEXcolorPicker">Click Here to View &nbsp;<i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="HEXcolorPicker">
          <div class="well">
            $css_output
          </div>
        </div>

        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">

        <p><b>Template CSS File: &nbsp; <a data-toggle="collapse" href="#editCSSfile" aria-expanded="false" aria-controls="editCSSfile"><i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="editCSSfile">
          <div class="well">
          <p>Below is the current Template CSS file and located at: <b>$sc_template_css_file</b> <br>Feel free to do any edits using the file contents box below, or you may download the Template CSS file via FTP and make the changes manually.</p>
          <p>This file loads after all the CSS framework files and will override any CSS styling that came before it.</p>
          </div>
        </div>
        <textarea name="changed_template_CSS_file" class="form-control" rows="30" wrap=off>$full_template_css_file</textarea>
        <p><br><br></p>

        <p><br><br></p>
        <input type="hidden" name="system_edit_success" value="yes">
        <input name="ChangeTemplateCSSfile" type="hidden" value="Submit">
        <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template CSS File</button>
        <p><br><br><br></p>

        </form>
	</div>


    <!-- End of tab 3 -->


	<div class="tab-pane" id="tabs-4">
        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Javascript (JS) File Editor</b></h2>
        <p><br></p>

        <p><b>Template JS File: &nbsp; <a data-toggle="collapse" href="#JSfileEditor" aria-expanded="false" aria-controls="JSfileEditor"><i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="JSfileEditor">
          <div class="well">
          <p>Below is the current Javascript file for the selected template. It is located at: <b>$sc_template_js_file</b> <br>Feel free to do any edits using the file contents box below, or you may download the Template Javascript file via FTP and make the changes manually.</p>
          <p>This file is where template specific Javascript/JS code is added.  IF you need additional JS code, add it here. It is loaded after all platforms, such a jQuery or Bootstrap, is loaded. Anything loaded prior to this file will be used first, so it must be unique or it will be ignored.</p>
          </div>
        </div>
        <textarea name="changed_template_JS_file" class="form-control" rows="30" wrap=off>$full_template_js_file</textarea>
        <p><br><br></p>

        <p><br><br></p>
        <input type="hidden" name="system_edit_success" value="yes">
        <input name="SaveTemplateJSfile" type="hidden" value="Submit">
        <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template JS File</button>
        <p><br><br><br></p>

        </form>
	</div>


    <!-- End of tab 4 -->


    <div class="tab-pane" id="tabs-5">
          <form class="form-horizontal" action="manager.cgi" method="post">
          <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
          <p><br></p>
          <h2 class="mgr-page-title"><b>Template: HTML &amp; Widgets File Editor</b></h2>
          <p><br></p>

          <p><b>HTML &amp; Widgets File: &nbsp; <a data-toggle="collapse" href="#templateHTMLwidgets" aria-expanded="false" aria-controls="templateHTMLwidgets"><i class="fa fa-info-circle"></i></a></b></p>
          <div class="collapse" id="templateHTMLwidgets">
            <div class="well">
            <p>Below is the current template file for the HTML & Widget variables and scaffolding that your selected template creates and/or overrides. This file is located at: <b>$sc_template_widgets_file</b> <br>Feel free to do any edits using the file contents box below, or for better control and reduced problems, you may manually download the Template HTML &amp; Widgets file via FTP and make the changes manually.</p>
            <p>HTML Widgets are generic HTML code snippets that the cart uses as a mini-like template for displaying data and other items in your store. Instead of editing code directly in your template headers and footers, or in the core application code, these widgets allow you to find and make changes quickly or override defaults by cutting and pasting entire widgets into the file below along with any changes you need for CSS styling or wording.<p>
            <p>HTML Widgets also allow positioning elements in different locations without altering the code. But note some widgets are designed for certain areas or formats, so additional widgets might need to be created with the desired formatting if the original format is still desired elsewhere.</p>
            </div>
          </div>
          <textarea name="changed_template_widgets_file" class="form-control" rows="30" wrap=off>$full_template_widgets_file</textarea>
          <p><br><br></p>

          <p><br><br></p>
          <input type="hidden" name="system_edit_success" value="yes">
          <input name="ChangeTemplateHTMLwidgets" type="hidden" value="Submit">
          <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template HTML Widgets</button>
          <p><br><br><br></p>

          </form>
  	</div>


      <!-- End of tab 5 -->

      <div class="tab-pane" id="tabs-6">
            <form class="form-horizontal" action="manager.cgi" method="post">
            <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
            <p><br></p>
            <h2 class="mgr-page-title"><b>Template: Home Page (ZoneHome) Widgets File Editor</b></h2>
            <p><br></p>

            <p><b>Home Page (ZoneHome) Widgets File: &nbsp; <a data-toggle="collapse" href="#templateZoneHomeWidgets" aria-expanded="false" aria-controls="templateZoneHomeWidgets"><i class="fa fa-info-circle"></i></a></b></p>
            <div class="collapse" id="templateZoneHomeWidgets">
              <div class="well">
              <p>Below is the current template file for the Home Page, or ZoneHome, Widget variables and scaffolding that your selected template creates and/or overrides. This file is located at: <b>$sc_template_homezone_file</b></p>
              <p>Home Page, or ZoneHome, Widgets are generic HTML code snippets that the cart uses as a mini-like template for displaying data and other items in your store. Instead of editing code directly in your template headers and footers, or in the core application code, these widgets allow you to find and make changes quickly or override defaults by cutting and pasting entire widgets into the file below along with any changes you need for CSS styling or wording.<p>
              <p>ZoneHome Widgets also allow positioning elements in different locations without altering the code. Howver to change the content, the individual widgets must be edited within the raw HTML code, for such things as title, product specs & links, descriptions, and other information changes.</p>
              <p>NOTE: Technically these template supplied widgets and any custom widgets you create acan be used on the main content areas of other pages, such as on an about us page, shipping info page, return policy, individual product information pages, etc.
              </div>
            </div>
            <textarea name="changed_template_homezone_widgets_file" class="form-control" rows="30" wrap=off>$full_template_homezone_file</textarea>
            <p><br><br></p>

            <p><br><br></p>
            <input type="hidden" name="system_edit_success" value="yes">
            <input name="ChangeTemplateZoneHomeWidgets" type="hidden" value="Submit">
            <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template ZoneHome Widgets</button>
            <p><br><br><br></p>

            </form>
    	</div>


        <!-- End of tab 6 -->


ENDOFTEXT

    if ( $sc_template_advanced_tabs_enabled eq 'yes' ) {
            $page_output .= <<ENDOFTEXT;
    <div class="tab-pane" id="tabs-8">

        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Advanced Feature: Template Manifest Editor</b></h2>
        <p><br></p>


        <p><b>Template Manifest File: &nbsp; <a data-toggle="collapse" href="#templateManifest" aria-expanded="false" aria-controls="templateManifest"><i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="templateManifest">
          <div class="well">
          <p>Below is the current manifest file for the your selected template that sets the locations and versions of CSS, JS, and other files needed for the template to work properly. This file is located at: <b>$temp_manifest_location</b> <br>Feel free to do any edits using the file contents box below, or for better control and reduced problems, you may manually download the Template Manifest file via FTP and make the changes manually.</p>
          </div>
        </div>
        <textarea name="changed_template_manifest_file" class="form-control" rows="30" wrap="off">$full_template_manifest_file</textarea>
        <p><br><br></p>

        <p><br><br></p>
        <input type="hidden" name="system_edit_success" value="yes">
        <input name="ChangeTemplateManifest" type="hidden" value="Submit">
        <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Template Manifest File</button>
        <p><br><br><br></p>

        </form>
  </div>


    <!-- End of tab 8 -->

    <div class="tab-pane" id="tabs-9">

        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Advanced Feature: Template Language Override File Editor</b></h2>
        <p><br></p>

        <p><b>Default language File - For Your Reference: &nbsp; <a data-toggle="collapse" href="#defaultLangFile" aria-expanded="false" aria-controls="defaultLangFile">Click Here to View &nbsp;<i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="defaultLangFile">
          <div class="well">
            <textarea name="donotchangethis" class="form-control" rows="30" wrap="off">$full_language_file</textarea>
          </div>
        </div>


        <p><b>Template Language Override File: &nbsp; <a data-toggle="collapse" href="#templateLangFile" aria-expanded="false" aria-controls="templateLangFile"><i class="fa fa-info-circle"></i></a></b></p>
        <div class="collapse" id="templateLangFile">
          <div class="well">
          <p>Below is the current language override file for the your selected template. This file allows your to edit language items for your store front that are contained in the default language file, using variable names (must be the exact same ones in the default language file to override/replace the default). Things you can override are messages, button names, generic page titles, etc. You can even add new variables needed for your templates and page layouts. This file is located at: <b>lang_override_location</b> <br><br>NOTE: THere are 3 language files that can be loaded. The first is the default language file. Second is one the template designer adds to your template to override and add items specific to the template. Last, this one loads so that you can override anything set in the other files, such as cart messages, default page titles, button text, etc.</p>
          </div>
        </div>
        <textarea name="changed_user_language_override_file" class="form-control" rows="30" wrap="off">$full_language_override_file</textarea>
        <p><br><br></p>

        <p><br><br></p>
        <input type="hidden" name="system_edit_success" value="yes">
        <input name="ChangeLangOverrideFile" type="hidden" value="Submit">
        <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Your language Override File</button>
        <p><br><br><br></p>

        </form>
  </div>


    <!-- End of tab 9 -->

ENDOFTEXT
        }
        $page_output .= <<ENDOFTEXT;

	<div class="tab-pane" id="tabs-11">

        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Copy Template</b></h2>
        <p><br></p>

         <p><b>Select Template to Copy: &nbsp; <a data-toggle="collapse" href="#selectTemplate2Copy" aria-expanded="false" aria-controls="selectTemplate2Copy"><i class="fa fa-info-circle"></i></a></b><span style="padding-left: 25px;"></span><select name="sm_template_to_change_id" required>
         $sm_templateSelectedOption
         <option value=""></option>
         $sm_templateOptions
         </select></p>
         <div class="collapse" id="selectTemplate2Copy">
              <div class="well">
                  <p>First template name listed is the currently selected template used by your store.</p>
              </div>
          </div>
          <p><hr></p>


           <p><b>New Template Name: &nbsp; <a data-toggle="collapse" href="#newTemplateName" aria-expanded="false" aria-controls="newTemplateName"><i class="fa fa-info-circle"></i></a></b><input name="sm_template_new_name" class="form-control" type="text" maxlength="50" placeholder="$sm_template_name" required></p>
           <div class="collapse" id="newTemplateName">
                <div class="well">
                    <p>Enter a name for the new template.</p>
                    <p>Can include spaces and the following 2 characters: - . (dash and period/dot)</p>
                </div>
            </div>
            <p><hr></p>


            <p><b>New Template ID: &nbsp; <a data-toggle="collapse" href="#newTemplateID" aria-expanded="false" aria-controls="newTemplateID"><i class="fa fa-info-circle"></i></a></b><input name="sm_template_new_id" class="form-control" type="text" maxlength="50" placeholder="$sm_template_id" required></p>
            <div class="collapse" id="newTemplateID">
                 <div class="well">
                     <p>Enter a ID for the new template.  Recommend that you use a ID similar to the new name entered above</p>
                     <p>Replace spaces with an underscore character "_"</p>
                     <p>Replace period characters, ".", with an the word "dot"</p>
                     <p>Dash characters "-" are okay to use.</p>
                     <p>All other characters other than letters (any case) and numbers should not be used.</p>
                 </div>
             </div>
             <p><hr></p>


                <p><br><br></p>
                <input type="hidden" name="system_edit_success" value="yes">
                <input name="CopyAtemplate" type="hidden" value="Submit">
                <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Copy Selected Template</button>
                <p><br><br><br></p>

                </form>
	</div>


    <!-- End of tab 11 -->

ENDOFTEXT

        if ( $sm_templateOptions ) {
            $page_output .= <<ENDOFTEXT;


    <div class="tab-pane" id="tabs-12">
        <form class="form-horizontal" action="manager.cgi" method="post">
        <input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Delete Unused Template</b></h2>
        <p><br></p>
        <input type="hidden" name="current_template_id" value="$sm_template_id">

         <p><b>Select an Unused Template to Delete: &nbsp; <a data-toggle="collapse" href="#selectTemplate2Delete" aria-expanded="false" aria-controls="selectTemplate2Delete"><i class="fa fa-info-circle"></i></a></b><span style="padding-left: 25px;"></span><select name="sm_template_to_delete_id" required>
         <option value=""></option>
         $sm_templateOptions
         </select></p>
         <div class="collapse" id="selectTemplate2Delete">
              <div class="well">
                  <p>The currently selected/used template is not available for deletion, until changed and saved in the template tab.</p>
                  <p><b>WARNING:</b> This action is not reversable.</p>
              </div>
          </div>
          <p><hr></p>


                <p><br><br></p>
                <input type="hidden" name="system_edit_success" value="yes">
                <input name="DeleteAtemplate" type="hidden" value="Submit">
                <button class="btn btn-primary btn-lg mgr-center" style="display: block;">Delete Selected Template</button>
                <p><br><br><br></p>

                </form>

    </div>


    <!-- End of tab 12 -->

ENDOFTEXT
        }

        # read official & freebie templates
        my $memtempl_count = 0;
        my $url = 'https://agoracart.com/downloadupdates/Route66/comtemplates66.txt';
        my $content  = &simple_secure_URL_file_getter($url);
        @templline = split( /\n/, $content );

        foreach my $line (@templline) {
            my ( $templkey, $templname, $templcssframework, $templuse, $templimg, $templnotes ) = split( /\|/, $line );
            chomp $templnotes;

            # check if exists. If already installed, skip
            if ( !(-e "$sc_hedfut_templates_dir/$templkey") ) {
                $memtempl_count++;
                $memtempl_output .= qq~
    <div class="row">
        <div class="col-md-3">
                <img class='img-responsive' style="padding-left:28px" src="$templimg">
        </div>
        <div class="col-md-9">
            <p class="text-left"><h3>$templname</h3><b>CSS Framework:</b> $templcssframework<br><b>Target Uses:</b> $templuse<br><b>Template Notes:</b> $templnotes</p>
            <form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
                <input type="hidden" name="system_edit_success" value="yes">
                <input name="template_key" type="hidden" value="$templkey">
                <input name="InstallTemplate" type="hidden" value="Submit">
                <button class="btn btn-primary">Install: $templname</button>
            </form>

        </div>
    </div><p><hr></p>\n~;

            }
        }
        if ( $memtempl_count < 1 ) {
            $memtempl_output = qq~
            <p class="text-center"><b>No Additional Templates Available</b></p>~;
        }

        $page_output .= <<ENDOFTEXT;

    <div class="tab-pane" id="tabs-14">
        <p><br></p>
        <h2 class="mgr-page-title"><b>Install a New Template</b></h2>
        <p><br></p>
        <p>This area allows you to install official templates available to you from AgoraCart. Only templates not currently installed are listed. All other template packages (custom created or from marketplace) must be uploaded manually via FTP to your store template directories located at: $sc_hedfut_templates_dir .  You may also copy an existing template and then customize it to your needs in the various tabs of this template manager.</p>
        <p><br></p>
        <h3 class='mgr-page-title'>"Community Version" Templates - Available for Install</h3>
        <p><br></p>
        $memtempl_output
        <p><br></p>

    </div>


    <!-- End of tab 14 -->

</div>
<p><br><br></p>
</div>

ENDOFTEXT

    $page_output .= &$manager_page_footer;
    print $page_output;
}

#######################################################################

1;
