    
$(document).ready(function() {
    
    sruForm = document.SRUForm;
    
    max = $("#maxIndex").val();

    $('.resetSearch').click(function() {
            $("input:text[value!='']").removeClass('filled');
            clearForm();
    });
    
    //~ uiSwitcher
    $('#uiSwitcher span').click(function() {
        var thisEl = $(this);
        if(thisEl.hasClass('viewCtrl')) {
            var thatEl = thisEl.siblings('span.viewCtrl_sel')
            thisEl.removeClass('viewCtrl');thisEl.addClass('viewCtrl_sel');
            thatEl.removeClass('viewCtrl_sel');thatEl.addClass('viewCtrl');

            var thisAEl = $('a',thisEl)
            thisAEl.replaceWith('<span>' + thisAEl.html() + '</span>');

            var thatSpanEl = $('span',thatEl)
            thatSpanEl.replaceWith('<a>' + thatSpanEl.html() + '</a>');
            
            if(thisEl.hasClass('showQuickUI')) {
                $('#searchInfoHeader').hide();
                $('form#SRUForm').hide();
                $('#quickUI').show();
            } else {
                $('#searchInfoHeader').show()
                $('form#SRUForm').show();
                $('#quickUI').hide();
            }
        }
    });
    
    //~ toggle searchInfo
    $('#toggleSearchInfo').click(function() {
        if($('#searchInfo').css('display')=='none') { 
            $('#searchInfo').show();
            $('#showSearchInfo').hide();
            $('#hideSearchInfo').show();
        } else {
            $('#searchInfo').hide();
            $('#showSearchInfo').show();
            $('#hideSearchInfo').hide();
        }
    });
    
    // focus first / 1st filled input
    $("form[name='SRUForm'] input:text[value!='']").length > 0 ? $("input:text[value!='']").eq(0).focus() : $("input[name='term1']").focus();
    
    //mark filled input-fields
    $("input:text[value!='']").addClass('filled');
    $("input:text").blur(function(){
        $("input:text[value='']").removeClass('filled')
        $("input:text[value!='']").addClass('filled')
    })
    
    $(".checkUncheckAll").click(function() {
        var checked = $(this).hasClass("checked");
        if(checked) {
            $(this).removeClass("checked");
            $("#setCollections input").removeAttr("checked")
        } else {
            $(this).addClass("checked");
            $("#setCollections input[type='checkbox']").attr("checked", 'checked');
        }
    });
    

});

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
// reset sruForm
function clearForm() {
    for (var idx = 1; idx <= max; idx++) {
        $("#term" + idx).attr('value','');
    }
    if($("#vlAny").length) {
        $("#vlAny").attr('value','');
    }    
    if($("#genreCode").length) {
        $("#genreCode option:selected").removeAttr('selected');
    }    
    if($("#type").length) {
        $("#type option:selected").removeAttr('selected');
    }    
    if($("#vlFulltext").length) {
        $("#vlFulltext").attr('value','');
    }    
    if($("#vlStructures").length) {
        $("#vlStructures").attr('value','');
    }
    if($("#vlAny").length) {
        $("#vlAny").attr('value','');
    }
    if($("#searchLanguage").length) {
        $("#searchLanguage option:selected").removeAttr('selected');
    }
    if($("#searchDomain").length) {
        $("#searchDomain option:selected").removeAttr('selected');
    }
    if($("#searchDomain").length) {
        $("#searchDomain option:selected").removeAttr('selected');
    }
    if($('div#setCollections input').length) {
        $("#setCollections input").removeClass("checked");
        $("#setCollections input").removeAttr("checked")
    }
    if($("#sortBy option:selected").length) {
        $("#sortBy option:selected").removeAttr('selected');
    }
    if($("#sortOrder option:selected").length) {
        $("#sortOrder option:selected").removeAttr('selected');
    }
    if($("#maximumRecords option:selected").length) {
        $("#maximumRecords option:selected").removeAttr('selected');
    }
}

function prepareQueryTerm(terms){
	
	//'a "a b" a"b "a "b b " "'.match(/(\s|^)"(.*?)"(\s|$)|([^\s]*"[^\s]*)|([^\s"]+)|(\s+)|(")/g);
	//["a", " "a b" ", "a"b", " "a "b b " ", """]
	//match(/(\s|^)"(.*?)"(\s|$)|([^\s]*"[^\s]*)|([^\s"]+)|(\s+)|(")/g);
	//match(/(\s|^)"(.*?)"(\s|$)|([^\s]*"[^\s]*)|([^\s"]+)|(\s+)|(")/g);
	
    var term_parts = terms.match(/(\s|^)"(.*?)"(\s|$)|([^\s]*"[^\s]*)|([^\s"]+)|(\s+)|(")/g);
    var clean_terms = "";
        
    if(term_parts){
    	for(var i = 0; i<term_parts.length; i++){
	    	var part = term_parts[i];

	    	var quoted_part = part.match(/^\s*".*"\s*$/);
	    	var space_part = part.match(/^\s*$/);
	    	
	    	if(quoted_part || space_part){
	    		clean_terms = clean_terms.concat(part);
	    	}else{
    			var dirty_part = part.match(/(["/<>=\(\)])/g); 
    			if(dirty_part){
	    			clean_terms = clean_terms.concat('"' + part.replace(/"/g, '\\"') + '"');
    			}
    			else{
    				clean_terms = clean_terms.concat(part);
    			}
    		}
	    }
    }
    clean_terms = trim(clean_terms);
    return clean_terms;
}

// munge sruFormFields to CQL query
function mungeForm() {
    try {
        var cql = "";
        // Step through elements in form to create CQL
        for (var idx = 1; idx <= max; idx++) {
        	var term = $("#term" + idx).val();
        	term = prepareQueryTerm(term);
        	
            field = $("#index" + idx).val()
            if (term != '') {
                if(cql != '') {
                    cql += " " + $("#bool" + idx).val() + " "; 
                }
                
                if (term.indexOf(' ') > -1){
                    if (field == 'dc.identifier' || field == 'vl.signature' || field == 'dc.date'){
                        cql += field + '="' + term + '"';
                    } else {
                        cql += field + "=(" + term + ')';
                    }
                } else {
                    cql += field + "=" + term;
                }
            }
        }
        
        if (cql != ''){
            // enclose with parenthesis if terms given
            cql = "(" + cql + ")";
        };
        
        if($("#genreCode").length) {
            var genreCode = $("#genreCode").attr('value');
            if(genreCode && genreCode != '') {
                if (cql != '') {
                    cql += ' and '
                }
                cql += 'rec.genreCode=' + genreCode;
            }
        }
        if($("#reference").length) {
            var reference = $("#reference").attr('value');
            if(reference && reference != '') {
                cql += ' and vl.reference =' + reference;
            }
        }
        if($("#subtype").length) {
            var subtype = $("#subtype option:selected").attr('value');
            if(subtype && subtype != '') {
                cql += ' and vl.subtype =' + subtype;
            }
        }
        if($("#ddc").length) {
            var ddc = $("#ddc").attr('value');
            if(ddc && ddc != '') {
                if(ddc.split(';').length > 1) {
                    list = ddc.split(';')
                    ddc='(';
                    for(i = 0; i < list.length; i++) {
                        ddc += list[i];
                        if(i < list.length - 1) ddc += ' or '; 
                    }
                    ddc += ')';
                }
                if (cql != '') {
                    cql += ' and '
                }
                cql += 'vl.ddc=' + ddc;
            }
        }
        
        if($("#vlFulltext").length) {
            var vlFulltext = $("#vlFulltext").attr('value');
            if(vlFulltext && vlFulltext != '') {
                if (cql != '') {
                    cql += ' and '
                }
                if (vlFulltext.indexOf(' ') > -1){
                    cql += 'vl.fulltext=(' + vlFulltext + ')';
                } else {
                    cql += 'vl.fulltext=' + vlFulltext;
                }
            }
        }
        
        if($("#vlStructures").length) {
            var vlStructures = $("#vlStructures").attr('value');
            if(vlStructures && vlStructures != '') {
                if (cql != '') {
                    cql += ' and '
                }
                if (vlStructures.indexOf(' ') > -1){
                    cql += 'vls.structures=(' + vlStructures + ')';
                } else {
                    cql += 'vls.structures=' + vlStructures;
                }
            }
        }
        if($("#vlAny").length) {
            var vlAny  = $("#vlAny").attr('value');
            if(vlAny && vlAny != '') {
                if (cql != '') {
                    cql += ' and '
                }
                if (vlAny.indexOf(' ') > -1){
                    cql += 'cql.anywhere=(' + vlAny + ')';
                } else {
                    cql += 'cql.anywhere=' + vlAny;
                }
            }
        }
        
        //up till now we should have something searchable, the rest is optional
        alertIfEmpty(cql);
        if(!cql) return false;
        
        if($("#searchLanguage").length) {
            var searchLanguage = $("#searchLanguage option:selected").attr('value');
            if(searchLanguage && searchLanguage != '') {
                cql += ' and dc.language=' + searchLanguage;
            }
        }
        
        var domain = ''
        if($("#searchDomain").length) {
            domain = $("#searchDomain option:selected").attr('value');
        
        } else if ($(".request#class").attr('value') != 'order'){
            // search/order should never send a domain via cql
            if ($(".domain#fulldata").attr('value') != 'true'){
                // fulldata domains should not send a domain via cql
                domain = $(".domain#name").attr('value');
            }
        }
        
        if(domain && domain != '') {
            cql += ' and vl.domain=' + domain;
        }
        
        
        //now handle collections
        if($('div#setCollections input').length) {
            collections = []
            $('div#setCollections input').each(function(){
                inputEl = $(this);
                if (inputEl.attr('checked')){
                    collections.push(inputEl.attr('value'));
                }
            })
            if (collections.length){
                cql += ' and vl.collections=('
                for (var idx = 0; idx < collections.length; idx++) {
                    cql += collections[idx];
                    if (idx < collections.length - 1){
                        cql += ' or ';
                    }
                }
                cql+= ')'
            }
        }
        
        if($("#sortBy option:selected").length) {
            sortBy = $("#sortBy option:selected").attr('value');
            cql += ' sortBy ' + sortBy;
            if($("#sortBy option:selected").length) {
                sortOrder = $("#sortOrder option:selected").attr('value');
                cql += '/' + sortOrder;
            }
        }


        sruForm.query.value = cql;
    
    } catch(e){
        alert(e)
        return false
    }
}
