﻿                                                                     Ext.namespace('Ext.Exemplar');

/*
* @class Ext.Mapper.FilterStore
* Wrapper round Ext.Data.Store to customize for combo-box filters
* @indexName: MarkLogic element range index
*/
Ext.Exemplar.FilterStore = function(indexName) {
	return new Ext.data.Store({
		proxy: new Ext.data.HttpProxy(
					new Ext.data.Connection({
						url: '/xqueries/filter.xqy',
						disableCaching: false,
						extraParams: { f: indexName },
						method: 'GET'
					})),
		reader: new Ext.data.XmlReader({ record: 'item' }, Ext.data.Record.create([{ name: 'name' }, { name: 'count'}]))
	});
};


function addVal(a) {
	if (a.length == 2) {
		var value = unescape(a[1]);
		switch (a[0]) {
			case "subject":
				Ext.get('subjectSelectBox').dom.value = value;
				break;
			case "publication":
				Ext.get('publicationSelectBox').dom.value = value;
				break;
		}
	}
}

Ext.onReady(function() {

	var qs = location.search;

	if (location.pathname.indexOf('about.aspx') > -1)
		return;

	if (qs.length > 1)
		qs = qs.substring(1);

	var params = Ext.urlDecode(qs.replace(/\+/g, " ") || '');

	if (params.q) {
		params.q = unescape(params.q);
		Ext.get('searchText').dom.value = params.q.substr(1, params.q.length - 2);
	}

	var subjectCombo = new Ext.form.ComboBox({
		name: 'subject',
		mode: 'remote',
		store: new Ext.Exemplar.FilterStore('meta:Subject'),
		displayField: 'name',
		valueField: 'name',
		minChars: 3,
		emptyText: 'Type and select from list',
		emptyClass: 'search_text',
		listWidth: 350,
		hideTrigger: true,
		applyTo: 'subjectSelectBox',
		tpl: new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{[this.high(values.name)]} ({count})</div></tpl>', {
			ownerId: 'subjectSelectBox',
			high: function(str) {
				return str.replace(new RegExp('(' + Ext.fly(this.ownerId).getValue() + ')', 'i'), '<em>$1</em>');
			}
		})
	});

	var journalCombo = new Ext.form.ComboBox({
		name: 'publication',
		mode: 'remote',
		store: new Ext.Exemplar.FilterStore('meta:Publication'),
		displayField: 'name',
		valueField: 'name',
		minChars: 3,
		emptyText: 'Type and select from list',
		emptyClass: 'search_text',
		listWidth: 350,
		hideTrigger: true,
		applyTo: 'publicationSelectBox',
		tpl: new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{[this.high(values.name)]} ({count})</div></tpl>', {
			ownerId: 'publicationSelectBox',
			high: function(str) {
				return str.replace(new RegExp('(' + Ext.fly(this.ownerId).getValue() + ')', 'i'), '<em>$1</em>');
			}
		})
	});

	var publicationBox = Ext.get('publicationSelectBox');
	publicationBox.dom.style["cssText"] = '';

	var subjectBox = Ext.get('subjectSelectBox');
	subjectBox.dom.style["cssText"] = '';

	switch (typeof params.val) {
		case "string":
		params.val = params.val.replace(params.val.substring(params.val.indexOf(":")+1), params.val.substring(params.val.indexOf(":")+1).replace(":", "%3A"));
			addVal(params.val.split(':'));
			break;
		case "object":
			for (var i = 0; i < params.val.length; i++) {
				addVal(params.val[i].split(':'));
			}
	}



})


function checkKeys(e) {
	//Check keypresses and remove characters that we do not want - such as "
	var keynum;
	var keychar;
	var numcheck;

	if (window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if (e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}

	if (keynum == 34)
		return false;

}

function submitForm() {

	var searchText = document.getElementById('searchText');
	var publication = document.getElementById('publicationSelectBox');
	var subject = document.getElementById('subjectSelectBox');
    //var openaccess = document.getElementById('ctl00_leftPlaceHolder_oa');
       
	var text = LTrim(RTrim(searchText.value));

	if (text == '')
		return; //Need to do some kind of alert here so that the user is aware they have entered
		//nothing.
		
	var newDestination = 'search.aspx?q="' + text + '"';
	
	if ((LTrim(RTrim(publication.value)) != '') && (LTrim(RTrim(publication.value)) != 'Type and select from list'))
		newDestination += '&val=publication:' + LTrim(RTrim(publication.value.replace(/&/g, "%26")));

	if ((LTrim(RTrim(subject.value)) != '') && (LTrim(RTrim(subject.value)) != 'Type and select from list'))
		newDestination += '&val=subject:' + LTrim(RTrim(subject.value.replace(/&/g, "%26")));
		
	this.window.location = newDestination;
    }

function toggleOA()
{
var searchText = document.getElementById('searchText');
var openaccess = document.getElementById('ToggleOA');
var querystring = window.location.search.substring(1);
var newDestination = 'search.aspx?' + querystring + '';
newDestination = newDestination.replace(/&oa=1/g, "").replace(/&oa=0/g, "");
   
 if ( openaccess.innerHTML == "Open Access articles only" ) 
    {
		 newDestination += '&oa=1';
	}
	else 
	{
		 newDestination += '&oa=0';
	}
	
	this.window.location = newDestination;
	return false;
	//location.replace(newDestination);
}
	
// Removes leading whitespaces
function LTrim(value) {

	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value) {

	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");

}

function trackLink(action, args) {
	try {
		var s = (arguments.length === 2 && args.toString() !== 'undefined') ? action + '/' + args : action;
		_gat._anonymizeIp();
		pageTracker._trackPageview(s);
	}
	catch (e) { }
	return true;
}
