<commit_before>// Inserts shortcut buttons after all of the following:
//     <input type="text" class="vDateField">
//     <input type="text" class="vTimeField">

var DateTimeShortcuts = {
    calendars: [],
    calendarInputs: [],
    clockInputs: [],
    calendarDivName1: 'calendarbox', // name of calendar
 that gets toggled
    calendarDivName2: 'calendarin',  // name of
 that contains calendar
    clockDivName: 'clockbox',        // name of clock
 that gets toggled

    init: function() {
        var inputs = document.getElementsByTagName('input');
        for (var i=0; i<inputs.length; i++) {
            var inp = inputs[i];
            if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) {
                DateTimeShortcuts.addClock(inp);
            }
            else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) {
                DateTimeShortcuts.addCalendar(inp);
            }
        }
    },

    // Add clock widget to a given field
    addClock: function(inp) {
        var num = DateTimeShortcuts.clockInputs.length;
        DateTimeShortcuts.clockInputs[num] = inp;

        // Shortcut links (clock icon and "Now" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var now_link = document.createElement('a');
        now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());");
        now_link.appendChild(document.createTextNode('Now'));
        var clock_link = document.createElement('a');
        clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');');
        quickElement('img', clock_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_clock.gif', 'alt', 'Clock');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(now_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(clock_link);

        // Create clock link div
        //
        // Markup looks like:
        //

        //
Choose a time

        //

        //
Now

        //
Midnight

        //
6 a.m.

        //
Noon

        //

        //
Cancel

        //

        var clock_box = document.createElement('div');
        clock_box.style.display = 'none';
        clock_box.style.position = 'absolute';
        clock_box.style.left = findPosX(clock_link) + 17 + 'px';
        clock_box.style.top = findPosY(clock_link) - 30 + 'px';
        clock_box.className = 'clockbox module';
        clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num);
        document.body.appendChild(clock_box);
        addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        quickElement('h2', clock_box, 'Choose a time');
        time_list = quickElement('ul', clock_box, '', 'class', 'timelist');
        quickElement("a", quickElement("li", time_list, ""), "Now", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());")
        quickElement("a", quickElement("li", time_list, ""), "Midnight", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '00:00');")
        quickElement("a", quickElement("li", time_list, ""), "6 a.m.", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '06:00');")
        quickElement("a", quickElement("li", time_list, ""), "Noon", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '12:00');")

        cancel_p = quickElement('p', clock_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');');
    },

    openClock: function(num) {
        document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; });
    },

    dismissClock: function(num) {
       document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none';
       window.onclick = null;
    },

    handleClockQuicklink: function(num, val) {
       DateTimeShortcuts.clockInputs[num].value = val;
       DateTimeShortcuts.dismissClock(num);
    },

    // Add calendar widget to a given field.
    addCalendar: function(inp) {
        var num = DateTimeShortcuts.calendars.length;

        DateTimeShortcuts.calendarInputs[num] = inp;

        // Shortcut links (calendar icon and "Today" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var today_link = document.createElement('a');
        today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        today_link.appendChild(document.createTextNode('Today'));
        var cal_link = document.createElement('a');
        cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');');
        quickElement('img', cal_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_calendar.gif', 'alt', 'Calendar');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(today_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(cal_link);

        // Create calendarbox div.
        //
        // Markup looks like:
        //
        //

        //

        //           ‹
        //           › February 2003
        //

        //

        //
        //

        //

        //          Yesterday | Today | Tomorrow
        //

        //
Cancel

        //

        var cal_box = document.createElement('div');
        cal_box.style.display = 'none';
        cal_box.style.position = 'absolute';
        cal_box.style.left = findPosX(cal_link) + 17 + 'px';
        cal_box.style.top = findPosY(cal_link) - 75 + 'px';
        cal_box.className = 'calendarbox module';
        cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num);
        document.body.appendChild(cal_box);
        addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        // next-prev links
        var cal_nav = quickElement('div', cal_box, '');
        quickElement('a', cal_nav, '<', 'class', 'calendarnav-previous', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');');
        quickElement('a', cal_nav, '>', 'class', 'calendarnav-next',     'href', 'javascript:DateTimeShortcuts.drawNext('+num+');');
        cal_box.appendChild(cal_nav);

        // main box
        var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num);
        cal_main.className = 'calendar';
        DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num));
        DateTimeShortcuts.calendars[num].drawCurrent();

        // calendar shortcuts
        var shortcuts = quickElement('div', cal_box, '', 'class', 'calendar-shortcuts');
        quickElement('a', shortcuts, 'Yesterday', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Today', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Tomorrow', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);');

        // cancel bar
        var cancel_p = quickElement('p', cal_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');');
    },

    openCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; });
    },

    dismissCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none';
        window.onclick = null;
    },

    drawPrev: function(num) {
        DateTimeShortcuts.calendars[num].drawPreviousMonth();
    },

    drawNext: function(num) {
        DateTimeShortcuts.calendars[num].drawNextMonth();
    },

    handleCalendarCallback: function(num) {
        return "function(y, m, d) { DateTimeShortcuts.calendarInputs["+num+"].value = y+'-'+m+'-'+d; document.getElementById(DateTimeShortcuts.calendarDivName1+"+num+").style.display='none';}";
    },

    handleCalendarQuickLink: function(num, offset) {
       var d = new Date();
       d.setDate(d.getDate() + offset)
       DateTimeShortcuts.calendarInputs[num].value = d.getISODate();
       DateTimeShortcuts.dismissCalendar(num);
    },

    cancelEventPropagation: function(e) {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stripPropagation) e.stopPropagation();
    }

}

addEvent(window, 'load', DateTimeShortcuts.init);
<commit_msg>Calendar next/prev popups now work in Safari (fixed #2)<commit_after>// Inserts shortcut buttons after all of the following:
//     <input type="text" class="vDateField">
//     <input type="text" class="vTimeField">

var DateTimeShortcuts = {
    calendars: [],
    calendarInputs: [],
    clockInputs: [],
    calendarDivName1: 'calendarbox', // name of calendar
 that gets toggled
    calendarDivName2: 'calendarin',  // name of
 that contains calendar
    clockDivName: 'clockbox',        // name of clock
 that gets toggled

    init: function() {
        var inputs = document.getElementsByTagName('input');
        for (var i=0; i<inputs.length; i++) {
            var inp = inputs[i];
            if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) {
                DateTimeShortcuts.addClock(inp);
            }
            else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) {
                DateTimeShortcuts.addCalendar(inp);
            }
        }
    },

    // Add clock widget to a given field
    addClock: function(inp) {
        var num = DateTimeShortcuts.clockInputs.length;
        DateTimeShortcuts.clockInputs[num] = inp;

        // Shortcut links (clock icon and "Now" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var now_link = document.createElement('a');
        now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());");
        now_link.appendChild(document.createTextNode('Now'));
        var clock_link = document.createElement('a');
        clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');');
        quickElement('img', clock_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_clock.gif', 'alt', 'Clock');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(now_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(clock_link);

        // Create clock link div
        //
        // Markup looks like:
        //

        //
Choose a time

        //

        //
Now

        //
Midnight

        //
6 a.m.

        //
Noon

        //

        //
Cancel

        //

        var clock_box = document.createElement('div');
        clock_box.style.display = 'none';
        clock_box.style.position = 'absolute';
        clock_box.style.left = findPosX(clock_link) + 17 + 'px';
        clock_box.style.top = findPosY(clock_link) - 30 + 'px';
        clock_box.className = 'clockbox module';
        clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num);
        document.body.appendChild(clock_box);
        addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        quickElement('h2', clock_box, 'Choose a time');
        time_list = quickElement('ul', clock_box, '', 'class', 'timelist');
        quickElement("a", quickElement("li", time_list, ""), "Now", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());")
        quickElement("a", quickElement("li", time_list, ""), "Midnight", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '00:00');")
        quickElement("a", quickElement("li", time_list, ""), "6 a.m.", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '06:00');")
        quickElement("a", quickElement("li", time_list, ""), "Noon", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '12:00');")

        cancel_p = quickElement('p', clock_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');');
    },

    openClock: function(num) {
        document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; });
    },

    dismissClock: function(num) {
       document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none';
       window.onclick = null;
    },

    handleClockQuicklink: function(num, val) {
       DateTimeShortcuts.clockInputs[num].value = val;
       DateTimeShortcuts.dismissClock(num);
    },

    // Add calendar widget to a given field.
    addCalendar: function(inp) {
        var num = DateTimeShortcuts.calendars.length;

        DateTimeShortcuts.calendarInputs[num] = inp;

        // Shortcut links (calendar icon and "Today" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var today_link = document.createElement('a');
        today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        today_link.appendChild(document.createTextNode('Today'));
        var cal_link = document.createElement('a');
        cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');');
        quickElement('img', cal_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_calendar.gif', 'alt', 'Calendar');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(today_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(cal_link);

        // Create calendarbox div.
        //
        // Markup looks like:
        //
        //

        //

        //           ‹
        //           › February 2003
        //

        //

        //
        //

        //

        //          Yesterday | Today | Tomorrow
        //

        //
Cancel

        //

        var cal_box = document.createElement('div');
        cal_box.style.display = 'none';
        cal_box.style.position = 'absolute';
        cal_box.style.left = findPosX(cal_link) + 17 + 'px';
        cal_box.style.top = findPosY(cal_link) - 75 + 'px';
        cal_box.className = 'calendarbox module';
        cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num);
        document.body.appendChild(cal_box);
        addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        // next-prev links
        var cal_nav = quickElement('div', cal_box, '');
        quickElement('a', cal_nav, '<', 'class', 'calendarnav-previous', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');');
        quickElement('a', cal_nav, '>', 'class', 'calendarnav-next',     'href', 'javascript:DateTimeShortcuts.drawNext('+num+');');
        cal_box.appendChild(cal_nav);

        // main box
        var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num);
        cal_main.className = 'calendar';
        DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num));
        DateTimeShortcuts.calendars[num].drawCurrent();

        // calendar shortcuts
        var shortcuts = quickElement('div', cal_box, '', 'class', 'calendar-shortcuts');
        quickElement('a', shortcuts, 'Yesterday', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Today', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Tomorrow', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);');

        // cancel bar
        var cancel_p = quickElement('p', cal_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');');
    },

    openCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; });
    },

    dismissCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none';
    },

    drawPrev: function(num) {
        DateTimeShortcuts.calendars[num].drawPreviousMonth();
    },

    drawNext: function(num) {
        DateTimeShortcuts.calendars[num].drawNextMonth();
    },

    handleCalendarCallback: function(num) {
        return "function(y, m, d) { DateTimeShortcuts.calendarInputs["+num+"].value = y+'-'+m+'-'+d; document.getElementById(DateTimeShortcuts.calendarDivName1+"+num+").style.display='none';}";
    },

    handleCalendarQuickLink: function(num, offset) {
       var d = new Date();
       d.setDate(d.getDate() + offset)
       DateTimeShortcuts.calendarInputs[num].value = d.getISODate();
       DateTimeShortcuts.dismissCalendar(num);
    },

    cancelEventPropagation: function(e) {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    }

}

addEvent(window, 'load', DateTimeShortcuts.init);
<|endoftext|>


<commit_before>    // First, put a steward DID and its keypair in the wallet. This doesn't write anything to the ledger,
    // but it gives us a key that we can use to sign a ledger transaction that we're going to submit later.
    // The DID and public verkey for this steward key are already in the ledger; they were part of the genesis
    // transactions we told the SDK to start with in the previous step. But we have to also put the DID, verkey,
    // and private signing key into our wallet, so we can use the signing key to submit an acceptably signed
    // transaction to the ledger, creating our *next* DID (which is truly new). This is why we use a hard-coded seed
    // when creating this DID--it guarantees that the same DID and key material are created that the genesis txns
    // expect.

    // 5.
    log('5. Generating and storing steward DID and verkey')
    const stewardSeed = '000000000000000000000000Steward1'
    const did = {'seed': stewardSeed}
    const [stewardDid, stewardVerkey] = await indy.createAndStoreMyDid(walletHandle, did)
    logValue('Steward DID: ', stewardDid)
    logValue('Steward Verkey: ', stewardVerkey)

    // Now, create a new DID and verkey for a trust anchor, and store it in our wallet as well. Don't use a seed;
    // this DID and its keyas are secure and random. Again, we're not writing to the ledger yet.

    // 6.
    log('6. Generating and storing trust anchor DID and verkey')
    const [trustAnchorDid, trustAnchorVerkey] = await indy.createAndStoreMyDid(walletHandle, "{}")
    logValue('Trust anchor DID: ', trustAnchorDid)
    logValue('Trust anchor Verkey: ', trustAnchorVerkey)

<commit_msg>docs(how-tos): fixes typo in comment<commit_after>    // First, put a steward DID and its keypair in the wallet. This doesn't write anything to the ledger,
    // but it gives us a key that we can use to sign a ledger transaction that we're going to submit later.
    // The DID and public verkey for this steward key are already in the ledger; they were part of the genesis
    // transactions we told the SDK to start with in the previous step. But we have to also put the DID, verkey,
    // and private signing key into our wallet, so we can use the signing key to submit an acceptably signed
    // transaction to the ledger, creating our *next* DID (which is truly new). This is why we use a hard-coded seed
    // when creating this DID--it guarantees that the same DID and key material are created that the genesis txns
    // expect.

    // 5.
    log('5. Generating and storing steward DID and verkey')
    const stewardSeed = '000000000000000000000000Steward1'
    const did = {'seed': stewardSeed}
    const [stewardDid, stewardVerkey] = await indy.createAndStoreMyDid(walletHandle, did)
    logValue('Steward DID: ', stewardDid)
    logValue('Steward Verkey: ', stewardVerkey)

    // Now, create a new DID and verkey for a trust anchor, and store it in our wallet as well. Don't use a seed;
    // this DID and its keys are secure and random. Again, we're not writing to the ledger yet.

    // 6.
    log('6. Generating and storing trust anchor DID and verkey')
    const [trustAnchorDid, trustAnchorVerkey] = await indy.createAndStoreMyDid(walletHandle, "{}")
    logValue('Trust anchor DID: ', trustAnchorDid)
    logValue('Trust anchor Verkey: ', trustAnchorVerkey)

<|endoftext|>


<commit_before>/**
 * Copyright © 2011-2014 EMBL - European Bioinformatics Institute
 *
 * 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.
 *
 * functions used for processing user input via SOLR calls. Process the response and
 * displays the results as facets on the left bar.
 *
 */

(function($){
	var jsonBase = MPI2.searchAndFacetConfig.facetParams;

	function _updateFacetCount(facet, facetResponse, facetMode){
		//var num = facetMode ? '' : facetResponse.response.numFound;

		num = facetResponse.response.numFound;

		$('div.flist li#' + facet + ' span.fcount').html(num);

		var freezeMode = num == 0 ? true : false;
		$.fn.freezeFacet($('li#' + facet + '.fmcat'), freezeMode);
	}

	function _getParams(facet, oUrlParams){
		facet += 'Facet';

		var params = $.extend({}, jsonBase[facet].srchParams, jsonBase[facet].filterParams);
		params.q = oUrlParams.q;

		if ( typeof oUrlParams.qf != 'undefined' ){
			params.qf = oUrlParams.qf;
		}

		//console.log(facet + ' --- ' + $.fn.stringifyJsonAsUrlParams(params));
		return params;
	}

	$.fn.fetchSolrFacetCount = function(oUrlParams){

		/* ---- q for SOLR --- */
		var q = oUrlParams.q;

		if ( typeof q == 'undefined' ){
			// check search kw
			q = window.location.search != '' ? $.fn.fetchQueryStr() : '*:*';
		}

		//console.log(q)
		// q to display in input box
		var qDisplay = q == '*:*'  ? '' : decodeURI(q);
		qDisplay = $.fn.convertNonDecodable(qDisplay);
		$('input#s').val(qDisplay);

		// q to search SOLR
		q = $.fn.process_q(q);
		q = $.fn.convertNonDecodable(q);

		oUrlParams.q  = q;
		oUrlParams.q = decodeURI(q); // send to solr through ajax, encoding not working for special char

		/* ---- end of q for SOLR --- */

		/* ---- fq for SOLR --- */
		if ( typeof oUrlParams.fq != 'undefined' ){
			oUrlParams.oriFq = oUrlParams.fq;
			oUrlParams.fq = oUrlParams.fq.replace(/img_/g, '');

			if (  typeof oUrlParams.coreName == 'undefined' ){
				jsonBase.geneFacet.filterParams = {'fq': oUrlParams.fq};
			}
		}
		/* ---- end of fq for SOLR --- */

		var facetMode = oUrlParams.facetName;
		var oFacets = {};
		oFacets.count = {};

		// facet types are done sequencially; starting from gene
	    $.ajax({
	    		url: solrUrl + '/gene/select',
	    		data: _getParams('gene', oUrlParams),
	       	    dataType: 'jsonp',
	       	    jsonp: 'json.wrf',
	       	    timeout: 5000,
	       	    success: function (geneResponse) {
	       	    	//console.log('gene');
	       	    	//console.log(geneResponse);
	       	    	$('div.flist li#gene span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
	       	    	oFacets.count.gene = geneResponse.response.numFound;
	       	    	_updateFacetCount('gene', geneResponse, facetMode);
	       	    	_doMPAutoSuggest(geneResponse, oFacets, facetMode, oUrlParams);
	       	    },
	       	    error: function (jqXHR, textStatus, errorThrown) {
	       	        $('div#facetSrchMsg').html('Error fetching data ...');
	       	    }
	    });
	}

	function _doMPAutoSuggest(geneResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.mpFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/mp/select',
    	    data: _getParams('mp', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (mpResponse) {
    	    	//console.log('mp');
    	    	//console.log(mpResponse);
    	    	$('div.flist li#mp span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
       	    	oFacets.count.mp = mpResponse.response.numFound;
       	    	_updateFacetCount('mp', mpResponse, facetMode);
    	    	_doDiseaseAutoSuggest(geneResponse, mpResponse, oFacets, facetMode, oUrlParams);
    	    },
    	    error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}
	function _doDiseaseAutoSuggest(geneResponse, mpResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.diseaseFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/disease/select',
    	    data: _getParams('disease', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 10000,
    	    success: function (diseaseResponse) {
    	    	//console.log('disease');
    	    	//console.log(diseaseResponse);
    	    	$('div.flist li#disease span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.disease = diseaseResponse.response.numFound;
    	    	_updateFacetCount('disease', diseaseResponse, facetMode);
    	    	_doTissueAutoSuggest(geneResponse, mpResponse, diseaseResponse, oFacets, facetMode, oUrlParams);
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doTissueAutoSuggest(geneResponse, mpResponse, diseaseResponse, oFacets, facetMode, oUrlParams){

		jsonBase.maFacet.srchParams.sort = 'ma_term asc';

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.maFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/ma/select',
    	    data: _getParams('ma', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 10000,
    	    success: function (maResponse) {
    	    	//console.log('ma');
    	    	//console.log(maResponse);
    	    	$('div.flist li#ma span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.ma = maResponse.response.numFound;
    	    	_updateFacetCount('ma', maResponse, facetMode);
    	    	_doPipelineAutoSuggest(geneResponse, mpResponse, diseaseResponse, maResponse, oFacets, facetMode, oUrlParams);

    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doPipelineAutoSuggest(geneResponse, mpResponse, diseaseResponse, maResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.pipelineFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/pipeline/select',
    	    data: _getParams('pipeline', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (pipelineResponse) {
    	    	//console.log('pipeline');
    	    	//console.log(pipelineResponse);
    	    	$('div.flist li#pipeline span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.pipeline = pipelineResponse.response.numFound;
    	    	_updateFacetCount('pipeline', pipelineResponse, facetMode);
    	    	_doImageAutosuggest(geneResponse, mpResponse, diseaseResponse, maResponse, pipelineResponse, oFacets, facetMode, oUrlParams);
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doImageAutosuggest(geneResponse, mpResponse, diseaseResponse, maResponse, pipelineResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.imagesFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/images/select',
    	    data: _getParams('images', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (imagesResponse) {
    	    	//console.log('images');
    	    	//console.log(imagesResponse);

    	    	$('div.flist li#images span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);

    	    	oFacets.count.images = imagesResponse.response.numFound;
    	    	_updateFacetCount('images', imagesResponse, facetMode);

    	    	/* now check which core needs to be displayed by default in the order of
    	    	 * gene -> mp -> ma -> pipeline -> images -> disease
    	    	 * ie, fetch facet full result for that facet and display only facet count for the rest of the facets
    	    	 * Other facet results will be fetched on demand */

    	    	$('div#facetSrchMsg').html(' ');

    	    	if ( ! _setSearchMode(oFacets.count) ){
    	    		// nothing found
    	    		$.fn.showNotFoundMsg();
    	    	}
    	    	else {
    	        	// remove all previous facet results before loading new facet results
    	    		//var thisCore = coreName ? coreName : facetName;
    	    		var thisCore = _setSearchMode(oFacets.count);

    	    		$('li.fmcat > ul').html('');

    	        	//var widgetName = coreName+'Facet';
    	        	var widgetName = thisCore+'Facet';

    	        	oUrlParams.fq = oUrlParams.fq ? oUrlParams.fq : jsonBase[widgetName].fq;
    	        	oUrlParams.oriFq = oUrlParams.oriFq ? oUrlParams.oriFq : jsonBase[widgetName].fq;
    	        	oUrlParams.widgetName = widgetName;

    	        	//console.log('started widget call')
    	        	window.jQuery('li#' + thisCore)[widgetName]({
    					data: {
    							core: thisCore,
    							facetCount: oFacets.count[thisCore],
    							hashParams: oUrlParams
    							},
    			        geneGridElem: 'div#mpi2-search'
    				});

    	        	// load none-zero facet results on demand
    	        	var aCores = MPI2.searchAndFacetConfig.megaCores;

    	        	//delete active core, no need to invoke again
    	        	var index;// = aCores.indexOf(coreName);
    	        	for ( var i=0; i< aCores.length; i++){
    	        		if (aCores[i] == thisCore ){
    	        			index = i;
    	        		}
    	        	}
    	        	aCores.splice(index, 1); // remove core that has the index result already in dataTable

    	        	for ( var i=0; i< aCores.length; i++){
    	        		var core = aCores[i];
    	        		_prepareCores(core, oUrlParams.q, oFacets, oUrlParams.fq, facetMode);
    	        	}
    	        	// restore the spliced core when done
    	        	aCores.push(thisCore);
    	    	}
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _prepareCores(core, q, oFacets, fq, facetMode){
		var widgetName = core + 'Facet';

		window.jQuery('li#' + core).click(function(){

			var $this = window.jQuery(this);

			// check widget has not been created
			if ( typeof $this.data(widgetName) === 'undefined' ){
				var hashParams = {};

				// core or facet?
				if ( typeof facetMode != 'undefined' ){
					hashParams.fq = fq ? fq : jsonBase[widgetName].fq;
				}
				else {
					hashParams.fq = jsonBase[widgetName].fq;
				}

	        	hashParams.widgetName = widgetName;
	        	hashParams.q = q;

	        	if ( $this.find('ul').html() == '' && $this.find('span.fcount').text() != '0' ){
					$this[widgetName]({
						data: {
							core: core,
							facetCount: oFacets.count[core],
							hashParams: hashParams
							},
							geneGridElem: 'div#mpi2-search'
					});
				}
			}
		});
	}

	function _setSearchMode(oCounts){

		// priority order of facet to be opened based on search result
		if ( oCounts.gene != 0 ){
			return 'gene';
		}
		else if ( oCounts.mp != 0){
			return 'mp';
		}
		else if ( oCounts.disease != 0 ){
			return 'disease';
		}
		else if ( oCounts.ma != 0){
			return 'ma';
		}
		else if ( oCounts.pipeline != 0 ){
			return 'pipeline';
		}
		else if ( oCounts.images != 0 ){
			return 'images';
		}
		else {
			return false; // nothing found
		}
	}

})(jQuery);
<commit_msg>behavior fix - when search for a kw by hitting ENTER without choosing from the autosuggest list: regardless if facet info is available (eg, when hitting ENTER too fast) open the facet with result by default<commit_after>/**
 * Copyright © 2011-2014 EMBL - European Bioinformatics Institute
 *
 * 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.
 *
 * functions used for processing user input via SOLR calls. Process the response and
 * displays the results as facets on the left bar.
 *
 */

(function($){
	var jsonBase = MPI2.searchAndFacetConfig.facetParams;

	function _updateFacetCount(facet, facetResponse, facetMode){
		//var num = facetMode ? '' : facetResponse.response.numFound;

		num = facetResponse.response.numFound;

		$('div.flist li#' + facet + ' span.fcount').html(num);

		var freezeMode = num == 0 ? true : false;
		$.fn.freezeFacet($('li#' + facet + '.fmcat'), freezeMode);
	}

	function _getParams(facet, oUrlParams){
		facet += 'Facet';

		var params = $.extend({}, jsonBase[facet].srchParams, jsonBase[facet].filterParams);
		params.q = oUrlParams.q;

		if ( typeof oUrlParams.qf != 'undefined' ){
			params.qf = oUrlParams.qf;
		}

		//console.log(facet + ' --- ' + $.fn.stringifyJsonAsUrlParams(params));
		return params;
	}

	$.fn.fetchSolrFacetCount = function(oUrlParams){

		/* ---- q for SOLR --- */
		var q = oUrlParams.q;

		if ( typeof q == 'undefined' ){
			// check search kw
			q = window.location.search != '' ? $.fn.fetchQueryStr() : '*:*';
		}

		//console.log(q)
		// q to display in input box
		var qDisplay = q == '*:*'  ? '' : decodeURI(q);
		qDisplay = $.fn.convertNonDecodable(qDisplay);
		$('input#s').val(qDisplay);

		// q to search SOLR
		q = $.fn.process_q(q);
		q = $.fn.convertNonDecodable(q);

		oUrlParams.q  = q;
		oUrlParams.q = decodeURI(q); // send to solr through ajax, encoding not working for special char

		/* ---- end of q for SOLR --- */

		/* ---- fq for SOLR --- */
		if ( typeof oUrlParams.fq != 'undefined' ){
			oUrlParams.oriFq = oUrlParams.fq;
			oUrlParams.fq = oUrlParams.fq.replace(/img_/g, '');

			if (  typeof oUrlParams.coreName == 'undefined' ){
				jsonBase.geneFacet.filterParams = {'fq': oUrlParams.fq};
			}
		}
		/* ---- end of fq for SOLR --- */

		var facetMode = oUrlParams.facetName;
		var oFacets = {};
		oFacets.count = {};

		// facet types are done sequencially; starting from gene
	    $.ajax({
	    		url: solrUrl + '/gene/select',
	    		data: _getParams('gene', oUrlParams),
	       	    dataType: 'jsonp',
	       	    jsonp: 'json.wrf',
	       	    timeout: 5000,
	       	    success: function (geneResponse) {
	       	    	//console.log('gene');
	       	    	//console.log(geneResponse);
	       	    	$('div.flist li#gene span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
	       	    	oFacets.count.gene = geneResponse.response.numFound;
	       	    	_updateFacetCount('gene', geneResponse, facetMode);
	       	    	_doMPAutoSuggest(geneResponse, oFacets, facetMode, oUrlParams);
	       	    },
	       	    error: function (jqXHR, textStatus, errorThrown) {
	       	        $('div#facetSrchMsg').html('Error fetching data ...');
	       	    }
	    });
	}

	function _doMPAutoSuggest(geneResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.mpFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/mp/select',
    	    data: _getParams('mp', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (mpResponse) {
    	    	//console.log('mp');
    	    	//console.log(mpResponse);
    	    	$('div.flist li#mp span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
       	    	oFacets.count.mp = mpResponse.response.numFound;
       	    	_updateFacetCount('mp', mpResponse, facetMode);
    	    	_doDiseaseAutoSuggest(geneResponse, mpResponse, oFacets, facetMode, oUrlParams);
    	    },
    	    error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}
	function _doDiseaseAutoSuggest(geneResponse, mpResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.diseaseFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/disease/select',
    	    data: _getParams('disease', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 10000,
    	    success: function (diseaseResponse) {
    	    	//console.log('disease');
    	    	//console.log(diseaseResponse);
    	    	$('div.flist li#disease span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.disease = diseaseResponse.response.numFound;
    	    	_updateFacetCount('disease', diseaseResponse, facetMode);
    	    	_doTissueAutoSuggest(geneResponse, mpResponse, diseaseResponse, oFacets, facetMode, oUrlParams);
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doTissueAutoSuggest(geneResponse, mpResponse, diseaseResponse, oFacets, facetMode, oUrlParams){

		jsonBase.maFacet.srchParams.sort = 'ma_term asc';

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.maFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/ma/select',
    	    data: _getParams('ma', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 10000,
    	    success: function (maResponse) {
    	    	//console.log('ma');
    	    	//console.log(maResponse);
    	    	$('div.flist li#ma span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.ma = maResponse.response.numFound;
    	    	_updateFacetCount('ma', maResponse, facetMode);
    	    	_doPipelineAutoSuggest(geneResponse, mpResponse, diseaseResponse, maResponse, oFacets, facetMode, oUrlParams);

    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doPipelineAutoSuggest(geneResponse, mpResponse, diseaseResponse, maResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.pipelineFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/pipeline/select',
    	    data: _getParams('pipeline', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (pipelineResponse) {
    	    	//console.log('pipeline');
    	    	//console.log(pipelineResponse);
    	    	$('div.flist li#pipeline span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);
    	    	oFacets.count.pipeline = pipelineResponse.response.numFound;
    	    	_updateFacetCount('pipeline', pipelineResponse, facetMode);
    	    	_doImageAutosuggest(geneResponse, mpResponse, diseaseResponse, maResponse, pipelineResponse, oFacets, facetMode, oUrlParams);
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _doImageAutosuggest(geneResponse, mpResponse, diseaseResponse, maResponse, pipelineResponse, oFacets, facetMode, oUrlParams){

		if ( typeof oUrlParams.fq != 'undefined' && typeof oUrlParams.coreName == 'undefined' ){
			jsonBase.imagesFacet.filterParams = {'fq': oUrlParams.fq};
		}

		$.ajax({
    	    url: solrUrl + '/images/select',
    	    data: _getParams('images', oUrlParams),
    	    dataType: 'jsonp',
    	    jsonp: 'json.wrf',
    	    timeout: 5000,
    	    success: function (imagesResponse) {
    	    	//console.log('images');
    	    	//console.log(imagesResponse);

    	    	$('div.flist li#images span.fcount').html(MPI2.searchAndFacetConfig.searchSpin);

    	    	oFacets.count.images = imagesResponse.response.numFound;
    	    	_updateFacetCount('images', imagesResponse, facetMode);

    	    	/* now check which core needs to be displayed by default in the order of
    	    	 * gene -> mp -> ma -> pipeline -> images -> disease
    	    	 * ie, fetch facet full result for that facet and display only facet count for the rest of the facets
    	    	 * Other facet results will be fetched on demand */

    	    	$('div#facetSrchMsg').html(' ');

    	    	if ( ! _setSearchMode(oFacets.count) ){
    	    		// nothing found
    	    		$.fn.showNotFoundMsg();
    	    	}
    	    	else {
    	        	// remove all previous facet results before loading new facet results

    	    		var defaultCore;
    	    		var firstCoreWithResult = _setSearchMode(oFacets.count);

    	    		if ( typeof facetMode == 'undefined' || oFacets.count[facetMode] == 0 ){
    	    			defaultCore =firstCoreWithResult;
        	    	}
    	    		else {
    	    			defaultCore = facetMode;
    	    		}

    	    		$('li.fmcat > ul').html('');

    	        	var widgetName = defaultCore+'Facet';

    	        	oUrlParams.fq = oUrlParams.fq ? oUrlParams.fq : jsonBase[widgetName].fq;
    	        	oUrlParams.oriFq = oUrlParams.oriFq ? oUrlParams.oriFq : jsonBase[widgetName].fq;
    	        	oUrlParams.widgetName = widgetName;

    	        	//console.log('started widget call')
    	        	window.jQuery('li#' + defaultCore)[widgetName]({
    					data: {
    							core: defaultCore,
    							facetCount: oFacets.count[defaultCore],
    							hashParams: oUrlParams
    							},
    			        geneGridElem: 'div#mpi2-search'
    				});

    	        	// load none-zero facet results on demand
    	        	var aCores = MPI2.searchAndFacetConfig.megaCores;

    	        	//delete active core, no need to invoke again
    	        	var index;// = aCores.indexOf(coreName);
    	        	for ( var i=0; i< aCores.length; i++){
    	        		if (aCores[i] == defaultCore ){
    	        			index = i;
    	        		}
    	        	}
    	        	aCores.splice(index, 1); // remove core that has the index result already in dataTable

    	        	for ( var i=0; i< aCores.length; i++){
    	        		var core = aCores[i];
    	        		_prepareCores(core, oUrlParams.q, oFacets, oUrlParams.fq, facetMode);
    	        	}
    	        	// restore the spliced core when done
    	        	aCores.push(defaultCore);
    	    	}
    	    },
			error: function (jqXHR, textStatus, errorThrown) {
				$('div#facetSrchMsg').html('Error fetching data ...');
			}
		});
	}

	function _prepareCores(core, q, oFacets, fq, facetMode){
		var widgetName = core + 'Facet';

		window.jQuery('li#' + core).click(function(){

			var $this = window.jQuery(this);

			// check widget has not been created
			if ( typeof $this.data(widgetName) === 'undefined' ){
				var hashParams = {};

				// core or facet?
				if ( typeof facetMode != 'undefined' ){
					hashParams.fq = fq ? fq : jsonBase[widgetName].fq;
				}
				else {
					hashParams.fq = jsonBase[widgetName].fq;
				}

	        	hashParams.widgetName = widgetName;
	        	hashParams.q = q;

	        	if ( $this.find('ul').html() == '' && $this.find('span.fcount').text() != '0' ){
					$this[widgetName]({
						data: {
							core: core,
							facetCount: oFacets.count[core],
							hashParams: hashParams
							},
							geneGridElem: 'div#mpi2-search'
					});
				}
			}
		});
	}

	function _setSearchMode(oCounts){

		// priority order of facet to be opened based on search result
		if ( oCounts.gene != 0 ){
			return 'gene';
		}
		else if ( oCounts.mp != 0){
			return 'mp';
		}
		else if ( oCounts.disease != 0 ){
			return 'disease';
		}
		else if ( oCounts.ma != 0){
			return 'ma';
		}
		else if ( oCounts.pipeline != 0 ){
			return 'pipeline';
		}
		else if ( oCounts.images != 0 ){
			return 'images';
		}
		else {
			return false; // nothing found
		}
	}

})(jQuery);
<|endoftext|>


<commit_before>(function($){
    "use strict";
    var preFormJson = "";
    var submitSucc = false;

    $.fn.submitForm = function (url) {
        if (!validator.checkAll(this)) {
            return;
        }
        var formJson = JSON.stringify(this.serializeJSON());
        $.ajax({
            type: "post",
            url: url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {json: formJson},
            dataType: "json",

            beforeSend: function(){
                if (preFormJson == formJson && submitSucc) {
                    alert("不能重复提交");
                    return false;
                }
            },

            success: function(data){
                if (data.result.indexOf("success") != -1) {
                    submitSucc = true;
                    alert("提交成功");
                } else {
                    submitSucc = false;
                    alert(data.result);
                }
            }
        });

        preFormJson = formJson;
    },

    $.fn.isFullSet = function(){
        var isFullSet = true;
        var nameValues = {};

        this.find(':input').filter('[required=required], .required, .optional').not('[disabled=disabled]').each(function() {
            if (nameValues[$(this).attr("name")] == null || nameValues[$(this).attr("name")] == undefined) {
                nameValues[$(this).attr("name")] = $(this).val();
            }
        });

        for (var key in nameValues ){
            if ($.trim(key) == "") {
                isFullSet = false;
                break;
            }
        }

        return isFullSet;
    },

    $.fn.preventEnterSubmit = function(){
        this.keypress(function(e){
            if(e.keyCode==13){
                e.preventDefault();
            }
        });
    }
})(jQuery);
<commit_msg>remend isFullSet bug<commit_after>/**
 * Copyright © 2012-2025 云南红掌柜珠宝有限公司 版权所有
 * 文件名: submitForm.js
 *类的详细说明
 *
 * @author smjie
 * @Date  2017/4/22
 * @version 1.00
 */
(function($){
    "use strict";
    var preFormJson = "";
    var submitSucc = false;

    $.fn.submitForm = function (url) {
        if (!validator.checkAll(this)) {
            return;
        }
        var formJson = JSON.stringify(this.serializeJSON());
        $.ajax({
            type: "post",
            url: url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {json: formJson},
            dataType: "json",

            beforeSend: function(){
                if (preFormJson == formJson && submitSucc) {
                    alert("不能重复提交");
                    return false;
                }
            },

            success: function(data){
                if (data.result.indexOf("success") != -1) {
                    submitSucc = true;
                    alert("提交成功");
                } else {
                    submitSucc = false;
                    alert(data.result);
                }
            }
        });

        preFormJson = formJson;
    },

    $.fn.isFullSet = function(){
        var isFullSet = true;
        var nameValues = {};

        this.find(':input').filter('[required=required], .required, .optional').not('[disabled=disabled]').each(function() {
            if (nameValues[$(this).attr("name")] == null || nameValues[$(this).attr("name")] == undefined) {
                nameValues[$(this).attr("name")] = "";
            } else {
                nameValues[$(this).attr("name")] += $(this).val()
            }
        });

        $.each(nameValues, function(name, value){
            if ($.trim(value) == "") {
                isFullSet = false;
            }
        });

        return isFullSet;
    },

    $.fn.preventEnterSubmit = function(){
        this.keypress(function(e){
            if(e.keyCode==13){
                e.preventDefault();
            }
        });
    }
})(jQuery);
<|endoftext|>


<commit_before>(function(){"use strict";function e(e){var n=t(e.units),a=Date.now(),o=r(e.from,n,a),u=r(e.to,n,a),i=o.timestamp-u.timestamp,s=Math.abs(i);return m(s,o,u)||b(s,i)}function t(e){if(e===void 0)return"ms";if("s"===e||"ms"===e)return e;throw Error("Invalid units")}function r(e,t,r){if(e===void 0)return i(r);if("string"==typeof e&&(e=parseInt(e,10)),n(e)&&o(e))throw Error("Invalid timestamp");return"number"==typeof e&&"s"===t&&(e*=1e3),i(e)}function n(e){return a(e)===!1}function a(e){return"[object Date]"===Object.prototype.toString.call(e)&&isNaN(e.getTime())===!1}function o(e){return u(e)===!1}function u(e){return"number"==typeof e&&isNaN(e)===!1}function i(e){return a(e)?s(e):u(e)?y(e):void 0}function s(e){return c(e.getTime(),e)}function c(e,t){return{timestamp:e,day:t.getDay(),week:f(t),month:t.getMonth(),year:t.getYear()}}function f(e){var t=0,r=new Date(e.getFullYear(),0,1);return r.getDay()>e.getDay()&&(t=1),Math.floor((e.getTime()-r.getTime())/M.week)+t-1}function y(e){return c(e,new Date(e))}function m(e,t,r){return 0===e?"now":d(e,t,r)||l(e,t,r)||k(e,t,r)||D(t,r)}function d(e,t,r){return g(e,"day",t,r,"today","tomorrow","yesterday")}function g(e,t,r,n,a,o,u){if(2*M[t]>e){if(r[t]===n[t])return a;if(w(r[t],n[t],x[t]))return o;if(w(n[t],r[t],x[t]))return u}}function w(e,t,r){return e===t-1||e===r-1&&0===t}function l(e,t,r){return h(e,"week",t,r)}function h(e,t,r,n){return g(e,t,r,n,"this "+t,"next "+t,"last "+t)}function k(e,t,r){return h(e,"month",t,r)}function D(e,t){return e.year===t.year?"this year":e.year===t.year+1?"last year":e.year===t.year-1?"next year":void 0}function b(e,t){var r=Math.floor(e/M.year);return 0>t?"in "+r+" years":r+" years ago"}function v(e){var t=new Date;switch(e){case"now":break;case"today":p(t);break;case"yesterday":t.setDate(t.getDate()-1),p(t);break;case"tomorrow":t.setDate(t.getDate()+1),p(t);break;case"last week":t.setDate(t.getDate()-7),p(t);break;case"next week":t.setDate(t.getDate()+7),p(t);break;case"last month":t.setMonth(t.getMonth()-1),p(t);break;case"next month":t.setMonth(t.getMonth()+1),p(t);break;case"last year":t.setYear(t.getYear()-1),p(t);break;case"next year":t.setYear(t.getYear()+1),p(t);break;case"whenever":t=new Date(0);break;default:throw Error("Invalid vague date")}return t}function p(e){e.setHours(23),e.setMinutes(59),e.setSeconds(59),e.setMilliseconds(999)}var M={day:864e5,week:6048e5,month:26784e5,year:31536e6},x={day:7,week:52,month:12},Y={get:e,set:v};"undefined"==typeof module||null===module?window.vagueDate=Y:module.exports=Y})();<commit_msg>Update minified script.<commit_after>(function(){"use strict";function e(e){var n=t(e.units),a=Date.now(),o=r(e.from,n,a),u=r(e.to,n,a),i=o.timestamp-u.timestamp,s=Math.abs(i);return m(s,o,u)||b(s,i)}function t(e){if(e===void 0)return"ms";if("s"===e||"ms"===e)return e;throw Error("Invalid units")}function r(e,t,r){if(e===void 0)return i(r);if("string"==typeof e&&(e=parseInt(e,10)),n(e)&&o(e))throw Error("Invalid time");return"number"==typeof e&&"s"===t&&(e*=1e3),i(e)}function n(e){return a(e)===!1}function a(e){return"[object Date]"===Object.prototype.toString.call(e)&&isNaN(e.getTime())===!1}function o(e){return u(e)===!1}function u(e){return"number"==typeof e&&isNaN(e)===!1}function i(e){return a(e)?s(e):u(e)?y(e):void 0}function s(e){return c(e.getTime(),e)}function c(e,t){return{timestamp:e,day:t.getDay(),week:f(t),month:t.getMonth(),year:t.getYear()}}function f(e){var t=0,r=new Date(e.getFullYear(),0,1);return r.getDay()>e.getDay()&&(t=1),Math.floor((e.getTime()-r.getTime())/M.week)+t-1}function y(e){return c(e,new Date(e))}function m(e,t,r){return 0===e?"now":d(e,t,r)||l(e,t,r)||k(e,t,r)||D(t,r)}function d(e,t,r){return g(e,"day",t,r,"today","tomorrow","yesterday")}function g(e,t,r,n,a,o,u){if(2*M[t]>e){if(r[t]===n[t])return a;if(w(r[t],n[t],x[t]))return o;if(w(n[t],r[t],x[t]))return u}}function w(e,t,r){return e===t-1||e===r-1&&0===t}function l(e,t,r){return h(e,"week",t,r)}function h(e,t,r,n){return g(e,t,r,n,"this "+t,"next "+t,"last "+t)}function k(e,t,r){return h(e,"month",t,r)}function D(e,t){return e.year===t.year?"this year":e.year===t.year+1?"last year":e.year===t.year-1?"next year":void 0}function b(e,t){var r=Math.floor(e/M.year);return 0>t?"in "+r+" years":r+" years ago"}function v(e){var t=new Date;switch(e){case"now":break;case"today":p(t);break;case"yesterday":t.setDate(t.getDate()-1),p(t);break;case"tomorrow":t.setDate(t.getDate()+1),p(t);break;case"last week":t.setDate(t.getDate()-7),p(t);break;case"next week":t.setDate(t.getDate()+7),p(t);break;case"last month":t.setMonth(t.getMonth()-1),p(t);break;case"next month":t.setMonth(t.getMonth()+1),p(t);break;case"last year":t.setYear(t.getYear()-1),p(t);break;case"next year":t.setYear(t.getYear()+1),p(t);break;case"whenever":t=new Date(0);break;default:throw Error("Invalid vague date")}return t}function p(e){e.setHours(23),e.setMinutes(59),e.setSeconds(59),e.setMilliseconds(999)}var M={day:864e5,week:6048e5,month:26784e5,year:31536e6},x={day:7,week:52,month:12},Y={get:e,set:v};"undefined"==typeof module||null===module?window.vagueDate=Y:module.exports=Y})();<|endoftext|>


<commit_before>/**
 * Resize function without multiple trigger
 *
 * Usage:
 * $(window).smartresize(function(){
 *     // code here
 * });
 */
(function($,sr){
    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced () {
            var obj = this, args = arguments;
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            }

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);
        };
    };

    // smartresize
    jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0],
    $BODY = $('body'),
    $MENU_TOGGLE = $('#menu_toggle'),
    $SIDEBAR_MENU = $('#sidebar-menu'),
    $SIDEBAR_FOOTER = $('.sidebar-footer'),
    $LEFT_COL = $('.left_col'),
    $RIGHT_COL = $('.right_col'),
    $NAV_MENU = $('.nav_menu'),
    $FOOTER = $('footer');

// Sidebar
function init_sidebar() {
// TODO: This is some kind of easy fix, maybe we can improve this
    var setContentHeight = function () {
        // reset height
        $RIGHT_COL.css('min-height', $(window).height());

        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

        // normalize content
        contentHeight -= $NAV_MENU.height() + footerHeight;

        $RIGHT_COL.css('min-height', contentHeight);
    };

    $SIDEBAR_MENU.find('a').on('click', function(ev) {
        console.log('clicked - sidebar_menu');
        var $li = $(this).parent();

        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $('ul:first', $li).slideUp(function() {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $SIDEBAR_MENU.find('li ul').slideUp();
            }else
            {
                if ( $BODY.is( ".nav-sm" ) )
                {
                    $SIDEBAR_MENU.find( "li" ).removeClass( "active active-sm" );
                    $SIDEBAR_MENU.find( "li ul" ).slideUp();
                }
            }
            $li.addClass('active');

            $('ul:first', $li).slideDown(function() {
                setContentHeight();
            });
        }
    });

// toggle small or large menu
    $MENU_TOGGLE.on('click', function() {
        console.log('clicked - menu toggle');

        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();
    });

    // check active menu
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function() {
        setContentHeight();
    }).parent().addClass('active');

    // recompute content when resizing
    $(window).smartresize(function(){
        setContentHeight();
    });

    setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel:{ preventDefault: true }
        });
    }
}

/* AUTOSIZE */

function init_autosize() {

    if(typeof $.fn.autosize !== 'undefined'){

        autosize($('.resizable_textarea'));

    }

}

var hisUrls = [], hisIndex = 0, hisLength = 10;
var dataListQueryJson = "{}", dataListQueryEntity = "";
var returnPage = false;
var username = "";

function render(url){
    $.ajax({
        type: "get",
        url:  url,

        success: function (pageContent) {
            if (isValid(pageContent, url.substring(0, url.indexOf("/")))) {
                setHisUrls(url);
                $("#pageContent").empty().html(pageContent);
            }
        }
    });
}

function renderAudit(element, url){
    $("#cancel, #return").unbind("click").click(function(){
        render(getPreUrls());
        returnPage = true;
    });

    $.ajax({
        type: "get",
        url:  url,
        success: function (pageContent) {
            if (isValid(pageContent, url.substring(0, url.indexOf("/")))) {

                pageContent = pageContent.replace("right_col", "").
                replace('', '');

                element.empty().html(pageContent);

                /**
                 * 蕴藏部分元素
                 */
                element.find(".page-title").css("display", "none");
                element.find(".clearfix").css("display", "none");
                element.find(".x_title").css("display", "none");
                var children = document.getElementById("form").children;
                var index = children.length - 1;
                for (; index >= 0; index--) {
                    if (children[index].tagName.toLowerCase() == "div") {
                        children[index].innerHTML = "";
                        break;
                    }
                }
                $('#result').attr("readonly", false).css("border", "1px solid #ccc");

                document.getElementById("submitDiv").parentNode.innerHTML = "";
            }
        }
    });
}

function isValid(pageContent, contextPath) {
    if (typeof pageContent == 'object' && pageContent.result.indexOf("对不起，你访问的页面不存在，或者会话已经过期") != -1) {
        $("#pageContent").empty().html("
" + pageContent.result +
            "

请重新登录
");

        return false;
    }

    return true;
}

function setHisUrls(url) {
    if (url != hisUrls[hisIndex]) {
        if (hisUrls.length == hisLength) {
            hisIndex = 0;
        } else {
            ++hisIndex;
        }

        hisUrls[hisIndex] = url;
    }
}

function getPreUrls() {
    if (hisIndex == 0 && hisUrls.length == hisLength) {
        hisIndex = hisUrls.length - 1;
    } else {
        --hisIndex;
    }

    return hisUrls[hisIndex];
}

function setSelect(src, value) {
    var options = src.options;
    for (var i = 0; i < options.length; i++) {
        if (options[i].value == value) {
            options[i].selected = true;
        }
    }
}

function setMutilSelect(src, values) {
    for (var vi in values) {
        setSelect(src, values[vi]);
    }
}

function init(editable) {
    $("#edit").unbind("click").click(function(){
        editable = true;

        $('#form :input').attr("readonly",false).css("border", "1px solid #ccc");
        $('#send, #delete, #recover').attr("disabled", false);
        $("#edit").attr("disabled", "disabled");
    });

    $("#editState").unbind("click").click(function(){
        $('#delete, #recover').attr("disabled", false);
        $("#editState").attr("disabled", "disabled");
    });

    if (!editable) {
        $('#form :input').attr("readonly","readonly").css("border", "0");
        $('#send, #delete, #recover').attr("disabled","disabled");
    }

    $("#cancel, #return").unbind("click").click(function(){
        render(getPreUrls());
        returnPage = true;
    });
}

$(document).ready(function() {
    init_sidebar();
    init_autosize();

    $("#auditA").click();

    $("#signOut").click(function(){
        $("#signOutForm").submit();
    });

    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
        });
    }

    $("#send").keydown(function(event){
        if(event.keyCode == 13){ //绑定回车
            this.click();
            // event.preventDefault();
            return false;
        }
    });

    $("#sidebar-menu ul li ul li a").click(function(){render($(this).attr("href").toString().substring(1));});
});
<commit_msg>add account style input<commit_after>/**
 * Resize function without multiple trigger
 *
 * Usage:
 * $(window).smartresize(function(){
 *     // code here
 * });
 */
(function($,sr){
    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced () {
            var obj = this, args = arguments;
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            }

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);
        };
    };

    // smartresize
    jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0],
    $BODY = $('body'),
    $MENU_TOGGLE = $('#menu_toggle'),
    $SIDEBAR_MENU = $('#sidebar-menu'),
    $SIDEBAR_FOOTER = $('.sidebar-footer'),
    $LEFT_COL = $('.left_col'),
    $RIGHT_COL = $('.right_col'),
    $NAV_MENU = $('.nav_menu'),
    $FOOTER = $('footer');

// Sidebar
function init_sidebar() {
// TODO: This is some kind of easy fix, maybe we can improve this
    var setContentHeight = function () {
        // reset height
        $RIGHT_COL.css('min-height', $(window).height());

        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

        // normalize content
        contentHeight -= $NAV_MENU.height() + footerHeight;

        $RIGHT_COL.css('min-height', contentHeight);
    };

    $SIDEBAR_MENU.find('a').on('click', function(ev) {
        console.log('clicked - sidebar_menu');
        var $li = $(this).parent();

        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $('ul:first', $li).slideUp(function() {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $SIDEBAR_MENU.find('li ul').slideUp();
            }else
            {
                if ( $BODY.is( ".nav-sm" ) )
                {
                    $SIDEBAR_MENU.find( "li" ).removeClass( "active active-sm" );
                    $SIDEBAR_MENU.find( "li ul" ).slideUp();
                }
            }
            $li.addClass('active');

            $('ul:first', $li).slideDown(function() {
                setContentHeight();
            });
        }
    });

// toggle small or large menu
    $MENU_TOGGLE.on('click', function() {
        console.log('clicked - menu toggle');

        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();
    });

    // check active menu
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function() {
        setContentHeight();
    }).parent().addClass('active');

    // recompute content when resizing
    $(window).smartresize(function(){
        setContentHeight();
    });

    setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel:{ preventDefault: true }
        });
    }
}

/* AUTOSIZE */

function init_autosize() {

    if(typeof $.fn.autosize !== 'undefined'){

        autosize($('.resizable_textarea'));

    }

}

var hisUrls = [], hisIndex = 0, hisLength = 10;
var dataListQueryJson = "{}", dataListQueryEntity = "";
var returnPage = false;
var username = "";

function render(url){
    $.ajax({
        type: "get",
        url:  url,

        success: function (pageContent) {
            if (isValid(pageContent, url.substring(0, url.indexOf("/")))) {
                setHisUrls(url);
                $("#pageContent").empty().html(pageContent);
            }
        }
    });
}

function renderAudit(element, url){
    $("#cancel, #return").unbind("click").click(function(){
        render(getPreUrls());
        returnPage = true;
    });

    $.ajax({
        type: "get",
        url:  url,
        success: function (pageContent) {
            if (isValid(pageContent, url.substring(0, url.indexOf("/")))) {

                pageContent = pageContent.replace("right_col", "").
                replace('', '');

                element.empty().html(pageContent);

                /**
                 * 蕴藏部分元素
                 */
                element.find(".page-title").css("display", "none");
                element.find(".clearfix").css("display", "none");
                element.find(".x_title").css("display", "none");
                var children = document.getElementById("form").children;
                var index = children.length - 1;
                for (; index >= 0; index--) {
                    if (children[index].tagName.toLowerCase() == "div") {
                        children[index].innerHTML = "";
                        break;
                    }
                }
                $('#result').attr("readonly", false).css("border", "1px solid #ccc");

                document.getElementById("submitDiv").parentNode.innerHTML = "";
            }
        }
    });
}

function isValid(pageContent, contextPath) {
    if (typeof pageContent == 'object' && pageContent.result.indexOf("对不起，你访问的页面不存在，或者会话已经过期") != -1) {
        $("#pageContent").empty().html("
" + pageContent.result +
            "

请重新登录
");

        return false;
    }

    return true;
}

function setHisUrls(url) {
    if (url != hisUrls[hisIndex]) {
        if (hisUrls.length == hisLength) {
            hisIndex = 0;
        } else {
            ++hisIndex;
        }

        hisUrls[hisIndex] = url;
    }
}

function getPreUrls() {
    if (hisIndex == 0 && hisUrls.length == hisLength) {
        hisIndex = hisUrls.length - 1;
    } else {
        --hisIndex;
    }

    return hisUrls[hisIndex];
}

function setSelect(src, value) {
    var options = src.options;
    for (var i = 0; i < options.length; i++) {
        if (options[i].value == value) {
            options[i].selected = true;
        }
    }
}

function setMutilSelect(src, values) {
    for (var vi in values) {
        setSelect(src, values[vi]);
    }
}

$.fn.accountInput = function(){
    $(this).keyup(function(event){
        if (event.keyCode != 8 || event.keyCode != 46) {  // 8: BackSpace key code, 46: delete key code
            var value = this.value.replace(/\s*/g, "");
            var spaceValue = "";
            for (var i = 0; i < value.length; i++) {
                spaceValue += value.charAt(i);
                if ((i+1)%4 == 0) {
                    spaceValue += " ";
                }
            }
            this.value = spaceValue;
        }
    });
}

function init(editable) {
    $("#edit").unbind("click").click(function(){
        editable = true;

        $('#form :input').attr("readonly",false).css("border", "1px solid #ccc");
        $('#send, #delete, #recover').attr("disabled", false);
        $("#edit").attr("disabled", "disabled");
    });

    $("#editState").unbind("click").click(function(){
        $('#delete, #recover').attr("disabled", false);
        $("#editState").attr("disabled", "disabled");
    });

    if (!editable) {
        $('#form :input').attr("readonly","readonly").css("border", "0");
        $('#send, #delete, #recover').attr("disabled","disabled");
    }

    $("#cancel, #return").unbind("click").click(function(){
        render(getPreUrls());
        returnPage = true;
    });
}

$(document).ready(function() {
    init_sidebar();
    init_autosize();

    $("#auditA").click();

    $("#signOut").click(function(){
        $("#signOutForm").submit();
    });

    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
        });
    }

    $("#send").keydown(function(event){
        if(event.keyCode == 13){ //绑定回车
            this.click();
            // event.preventDefault();
            return false;
        }
    });

    $("#sidebar-menu ul li ul li a").click(function(){render($(this).attr("href").toString().substring(1));});
});
<|endoftext|>


<commit_before>(function(){"use strict";function t(t){var u,o,i=r(t.units),f=Date.now(),s=n(t.from,i,f),a=n(t.to,i,f);return u=s-a,u>0?o="past":(o="future",u=-u),e(u,o)}function r(t){if(t===void 0)return"s";if("s"===t||"ms"===t)return t;throw Error("Invalid units")}function n(t,r,n){if(t===void 0)return n;if("string"==typeof t&&(t=parseInt(t,10)),"number"!=typeof t||isNaN(t))throw Error("Invalid timestamp");return"s"===r?1e3*t:t}function e(t,r){var n,e;for(n in f)if(f.hasOwnProperty(n)&&t>=f[n])return e=Math.floor(t/f[n]),a[r](e,u(n,e));return s[r]}function u(t,r){return t+(r>1?"s":"")}function o(t,r){return t+" "+r+" ago"}function i(t,r){return"in "+t+" "+r}var f={year:315576e5,month:26298e5,week:6048e5,day:864e5,hour:36e5,minute:6e4},s={past:"just now",future:"now"},a={past:o,future:i};"undefined"==typeof exports||null===exports?window.vagueTime={get:t}:exports.get=t})();<commit_msg>Update minified script.<commit_after>(function(){"use strict";function t(t){var u,o=r(t.units),i=Date.now(),f=n(t.from,o,i),s=n(t.to,o,i),a=f-s;return a>0?u="past":(u="future",a=-a),e(a,u)}function r(t){if(t===void 0)return"ms";if("s"===t||"ms"===t)return t;throw Error("Invalid units")}function n(t,r,n){if(t===void 0)return n;if("string"==typeof t&&(t=parseInt(t,10)),"number"!=typeof t||isNaN(t))throw Error("Invalid timestamp");return"s"===r?1e3*t:t}function e(t,r){var n,e;for(n in f)if(f.hasOwnProperty(n)&&t>=f[n])return e=Math.floor(t/f[n]),a[r](e,u(n,e));return s[r]}function u(t,r){return t+(r>1?"s":"")}function o(t,r){return t+" "+r+" ago"}function i(t,r){return"in "+t+" "+r}var f={year:315576e5,month:26298e5,week:6048e5,day:864e5,hour:36e5,minute:6e4},s={past:"just now",future:"now"},a={past:o,future:i};"undefined"==typeof exports||null===exports?window.vagueTime={get:t}:exports.get=t})();<|endoftext|>


<commit_before>import React from 'react';
import {
  branch,
  compose,
  renderComponent,
  withState,
} from 'recompose';
import { connect } from 'react-redux';
import { addAnalysis } from '@ncigdc/dux/analysis';
import withRouter from '@ncigdc/utils/withRouter';
import Button from '@ncigdc/uikit/Button';
import { Row } from '@ncigdc/uikit/Flex';
import { zDepth1 } from '@ncigdc/theme/mixins';
import availableAnalysis from './availableAnalysis';
import SelectSet from './SelectSet';
import DemoButton from './DemoButton';
import defaultVariables from './defaultCDAVEvariables';

const enhance = compose(
  branch(
    () => !availableAnalysis.length,
    renderComponent(() => (

        No analysis currently available

    )),
  ),
  withState('analysis', 'setAnalysis', null),
  connect(state => ({
    numAnalysis: state.analysis.saved.filter(analysis => analysis.type === 'clinical_data').length,
  })),
  withRouter,
);

const CreateAnalysis = ({
  analysis,
  dispatch,
  numAnalysis,
  push,
  setAnalysis,
}) => {
  return analysis
    ? (
      <SelectSet
        analysisProps={analysis}
        onCancel={() => setAnalysis(null)}
        onRun={sets => {
          const created = new Date().toISOString();
          const id = created;

          dispatch(
            addAnalysis({
              created,
              id,
              sets,
              type: analysis.type,
              ...analysis.type === 'clinical_data' && {
                displayVariables: defaultVariables,
                name: `Custom Analysis ${numAnalysis + 1}`,
              },
            }),
          ).then(() => {
            push({
              query: {
                analysisId: id,
                analysisTableTab: 'result',
              },
            });
          });
        }}
        />
    )
    : (
      <Row
        style={{
          flexFlow: 'row wrap',
          justifyContent: 'space-between',
          margin: '0 2rem',
          padding: '2rem 2.5rem',
        }}
        >
        {availableAnalysis.map(item => {
          const isSCRNASeq = item.type === 'scrna_seq';

          return (
            <Row
              key={item.type}
              style={{
                ...zDepth1,
                margin: '2rem',
                padding: '2rem',
                width: '45%',
              }}
              >

                <item.Icon />

{item.label}

{item.description}

                <Row spacing={5}>
                  {isSCRNASeq || (
                    <Button onClick={() => setAnalysis(item)}>Select</Button>
                  )}
                  <DemoButton demoData={item.demoData} type={item.type} />
                </Row>

            </Row>
          );
        })}
      </Row>
    );
};

export default enhance(CreateAnalysis);
<commit_msg>[PRTL-3190] add demo button for scrna-seq (#2896)<commit_after>import React from 'react';
import {
  branch,
  compose,
  renderComponent,
  withState,
} from 'recompose';
import { connect } from 'react-redux';
import { addAnalysis } from '@ncigdc/dux/analysis';
import withRouter from '@ncigdc/utils/withRouter';
import Button from '@ncigdc/uikit/Button';
import { Row } from '@ncigdc/uikit/Flex';
import { zDepth1 } from '@ncigdc/theme/mixins';
import Tooltip from '@ncigdc/uikit/Tooltip/Tooltip';
import availableAnalysis from './availableAnalysis';
import SelectSet from './SelectSet';
import DemoButton from './DemoButton';
import defaultVariables from './defaultCDAVEvariables';

const enhance = compose(
  branch(
    () => !availableAnalysis.length,
    renderComponent(() => (

        No analysis currently available

    )),
  ),
  withState('analysis', 'setAnalysis', null),
  connect(state => ({
    numAnalysis: state.analysis.saved.filter(analysis => analysis.type === 'clinical_data').length,
  })),
  withRouter,
);

const CreateAnalysis = ({
  analysis,
  dispatch,
  numAnalysis,
  push,
  setAnalysis,
}) => {
  return analysis
    ? (
      <SelectSet
        analysisProps={analysis}
        onCancel={() => setAnalysis(null)}
        onRun={sets => {
          const created = new Date().toISOString();
          const id = created;

          dispatch(
            addAnalysis({
              created,
              id,
              sets,
              type: analysis.type,
              ...analysis.type === 'clinical_data' && {
                displayVariables: defaultVariables,
                name: `Custom Analysis ${numAnalysis + 1}`,
              },
            }),
          ).then(() => {
            push({
              query: {
                analysisId: id,
                analysisTableTab: 'result',
              },
            });
          });
        }}
        />
    )
    : (
      <Row
        style={{
          flexFlow: 'row wrap',
          justifyContent: 'space-between',
          margin: '0 2rem',
          padding: '2rem 2.5rem',
        }}
        >
        {availableAnalysis.map(item => {
          const isSCRNASeq = item.type === 'scrna_seq';

          return (
            <Row
              key={item.type}
              style={{
                ...zDepth1,
                margin: '2rem',
                padding: '2rem',
                width: '45%',
              }}
              >

                <item.Icon />

{item.label}

{item.description}

                {isSCRNASeq
                // TEMP: scrnaseq only has a demo button,
                // and it goes to the select page
                  ? (
                    <Tooltip
                      Component={
{item.demoData.message}
}
                      >
                      <Button onClick={() => setAnalysis(item)}>Demo</Button>
                    </Tooltip>
                  )
                  : (
                    <Row spacing={5}>
                      <Button onClick={() => setAnalysis(item)}>Select</Button>
                      <DemoButton demoData={item.demoData} type={item.type} />
                    </Row>
                  )
                }

            </Row>
          );
        })}
      </Row>
    );
};

export default enhance(CreateAnalysis);
<|endoftext|>


<commit_before>mwUI.Backbone.NestedModel = Backbone.NestedModel = Backbone.Model.extend({

  nested: function () {
    return {};
  },

  _prepare: function () {
    var nestedAttributes = this.nested(),
      instanceObject = {};
    for (var key in nestedAttributes) {
      if (typeof nestedAttributes[key] === 'function') {
        var instance = new nestedAttributes[key]();

        instance.parent = this;
        instanceObject[key] = instance;
      } else {
        throw new Error('Nested attribute ' + key + ' is not a valid constructor. Do not set an instance as nested attribute.');
      }
    }

    return instanceObject;
  },

  _setNestedModel: function (key, value) {
    if (_.isObject(value)) {
      this.get(key).set(value);
    } else {
      var id = this.get(key).idAttribute;
      this.get(key).set(id, value);
    }
  },

  _setNestedCollection: function (key, value) {
    if (_.isObject(value) && !_.isArray(value)) {
      this.get(key).add(value);
    } else if (_.isArray(value)) {
      value.forEach(function (val) {
        this._setNestedCollection(key, val);
      }.bind(this));
    } else {
      var id = this.get(key).model.prototype.idAttribute,
        obj = {};

      obj[id] = value;
      this.get(key).add(obj);
    }
  },

  _setNestedAttributes: function (obj) {

    for (var key in obj) {
      var nestedAttrs = this.nested(),
        value = obj[key],
        nestedValue = nestedAttrs[key];

      if (nestedValue && !(value instanceof nestedValue) && this.get(key)) {

        if (this.get(key) instanceof Backbone.Model) {
          this._setNestedModel(key, value);
        } else if (this.get(key) instanceof Backbone.Collection) {
          this._setNestedCollection(key, value);
        }

        delete obj[key];
      }
    }

    return obj;
  },

  _nestedModelToJson: function (model) {
    var result;

    if (model instanceof Backbone.NestedModel) {
      result = model._prepareDataForServer();
    } else {
      result = model.toJSON();
    }

    return result;
  },

  _prepareDataForServer: function () {
    var attrs = _.extend({}, this.attributes),
      nestedAttrs = this.nested();

    for (var key in nestedAttrs) {
      var nestedAttr = this.get(key);

      if (nestedAttr instanceof Backbone.Model) {
        attrs[key] = this._nestedModelToJson(nestedAttr);
      } else if (nestedAttr instanceof Backbone.Collection) {
        var result = [];

        nestedAttr.each(function (model) {
          result.push(this._nestedModelToJson(model));
        }.bind(this));

        attrs[key] = result;
      }
    }

    return this.compose(attrs);
  },

  constructor: function (attributes, options) {
    options = options || {};
    if (options.parse) {
      attributes = this.parse(attributes);
      options.parse = false;
    }
    this.attributes = this._prepare();
    this.set(attributes);
    attributes = this.attributes;
    return Backbone.Model.prototype.constructor.call(this, attributes, options);
  },

  set: function (attributes, options) {
    var obj = {};

    if (_.isString(attributes)) {
      obj[attributes] = options;
    } else if (_.isObject(attributes)) {
      obj = attributes;
    }

    obj = this._setNestedAttributes(obj);

    return Backbone.Model.prototype.set.call(this, obj);
  },

  compose: function (attrs) {
    return attrs;
  },

  toJSON: function (options) {
    // When options are set toJSON is called from the sync method so it is called before the object is send to the server
    // We use this to transform our data before we are sending it to the server
    // It is the counterpart of parse for the server
    if (options) {
      return this._prepareDataForServer();
    } else {
      return Backbone.Model.prototype.toJSON.apply(this, arguments);
    }
  },

  clear: function () {
    var superClear = Backbone.Model.prototype.clear.apply(this, arguments);
    this.attributes = this._prepare();
    return superClear;
  }
});

<commit_msg>fixes bug that options where not passed through<commit_after>mwUI.Backbone.NestedModel = Backbone.NestedModel = Backbone.Model.extend({

  nested: function () {
    return {};
  },

  _prepare: function () {
    var nestedAttributes = this.nested(),
      instanceObject = {};
    for (var key in nestedAttributes) {
      if (typeof nestedAttributes[key] === 'function') {
        var instance = new nestedAttributes[key]();

        instance.parent = this;
        instanceObject[key] = instance;
      } else {
        throw new Error('Nested attribute ' + key + ' is not a valid constructor. Do not set an instance as nested attribute.');
      }
    }

    return instanceObject;
  },

  _setNestedModel: function (key, value) {
    if (_.isObject(value)) {
      this.get(key).set(value);
    } else {
      var id = this.get(key).idAttribute;
      this.get(key).set(id, value);
    }
  },

  _setNestedCollection: function (key, value) {
    if (_.isObject(value) && !_.isArray(value)) {
      this.get(key).add(value);
    } else if (_.isArray(value)) {
      value.forEach(function (val) {
        this._setNestedCollection(key, val);
      }.bind(this));
    } else {
      var id = this.get(key).model.prototype.idAttribute,
        obj = {};

      obj[id] = value;
      this.get(key).add(obj);
    }
  },

  _setNestedAttributes: function (obj) {

    for (var key in obj) {
      var nestedAttrs = this.nested(),
        value = obj[key],
        nestedValue = nestedAttrs[key];

      if (nestedValue && !(value instanceof nestedValue) && this.get(key)) {

        if (this.get(key) instanceof Backbone.Model) {
          this._setNestedModel(key, value);
        } else if (this.get(key) instanceof Backbone.Collection) {
          this._setNestedCollection(key, value);
        }

        delete obj[key];
      }
    }

    return obj;
  },

  _nestedModelToJson: function (model) {
    var result;

    if (model instanceof Backbone.NestedModel) {
      result = model._prepareDataForServer();
    } else {
      result = model.toJSON();
    }

    return result;
  },

  _prepareDataForServer: function () {
    var attrs = _.extend({}, this.attributes),
      nestedAttrs = this.nested();

    for (var key in nestedAttrs) {
      var nestedAttr = this.get(key);

      if (nestedAttr instanceof Backbone.Model) {
        attrs[key] = this._nestedModelToJson(nestedAttr);
      } else if (nestedAttr instanceof Backbone.Collection) {
        var result = [];

        nestedAttr.each(function (model) {
          result.push(this._nestedModelToJson(model));
        }.bind(this));

        attrs[key] = result;
      }
    }

    return this.compose(attrs);
  },

  constructor: function (attributes, options) {
    options = options || {};
    if (options.parse) {
      attributes = this.parse(attributes);
      options.parse = false;
    }
    this.attributes = this._prepare();
    this.set(attributes);
    attributes = this.attributes;
    return Backbone.Model.prototype.constructor.call(this, attributes, options);
  },

  set: function (attributes, options) {
    var obj = {};

    if (_.isString(attributes)) {
      obj[attributes] = options;
    } else if (_.isObject(attributes)) {
      obj = attributes;
    }

    if(!_.isObject(options)){
      options = null;
    }

    obj = this._setNestedAttributes(obj);

    return Backbone.Model.prototype.set.call(this, obj, options);
  },

  compose: function (attrs) {
    return attrs;
  },

  toJSON: function (options) {
    // When options are set toJSON is called from the sync method so it is called before the object is send to the server
    // We use this to transform our data before we are sending it to the server
    // It is the counterpart of parse for the server
    if (options) {
      return this._prepareDataForServer();
    } else {
      return Backbone.Model.prototype.toJSON.apply(this, arguments);
    }
  },

  clear: function () {
    var superClear = Backbone.Model.prototype.clear.apply(this, arguments);
    this.attributes = this._prepare();
    return superClear;
  }
});

<|endoftext|>