From 8d87c7184953fdf4610178818d0fae97809f2c20 Mon Sep 17 00:00:00 2001
From: simith <simith@inlibro.com>
Date: Thu, 20 Nov 2014 09:14:36 -0500
Subject: [PATCH] Create a link to the last advanced search in search result
 page (OPAC)

http://bugs.koha-community.org/show_bug.cgi?id=13307
---
 .htaccess                                          |   9 --
 .../opac-tmpl/bootstrap/en/includes/masthead.inc   |  12 ++
 .../bootstrap/en/modules/opac-advsearch.tt         |  62 +++++++++-
 .../opac-tmpl/bootstrap/en/modules/opac-results.tt |  13 +-
 .../lib/jquery/plugins/jquery.cookie.min.js        |  72 +++++++++++
 .../lib/jquery/plugins/jquery.deserialize.js       | 134 +++++++++++++++++++++
 opac/opac-search.pl                                |  21 ++++
 7 files changed, 307 insertions(+), 16 deletions(-)
 delete mode 100644 .htaccess
 create mode 100644 koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.cookie.min.js
 create mode 100644 koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.deserialize.js

diff --git a/.htaccess b/.htaccess
deleted file mode 100644
index 493fba5..0000000
--- a/.htaccess
+++ /dev/null
@@ -1,9 +0,0 @@
-# .htaccess
-
-ErrorDocument 400 /cgi-bin/koha/errors/400.pl
-ErrorDocument 401 /cgi-bin/koha/errors/401.pl
-ErrorDocument 403 /cgi-bin/koha/errors/403.pl
-ErrorDocument 404 /cgi-bin/koha/errors/404.pl
-ErrorDocument 500 /cgi-bin/koha/errors/500.pl
-
-
diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/masthead.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/masthead.inc
index 94dec72..aeebb1d 100644
--- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/masthead.inc
+++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/masthead.inc
@@ -316,3 +316,15 @@
             </div>
         </form> <!-- /#auth -->
     </div>  <!-- /#modalAuth  -->
+
+<script type="text/javascript">
+document.getElementById("searchsubmit").onclick=function(){
+    var exp = new Date();
+    exp.setTime(exp.getTime()-1);
+    document.cookie = "form_serialized=null; path=/; expires=" + exp.toGMTString();
+    document.cookie = "form_serialized_itype=null; path=/; expires=" + exp.toGMTString();
+    document.cookie = "form_serialized_limits=null; path=/; expires=" + exp.toGMTString();
+    document.cookie = "num_paragraph=null; path=/; expires=" + exp.toGMTString();
+    document.cookie = "search_path_code=null; path=/; expires=" + exp.toGMTString();
+};
+</script>
diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-advsearch.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-advsearch.tt
index 12dd94f..df35798 100644
--- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-advsearch.tt
+++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-advsearch.tt
@@ -248,7 +248,7 @@
                                     <div class="span3">
                                         <fieldset>
                                             <legend>Audience</legend>
-                                            <select name="limit" class="subtype">
+                                            <select id="subtype_audience" name="limit" class="subtype">
                                             <option value="" selected="selected" class="menuheader">Any audience</option>
                                                 <option value="aud:a">Preschool</option>
                                                 <option value="aud:b">Primary</option>
@@ -265,7 +265,7 @@
                                     <div class="span3">
                                         <fieldset>
                                             <legend>Content</legend>
-                                            <select name="limit" class="subtype">
+                                            <select id="subtype_content"  name="limit" class="subtype">
                                                 <option value="" selected="selected" class="menuheader">Any content</option>
                                                 <option value="fic:1">Fiction</option>
                                                 <option value="fic:0">Non fiction</option>
@@ -279,7 +279,7 @@
                                     <div class="span3">
                                         <fieldset>
                                             <legend>Format</legend>
-                                            <select name="limit" class="subtype">
+                                            <select id="subtype_format" name="limit" class="subtype">
                                                 <option value="" selected="selected" class="menuheader">Any format</option>
                                                 <option value="l-format:ta">Regular print</option>
                                                 <option value="l-format:tb">Large print</option>
@@ -298,7 +298,7 @@
                                     <div class="span3">
                                         <fieldset>
                                             <legend>Additional content types for books/printed materials</legend>
-                                            <select name="limit" class="subtype">
+                                            <select id="subtype_additional" name="limit" class="subtype">
                                                 <option value="">Any</option>
                                                 <option value="ctype:a">Abstracts/summaries</option>
                                                 <option value="ctype:b">Bibliographies</option>
@@ -372,10 +372,60 @@
 [% END %]
 
 [% BLOCK jsinclude %]
+<script type="text/javascript" src="[% interface %]/[% theme %]/lib/jquery/plugins/jquery.deserialize.js"></script>
+<script type="text/javascript" src="[% interface %]/[% theme %]/lib/jquery/plugins/jquery.cookie.min.js"></script>
 <script type="text/javascript">//<![CDATA[
-    $(document).ready(function() {
-        $('#advsearches').tabs();
+$(document).ready(function() {
+    $('#advsearches').tabs();
+    jQuery.cookie.json = true;
+    //$('#advsearches > ul').tabs();
+
+    [% IF ( ReturnToSearch ) %]
+        if (form_serialized = jQuery.cookie("form_serialized")) {
+            $('#advsearch form').deserialize(form_serialized);
+        }
+        if (form_serialized_limits = jQuery.cookie("form_serialized_limits")) {
+            $('#language-limit')     .val(form_serialized_limits[0]);
+            $('#branchloop')         .val(form_serialized_limits[1]);
+            $('#subtype_audience')   .val(form_serialized_limits[2]);
+            $('#subtype_content')    .val(form_serialized_limits[3]);
+            $('#subtype_format')     .val(form_serialized_limits[4]);
+            $('#subtype_additional') .val(form_serialized_limits[5]);
+            $('#locloop')            .val(form_serialized_limits[6]);
+        }
+    [% ELSE %]
+        //Clear all form cookies
+        jQuery.cookie("form_serialized", null,{ path: '/'});
+        jQuery.cookie("form_serialized_itype", null,{ path: '/'});
+        jQuery.cookie("form_serialized_limits", null,{ path: '/'});
+        jQuery.cookie("num_paragraph", null,{ path: '/'});
+        jQuery.cookie("search_path_code", null,{ path: '/'});
+    [% END %]
+    $('#advsearch form').submit(function() {
+        form_serialized = $(this).serialize();
+        jQuery.cookie("form_serialized", form_serialized,{ path: '/'});
+        form_serialized_limits = [
+            $('#language-limit').val(),   $('#branchloop').val(),
+            $('#subtype_audience').val(), $('#subtype_content').val(),
+            $('#subtype_format').val(),   $('#subtype_additional').val(),
+            $('#locloop').val()
+        ];
+        jQuery.cookie("form_serialized_limits", form_serialized_limits,{ path: '/'});
+        [% IF ( expanded_options ) %]
+        var numPar = $("#booleansearch fieldset p").size();
+        if (numPar > [% search_boxes_count %]){
+            jQuery.cookie("num_paragraph", numPar,{ path: '/'});
+        }else{
+            jQuery.cookie("num_paragraph", null,{ path: '/'});
+        }
+        jQuery.cookie("search_path_code", 'exs',{ path: '/'});
+        [% ELSE %]
+        jQuery.cookie("search_path_code", 'ads',{ path: '/'});
+        jQuery.cookie("num_paragraph", null,{ path: '/'});
+        [% END %]
     });
+
+});
     /* This function allows to display a new field to search.
     */
     $(document).on("click", '.ButtonPlus', function(e) {
diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-results.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-results.tt
index 72a3a89..16d6319 100644
--- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-results.tt
+++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-results.tt
@@ -46,6 +46,11 @@
                                 You did not specify any search criteria.
                             [% END %]
                         </p>
+                        [% IF ( ReturnPath ) %]
+                           <div class="returntosearch">
+                                <p><a href="[% ReturnPath %]">Return to the last advanced search</a></p>
+                            </div>
+                        [% END %]
                         [% IF ( OPACNoResultsFound ) %]
                             <div id="noresultsfound">
                                 [% OPACNoResultsFound %]
@@ -102,7 +107,13 @@
                             [% END %]
                         </ul>
                     [% END # / IF koha_spsuggest%]
-
+                    [% IF ( total ) %]
+                        [% IF ( ReturnPath ) %]
+                            <div class="returntosearch">
+                                <p><a href="[% ReturnPath %]">Return to the last advanced search</a></p>
+                            </div>
+                        [% END %]
+                    [% END %]
                     [% IF ( query_error ) %]
                         <div class="dialog alert">
                             <h4>Error:</h4>
diff --git a/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.cookie.min.js b/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.cookie.min.js
new file mode 100644
index 0000000..2d4c05a
--- /dev/null
+++ b/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.cookie.min.js
@@ -0,0 +1,72 @@
+/*!
+ * jQuery Cookie Plugin v1.3
+ * https://github.com/carhartl/jquery-cookie
+ *
+ * Copyright 2011, Klaus Hartl
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.opensource.org/licenses/GPL-2.0
+ */
+(function ($, document, undefined) {
+
+	var pluses = /\+/g;
+
+	function raw(s) {
+		return s;
+	}
+
+	function decoded(s) {
+		return decodeURIComponent(s.replace(pluses, ' '));
+	}
+
+	var config = $.cookie = function (key, value, options) {
+
+		// write
+		if (value !== undefined) {
+			options = $.extend({}, config.defaults, options);
+
+			if (value === null) {
+				options.expires = -1;
+			}
+
+			if (typeof options.expires === 'number') {
+				var days = options.expires, t = options.expires = new Date();
+				t.setDate(t.getDate() + days);
+			}
+
+			value = config.json ? JSON.stringify(value) : String(value);
+
+			return (document.cookie = [
+				encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
+				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
+				options.path    ? '; path=' + options.path : '',
+				options.domain  ? '; domain=' + options.domain : '',
+				options.secure  ? '; secure' : ''
+			].join(''));
+		}
+
+		// read
+		var decode = config.raw ? raw : decoded;
+		var cookies = document.cookie.split('; ');
+		for (var i = 0, l = cookies.length; i < l; i++) {
+			var parts = cookies[i].split('=');
+			if (decode(parts.shift()) === key) {
+				var cookie = decode(parts.join('='));
+				return config.json ? JSON.parse(cookie) : cookie;
+			}
+		}
+
+		return null;
+	};
+
+	config.defaults = {};
+
+	$.removeCookie = function (key, options) {
+		if ($.cookie(key) !== null) {
+			$.cookie(key, null, options);
+			return true;
+		}
+		return false;
+	};
+
+})(jQuery, document);
diff --git a/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.deserialize.js b/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.deserialize.js
new file mode 100644
index 0000000..a0e98ce
--- /dev/null
+++ b/koha-tmpl/opac-tmpl/bootstrap/lib/jquery/plugins/jquery.deserialize.js
@@ -0,0 +1,134 @@
+/**
+ * @author Kyle Florence <kyle[dot]florence[at]gmail[dot]com>
+ * @website https://github.com/kflorence/jquery-deserialize/
+ * @version 1.2.1
+ *
+ * Dual licensed under the MIT and GPLv2 licenses.
+ */
+(function( jQuery, undefined ) {
+
+var push = Array.prototype.push,
+    rcheck = /^(?:radio|checkbox)$/i,
+    rplus = /\+/g,
+    rselect = /^(?:option|select-multiple)$/i,
+    rvalue = /^(?:button|select-one|color|date|datetime|datetime-local|email|hidden|month|number|password|range|reset|search|submit|tel|text|textarea|time|url|week)$/i;
+
+function getElements( elements ) {
+    return elements.map(function() {
+            return this.elements ? jQuery.makeArray( this.elements ) : this;
+        }).filter( ":input:not(:disabled)" ).get();
+}
+
+function getElementsByName( elements ) {
+    var current,
+        elementsByName = {};
+
+    jQuery.each( elements, function( i, element ) {
+        current = elementsByName[ element.name ];
+        elementsByName[ element.name ] = current === undefined ? element :
+            ( jQuery.isArray( current ) ? current.concat( element ) : [ current, element ] );
+    });
+
+    return elementsByName;
+}
+
+jQuery.fn.deserialize = function( data, options ) {
+    var i, length,
+        elements = getElements( this ),
+        normalized = [];
+
+    if ( !data || !elements.length ) {
+        return this;
+    }
+
+    if ( jQuery.isArray( data ) ) {
+        normalized = data;
+
+    } else if ( typeof data === "string" ) {
+        var parts;
+
+        data = data.split( "&" );
+
+        for ( i = 0, length = data.length; i < length; i++ ) {
+            parts =  data[ i ].split( "=" );
+            push.call( normalized, {
+                name: decodeURIComponent( parts[ 0 ] ),
+                value: decodeURIComponent( parts[ 1 ].replace( rplus, "%20" ) )
+            });
+        }
+    }
+
+    if ( !( length = normalized.length ) ) {
+        return this;
+    }
+
+    var current, element, j, len, name, property, type, value,
+        change = function() {},
+        complete = function() {},
+        names = {};
+
+    options = options || {};
+    elements = getElementsByName( elements );
+
+    // Backwards compatible with old arguments: data, callback
+    if ( jQuery.isFunction( options ) ) {
+        complete = options;
+
+    } else {
+        change = jQuery.isFunction( options.change ) ? options.change : change;
+        complete = jQuery.isFunction( options.complete ) ? options.complete : complete;
+    }
+
+    for ( i = 0; i < length; i++ ) {
+        current = normalized[ i ];
+
+        name = current.name;
+        value = current.value;
+
+        if ( !( element = elements[ name ] ) ) {
+            continue;
+        }
+
+        type = ( len = element.length ) ? element[ 0 ] : element;
+        type = ( type.type || type.nodeName ).toLowerCase();
+        property = null;
+
+        if ( rvalue.test( type ) ) {
+            if ( len ) {
+                j = names[ name ];
+                element = element[ names[ name ] = ( j == undefined ) ? 0 : ++j ];
+            }
+
+            if (element) {
+                change.call( element, ( element.value = value ) );
+            }
+
+        } else if ( rcheck.test( type ) ) {
+            property = "checked";
+
+        } else if ( rselect.test( type ) ) {
+            property = "selected";
+        }
+
+        if ( property ) {
+            if ( !len ) {
+                element = [ element ];
+                len = 1;
+            }
+
+            for ( j = 0; j < len; j++ ) {
+                current = element[ j ];
+
+                if ( current.value == value ) {
+                    change.call( current, ( current[ property ] = true ) && value );
+                }
+            }
+        }
+    }
+
+    complete.call( this );
+
+    return this;
+};
+
+})( jQuery );
diff --git a/opac/opac-search.pl b/opac/opac-search.pl
index e01193a..fdf35c0 100755
--- a/opac/opac-search.pl
+++ b/opac/opac-search.pl
@@ -184,6 +184,21 @@ if (C4::Context->preference('TagsEnabled')) {
 
 # load the branches
 
+if ($cgi->param("returntosearch")) {
+    $template->param('ReturnToSearch' => 1);
+}
+if ($cgi->cookie("search_path_code")) {
+    my $pathcode = $cgi->cookie("search_path_code");
+    given ($pathcode)
+    {
+        when ('"ads"') { $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1'); }
+        when ('"exs"') {
+            $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
+        }
+        default {warn "ReturnPath swith error";}
+    }
+}
+
 my $branches = GetBranches();   # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
 $template->param(
     searchdomainloop => GetBranchCategories('searchdomain'),
@@ -281,6 +296,12 @@ if ( $template_type && $template_type eq 'advsearch' ) {
     # box should only appear on the last, etc.
     my @search_boxes_array;
     my $search_boxes_count = 3; # begin whith 3 boxes
+    $template->param( search_boxes_count => $search_boxes_count );
+
+    if ($cgi->cookie("num_paragraph")){
+        $search_boxes_count = $cgi->cookie("num_paragraph");
+    }
+
     for (my $i=1;$i<=$search_boxes_count;$i++) {
         # if it's the first one, don't display boolean option, but show scan indexes
         if ($i==1) {
-- 
1.9.1