<commit_before>"use strict";

// Submission ID, S7755084
// Common Name, Black-bellied Whistling-Duck
// Scientific Name, Dendrocygna autumnalis
// Taxonomic Order, 215
// Count, X
// State/Province, US-TX
// County, Cameron
// Location, Brownsville
// Latitude, 25.911388
// Longitude, -97.4904876
// Date, 04-17-2004
// Time,
// Protocol, eBird - Casual Observation
// Duration (Min),
// All Obs Reported,
// Distance Traveled (km),
// Area Covered (ha),
// Number of Observers,
// Breeding Code,
// Species Comments,
// Checklist Comments

var gSightings = [];
var gChecklists = [];
var gEarliestSightingDateObject = null;
var gLatestSightingDateObject = null;
var gOmittedCommonNames = [];
var gLifeSightingsTaxonomic = [];
var gLifeSightingsChronological = [];
var gSightingsByYear = {};
var gEarliestSightingByCommonName = {};
var gLocations = [];
var gDates = [];
var gCustomDayNames = [];

function getEarliestSighting(sightingList) {
	sightingList.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });
	return sightingList[0];
}

function getLatestSighting(sightingList) {
	sightingList.sort(function(a, b) { return b['DateObject'] - a['DateObject']; });
	return sightingList[0];
}

function getUniqueValues(sightingList, fieldName) {
	var values = [];

	for (var index = 1; index < sightingList.length; index++) {
		var aValue = sightingList[index][fieldName];
		if (values.indexOf(aValue) < 0) {
			values.push(aValue);
		}
	}

	return values;
};

function addDateObjects() {
	for (var index = 0; index < gSightings.length; index++) {
		var sighting = gSightings[index];

		if (sighting['Date']) {
			var pieces = sighting['Date'].split('-');
			var fixedDateString = [pieces[0], '/', pieces[1], '/', pieces[2]].join('');
			var newDate = new Date(fixedDateString);
			gSightings[index]['DateObject'] = newDate;

			if (gEarliestSightingDateObject == null || newDate < gEarliestSightingDateObject) {
				gEarliestSightingDateObject = newDate;
			}

			if (gLatestSightingDateObject == null || newDate > gLatestSightingDateObject) {
				gLatestSightingDateObject = newDate;
			}

			if (! gSightingsByYear[pieces[2]]) {
				gSightingsByYear[pieces[2]] = [];
			}
			gSightingsByYear[pieces[2]].push(sighting);

			var omit = gOmittedCommonNames.indexOf(sighting['Common Name']) >=0;

			if (! omit) {
				if (! gEarliestSightingByCommonName[sighting['Common Name']]) {
					gEarliestSightingByCommonName[sighting['Common Name']] = sighting;
				} else if (sighting.DateObject < gEarliestSightingByCommonName[sighting['Common Name']].DateObject) {
					gEarliestSightingByCommonName[sighting['Common Name']] = sighting;
				}
			}
		}
	}

	gSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });
}

function renderTemplate(inPrefix, inData) {
    var theTemplateScript = document.getElementById(inPrefix + '-template').innerHTML;
    var theTemplate = Handlebars.compile(theTemplateScript);
	var newDiv = document.createElement("div");
	newDiv.innerHTML = theTemplate(inData);

	var results = document.getElementById(inPrefix + '-results');
	while (results.firstChild) {
	    results.removeChild(results.firstChild);
	}

    results.appendChild(newDiv);
}

function showSection(inSelector) {
	var sections = document.querySelectorAll(inSelector);
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('hidden');
		sections[index].classList.add('visible');
	}
}

function hideAllSections() {
	var sections = document.querySelectorAll('section.card');
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('visible');
		sections[index].classList.add('hidden');
	}
}

function barGraphCountsForSightings(inData, inElement) {
	var labels = Object.keys(inData).map(function(k){return k;});
	var values = Object.keys(inData).map(function(k){return inData[k].length;});
	var values2 = Object.keys(inData).map(function(k){return getUniqueValues(inData[k], 'Common Name').length;});
	var values3 = Object.keys(inData).map(function(k){return getUniqueValues(inData[k], 'Location').length;});

	labels.unshift('x');
	values.unshift('sightings');
	values2.unshift('species');
	values3.unshift('locations');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		data: {
			x: 'x',
			columns: [
				values,
				values2,
				values3,
				labels,
			],
			types: {
				sightings: 'line',
				species: 'line',
				locations: 'line'
			}
		}
	});
}

var routingMap = {
	'#home' : function() {
		renderTemplate('home', {
			numSightings: gSightings.length,
			sightingsByYear: gSightingsByYear,
			chartID: 'byYear',
			numChecklists: getUniqueValues(gSightings, 'Submission ID').length,
			earliest: gEarliestSightingDateObject,
			latest: gLatestSightingDateObject,
			owner: 'Bill Walker'
		});

		showSection('section#home');
	},
	'#chrono' : function() {
		gLifeSightingsChronological = Object.keys(gEarliestSightingByCommonName).map(function(k){return gEarliestSightingByCommonName[k]});
		gLifeSightingsChronological.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

		renderTemplate('chrono', {
			firstSightings: gLifeSightingsChronological
		});

		showSection('section#chrono');
	},
	'#trips' : function() {
		renderTemplate('trips', {
			trips: gDates,
			customDayNames: gCustomDayNames
		});

		showSection('section#trips');
	},
	'#trip' : function(inDate) {
		var tripSightings = gSightings.filter(function(s) { return s['Date'] == inDate; });

		renderTemplate('trip', {
			name: inDate,
			customName: gCustomDayNames[inDate],
			comments: getUniqueValues(tripSightings, 'Checklist Comments'),
			submissions: getUniqueValues(tripSightings, 'Submission ID'),
			sightings: tripSightings
		});

		showSection('section#trip');
	},
	'#locations' : function() {
		renderTemplate('locations', {
			locations: gLocations
		});

		showSection('section#locations');
	},
	'#location' : function(inLocationName) {
		var locationSightingsChronological = gSightings.filter(function(s) { return s['Location'] == inLocationName; });
		locationSightingsChronological.sort(function(a, b) { return b['DateObject'] - a['DateObject']; });

		var locationSightingsTaxonomic = locationSightingsChronological.slice(0);
		locationSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

		renderTemplate('location', {
			name: inLocationName,
			county: locationSightingsChronological[0]["County"],
			state: locationSightingsChronological[0]["State/Province"],
			locationSightingsTaxonomic: locationSightingsTaxonomic,
			longitude: locationSightingsChronological[0]["Longitude"],
			latitude: locationSightingsChronological[0]["Latitude"],
			dates: getUniqueValues(locationSightingsChronological, "Date"),
			taxons: getUniqueValues(locationSightingsTaxonomic, "Common Name")
		});

		showSection('section#location');
	},
	'#taxons' : function() {
		gLifeSightingsTaxonomic = Object.keys(gEarliestSightingByCommonName).map(function(k){return gEarliestSightingByCommonName[k]});
		gLifeSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

		renderTemplate('taxons', {

			lifeSightings: gLifeSightingsTaxonomic
		});

		showSection('section#taxons');
	},
	'#taxon' : function(inCommonName) {
		var taxonSightings = gSightings.filter(function(s) { return s['Common Name'] == inCommonName; });
		taxonSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

		renderTemplate('taxon', {
			name: inCommonName,
			scientificName: taxonSightings[0]["Scientific Name"],
			sightings: taxonSightings
		});

		showSection('section#taxon');
	},
}

function routeBasedOnHash() {
	// On every hash change the render function is called with the new hash.
	// This is how the navigation of our app happens.
	var theHashParts = window.location.hash.split('/');
	console.log('changed', theHashParts[0], theHashParts[1]);

	hideAllSections();

	if(routingMap[theHashParts[0]]) {
		routingMap[theHashParts[0]](decodeURI(theHashParts[1]));
	} else {
		console.log('not found', window.location.hash);
	}
}

function loadCustomDayNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gCustomDayNames = JSON.parse(this.responseText);
	  console.log('loaded custom day names', Object.keys(gCustomDayNames).length);
	});
	oReq.open("GET", "./data/day-names.json");
	oReq.send();
}

function loadOmittedCommonNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gOmittedCommonNames = JSON.parse(this.responseText);
	  console.log('loaded omitted common names', gOmittedCommonNames.length);
	});
	oReq.open("GET", "./data/omitted-common-names.json");
	oReq.send();
}

document.addEventListener("DOMContentLoaded", function(event) {
	console.log('start DOMContentLoaded');

	Handlebars.registerHelper('nicedate', function(inDate) {
		return new Handlebars.SafeString(
			d3.time.format("%b %d, %Y")(inDate)
		);
	});

	Handlebars.registerHelper('nicenumber', function(inNumber) {
	  return new Handlebars.SafeString(
	    inNumber.toLocaleString()
	  );
	});

	Handlebars.registerHelper('bargraph', function(inData, inElement) {
		// per @digitarald use timeout to reorder helper after Handlebars templating
		window.setTimeout(function () { barGraphCountsForSightings(inData, '#' + inElement) }, 1);
	});

	console.log('end DOMContentLoaded');
});

Papa.parse("./data/ebird.csv", {
	download: true,
	header: true,
	complete: function(results) {
		gSightings = results.data;

		addDateObjects();

		gLocations = getUniqueValues(gSightings, 'Location');
		gDates = getUniqueValues(gSightings, 'Date');
		gChecklists = getUniqueValues(gSightings, 'Submission ID');

		routeBasedOnHash();
	}
});

window.onhashchange = routeBasedOnHash;

loadCustomDayNames();
loadOmittedCommonNames();

<commit_msg>use d3 for number formatting<commit_after>"use strict";

// Submission ID, S7755084
// Common Name, Black-bellied Whistling-Duck
// Scientific Name, Dendrocygna autumnalis
// Taxonomic Order, 215
// Count, X
// State/Province, US-TX
// County, Cameron
// Location, Brownsville
// Latitude, 25.911388
// Longitude, -97.4904876
// Date, 04-17-2004
// Time,
// Protocol, eBird - Casual Observation
// Duration (Min),
// All Obs Reported,
// Distance Traveled (km),
// Area Covered (ha),
// Number of Observers,
// Breeding Code,
// Species Comments,
// Checklist Comments

var gSightings = [];
var gChecklists = [];
var gEarliestSightingDateObject = null;
var gLatestSightingDateObject = null;
var gOmittedCommonNames = [];
var gLifeSightingsTaxonomic = [];
var gLifeSightingsChronological = [];
var gSightingsByYear = {};
var gEarliestSightingByCommonName = {};
var gLocations = [];
var gDates = [];
var gCustomDayNames = [];

function getEarliestSighting(sightingList) {
	sightingList.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });
	return sightingList[0];
}

function getLatestSighting(sightingList) {
	sightingList.sort(function(a, b) { return b['DateObject'] - a['DateObject']; });
	return sightingList[0];
}

function getUniqueValues(sightingList, fieldName) {
	var values = [];

	for (var index = 1; index < sightingList.length; index++) {
		var aValue = sightingList[index][fieldName];
		if (values.indexOf(aValue) < 0) {
			values.push(aValue);
		}
	}

	return values;
};

function addDateObjects() {
	for (var index = 0; index < gSightings.length; index++) {
		var sighting = gSightings[index];

		if (sighting['Date']) {
			var pieces = sighting['Date'].split('-');
			var fixedDateString = [pieces[0], '/', pieces[1], '/', pieces[2]].join('');
			var newDate = new Date(fixedDateString);
			gSightings[index]['DateObject'] = newDate;

			if (gEarliestSightingDateObject == null || newDate < gEarliestSightingDateObject) {
				gEarliestSightingDateObject = newDate;
			}

			if (gLatestSightingDateObject == null || newDate > gLatestSightingDateObject) {
				gLatestSightingDateObject = newDate;
			}

			if (! gSightingsByYear[pieces[2]]) {
				gSightingsByYear[pieces[2]] = [];
			}
			gSightingsByYear[pieces[2]].push(sighting);

			var omit = gOmittedCommonNames.indexOf(sighting['Common Name']) >=0;

			if (! omit) {
				if (! gEarliestSightingByCommonName[sighting['Common Name']]) {
					gEarliestSightingByCommonName[sighting['Common Name']] = sighting;
				} else if (sighting.DateObject < gEarliestSightingByCommonName[sighting['Common Name']].DateObject) {
					gEarliestSightingByCommonName[sighting['Common Name']] = sighting;
				}
			}
		}
	}

	gSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });
}

function renderTemplate(inPrefix, inData) {
    var theTemplateScript = document.getElementById(inPrefix + '-template').innerHTML;
    var theTemplate = Handlebars.compile(theTemplateScript);
	var newDiv = document.createElement("div");
	newDiv.innerHTML = theTemplate(inData);

	var results = document.getElementById(inPrefix + '-results');
	while (results.firstChild) {
	    results.removeChild(results.firstChild);
	}

    results.appendChild(newDiv);
}

function showSection(inSelector) {
	var sections = document.querySelectorAll(inSelector);
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('hidden');
		sections[index].classList.add('visible');
	}
}

function hideAllSections() {
	var sections = document.querySelectorAll('section.card');
	for (var index = 0; index < sections.length; index++) {
		sections[index].classList.remove('visible');
		sections[index].classList.add('hidden');
	}
}

function barGraphCountsForSightings(inData, inElement) {
	var labels = Object.keys(inData).map(function(k){return k;});
	var values = Object.keys(inData).map(function(k){return inData[k].length;});
	var values2 = Object.keys(inData).map(function(k){return getUniqueValues(inData[k], 'Common Name').length;});
	var values3 = Object.keys(inData).map(function(k){return getUniqueValues(inData[k], 'Location').length;});

	labels.unshift('x');
	values.unshift('sightings');
	values2.unshift('species');
	values3.unshift('locations');

	var chart = c3.generate({
		bindto: d3.select(inElement),
		data: {
			x: 'x',
			columns: [
				values,
				values2,
				values3,
				labels,
			],
			types: {
				sightings: 'line',
				species: 'line',
				locations: 'line'
			}
		}
	});
}

var routingMap = {
	'#home' : function() {
		renderTemplate('home', {
			numSightings: gSightings.length,
			sightingsByYear: gSightingsByYear,
			chartID: 'byYear',
			numChecklists: getUniqueValues(gSightings, 'Submission ID').length,
			earliest: gEarliestSightingDateObject,
			latest: gLatestSightingDateObject,
			owner: 'Bill Walker'
		});

		showSection('section#home');
	},
	'#chrono' : function() {
		gLifeSightingsChronological = Object.keys(gEarliestSightingByCommonName).map(function(k){return gEarliestSightingByCommonName[k]});
		gLifeSightingsChronological.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

		renderTemplate('chrono', {
			firstSightings: gLifeSightingsChronological
		});

		showSection('section#chrono');
	},
	'#trips' : function() {
		renderTemplate('trips', {
			trips: gDates,
			customDayNames: gCustomDayNames
		});

		showSection('section#trips');
	},
	'#trip' : function(inDate) {
		var tripSightings = gSightings.filter(function(s) { return s['Date'] == inDate; });

		renderTemplate('trip', {
			name: inDate,
			customName: gCustomDayNames[inDate],
			comments: getUniqueValues(tripSightings, 'Checklist Comments'),
			submissions: getUniqueValues(tripSightings, 'Submission ID'),
			sightings: tripSightings
		});

		showSection('section#trip');
	},
	'#locations' : function() {
		renderTemplate('locations', {
			locations: gLocations
		});

		showSection('section#locations');
	},
	'#location' : function(inLocationName) {
		var locationSightingsChronological = gSightings.filter(function(s) { return s['Location'] == inLocationName; });
		locationSightingsChronological.sort(function(a, b) { return b['DateObject'] - a['DateObject']; });

		var locationSightingsTaxonomic = locationSightingsChronological.slice(0);
		locationSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

		renderTemplate('location', {
			name: inLocationName,
			county: locationSightingsChronological[0]["County"],
			state: locationSightingsChronological[0]["State/Province"],
			locationSightingsTaxonomic: locationSightingsTaxonomic,
			longitude: locationSightingsChronological[0]["Longitude"],
			latitude: locationSightingsChronological[0]["Latitude"],
			dates: getUniqueValues(locationSightingsChronological, "Date"),
			taxons: getUniqueValues(locationSightingsTaxonomic, "Common Name")
		});

		showSection('section#location');
	},
	'#taxons' : function() {
		gLifeSightingsTaxonomic = Object.keys(gEarliestSightingByCommonName).map(function(k){return gEarliestSightingByCommonName[k]});
		gLifeSightingsTaxonomic.sort(function(a, b) { return a['Taxonomic Order'] - b['Taxonomic Order']; });

		renderTemplate('taxons', {

			lifeSightings: gLifeSightingsTaxonomic
		});

		showSection('section#taxons');
	},
	'#taxon' : function(inCommonName) {
		var taxonSightings = gSightings.filter(function(s) { return s['Common Name'] == inCommonName; });
		taxonSightings.sort(function(a, b) { return a['DateObject'] - b['DateObject']; });

		renderTemplate('taxon', {
			name: inCommonName,
			scientificName: taxonSightings[0]["Scientific Name"],
			sightings: taxonSightings
		});

		showSection('section#taxon');
	},
}

function routeBasedOnHash() {
	// On every hash change the render function is called with the new hash.
	// This is how the navigation of our app happens.
	var theHashParts = window.location.hash.split('/');
	console.log('changed', theHashParts[0], theHashParts[1]);

	hideAllSections();

	if(routingMap[theHashParts[0]]) {
		routingMap[theHashParts[0]](decodeURI(theHashParts[1]));
	} else {
		console.log('not found', window.location.hash);
	}
}

function loadCustomDayNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gCustomDayNames = JSON.parse(this.responseText);
	  console.log('loaded custom day names', Object.keys(gCustomDayNames).length);
	});
	oReq.open("GET", "./data/day-names.json");
	oReq.send();
}

function loadOmittedCommonNames() {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", function() {
	  gOmittedCommonNames = JSON.parse(this.responseText);
	  console.log('loaded omitted common names', gOmittedCommonNames.length);
	});
	oReq.open("GET", "./data/omitted-common-names.json");
	oReq.send();
}

document.addEventListener("DOMContentLoaded", function(event) {
	console.log('start DOMContentLoaded');

	Handlebars.registerHelper('nicedate', function(inDate) {
		return new Handlebars.SafeString (
			d3.time.format("%b %d, %Y")(inDate)
		);
	});

	Handlebars.registerHelper('nicenumber', function(inNumber) {
		return new Handlebars.SafeString (
			d3.format(",d")(inNumber)
		);
	});

	Handlebars.registerHelper('bargraph', function(inData, inElement) {
		// per @digitarald use timeout to reorder helper after Handlebars templating
		window.setTimeout(function () { barGraphCountsForSightings(inData, '#' + inElement) }, 1);
	});

	console.log('end DOMContentLoaded');
});

Papa.parse("./data/ebird.csv", {
	download: true,
	header: true,
	complete: function(results) {
		gSightings = results.data;

		addDateObjects();

		gLocations = getUniqueValues(gSightings, 'Location');
		gDates = getUniqueValues(gSightings, 'Date');
		gChecklists = getUniqueValues(gSightings, 'Submission ID');

		routeBasedOnHash();
	}
});

window.onhashchange = routeBasedOnHash;

loadCustomDayNames();
loadOmittedCommonNames();

<|endoftext|>


<commit_before>var init = {
    /*
     * Notice when (auto)depublish date is in the past
     * TODO: add timer, to check depublish date has passed during editing.
     *
     * @returns {undefined}
     */
    depublishTracking: function () {
        "use strict";

        var noticeID = 'dateDepublishNotice',
            msg = $('#datedepublish').data('notice');

        $('#datedepublish, #statusselect').on('change', function (){

            var status = $('#statusselect').val(),
                depublish = $('#datedepublish').val();

            // remove old notice
            $('.' + noticeID).remove();

            if (depublish === '') {
                return;
            }

            if (status === 'published' && moment(depublish + Bolt.conf('timezone.offset')) < moment()) {
                $('
' +
                    '<button type="button" class="close" data-dismiss="alert">×</button>' + msg + '
')
                    .hide()
                    .insertAfter('.depublish-group')
                    .slideDown('fast');
            }

        });

        // trigger on load
        $('#datedepublish').trigger('change');

    },

    /*
     * Bind editfile field
     *
     * @param {object} data
     * @returns {undefined}
     *
     * @fires "Bolt.File.Save.Start"
     * @fires "Bolt.File.Save.Done"
     * @fires "Bolt.File.Save.Fail"
     * @fires "Bolt.File.Save.Always"
     */
    bindEditFile: function (data) {
        "use strict";

        var editor;

        if (typeof CodeMirror !== 'undefined') {
            editor = CodeMirror.fromTextArea(document.getElementById('form_contents'), {
                lineNumbers: true,
                autofocus: true,
                foldGutter: {
                    rangeFinder: CodeMirror.fold.indent
                },
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                extraKeys: {
                    "Ctrl-Q": function(cm){
                        cm.foldCode(
                            cm.getCursor(),
                            {
                                rangeFinder: CodeMirror.fold.indent,
                                minFoldSize: 3
                            }
                        );
                    },
                },
                tabSize: 4,
                indentUnit: 4,
                indentWithTabs: false,
                readOnly: data.readonly
            });
            var newheight = $(window).height() - 312;
            if (newheight < 200) {
                newheight = 200;
            }
            editor.setSize(null, newheight);
        }

        $('#saveeditfile').on('click', function () {
            Bolt.events.fire('Bolt.File.Save.Start');

            // Copy back to the textarea.
            if (editor) {
                editor.save();
            }

            var msgNotSaved = 'Not saved';

            // Disable the buttons, to indicate stuff is being done.
            $('#saveeditfile').addClass('disabled');
            $('#saveeditfile i').addClass('fa-spin fa-spinner');
            $('p.lastsaved').text(Bolt.data('editcontent.msg.saving'));

            $.post('?returnto=ajax', $('#editfile').serialize())
                .done(function (data) {
                    if (!data.ok) {
                        alert(data.msg);
                        Bolt.events.fire('Bolt.File.Save.Fail', data);
                    } else {
                        Bolt.events.fire('Bolt.File.Save.Done', data);
                    }
                    $('p.lastsaved').html(data.msg);
                })
                .fail(function () {
                    Bolt.events.fire('Bolt.File.Save.Fail');
                    alert(msgNotSaved);
                })
                .always(function () {
                    Bolt.events.fire('Bolt.File.Save.Always');

                    // Re-enable buttons
                    window.setTimeout(function () {
                        $('#saveeditfile').removeClass('disabled').blur();
                        $('#saveeditfile i').removeClass('fa-spin fa-spinner');
                    }, 300);
                });
        });
    },

    /*
     * Bind editlocale field
     *
     * @param {object} data
     * @returns {undefined}
     */
    bindEditLocale: function (data) {
        "use strict";

        var editor = CodeMirror.fromTextArea(document.getElementById('form_contents'), {
            lineNumbers: true,
            autofocus: true,
            tabSize: 4,
            indentUnit: 4,
            indentWithTabs: false,
            readOnly: data.readonly
        });

        editor.setSize(null, $(window).height() - 276);
    },

    /*
     * Bind filebrowser
     */
    bindFileBrowser: function () {
        "use strict";

        $('#myTab a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        });

        var getUrlParam = function (paramName) {
            var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i'),
                match = window.location.search.match(reParam);

            return match && match.length > 1 ? match[1] : null;
        };
        var funcNum = getUrlParam('CKEditorFuncNum');

        $('a.filebrowserCallbackLink').bind('click', function (e) {
            e.preventDefault();
            var url = $(this).attr('href');
            window.opener.CKEDITOR.tools.callFunction(funcNum, url);
            window.close();
        });

        $('a.filebrowserCloseLink').bind('click', function () {
            window.close();
        });
    },

    bindCkFileSelect: function () {
        "use strict";

        var getUrlParam = function (paramName) {
            var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i'),
                match = window.location.search.match(reParam);

            return match && match.length > 1 ? match[1] : null;
        };

        var funcNum = getUrlParam('CKEditorFuncNum');
        $('a.filebrowserCallbackLink').bind('click', function (event) {
            event.preventDefault();
            var url = $(this).attr('href');
            window.opener.CKEDITOR.tools.callFunction(funcNum, url);
            window.close();
        });
    },

    /*
     * Bind prefill
     */
    bindPrefill: function () {
        "use strict";

        $('#check-all').on('click', function () {
            // because jQuery is being retarded.
            // See: http://stackoverflow.com/questions/5907645/jquery-chrome-and-checkboxes-strange-behavior
            $("#form_contenttypes :checkbox").removeAttr('checked').trigger('click');
        });
        $('#uncheck-all').on('click', function () {
            $("#form_contenttypes :checkbox").removeAttr('checked');
        });
    },

    /**
     * Any link (or clickable -icon) with a class='confirm' gets a confirmation dialog.
     *
     * @returns {undefined}
     */
    confirmationDialogs: function () {
        "use strict";

        $('.confirm').on('click', function () {
            return confirm($(this).data('confirm'));
        });
    },

    /*
     * Smarter dropdowns/dropups based on viewport height.
     * Based on: https://github.com/twbs/bootstrap/issues/3637#issuecomment-9850709
     *
     * @returns {undefined}
     */
    dropDowns: function () {
        "use strict";

        $('[data-toggle="dropdown"]').each(function (index, item) {
            var mouseEvt;
            if (typeof event === 'undefined') {
                $(item).parent().click(function (e) {
                    mouseEvt = e;
                });
            } else {
                mouseEvt = event;
            }
            $(item).parent().on('show.bs.dropdown', function () {

                // Prevent breakage on old IE.
                if (typeof mouseEvt !== "undefined" && mouseEvt !== null) {
                    var self = $(this).find('[data-toggle="dropdown"]'),
                        menu = self.next('.dropdown-menu'),
                        mousey = mouseEvt.pageY + 20,
                        menuHeight = menu.height(),
                        menuVisY = $(window).height() - mousey + menuHeight, // Distance from the bottom of viewport
                        profilerHeight = 37; // The size of the Symfony Profiler Bar is 37px.

                    // The whole menu must fit when trying to 'dropup', but always prefer to 'dropdown' (= default).
                    if (mousey - menuHeight > 20 && menuVisY < profilerHeight) {
                        menu.css({
                            top: 'auto',
                            bottom: '100%'
                        });
                    }
                }
            });
        });
    },

    /*
     * Show 'dropzone' for jQuery file uploader.
     *
     * @returns {undefined}
     */
    dropZone: function () {
        "use strict";

        // @todo make it prettier, and distinguish between '.in' and '.hover'.
        $(document).bind('dragover', function (e) {
            var dropZone = $('.dropzone'),
                timeout = window.dropZoneTimeout;
            if (!timeout) {
                dropZone.addClass('in');
            } else {
                clearTimeout(timeout);
            }
            if (e.target === dropZone[0]) {
                dropZone.addClass('hover');
            } else {
                dropZone.removeClass('hover');
            }
            window.dropZoneTimeout = setTimeout(function () {
                window.dropZoneTimeout = null;
                dropZone.removeClass('in hover');
            }, 100);
        });
    },

    /*
     * Initialize the Magnific popup shizzle. Fancybox is still here as a trigger, for backwards compatibility.
     */
    magnificPopup: function () {
        "use strict";

        $('.magnific, .fancybox').magnificPopup({
            type: 'image',
            gallery: {
                enabled: true
            },
            disableOn: 400,
            closeBtnInside: true,
            enableEscapeKey: true,
            mainClass: 'mfp-with-zoom',
            zoom: {
                enabled: true,
                duration: 300,
                easing: 'ease-in-out',
                opener: function (openerElement) {
                    return openerElement.parent().parent().find('img');
                }
            }
        });
    },

    /*
     * Initialize current status display setting focus on status select
     *
     * @returns {undefined}
     */
    focusStatusSelect: function () {
        "use strict";

        $('#lastsavedstatus').click(function (e) {
            e.preventDefault();
            $('a[href="#tab-meta"]').click();
            $('#statusselect').focus();
        });
    },

    /*
     * Toggle options for showing / hiding the password input on the logon screen.
     *
     * @returns {undefined}
     */
    passwordInput: function () {
        "use strict";

        $(".togglepass").on('click', function () {
            if ($(this).hasClass('show-password')) {
                $('input[name="password"]').attr('type', 'text');
                $('.togglepass.show-password').hide();
                $('.togglepass.hide-password').show();
            } else {
                $('input[name="password"]').attr('type', 'password');
                $('.togglepass.show-password').show();
                $('.togglepass.hide-password').hide();
            }
        });

        $('.login-forgot').bind('click', function () {
            $('.login-group, .password-group').hide();
            $('.reset-group').show();
        });

        $('.login-remembered').bind('click', function () {
            $('.login-group, .password-group').show();
            $('.reset-group').hide();
        });
    },

    /*
     * Initialize popovers.
     */
    popOvers: function () {
        "use strict";

        $('.info-pop').popover({
            trigger: 'hover',
            delay: {
                show: 500,
                hide: 200
            }
        });
    },

    /*
     * ?
     */
    sortables: function () {
        "use strict";

        $('tbody.sortable').sortable({
            items: 'tr',
            opacity: '0.5',
            axis: 'y',
            handle: '.sorthandle',
            update: function () {
                var serial = $(this).sortable('serialize');
                // Sorting request
                $.ajax({
                    url: $('#baseurl').attr('value') + 'content/sortcontent/' +
                        $(this).parent('table').data('contenttype'),
                    type: 'POST',
                    data: serial,
                    success: function () {
                        // Do nothing
                    }
                });
            }
        });
    }
};
<commit_msg>Adding extrakeys<commit_after>var init = {
    /*
     * Notice when (auto)depublish date is in the past
     * TODO: add timer, to check depublish date has passed during editing.
     *
     * @returns {undefined}
     */
    depublishTracking: function () {
        "use strict";

        var noticeID = 'dateDepublishNotice',
            msg = $('#datedepublish').data('notice');

        $('#datedepublish, #statusselect').on('change', function (){

            var status = $('#statusselect').val(),
                depublish = $('#datedepublish').val();

            // remove old notice
            $('.' + noticeID).remove();

            if (depublish === '') {
                return;
            }

            if (status === 'published' && moment(depublish + Bolt.conf('timezone.offset')) < moment()) {
                $('
' +
                    '<button type="button" class="close" data-dismiss="alert">×</button>' + msg + '
')
                    .hide()
                    .insertAfter('.depublish-group')
                    .slideDown('fast');
            }

        });

        // trigger on load
        $('#datedepublish').trigger('change');

    },

    /*
     * Bind editfile field
     *
     * @param {object} data
     * @returns {undefined}
     *
     * @fires "Bolt.File.Save.Start"
     * @fires "Bolt.File.Save.Done"
     * @fires "Bolt.File.Save.Fail"
     * @fires "Bolt.File.Save.Always"
     */
    bindEditFile: function (data) {
        "use strict";

        var editor;

        if (typeof CodeMirror !== 'undefined') {
            editor = CodeMirror.fromTextArea(document.getElementById('form_contents'), {
                lineNumbers: true,
                autofocus: true,
                foldGutter: {
                    rangeFinder: CodeMirror.fold.indent
                },
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                extraKeys: {
                    "Ctrl-Q": function(cm){
                        cm.foldCode(
                            cm.getCursor(),
                            {
                                rangeFinder: CodeMirror.fold.indent,
                                minFoldSize: 3
                            }
                        );
                    },
                    "Tab": function(cm) {
                        if (cm.somethingSelected()) {
                            cm.indentSelection("add");
                        } else {
                            cm.replaceSelection(cm.getOption("indentWithTabs")? "\t":
                            Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");
                        }
                    },
                    "Ctrl-S": function() {
                         $('#saveeditfile').click();
                    },
                    "Ctrl-H": "replaceAll",
                },
                tabSize: 4,
                indentUnit: 4,
                indentWithTabs: false,
                readOnly: data.readonly
            });
            var newheight = $(window).height() - 312;
            if (newheight < 200) {
                newheight = 200;
            }
            editor.setSize(null, newheight);
        }

        $('#saveeditfile').on('click', function () {
            Bolt.events.fire('Bolt.File.Save.Start');

            // Copy back to the textarea.
            if (editor) {
                editor.save();
            }

            var msgNotSaved = 'Not saved';

            // Disable the buttons, to indicate stuff is being done.
            $('#saveeditfile').addClass('disabled');
            $('#saveeditfile i').addClass('fa-spin fa-spinner');
            $('p.lastsaved').text(Bolt.data('editcontent.msg.saving'));

            $.post('?returnto=ajax', $('#editfile').serialize())
                .done(function (data) {
                    if (!data.ok) {
                        alert(data.msg);
                        Bolt.events.fire('Bolt.File.Save.Fail', data);
                    } else {
                        Bolt.events.fire('Bolt.File.Save.Done', data);
                    }
                    $('p.lastsaved').html(data.msg);
                })
                .fail(function () {
                    Bolt.events.fire('Bolt.File.Save.Fail');
                    alert(msgNotSaved);
                })
                .always(function () {
                    Bolt.events.fire('Bolt.File.Save.Always');

                    // Re-enable buttons
                    window.setTimeout(function () {
                        $('#saveeditfile').removeClass('disabled').blur();
                        $('#saveeditfile i').removeClass('fa-spin fa-spinner');
                    }, 300);
                });
        });
    },

    /*
     * Bind editlocale field
     *
     * @param {object} data
     * @returns {undefined}
     */
    bindEditLocale: function (data) {
        "use strict";

        var editor = CodeMirror.fromTextArea(document.getElementById('form_contents'), {
            lineNumbers: true,
            autofocus: true,
            tabSize: 4,
            indentUnit: 4,
            indentWithTabs: false,
            readOnly: data.readonly
        });

        editor.setSize(null, $(window).height() - 276);
    },

    /*
     * Bind filebrowser
     */
    bindFileBrowser: function () {
        "use strict";

        $('#myTab a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        });

        var getUrlParam = function (paramName) {
            var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i'),
                match = window.location.search.match(reParam);

            return match && match.length > 1 ? match[1] : null;
        };
        var funcNum = getUrlParam('CKEditorFuncNum');

        $('a.filebrowserCallbackLink').bind('click', function (e) {
            e.preventDefault();
            var url = $(this).attr('href');
            window.opener.CKEDITOR.tools.callFunction(funcNum, url);
            window.close();
        });

        $('a.filebrowserCloseLink').bind('click', function () {
            window.close();
        });
    },

    bindCkFileSelect: function () {
        "use strict";

        var getUrlParam = function (paramName) {
            var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i'),
                match = window.location.search.match(reParam);

            return match && match.length > 1 ? match[1] : null;
        };

        var funcNum = getUrlParam('CKEditorFuncNum');
        $('a.filebrowserCallbackLink').bind('click', function (event) {
            event.preventDefault();
            var url = $(this).attr('href');
            window.opener.CKEDITOR.tools.callFunction(funcNum, url);
            window.close();
        });
    },

    /*
     * Bind prefill
     */
    bindPrefill: function () {
        "use strict";

        $('#check-all').on('click', function () {
            // because jQuery is being retarded.
            // See: http://stackoverflow.com/questions/5907645/jquery-chrome-and-checkboxes-strange-behavior
            $("#form_contenttypes :checkbox").removeAttr('checked').trigger('click');
        });
        $('#uncheck-all').on('click', function () {
            $("#form_contenttypes :checkbox").removeAttr('checked');
        });
    },

    /**
     * Any link (or clickable -icon) with a class='confirm' gets a confirmation dialog.
     *
     * @returns {undefined}
     */
    confirmationDialogs: function () {
        "use strict";

        $('.confirm').on('click', function () {
            return confirm($(this).data('confirm'));
        });
    },

    /*
     * Smarter dropdowns/dropups based on viewport height.
     * Based on: https://github.com/twbs/bootstrap/issues/3637#issuecomment-9850709
     *
     * @returns {undefined}
     */
    dropDowns: function () {
        "use strict";

        $('[data-toggle="dropdown"]').each(function (index, item) {
            var mouseEvt;
            if (typeof event === 'undefined') {
                $(item).parent().click(function (e) {
                    mouseEvt = e;
                });
            } else {
                mouseEvt = event;
            }
            $(item).parent().on('show.bs.dropdown', function () {

                // Prevent breakage on old IE.
                if (typeof mouseEvt !== "undefined" && mouseEvt !== null) {
                    var self = $(this).find('[data-toggle="dropdown"]'),
                        menu = self.next('.dropdown-menu'),
                        mousey = mouseEvt.pageY + 20,
                        menuHeight = menu.height(),
                        menuVisY = $(window).height() - mousey + menuHeight, // Distance from the bottom of viewport
                        profilerHeight = 37; // The size of the Symfony Profiler Bar is 37px.

                    // The whole menu must fit when trying to 'dropup', but always prefer to 'dropdown' (= default).
                    if (mousey - menuHeight > 20 && menuVisY < profilerHeight) {
                        menu.css({
                            top: 'auto',
                            bottom: '100%'
                        });
                    }
                }
            });
        });
    },

    /*
     * Show 'dropzone' for jQuery file uploader.
     *
     * @returns {undefined}
     */
    dropZone: function () {
        "use strict";

        // @todo make it prettier, and distinguish between '.in' and '.hover'.
        $(document).bind('dragover', function (e) {
            var dropZone = $('.dropzone'),
                timeout = window.dropZoneTimeout;
            if (!timeout) {
                dropZone.addClass('in');
            } else {
                clearTimeout(timeout);
            }
            if (e.target === dropZone[0]) {
                dropZone.addClass('hover');
            } else {
                dropZone.removeClass('hover');
            }
            window.dropZoneTimeout = setTimeout(function () {
                window.dropZoneTimeout = null;
                dropZone.removeClass('in hover');
            }, 100);
        });
    },

    /*
     * Initialize the Magnific popup shizzle. Fancybox is still here as a trigger, for backwards compatibility.
     */
    magnificPopup: function () {
        "use strict";

        $('.magnific, .fancybox').magnificPopup({
            type: 'image',
            gallery: {
                enabled: true
            },
            disableOn: 400,
            closeBtnInside: true,
            enableEscapeKey: true,
            mainClass: 'mfp-with-zoom',
            zoom: {
                enabled: true,
                duration: 300,
                easing: 'ease-in-out',
                opener: function (openerElement) {
                    return openerElement.parent().parent().find('img');
                }
            }
        });
    },

    /*
     * Initialize current status display setting focus on status select
     *
     * @returns {undefined}
     */
    focusStatusSelect: function () {
        "use strict";

        $('#lastsavedstatus').click(function (e) {
            e.preventDefault();
            $('a[href="#tab-meta"]').click();
            $('#statusselect').focus();
        });
    },

    /*
     * Toggle options for showing / hiding the password input on the logon screen.
     *
     * @returns {undefined}
     */
    passwordInput: function () {
        "use strict";

        $(".togglepass").on('click', function () {
            if ($(this).hasClass('show-password')) {
                $('input[name="password"]').attr('type', 'text');
                $('.togglepass.show-password').hide();
                $('.togglepass.hide-password').show();
            } else {
                $('input[name="password"]').attr('type', 'password');
                $('.togglepass.show-password').show();
                $('.togglepass.hide-password').hide();
            }
        });

        $('.login-forgot').bind('click', function () {
            $('.login-group, .password-group').hide();
            $('.reset-group').show();
        });

        $('.login-remembered').bind('click', function () {
            $('.login-group, .password-group').show();
            $('.reset-group').hide();
        });
    },

    /*
     * Initialize popovers.
     */
    popOvers: function () {
        "use strict";

        $('.info-pop').popover({
            trigger: 'hover',
            delay: {
                show: 500,
                hide: 200
            }
        });
    },

    /*
     * ?
     */
    sortables: function () {
        "use strict";

        $('tbody.sortable').sortable({
            items: 'tr',
            opacity: '0.5',
            axis: 'y',
            handle: '.sorthandle',
            update: function () {
                var serial = $(this).sortable('serialize');
                // Sorting request
                $.ajax({
                    url: $('#baseurl').attr('value') + 'content/sortcontent/' +
                        $(this).parent('table').data('contenttype'),
                    type: 'POST',
                    data: serial,
                    success: function () {
                        // Do nothing
                    }
                });
            }
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

angular.module('Frontend.Venta', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/venta', {
    templateUrl: 'venta/venta.html',
    controller: 'VentaController'
  });
}])

.controller('VentaController', function($scope, store, jwtHelper, $http, backendAPIservice, $location, $window) {
    $scope.terminado=false;
    $scope.contado=true;
    $scope.cliente=1;
    $scope.base21=0.00;
    $scope.iva21=0.00;
    $scope.base10=0.00;
    $scope.iva10=0.00;
    $scope.base4=0.00;
    $scope.iva4=0.00;
    $scope.total=0.00;
    $scope.articulopr;
    $scope.respuesta;
    $scope.error;
    $scope.codigo;
    $scope.cero=0;
    $scope.prueba;
    $scope.activo;
    $scope.numventa;

    $scope.listaVenta = [];
    $scope.listaProducto = [];
    $scope.listaSocio = [];
    $scope.listaTipo = [];

    if(store.get('token')){
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
          store.set('token',recibe.response.token);

        });

        backendAPIservice.getClientes().success(function (recibe) {
          var sociosArray = recibe.response.socios;
          console.log(JSON.stringify(sociosArray));
          $scope.listaSocio = sociosArray;
          store.set('token',recibe.response.token);
        });

        backendAPIservice.getTipos().success(function (recibe) {
          var tiposArray = recibe.response.tipos;
          console.log(JSON.stringify(tiposArray));
          $scope.listaTipo = tiposArray;
          store.set('token',recibe.response.token);
        });
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      store.set('nombre', "Sin conexion");
      $location.path("/login");
    }

    $scope.Aniadir=function(pid, pnombre, pprecio, piva)
    {
      var elemento;
      var anadido=false;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].id == pid) {
          $scope.listaVenta[elemento].cantidad = $scope.listaVenta[elemento].cantidad+1;
          anadido=true;
        }
      }
      if(anadido==false)
      {
        $scope.listaVenta.push({id:pid, nombre:pnombre, precio:pprecio, iva:piva, cantidad:1 });
      }
      $scope.Totales();
    };

    $scope.clienteElegido=function(value) {
      if($scope.cliente==1){ $scope.contado=true; }
      if (value.id==$scope.cliente){
        return true;
      } else {
        return false;
      }
    };

    $scope.Borrar=function(index) {
      $scope.listaVenta.splice(index, 1);
      $scope.Totales();
    };

    $scope.Totales=function() {
      var elemento;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].iva=="21") {
         $scope.base21 += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva21 = ($scope.base21 * 21.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==10) {
         $scope.base10  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva10 = ($scope.base10 * 10.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==4) {
         $scope.base4  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva4 = ($scope.base4 * 4.00 )/100.00;
        };
      }
      $scope.total = $scope.base21 + $scope.iva21 + $scope.base10 + $scope.iva10 + $scope.base4 + $scope.iva4;
    };

    $scope.Finalizar=function() {
      backendAPIservice.postVenta($scope.cliente, $scope.contado, $scope.listaVenta).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        var numventa = recibe.response.venta;
        console.log(JSON.stringify(respuesta1));
        console.log(JSON.stringify(numventa));
        $scope.respuesta = respuesta1;
        $scope.numventa = numventa;
        if(recibe.code==0) store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    };

    $scope.Continuar=function() {
      /*html2canvas(document.getElementById('imprimeesto'), {
        onrendered: function (canvas) {
          var data = canvas.toDataURL();
          var docDefinition = {
            content: [{
              image: data,
              width: 500,
            }]
          };
          pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
        }
      })*/
      $scope.terminado=false;
      $scope.contado=true;
      $scope.cliente=1;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      $scope.total=0.00;
      $scope.articulopr;
      $scope.respuesta;
      $scope.error;
      $scope.codigo;
      $scope.cero=0;
      $scope.prueba;
      $scope.activo;

      $scope.listaVenta = [];
      $scope.listaProducto = [];
      $scope.listaSocio = [];
      $scope.listaTipo = [];

      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getProductos().success(function (recibe) {
            var productosArray = recibe.response.productos;
            console.log(JSON.stringify(productosArray));
            $scope.listaProducto = productosArray;
            store.set('token',recibe.response.token);

          });

          backendAPIservice.getClientes().success(function (recibe) {
            var sociosArray = recibe.response.socios;
            console.log(JSON.stringify(sociosArray));
            $scope.listaSocio = sociosArray;
            store.set('token',recibe.response.token);
          });

          backendAPIservice.getTipos().success(function (recibe) {
            var tiposArray = recibe.response.tipos;
            console.log(JSON.stringify(tiposArray));
            $scope.listaTipo = tiposArray;
            store.set('token',recibe.response.token);
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    /*$scope.printDiv=function(divName){
      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
    };*/

    /*$scope.printDiv = function(divName) {
      var printContents = document.getElementById(divName).innerHTML;
      var popupWin = window.open('', '_blank', 'width=300,height=300');
      popupWin.document.open();
      popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
      popupWin.document.close();
    };*/

    $scope.printDiv = function (divName) {

      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;

      if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
          var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
          popupWin.window.focus();
          popupWin.document.write('<!DOCTYPE html>' +
              '<link rel="stylesheet" type="text/css" href="app.css" />' +
              '
' + printContents + '
');
          popupWin.onbeforeunload = function (event) {
              popupWin.close();
              return '.\n';
          };
          popupWin.onabort = function (event) {
              popupWin.document.close();
              popupWin.close();
          }
      } else {
          var popupWin = window.open('', '_blank', 'width=800,height=600');
          popupWin.document.open();
          popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
          popupWin.document.close();
      }
      popupWin.document.close();

      return true;
    };

});<commit_msg>20160906-1100<commit_after>'use strict';

angular.module('Frontend.Venta', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/venta', {
    templateUrl: 'venta/venta.html',
    controller: 'VentaController'
  });
}])

.controller('VentaController', function($scope, store, jwtHelper, $http, backendAPIservice, $location, $window) {
    $scope.terminado=false;
    $scope.cerrado=false;
    $scope.contado=true;
    $scope.cliente=1;
    $scope.cliente2=1;
    $scope.base21=0.00;
    $scope.iva21=0.00;
    $scope.base10=0.00;
    $scope.iva10=0.00;
    $scope.base4=0.00;
    $scope.iva4=0.00;
    $scope.total=0.00;
    $scope.articulopr;
    $scope.respuesta;
    $scope.error;
    $scope.codigo;
    $scope.codigo2;
    $scope.cero=0;
    $scope.prueba;
    $scope.activo;
    $scope.numventa;
    //$scope.socio;

    $scope.listaVenta = [];
    $scope.listaProducto = [];
    $scope.listaSocio = [];
    $scope.listaTipo = [];

    if(store.get('token')){
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        /*backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
          store.set('token',recibe.response.token);
        });*/
        backendAPIservice.getProductos().success(function (recibe) {
          store.set('token',recibe.response.token);
          var codigo2=recibe.code;
          console.log(JSON.stringify(codigo2));
          $scope.codigo2=codigo2;
          if($scope.codigo2==0)
          {
            var productosArray = recibe.response.productos;
            console.log(JSON.stringify(productosArray));
            $scope.listaProducto = productosArray;
          }
          else
          {
            $scope.cerrado=true;
            var respuesta1 = recibe.response.respuesta;
            console.log(JSON.stringify(respuesta1));
            $scope.respuesta = respuesta1;
          }
        });

        backendAPIservice.getTipos().success(function (recibe) {
          var tiposArray = recibe.response.tipos;
          console.log(JSON.stringify(tiposArray));
          $scope.listaTipo = tiposArray;
          store.set('token',recibe.response.token);
        });

        backendAPIservice.getClientes().success(function (recibe) {
          var sociosArray = recibe.response.socios;
          console.log(JSON.stringify(sociosArray));
          $scope.listaSocio = sociosArray;
          store.set('token',recibe.response.token);
        });

      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      store.set('nombre', "Sin conexion");
      $location.path("/login");
    }

    $scope.Aniadir=function(pid, pnombre, pprecio, piva)
    {
      var elemento;
      var anadido=false;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].id == pid) {
          $scope.listaVenta[elemento].cantidad = $scope.listaVenta[elemento].cantidad+1;
          anadido=true;
        }
      }
      if(anadido==false)
      {
        $scope.listaVenta.push({id:pid, nombre:pnombre, precio:pprecio, iva:piva, cantidad:1 });
      }
      $scope.Totales();
    };

    $scope.clienteElegido=function(value) {
      if($scope.cliente2==1){ $scope.contado=true; }
      if (value.id==$scope.cliente2)
      {
        return true;
      }
      else
      {
        return false;
      }
    };

    $scope.Borrar=function(index) {
      $scope.listaVenta.splice(index, 1);
      $scope.Totales();
    };

    $scope.Totales=function() {
      var elemento;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].iva=="21") {
         $scope.base21 += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva21 = ($scope.base21 * 21.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==10) {
         $scope.base10  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva10 = ($scope.base10 * 10.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==4) {
         $scope.base4  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva4 = ($scope.base4 * 4.00 )/100.00;
        };
      }
      $scope.total = $scope.base21 + $scope.iva21 + $scope.base10 + $scope.iva10 + $scope.base4 + $scope.iva4;
    };

    $scope.Finalizar=function() {
      backendAPIservice.postVenta($scope.cliente, $scope.contado, $scope.listaVenta).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        var numventa = recibe.response.venta;
        console.log(JSON.stringify(respuesta1));
        console.log(JSON.stringify(numventa));
        $scope.respuesta = respuesta1;
        $scope.numventa = numventa;
        store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    };

    $scope.Continuar=function() {
      /*html2canvas(document.getElementById('imprimeesto'), {
        onrendered: function (canvas) {
          var data = canvas.toDataURL();
          var docDefinition = {
            content: [{
              image: data,
              width: 500,
            }]
          };
          pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
        }
      })*/
      $scope.terminado=false;
      $scope.contado=true;
      $scope.cerrado=false;
      $scope.cliente=1;
      $scope.cliente2=1;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      $scope.total=0.00;
      $scope.articulopr;
      $scope.respuesta;
      $scope.error;
      $scope.codigo;
      $scope.cero=0;
      $scope.prueba;
      $scope.activo;

      $scope.listaVenta = [];
      $scope.listaProducto = [];
      $scope.listaSocio = [];
      $scope.listaTipo = [];

      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getProductos().success(function (recibe) {
            var productosArray = recibe.response.productos;
            store.set('token',recibe.response.token);
            if(recibe.code!=0)
            {
              $scope.cerrado=true;
              var respuesta1 = recibe.response.respuesta;
              console.log(JSON.stringify(respuesta1));
              $scope.respuesta = respuesta1;
            }
            else
            {
              console.log(JSON.stringify(productosArray));
              $scope.listaProducto = productosArray;
            }
          });

          /*backendAPIservice.getProductos().success(function (recibe) {
            var productosArray = recibe.response.productos;
            console.log(JSON.stringify(productosArray));
            $scope.listaProducto = productosArray;
            store.set('token',recibe.response.token);
          });  */

          backendAPIservice.getClientes().success(function (recibe) {
            var sociosArray = recibe.response.socios;
            console.log(JSON.stringify(sociosArray));
            $scope.listaSocio = sociosArray;
            store.set('token',recibe.response.token);
          });

          backendAPIservice.getTipos().success(function (recibe) {
            var tiposArray = recibe.response.tipos;
            console.log(JSON.stringify(tiposArray));
            $scope.listaTipo = tiposArray;
            store.set('token',recibe.response.token);
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    /*$scope.printDiv=function(divName){
      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
    };*/

    /*$scope.printDiv = function(divName) {
      var printContents = document.getElementById(divName).innerHTML;
      var popupWin = window.open('', '_blank', 'width=300,height=300');
      popupWin.document.open();
      popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
      popupWin.document.close();
    };*/

    $scope.printDiv = function (divName) {

      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;

      if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
          var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
          popupWin.window.focus();
          popupWin.document.write('<!DOCTYPE html>' +
              '<link rel="stylesheet" type="text/css" href="app.css" />' +
              '
' + printContents + '
');
          popupWin.onbeforeunload = function (event) {
              popupWin.close();
              return '.\n';
          };
          popupWin.onabort = function (event) {
              popupWin.document.close();
              popupWin.close();
          }
      } else {
          var popupWin = window.open('', '_blank', 'width=800,height=600');
          popupWin.document.open();
          popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
          popupWin.document.close();
      }
      popupWin.document.close();

      return true;
    };

});<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngSanitize', 'myApp.config'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl',
    controllerAs: 'view1'
  });
}])

.factory('view1Fact', ['$http', 'myConfig', function($http, myConfig) {

  return {
    newMessage: 'noooo',

    pages: function() {
      return $http.get(myConfig.wordpressPages);
    }

  }
}])

.factory('terminalText', function() {

  function blinky() {
    document.querySelector('.terminal').innerHTML = 'hello' + document.querySelector('.terminal').innerHTML;

    var blinkText = document.querySelector('.blink');

    var blink = setInterval( function() { if (blinkText.style.opacity == 0 || blinkText.style.opacity == '' ) { blinkText.style.opacity = 1 } else {blinkText.style.opacity = 0 }}, 1000);
  }

  return {
    terminal: blinky

  }
})

.controller('View1Ctrl', ['view1Fact', 'terminalText', function(view1Fact, terminalText) {
    var self = this;
    this.message = "Take the blue pill";
    this.newMessage = view1Fact.newMessage;
    this.terminalText = terminalText.terminal;
    view1Fact.pages().then(function(response) {
      self.homepage = response.data;
    });

}]);<commit_msg>animates through text at manually set timeouts<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngSanitize', 'myApp.config'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl',
    controllerAs: 'view1'
  });
}])

.factory('view1Fact', ['$http', 'myConfig', function($http, myConfig) {

  return {
    newMessage: 'noooo',

    pages: function() {
      return $http.get(myConfig.wordpressPages);
    }

  }
}])

.factory('terminalText', function() {

  function setBlinky() {

    var blinkLetters = document.querySelector('.terminal').innerHTML;

    document.querySelector('.terminal').innerHTML = '|';

    var blinkText = document.querySelector('.blink');

    var blink = setInterval( function() { if (blinkText.style.opacity == 0 || blinkText.style.opacity == '' ) { blinkText.style.opacity = 1 } else {blinkText.style.opacity = 0 }}, 600);

    /**
     * Animates through the string.
     */
    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,1);
    }, 3000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,2);
    }, 3500);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,3);
    }, 4000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,4);
    }, 4500);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,5);
    }, 5000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,6);
    }, 6500);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,7);
    }, 7000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,8);
    }, 8000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,9);
    }, 8500);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,10);
    }, 9000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,11);
    }, 9500);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,12);
    }, 10000);

    setTimeout(function(){
      document.querySelector('.terminalText1').innerHTML = blinkLetters.substr(0,13);
    }, 10500);

  }

  return {
    terminal: setBlinky

  }
})

.controller('View1Ctrl', ['view1Fact', 'terminalText', function(view1Fact, terminalText) {
    var self = this;
    this.message = "Take the blue pill";
    this.newMessage = view1Fact.newMessage;
    this.terminalText = terminalText.terminal();
    view1Fact.pages().then(function(response) {
      self.homepage = response.data;
    });

}]);<|endoftext|>


<commit_before>import { keys, onKey } from './keys'
import inspecting from './lib/inspecting'

const Tools = _DT
const toEditor = Tools.messageEditor

view Menu {
  let active = false
  let top, left
  let elements = []

  // prevent select and show custom cursor when ready for context
  let focused
  on.keydown(() => {
    if (keys.alt && keys.command) {
      document.body.classList.add('__motionfocus')
      focused = true
    }
  })

  on.keyup(() => {
    if (focused) {
      document.body.classList.remove('__motionfocus')
      focused = false
    }
  })

  on.event('contextmenu', e => {
    const mode = keys.alt && keys.command
    if (!mode) return

    e.preventDefault()

    const { clientX, clientY } = e

    left = clientX
    top = clientY - 18
    active = true
    elements = inspecting.all()
  })

  on.click(window, e => {
    if (active) {
      e.stopPropagation()
      e.preventDefault()
      active = false
      return
    }
  })

  function focusElement(el) {
    return function() {
      // slicing because h11 -> h1
      toEditor({ type: 'focus:element', key: el.key.slice(0, -1), view: el.view })
    }
  }

  function focusStyle(el) {
    return function() {
      toEditor({ type: 'focus:style', el: el.el, view: el.view })
    }
  }

  <menu class={{ internal: true, active }}>
    <item
      repeat={elements.filter(i => !!i.view)}
      class={{
        first: _index == 0,
        last: _index == elements.length - 1
      }}
    >
      <toEl class="hl" onClick={focusElement(_)}>{_.view.replace(/\-/g, '.')}</toEl>
      <toStyle class="hl">
        <Dollar onClick={focusStyle(_)}/>
      </toStyle>
    </item>
  </menu>

  const rad = 2

  $menu = {
    borderRadius: rad,
    border: '1px solid #ddd',
    boxShadow: '0 2px 2px rgba(0,0,0,0.1)',
    position: 'absolute',
    top,
    left,
    background: '#fcfcfc',
    zIndex: 2147483647,
    transition: 'opacity ease-in 30ms, transform ease-in 30ms',
    opacity: 0,
    transform: { y: -10 },
    pointerEvents: 'none',
    padding: 0
  }

  $active = {
    pointerEvents: 'auto',
    opacity: 1,
    transform: { y: 0 }
  }

  $Dollar = {
    marginTop: 2,
    opacity: 0.8,
  }

  $item = {
    borderTop: _index === 0 ? undefined : '1px solid rgba(0,0,0,0.1)',
    minWidth: 120,
    cursor: 'pointer',
    flexFlow: 'row',
  }

  $first = {
    borderTopLeftRadius: rad,
    borderTopRightRadius: rad,
    overflow: 'hidden'
  }

  $last = {
    borderBottomLeftRadius: rad,
    borderBottomRightRadius: rad,
    overflow: 'hidden'
  }

  $hl = {
    padding: [8, 8],
    hover: {
      background: [0,0,0,0.05]
    }
  }

  $sub = {
    marginTop: 5,
    marginLeft: 0,
    fontSize: 13,
  }

  $toStyle = {
    hover: {
      borderLeft: '1px solid rgba(0,0,0, 0.1)',
    }
  }

  $toEl = {
    flexGrow: 1,
    hover: {
      fontSize: 30,
      borderRight: '1px solid rgba(0,0,0, 0.1)',
    }
  }
}
<commit_msg>:new: Add filePath to focus:element meta<commit_after>import { keys, onKey } from './keys'
import inspecting from './lib/inspecting'

const Tools = _DT
const toEditor = Tools.messageEditor

view Menu {
  let active = false
  let top, left
  let elements = []

  // prevent select and show custom cursor when ready for context
  let focused
  on.keydown(() => {
    if (keys.alt && keys.command) {
      document.body.classList.add('__motionfocus')
      focused = true
    }
  })

  on.keyup(() => {
    if (focused) {
      document.body.classList.remove('__motionfocus')
      focused = false
    }
  })

  on.event('contextmenu', e => {
    const mode = keys.alt && keys.command
    if (!mode) return

    e.preventDefault()

    const { clientX, clientY } = e

    left = clientX
    top = clientY - 18
    active = true
    elements = inspecting.all()
  })

  on.click(window, e => {
    if (active) {
      e.stopPropagation()
      e.preventDefault()
      active = false
      return
    }
  })

  function focusElement(el) {
    return function() {
      // slicing because h11 -> h1
      toEditor({
        type: 'focus:element',
        key: el.key.slice(0, -1),
        view: el.view,
        filePath: _Motion.views[el.view].file
      })
    }
  }

  function focusStyle(el) {
    return function() {
      toEditor({ type: 'focus:style', el: el.el, view: el.view })
    }
  }

  <menu class={{ internal: true, active }}>
    <item
      repeat={elements.filter(i => !!i.view)}
      class={{
        first: _index == 0,
        last: _index == elements.length - 1
      }}
    >
      <toEl class="hl" onClick={focusElement(_)}>{_.view.replace(/\-/g, '.')}</toEl>
      <toStyle class="hl">
        <Dollar onClick={focusStyle(_)}/>
      </toStyle>
    </item>
  </menu>

  const rad = 2

  $menu = {
    borderRadius: rad,
    border: '1px solid #ddd',
    boxShadow: '0 2px 2px rgba(0,0,0,0.1)',
    position: 'absolute',
    top,
    left,
    background: '#fcfcfc',
    zIndex: 2147483647,
    transition: 'opacity ease-in 30ms, transform ease-in 30ms',
    opacity: 0,
    transform: { y: -10 },
    pointerEvents: 'none',
    padding: 0
  }

  $active = {
    pointerEvents: 'auto',
    opacity: 1,
    transform: { y: 0 }
  }

  $Dollar = {
    marginTop: 2,
    opacity: 0.8,
  }

  $item = {
    borderTop: _index === 0 ? undefined : '1px solid rgba(0,0,0,0.1)',
    minWidth: 120,
    cursor: 'pointer',
    flexFlow: 'row',
  }

  $first = {
    borderTopLeftRadius: rad,
    borderTopRightRadius: rad,
    overflow: 'hidden'
  }

  $last = {
    borderBottomLeftRadius: rad,
    borderBottomRightRadius: rad,
    overflow: 'hidden'
  }

  $hl = {
    padding: [8, 8],
    hover: {
      background: [0,0,0,0.05]
    }
  }

  $sub = {
    marginTop: 5,
    marginLeft: 0,
    fontSize: 13,
  }

  $toStyle = {
    hover: {
      borderLeft: '1px solid rgba(0,0,0, 0.1)',
    }
  }

  $toEl = {
    flexGrow: 1,
    hover: {
      fontSize: 30,
      borderRight: '1px solid rgba(0,0,0, 0.1)',
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var isArray = Array.isArray, forEach = Array.prototype.forEach;

module.exports = function () {
	var r = [];
	forEach.call(this, function self(x) {
		if (isArray(x)) x.forEach(self);
		else r.push(x);
	});
	return r;
};
<commit_msg>Stack trace friendly implementation<commit_after>// Stack grow safe implementation

'use strict';

var ensureValue = require('../../object/valid-value')
  , isArray     = Array.isArray;

module.exports = function () {
	var input = ensureValue(this), remaining, l, i, result = [];
	main: //jslint: ignore
	while (input) {
		l = input.length;
		for (i = 0; i < l; ++i) {
			if (isArray(input[i])) {
				if (i < (l - 1)) {
					if (!remaining) remaining = [];
					remaining.unshift(input.slice(i + 1));
				}
				input = input[i];
				continue main;
			}
			result.push(input[i]);
		}
		input = remaining ? remaining.shift() : null;
	}
	return result;
};
<|endoftext|>


<commit_before>import Vue from 'vue'
import App from './App.vue'

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { App }
});

<commit_msg>Setup router<commit_after>import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.use(VueRouter);

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { App }
});

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Dickson Tam
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */

(function() {

  function Tokenizer() {}

  Tokenizer.prototype.__proto__ = Array.prototype

  Tokenizer.prototype.extract = function(times) {
    times = times || 1;

    if (this.length < 1)  return this;

    var matches = this[this.length - 1].match(this.regex);
    var newToken, rest;

    if (matches) {
      if (this.opts.incorporateDelimiter) {
        if (matches[1].length > 0) {
          newToken = matches[1];
          rest = matches[2] + matches[matches.length - 1];
        } else {
          newToken = matches[1] + matches[2];
          rest = matches[matches.length - 1];
        }
        this.delimiters.push('');
      } else {
        newToken = matches[1];
        this.delimiters.push(matches[2]);
        rest = matches[3];
      }
      this.lastDelimiterExtracted = matches[2];
      this[this.length - 1] = newToken;
      this[this.length] = rest;
      this.extractionLevel++;
    }

    return (times > 1)? this.extract(times - 1) : this;
  }

  Tokenizer.prototype.retract = function(times) {
    times = times || 1;
    if (this.length < 2) return;

    var delimiter = this.delimiters[this.delimiters.length - 1] || '';

    if (typeof(this[this.length - 2]) != 'string' || typeof(this[this.length - 1]) != 'string')
      throw new Error('retoken: Tried to retract a token that is not a string');

    if (typeof(delimiter) != 'string')
      throw new Error('retoken: Tried to retract a delimiter that is not a string');

    this[this.length - 2] += delimiter + this[this.length - 1];
    this.pop();
    this.extractionLevel--;

    return (times > 1)? this.retract(times - 1) : this;
  }

  Tokenizer.prototype.replaceToken = function(token, replacement) {
     var index = this.indexOf(token);
     if (!~index) return this;

     this[index] = replacement;

     return this;
  }

  function TOKENIZER_OVERRIDE_NOT_IMPLEMENTED(fxname) {
    Tokenizer.prototype[fxname] = function() {
      throw new Error('retoken: Function ' + fxname + ' not yet implemented in tokenizer');
    }
  }

  Tokenizer.prototype.reverse = function() {
    Array.prototype.reverse.call(this);
    this.delimiters.reverse();
    return this;
  }

  TOKENIZER_OVERRIDE_NOT_IMPLEMENTED('splice');
  TOKENIZER_OVERRIDE_NOT_IMPLEMENTED('sort');

  Tokenizer.prototype.insertToken = function(index, token, delimiter) {
    if (typeof(token) != 'string')
      throw new Error('retoken: Second argument [token] is not a string: ' + token);

    if (delimiter != null && typeof(delimiter) != 'string')
      throw new Error('retoken: Third argument [delimiter] is not a string: ' + delimiter);

    Array.prototype.splice.call(this, index, 0, token);

    if (this.length > 1) {
      delimiter = delimiter || ''
      this.delimiters.splice(index, 0, delimiter);
    }

    return this;
  }

  Tokenizer.prototype.push = function(str, delimiter) {
    Array.prototype.push.call(this, str);

    if (this.length > 1) this.delimiters.push(delimiter || '');

    return this;
  }

  Tokenizer.prototype.unshift = function(str, delimiter) {
    Array.prototype.unshift.call(this, str);
    this.delimiters.unshift(delimiter || '');
    return this;
  }

  Tokenizer.prototype.shift = function() {
    var elem = Array.prototype.shift.call(this);
    this.delimiters.shift();
    return elem;
  }

  Tokenizer.prototype.pop = function() {
    var elem = Array.prototype.pop.call(this);
    this.delimiters.pop();
    return elem;
  }

  Tokenizer.prototype.toArray = function() {
    var arr = new Array(this.length);

    for(var i=0; i < this.length; i++) {
      arr[i] = this[i];
    }

    return arr;
  }

  Object.defineProperty(Tokenizer.prototype, 'head', {
    get: function() { return this[0]; },
    set: function(token) { this[0] = token; },
    enumerable: true
  })

  Object.defineProperty(Tokenizer.prototype, 'tail', {
    get: function() { return this[this.length - 1]; },
    set: function(token) { this[this.length - 1] = token; },
    enumerable: true
  })

  function tokenizer(delimiter, opts) {
    var instance = [ ];

    instance.__proto__ = Tokenizer.prototype;

    instance.opts = opts || {};
    instance.delimiters = [];
    instance.extractionLevel = 0;

    var reCore;

    if (delimiter instanceof RegExp) {
      reCore = delimiter.source.replace('/^\^/', '').replace('/\$$/', '');
    } else {
      reCore = delimiter.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    Object.defineProperty(instance, 'regex', {
      value: new RegExp('^(.*?)(' + reCore + ')(.*)$'),
      enumerable: true
    });

    return instance;
  }

  if (typeof module !== 'undefined' && module && module.exports) { // Node.js & CommonJS
    module.exports = tokenizer;
  } else if (typeof define === 'function' && define.amd) {
    define('retoken', [], function() {
      return tokenizer;
    });
  } else { // Browser
    window.retoken = tokenizer;
  }

})();
<commit_msg>Repositioned constructor under Tokenizer.<commit_after>/*
 * Copyright (c) 2015 Dickson Tam
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */

(function() {

  function Tokenizer(delimiter, opts) {
    var instance = [ ];

    instance.__proto__ = Tokenizer.prototype;

    instance.opts = opts || {};
    instance.delimiters = [];
    instance.extractionLevel = 0;

    var reCore;

    if (delimiter instanceof RegExp) {
      reCore = delimiter.source.replace('/^\^/', '').replace('/\$$/', '');
    } else {
      reCore = delimiter.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    Object.defineProperty(instance, 'regex', {
      value: new RegExp('^(.*?)(' + reCore + ')(.*)$'),
      enumerable: true
    });

    return instance;
  }

  Tokenizer.prototype.__proto__ = Array.prototype

  Tokenizer.prototype.extract = function(times) {
    times = times || 1;

    if (this.length < 1)  return this;

    var matches = this[this.length - 1].match(this.regex);
    var newToken, rest;

    if (matches) {
      if (this.opts.incorporateDelimiter) {
        if (matches[1].length > 0) {
          newToken = matches[1];
          rest = matches[2] + matches[matches.length - 1];
        } else {
          newToken = matches[1] + matches[2];
          rest = matches[matches.length - 1];
        }
        this.delimiters.push('');
      } else {
        newToken = matches[1];
        this.delimiters.push(matches[2]);
        rest = matches[3];
      }
      this.lastDelimiterExtracted = matches[2];
      this[this.length - 1] = newToken;
      this[this.length] = rest;
      this.extractionLevel++;
    }

    return (times > 1)? this.extract(times - 1) : this;
  }

  Tokenizer.prototype.retract = function(times) {
    times = times || 1;
    if (this.length < 2) return;

    var delimiter = this.delimiters[this.delimiters.length - 1] || '';

    if (typeof(this[this.length - 2]) != 'string' || typeof(this[this.length - 1]) != 'string')
      throw new Error('retoken: Tried to retract a token that is not a string');

    if (typeof(delimiter) != 'string')
      throw new Error('retoken: Tried to retract a delimiter that is not a string');

    this[this.length - 2] += delimiter + this[this.length - 1];
    this.pop();
    this.extractionLevel--;

    return (times > 1)? this.retract(times - 1) : this;
  }

  Tokenizer.prototype.replaceToken = function(token, replacement) {
     var index = this.indexOf(token);
     if (!~index) return this;

     this[index] = replacement;

     return this;
  }

  function TOKENIZER_OVERRIDE_NOT_IMPLEMENTED(fxname) {
    Tokenizer.prototype[fxname] = function() {
      throw new Error('retoken: Function ' + fxname + ' not yet implemented in tokenizer');
    }
  }

  Tokenizer.prototype.reverse = function() {
    Array.prototype.reverse.call(this);
    this.delimiters.reverse();
    return this;
  }

  TOKENIZER_OVERRIDE_NOT_IMPLEMENTED('splice');
  TOKENIZER_OVERRIDE_NOT_IMPLEMENTED('sort');

  Tokenizer.prototype.insertToken = function(index, token, delimiter) {
    if (typeof(token) != 'string')
      throw new Error('retoken: Second argument [token] is not a string: ' + token);

    if (delimiter != null && typeof(delimiter) != 'string')
      throw new Error('retoken: Third argument [delimiter] is not a string: ' + delimiter);

    Array.prototype.splice.call(this, index, 0, token);

    if (this.length > 1) {
      delimiter = delimiter || ''
      this.delimiters.splice(index, 0, delimiter);
    }

    return this;
  }

  Tokenizer.prototype.push = function(str, delimiter) {
    Array.prototype.push.call(this, str);

    if (this.length > 1) this.delimiters.push(delimiter || '');

    return this;
  }

  Tokenizer.prototype.unshift = function(str, delimiter) {
    Array.prototype.unshift.call(this, str);
    this.delimiters.unshift(delimiter || '');
    return this;
  }

  Tokenizer.prototype.shift = function() {
    var elem = Array.prototype.shift.call(this);
    this.delimiters.shift();
    return elem;
  }

  Tokenizer.prototype.pop = function() {
    var elem = Array.prototype.pop.call(this);
    this.delimiters.pop();
    return elem;
  }

  Tokenizer.prototype.toArray = function() {
    var arr = new Array(this.length);

    for(var i=0; i < this.length; i++) {
      arr[i] = this[i];
    }

    return arr;
  }

  Object.defineProperty(Tokenizer.prototype, 'head', {
    get: function() { return this[0]; },
    set: function(token) { this[0] = token; },
    enumerable: true
  })

  Object.defineProperty(Tokenizer.prototype, 'tail', {
    get: function() { return this[this.length - 1]; },
    set: function(token) { this[this.length - 1] = token; },
    enumerable: true
  })

  if (typeof module !== 'undefined' && module && module.exports) { // Node.js & CommonJS
    module.exports = Tokenizer;
  } else if (typeof define === 'function' && define.amd) {
    define('retoken', [], function() {
      return Tokenizer;
    });
  } else { // Browser
    window.retoken = Tokenizer;
  }

})();
<|endoftext|>