﻿																	 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.replace(/\"/g, '');
	}

	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(':'));
			}
	}


	//wordTreeLight();
})



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="' + encodeURIComponent(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 wordTreeLight() {

	if (searchTerm != '') {
		Ext.Ajax.request({
			url: '/Handlers/WordTreeLight.ashx',
			params: { searchTerm: searchTerm },
			timeout: 60000,
			success: function (result, request) {
				Ext.fly('wordTreeSampleResults').dom.innerHTML = result.responseText;
			}
		});
	}
	else {
		Ext.fly('wordTreeSampleResults').dom.innerHTML = 'Unable to get WordTree';
	}
}

function closeWordTreeLight() {

	var wordTreeSampleResults = Ext.get('wordTreeSampleResults');
	var wordTreeToggle = Ext.get('closeWordTreeLink');
	var wordTreeToggleSpan = Ext.get('closeWordTree');

	if (wordTreeSampleResults.dom.style.display == 'none') {
		wordTreeSampleResults.dom.style.display = 'block';
		wordTreeToggle.dom.innerHTML = 'Hide';
		wordTreeToggleSpan.dom.className = '';
	} else {
		wordTreeSampleResults.dom.style.display = 'none';
		wordTreeToggle.dom.innerHTML = 'Show Tree Search';
		wordTreeToggleSpan.dom.className = 'Show';
	}
}

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;
}

