<commit_before>define(['fsm'], function (Fsm) {

    /**
     * Fsm test plan.
     */
    describe('Fsm', function() {

        /**
         * Insert test.
         */
        it('should be able to be started given a new state', function () {
            var fsm = new Fsm();
            var state = new Fsm.State({
                name: 'state',
                fsm: fsm
            });

            expect(state.name()).toEqual('state');
            fsm.start(state);
            expect(fsm.state()).toBe(state);
        });

        /**
         * Transition between states.
         */
        it('should be able to transition between states', function () {
            var fsm = new Fsm();

            // Creating a `red` state.
            var red = new Fsm.State({
                name: 'red',
                fsm: fsm
            });

            // Creating a `green` state.
            var green = new Fsm.State({
                name: 'green',
                fsm: fsm
            });

            fsm.start(red);
            fsm.transitionTo(green);
            expect(fsm.state()).toBe(green);
            fsm.transitionTo(red);
            expect(fsm.state()).toBe(red);
        });

        /**
         * Transition between states.
         */
        it('should be able to transition between states using events', function () {
            var fsm = new Fsm();

            // Creating a `red` state.
            var red = new Fsm.State({
                name: 'red',
                fsm: fsm,
                onEvent: function (event) {
                    if (event === 'green') {
                        this.transitionTo(green);
                    }
                }
            });

            // Creating a `green` state.
            var green = new Fsm.State({
                name: 'green',
                fsm: fsm,
                onEvent: function (event) {
                    if (event == 'red') {
                        this.transitionTo(red);
                    }
                }
            });

            fsm.start(red);
            fsm.postEvent('green');
            expect(fsm.state()).toBe(green);
            fsm.postEvent('red');
            expect(fsm.state()).toBe(red);
            fsm.postEvent('red');
            expect(fsm.state()).toBe(red);
        });

        /**
         * State lifecycle test.
         */
        it('should respect the states lifecycle', function () {
            var fsm = new Fsm();

            var red = new Fsm.State({
                name: 'red',
                fsm: fsm,
                onEntry: function () {},
                onExit: function () {},
                onEvent: function (event) {}
            });

            var green = new Fsm.State({
                name: 'green',
                fsm: fsm,
                onEntry: function () {},
                onExit: function () {},
                onEvent: function (event) {}
            });

            // Spying on the red state callbacks.
            spyOn(red, "onEntry");
            spyOn(red, "onExit");
            spyOn(red, "onEvent");

            // Spying on the green state callbacks.
            spyOn(green, "onEntry");
            spyOn(green, "onExit");
            spyOn(green, "onEvent");

            // Starting the Fsm.
            fsm.start(red);
            // Testing whether the red state has been
            // entered.
            expect(red.onEntry).toHaveBeenCalled();
            expect(red.onExit).not.toHaveBeenCalled();
            expect(red.onEvent).not.toHaveBeenCalled();
            // Transitioning to the green state.
            fsm.transitionTo(green);
            // Testing whether the green state has been
            // entered.
            expect(red.onExit).toHaveBeenCalled();
            expect(green.onEntry).toHaveBeenCalled();
            expect(green.onExit).not.toHaveBeenCalled();
            expect(green.onEvent).not.toHaveBeenCalled();
            // Posting an event.
            fsm.postEvent({ foo: 'bar'});
            // Testing whether the current state's `onEvent`
            // callback has been called.
            expect(green.onEvent).toHaveBeenCalledWith({ foo: 'bar' });
        });

    });

});<commit_msg>Using the strict comparison operator<commit_after>define(['fsm'], function (Fsm) {

    /**
     * Fsm test plan.
     */
    describe('Fsm', function() {

        /**
         * Insert test.
         */
        it('should be able to be started given a new state', function () {
            var fsm = new Fsm();
            var state = new Fsm.State({
                name: 'state',
                fsm: fsm
            });

            expect(state.name()).toEqual('state');
            fsm.start(state);
            expect(fsm.state()).toBe(state);
        });

        /**
         * Transition between states.
         */
        it('should be able to transition between states', function () {
            var fsm = new Fsm();

            // Creating a `red` state.
            var red = new Fsm.State({
                name: 'red',
                fsm: fsm
            });

            // Creating a `green` state.
            var green = new Fsm.State({
                name: 'green',
                fsm: fsm
            });

            fsm.start(red);
            fsm.transitionTo(green);
            expect(fsm.state()).toBe(green);
            fsm.transitionTo(red);
            expect(fsm.state()).toBe(red);
        });

        /**
         * Transition between states.
         */
        it('should be able to transition between states using events', function () {
            var fsm = new Fsm();

            // Creating a `red` state.
            var red = new Fsm.State({
                name: 'red',
                fsm: fsm,
                onEvent: function (event) {
                    if (event === 'green') {
                        this.transitionTo(green);
                    }
                }
            });

            // Creating a `green` state.
            var green = new Fsm.State({
                name: 'green',
                fsm: fsm,
                onEvent: function (event) {
                    if (event === 'red') {
                        this.transitionTo(red);
                    }
                }
            });

            fsm.start(red);
            fsm.postEvent('green');
            expect(fsm.state()).toBe(green);
            fsm.postEvent('red');
            expect(fsm.state()).toBe(red);
            fsm.postEvent('red');
            expect(fsm.state()).toBe(red);
        });

        /**
         * State lifecycle test.
         */
        it('should respect the states lifecycle', function () {
            var fsm = new Fsm();

            var red = new Fsm.State({
                name: 'red',
                fsm: fsm,
                onEntry: function () {},
                onExit: function () {},
                onEvent: function (event) {}
            });

            var green = new Fsm.State({
                name: 'green',
                fsm: fsm,
                onEntry: function () {},
                onExit: function () {},
                onEvent: function (event) {}
            });

            // Spying on the red state callbacks.
            spyOn(red, "onEntry");
            spyOn(red, "onExit");
            spyOn(red, "onEvent");

            // Spying on the green state callbacks.
            spyOn(green, "onEntry");
            spyOn(green, "onExit");
            spyOn(green, "onEvent");

            // Starting the Fsm.
            fsm.start(red);
            // Testing whether the red state has been
            // entered.
            expect(red.onEntry).toHaveBeenCalled();
            expect(red.onExit).not.toHaveBeenCalled();
            expect(red.onEvent).not.toHaveBeenCalled();
            // Transitioning to the green state.
            fsm.transitionTo(green);
            // Testing whether the green state has been
            // entered.
            expect(red.onExit).toHaveBeenCalled();
            expect(green.onEntry).toHaveBeenCalled();
            expect(green.onExit).not.toHaveBeenCalled();
            expect(green.onEvent).not.toHaveBeenCalled();
            // Posting an event.
            fsm.postEvent({ foo: 'bar'});
            // Testing whether the current state's `onEvent`
            // callback has been called.
            expect(green.onEvent).toHaveBeenCalledWith({ foo: 'bar' });
        });

    });

});
<|endoftext|>


<commit_before>export const DEFAULT_CALENDAR = {
    name: 'My calendar',
    color: '#657ee4',
    description: ''
};

export const SETTINGS_VIEW = {
    DAY: 0,
    WEEK: 1,
    MONTH: 2,
    YEAR: 3,
    PLANNING: 4
};

export const SETTINGS_WEEK_START = {
    MONDAY: 1,
    SATURDAY: 6,
    SUNDAY: 7
};

export const VIEWS = {
    DAY: 1,
    WEEK: 2,
    MONTH: 3,
    YEAR: 4,
    AGENDA: 5,
    CUSTOM: 6
};

export const DAY_TO_NUMBER = {
    SU: 0,
    MO: 1,
    TU: 2,
    WE: 3,
    TH: 4,
    FR: 5,
    SA: 6
};

export const NUMBER_TO_DAY = {
    0: 'SU',
    1: 'MO',
    2: 'TU',
    3: 'WE',
    4: 'TH',
    5: 'FR',
    6: 'SA'
};

export const MINUTE = 60;
export const HOUR = MINUTE * 60;
export const DAY = HOUR * 24;
export const WEEK = DAY * 7;

export const SETTINGS_DATE_FORMAT = {
    DDMMYYYY: 0,
    MMDDYYYY: 1,
    YYYYMMDD: 2
};

export const SETTINGS_TIME_FORMAT = {
    H24: 0,
    H12: 1
};

export const NOTIFICATION_WHEN = {
    BEFORE: '-',
    AFTER: ''
};

export const NOTIFICATION_TYPE = {
    EMAIL: 0,
    DEVICE: 1
};

export const NOTIFICATION_UNITS = {
    WEEK: 1,
    DAY: 2,
    HOURS: 3,
    MINUTES: 4
};

export const NOTIFICATION_UNITS_MAX = {
    [NOTIFICATION_UNITS.WEEK]: 1000,
    [NOTIFICATION_UNITS.DAY]: 7000,
    [NOTIFICATION_UNITS.HOURS]: 1000,
    [NOTIFICATION_UNITS.MINUTES]: 10000
};

export const FREQUENCY = {
    ONCE: 'ONCE',
    DAILY: 'DAILY',
    WEEKLY: 'WEEKLY',
    MONTHLY: 'MONTHLY',
    YEARLY: 'YEARLY',
    CUSTOM: 'CUSTOM'
};

export const FREQUENCY_INTERVALS_MAX = {
    [FREQUENCY.DAILY]: 1000,
    [FREQUENCY.WEEKLY]: 5000,
    [FREQUENCY.MONTHLY]: 1000,
    [FREQUENCY.YEARLY]: 100
};

export const FREQUENCY_COUNT_MAX = 50;

export const MAX_CALENDARS_PER_USER = 10;

export const DAILY_TYPE = {
    ALL_DAYS: 0
};

export const WEEKLY_TYPE = {
    ON_DAYS: 0
};

export const MONTHLY_TYPE = {
    ON_MONTH_DAY: 0,
    ON_NTH_DAY: 1,
    ON_MINUS_NTH_DAY: -1
};

export const YEARLY_TYPE = {
    BY_MONTH_ON_MONTH_DAY: 0
};

export const END_TYPE = {
    NEVER: 'NEVER',
    AFTER_N_TIMES: 'COUNT',
    UNTIL: 'UNTIL'
};

export const DEFAULT_EVENT_DURATION = 30;

export const COLORS = {
    BLACK: '#000',
    WHITE: '#FFF'
};

export const MAX_LENGTHS = {
    CALENDAR_NAME: 100,
    TITLE: 255,
    DESCRIPTION: 3000,
    LOCATION: 255
};

export const MAX_DEFAULT_NOTIFICATIONS = 5;

export const RECURRING_DELETE_TYPES = {
    ALL: 1,
    FUTURE: 2,
    SINGLE: 3
};

export const MINIMUM_DATE = new Date(1970, 0, 1);
export const MINIMUM_DATE_UTC = new Date(
    Date.UTC(MINIMUM_DATE.getFullYear(), MINIMUM_DATE.getMonth(), MINIMUM_DATE.getDate())
);

export const MAXIMUM_DATE = new Date(9999, 11, 31);
export const MAXIMUM_DATE_UTC = new Date(
    Date.UTC(MAXIMUM_DATE.getFullYear(), MAXIMUM_DATE.getMonth(), MAXIMUM_DATE.getDate())
);
<commit_msg>Restrict max limit to the year 2038<commit_after>export const DEFAULT_CALENDAR = {
    name: 'My calendar',
    color: '#657ee4',
    description: ''
};

export const SETTINGS_VIEW = {
    DAY: 0,
    WEEK: 1,
    MONTH: 2,
    YEAR: 3,
    PLANNING: 4
};

export const SETTINGS_WEEK_START = {
    MONDAY: 1,
    SATURDAY: 6,
    SUNDAY: 7
};

export const VIEWS = {
    DAY: 1,
    WEEK: 2,
    MONTH: 3,
    YEAR: 4,
    AGENDA: 5,
    CUSTOM: 6
};

export const DAY_TO_NUMBER = {
    SU: 0,
    MO: 1,
    TU: 2,
    WE: 3,
    TH: 4,
    FR: 5,
    SA: 6
};

export const NUMBER_TO_DAY = {
    0: 'SU',
    1: 'MO',
    2: 'TU',
    3: 'WE',
    4: 'TH',
    5: 'FR',
    6: 'SA'
};

export const MINUTE = 60;
export const HOUR = MINUTE * 60;
export const DAY = HOUR * 24;
export const WEEK = DAY * 7;

export const SETTINGS_DATE_FORMAT = {
    DDMMYYYY: 0,
    MMDDYYYY: 1,
    YYYYMMDD: 2
};

export const SETTINGS_TIME_FORMAT = {
    H24: 0,
    H12: 1
};

export const NOTIFICATION_WHEN = {
    BEFORE: '-',
    AFTER: ''
};

export const NOTIFICATION_TYPE = {
    EMAIL: 0,
    DEVICE: 1
};

export const NOTIFICATION_UNITS = {
    WEEK: 1,
    DAY: 2,
    HOURS: 3,
    MINUTES: 4
};

export const NOTIFICATION_UNITS_MAX = {
    [NOTIFICATION_UNITS.WEEK]: 1000,
    [NOTIFICATION_UNITS.DAY]: 7000,
    [NOTIFICATION_UNITS.HOURS]: 1000,
    [NOTIFICATION_UNITS.MINUTES]: 10000
};

export const FREQUENCY = {
    ONCE: 'ONCE',
    DAILY: 'DAILY',
    WEEKLY: 'WEEKLY',
    MONTHLY: 'MONTHLY',
    YEARLY: 'YEARLY',
    CUSTOM: 'CUSTOM'
};

export const FREQUENCY_INTERVALS_MAX = {
    [FREQUENCY.DAILY]: 1000,
    [FREQUENCY.WEEKLY]: 5000,
    [FREQUENCY.MONTHLY]: 1000,
    [FREQUENCY.YEARLY]: 100
};

export const FREQUENCY_COUNT_MAX = 50;

export const MAX_CALENDARS_PER_USER = 10;

export const DAILY_TYPE = {
    ALL_DAYS: 0
};

export const WEEKLY_TYPE = {
    ON_DAYS: 0
};

export const MONTHLY_TYPE = {
    ON_MONTH_DAY: 0,
    ON_NTH_DAY: 1,
    ON_MINUS_NTH_DAY: -1
};

export const YEARLY_TYPE = {
    BY_MONTH_ON_MONTH_DAY: 0
};

export const END_TYPE = {
    NEVER: 'NEVER',
    AFTER_N_TIMES: 'COUNT',
    UNTIL: 'UNTIL'
};

export const DEFAULT_EVENT_DURATION = 30;

export const COLORS = {
    BLACK: '#000',
    WHITE: '#FFF'
};

export const MAX_LENGTHS = {
    CALENDAR_NAME: 100,
    TITLE: 255,
    DESCRIPTION: 3000,
    LOCATION: 255
};

export const MAX_DEFAULT_NOTIFICATIONS = 5;

export const RECURRING_DELETE_TYPES = {
    ALL: 1,
    FUTURE: 2,
    SINGLE: 3
};

export const MINIMUM_DATE = new Date(1970, 0, 1);
export const MINIMUM_DATE_UTC = new Date(
    Date.UTC(MINIMUM_DATE.getFullYear(), MINIMUM_DATE.getMonth(), MINIMUM_DATE.getDate())
);

export const MAXIMUM_DATE = new Date(2037, 11, 31);
export const MAXIMUM_DATE_UTC = new Date(
    Date.UTC(MAXIMUM_DATE.getFullYear(), MAXIMUM_DATE.getMonth(), MAXIMUM_DATE.getDate())
);
<|endoftext|>


<commit_before>const { getConfigDesc } = require('./config-description');
const { getErrors, getWarnings } = require('./errors-warnings');
const { getBaseBranchDesc } = require('./base-branch');
const { getPrList } = require('./pr-list');

const prTemplate = `Welcome to [Renovate](https://renovateapp.com)!

This is an onboarding PR to help you understand and configure Renovate before any regular Pull Requests begin. Once you close this Pull Request, Renovate will begin keeping your dependencies up-to-date via automated Pull Requests.

If you have any questions, try reading our [Configuring Renovate](https://renovateapp.com/docs/getting-started/configure-renovate) help page first, or feel free to ask the app author @rarkins a question in a comment below.

---
{{CONFIG}}
{{WARNINGS}}
{{ERRORS}}
{{BASEBRANCH}}
{{PRLIST}}

---

#### Don't want a \`renovate.json\` file?

Renovate will begin once this "Configure Renovate" PR is merged *or* closed, but it's recommended that you add the \`renovate.json\` to your repository to ensure behaviour matches what you see described here. Alternatively, you can add the same configuration settings into a "renovate" section of your \`package.json\` file(s) in this branch and delete the \`renovate.json\` from this PR.

#### Want to start over?

If you'd like Renovate to recreate this "Configure Renovate" PR from scratch - for example if your base branch has had substantial changes - then you need to:

1. (IMPORTANT) Rename this PR to something else, e.g. "Configure Renovate - old"
2. Close the PR and delete the branch

If later on you ever wish to reconfigure Renovate then you can use this same trick of renaming the PR, but you'll also need to delete any \`renovate.json\` file too. You should then get a new "Configure Renovate" PR like this.
`;

async function ensureOnboardingPr(config) {
  logger.debug('ensureOnboardingPr()');
  logger.trace({ config });
  const onboardingBranch = `${config.branchPrefix}configure`;
  const onboardingPrTitle = 'Configure Renovate';
  logger.debug('Filling in onboarding PR template');
  let prBody = prTemplate;
  prBody = prBody.replace('{{CONFIG}}\n', getConfigDesc(config));
  prBody = prBody.replace('{{WARNINGS}}\n', getWarnings(config));
  prBody = prBody.replace('{{ERRORS}}\n', getErrors(config));
  prBody = prBody.replace('{{BASEBRANCH}}\n', getBaseBranchDesc(config));
  prBody = prBody.replace('{{PRLIST}}\n', getPrList(config));
  logger.trace('prBody:\n' + prBody);

  // Check if existing PR exists
  const existingPr = await platform.getBranchPr(
    `${config.branchPrefix}configure`
  );
  if (existingPr) {
    // Check if existing PR needs updating
    if (existingPr.title === onboardingPrTitle && existingPr.body === prBody) {
      logger.info(`${existingPr.displayNumber} does not need updating`);
      return;
    }
    // PR must need updating
    await platform.updatePr(existingPr.number, onboardingPrTitle, prBody);
    logger.info(`Updated ${existingPr.displayNumber}`);
    return;
  }
  const labels = [];
  const useDefaultBranch = true;
  const pr = await platform.createPr(
    onboardingBranch,
    onboardingPrTitle,
    prBody,
    labels,
    useDefaultBranch
  );
  logger.info({ pr: pr.displayNumber }, 'Created onboarding PR');
}

module.exports = {
  ensureOnboardingPr,
};
<commit_msg>refactor: return ‘onboarding’ from ensureOnboardingPr (#1250)<commit_after>const { getConfigDesc } = require('./config-description');
const { getErrors, getWarnings } = require('./errors-warnings');
const { getBaseBranchDesc } = require('./base-branch');
const { getPrList } = require('./pr-list');

const prTemplate = `Welcome to [Renovate](https://renovateapp.com)!

This is an onboarding PR to help you understand and configure Renovate before any regular Pull Requests begin. Once you close this Pull Request, Renovate will begin keeping your dependencies up-to-date via automated Pull Requests.

If you have any questions, try reading our [Configuring Renovate](https://renovateapp.com/docs/getting-started/configure-renovate) help page first, or feel free to ask the app author @rarkins a question in a comment below.

---
{{CONFIG}}
{{WARNINGS}}
{{ERRORS}}
{{BASEBRANCH}}
{{PRLIST}}

---

#### Don't want a \`renovate.json\` file?

Renovate will begin once this "Configure Renovate" PR is merged *or* closed, but it's recommended that you add the \`renovate.json\` to your repository to ensure behaviour matches what you see described here. Alternatively, you can add the same configuration settings into a "renovate" section of your \`package.json\` file(s) in this branch and delete the \`renovate.json\` from this PR.

#### Want to start over?

If you'd like Renovate to recreate this "Configure Renovate" PR from scratch - for example if your base branch has had substantial changes - then you need to:

1. (IMPORTANT) Rename this PR to something else, e.g. "Configure Renovate - old"
2. Close the PR and delete the branch

If later on you ever wish to reconfigure Renovate then you can use this same trick of renaming the PR, but you'll also need to delete any \`renovate.json\` file too. You should then get a new "Configure Renovate" PR like this.
`;

async function ensureOnboardingPr(config) {
  logger.debug('ensureOnboardingPr()');
  logger.trace({ config });
  const onboardingBranch = `${config.branchPrefix}configure`;
  const onboardingPrTitle = 'Configure Renovate';
  logger.debug('Filling in onboarding PR template');
  let prBody = prTemplate;
  prBody = prBody.replace('{{CONFIG}}\n', getConfigDesc(config));
  prBody = prBody.replace('{{WARNINGS}}\n', getWarnings(config));
  prBody = prBody.replace('{{ERRORS}}\n', getErrors(config));
  prBody = prBody.replace('{{BASEBRANCH}}\n', getBaseBranchDesc(config));
  prBody = prBody.replace('{{PRLIST}}\n', getPrList(config));
  logger.trace('prBody:\n' + prBody);

  // Check if existing PR exists
  const existingPr = await platform.getBranchPr(
    `${config.branchPrefix}configure`
  );
  if (existingPr) {
    // Check if existing PR needs updating
    if (existingPr.title === onboardingPrTitle && existingPr.body === prBody) {
      logger.info(`${existingPr.displayNumber} does not need updating`);
      return 'onboarding';
    }
    // PR must need updating
    await platform.updatePr(existingPr.number, onboardingPrTitle, prBody);
    logger.info(`Updated ${existingPr.displayNumber}`);
    return 'onboarding';
  }
  const labels = [];
  const useDefaultBranch = true;
  const pr = await platform.createPr(
    onboardingBranch,
    onboardingPrTitle,
    prBody,
    labels,
    useDefaultBranch
  );
  logger.info({ pr: pr.displayNumber }, 'Created onboarding PR');
  return 'onboarding';
}

module.exports = {
  ensureOnboardingPr,
};
<|endoftext|>


<commit_before>var schedulechanges;

function getHTML(URL) {
var client = Ti.Network.createHTTPClient({
	onload: function(){
		Ti.API.info("Received HTML!");
		return this.responseText;
	},
	onerror: function(e){
		Ti.API.debug(e.error);
		alert('Internetverbinding mislukt. Probeer het later opnieuw.');
	},
	timeout : 5000
});
client.open("GET", URL);
client.send();
}

function loadschedule(){
	var subst = 1;
	var tables = [];
	// EDIT THIS!
	var schoollink = 'gym';
	var link = 'http://www3.pj.nl/' + schoollink + '_info_leerlingen/subst_00';
	while (1) {
		parselink = link + subst + '.htm';
		var html = getHTML(parselink);
		var regex = /Pagina (\d) \/ (\d)/;
		var paginas = regex.exec(html);
		if ((paginas !== null && paginas[0] <= paginas[1]) || subst == 1){
			tables.push(/(<tr.*<\/tr>)/mg.exec(html));
			subst = subst + 1;
		}
		if (paginas == null || paginas[0] == paginas[1]){
			break;
		}
	}
	Ti.API.info(tables);
	schedulechanges = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory(),'schedulechanges.html');
	var template = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'schedulechangestemplate.html');
	//Enter year filtering here
	tablesString = tables.join(" ");
	var templateString = template.read();
	schedulechanges.write(templateString + tablesString + '

');
}

var win = Titanium.UI.createWindow({
	backgroundColor: 'white',
	exitOnClose: true
});

var mainview = Titanium.UI.createView({
	height:'81%',
	top:'10%'
});

win.add(mainview);

loadschedule();

var webview1 = Titanium.UI.createWebView({
	url: schedulechanges.nativePath
});

var webview1EventListener = function(){
	webview1.reload();
};

mainview.add(webview1);

var webview2 = Titanium.UI.createWebView({
	url:'http://www3.pj.nl/infoschermgymnasium/'
});

var webview2EventListener = function(){
	webview2.reload();
};

var actionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'10%'
});

var titlelabel = Titanium.UI.createLabel({
	text:'PJ Info',
	textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
	color:'#fff',
	font:{fontSize:24}
});

actionbar.add(titlelabel);

var settingsbutton = Titanium.UI.createImageView({
	image:'settings.png',
	height:'80%',
	left:'3%'
});

var settingsactionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'10%'
});

settingsbutton.addEventListener('click',function(){
	var settingswin = Titanium.UI.createWindow({
		backgroundColor:'#fff'
	});

	var backbutton = Titanium.UI.createImageView({
		image:'back.png',
		height:'80%',
		left:'3%'
	});

	backbutton.addEventListener('click',function(e){
		settingswin.close();
	});

	settingsactionbar.add(backbutton);

	var titlelabel = Titanium.UI.createLabel({
		text:'Instellingen',
		textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
		color:'#fff',
		font:{fontSize:24}
	});

	var setschoolbutton = Titanium.UI.createButton({
		title:'Kies je school...',
		top:'35%',
		height:60,
		width:150,
		borderWidth:2,
		borderColor:'#003c6d',
		backgroundColor:'#fff',
		color:'#003c6d'
	});

	var schools = ['!mpulse', '!mpulse Kollum', 'Dalton Dokkum', 'De Brêge', 'De Dyk', 'De Foorakker',
	'ISK', 'Leeuwarder Lyceum', 'Montessori High School', 'Stedelijk Gymnasium', 'YnSicht'];

	setschoolbutton.addEventListener('click',function(){
		var schooloptions = {
		title:'School selecteren',
		options:schools
		};
		var setschool = Ti.UI.createOptionDialog(schooloptions);
		setschool.show();
		setschool.addEventListener('click', onSelectOptionDialog);
		function onSelectOptionDialog(event){
		    var selectedIndex = event.source.selectedIndex;
		    if (schools[selectedIndex] != null) {
		    	settingswin.remove(setschoolbutton);
			    setschoolbutton.title=schools[selectedIndex];
			    settingswin.add(setschoolbutton);
		    }
		}
	});

	var years = ['Leerjaar 1', 'Leerjaar 2', 'Leerjaar 3', 'Leerjaar 4', 'Leerjaar 5', 'Leerjaar 6'];

	var setyearbutton = Titanium.UI.createButton({
		title:'Kies je leerjaar...',
		top:'65%',
		height:60,
		width:150,
		borderWidth:2,
		borderColor:'#003c6d',
		backgroundColor:'#fff',
		color:'#003c6d'
	});

	setyearbutton.addEventListener('click',function(){
		var yearoptions = {
		title:'Leerjaar selecteren',
		options:years
		};
		var setyear = Ti.UI.createOptionDialog(yearoptions);
		setyear.show();
		setyear.addEventListener('click', onSelectOptionDialog);
		function onSelectOptionDialog(event){
		    var selectedIndex = event.source.selectedIndex;
		    if (years[selectedIndex] != null) {
		    	settingswin.remove(setyearbutton);
			    setyearbutton.title=years[selectedIndex];
			    settingswin.add(setyearbutton);
		    }
		}
	});

	Ti.Gesture.addEventListener('orientationchange', function(e){
		if(e.source.isPortrait()) {
			settingsactionbar.applyProperties({
				height:'10%'
			});
		} else if(e.source.isLandscape()) {
			settingsactionbar.applyProperties({
				height:'15%'
			});
		};
	});

	settingsactionbar.add(titlelabel);

	settingswin.add(settingsactionbar);
	settingswin.add(setschoolbutton);
	settingswin.add(setyearbutton);
	settingswin.open();
});

actionbar.add(settingsbutton);

var refreshbutton = Titanium.UI.createImageView({
	image:'refresh.png',
	height:'80%',
	right:'3%'
});

actionbar.add(refreshbutton);
win.add(actionbar);

var tabsview = Titanium.UI.createView({
	bottom:0,
	height:'10%',
	left:0,
	right:0
});

win.add(tabsview);

var label1 = Titanium.UI.createLabel({
	text:'Roosterwijzigingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'10%',
	bottom:0,
	left:0,
	width:'43%',
	color:'#003c6d',
	backgroundColor:'#fff'
});

var label2 = Titanium.UI.createLabel({
	text:'Mededelingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'10%',
	bottom:0,
	left:'44%',
	width:'34%',
	color:'#fff',
	backgroundColor:'#003c6d'
});

var imageview = Titanium.UI.createView({
	top:'10%',
	bottom:0,
	left:'79%',
	height:'90%',
	width:'21%',
	backgroundColor:'#003c6d'
});

var image = Titanium.UI.createImageView({
	image:'stentor.png'
});

imageview.add(image);

var divisionborder1 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'10%',
    bottom:0,
    width:'1%',
    left:'43%',
    right:'55%'
});

var divisionborder2 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'10%',
    bottom:0,
    width:'1%',
    left:'78%',
    right:'21%'
});

tabsview.add(divisionborder1);
tabsview.add(divisionborder2);

tabsview.add(label1);
tabsview.add(label2);
tabsview.add(imageview);

Ti.Gesture.addEventListener('orientationchange', function(e){
	if(e.source.isPortrait()) {
		mainview.applyProperties({
			height:'81%',
			top:'10%'
		});
		actionbar.applyProperties({
			height:'10%'
		});
		tabsview.applyProperties({
			height:'10%'
		});
		label1.applyProperties({
			top:'10%'
		});
		label2.applyProperties({
			top:'10%'
		});
		imageview.applyProperties({
			height:'90%',
			top:'10%'
		});
		divisionborder1.applyProperties({
			top:'10%'
		});
		divisionborder2.applyProperties({
			top:'10%'
		});
		settingsbutton.addEventListener('click',function(e){
			settingsactionbar.applyProperties({
				height:'10%'
			});
		});
	} else if(e.source.isLandscape()) {
		mainview.applyProperties({
			height:'72.5%',
			top:'15%'
		});
		actionbar.applyProperties({
			height:'15%'
		});
		tabsview.applyProperties({
			height:'15%'
		});
		label1.applyProperties({
			top:'15%'
		});
		label2.applyProperties({
			top:'15%'
		});
		imageview.applyProperties({
			height:'85%',
			top:'15%'
		});
		divisionborder1.applyProperties({
			top:'15%'
		});
		divisionborder2.applyProperties({
			top:'15%'
		});
		settingsbutton.addEventListener('click',function(e){
			settingsactionbar.applyProperties({
				height:'15%'
			});
		});
	};
});

label1.addEventListener('click',function(){
	label1.color = '#003c6d';
	label1.backgroundColor = '#fff';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview2EventListener);

	refreshbutton.addEventListener('click',webview1EventListener);

	mainview.remove(webview2);
	mainview.add(webview1);
});
label2.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#003c6d';
	label2.backgroundColor = '#fff';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview1EventListener);

	refreshbutton.addEventListener('click',webview2EventListener);

	mainview.remove(webview1);
	mainview.add(webview2);
});
imageview.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#fff';

	mainview.remove(webview1);
	mainview.remove(webview2);
	actionbar.remove(refreshbutton);

	var stentorview = Titanium.UI.createView({
    	backgroundColor: '#fff',
    	height:'81%',
    	top:'10%'
	});

	var gwbutton = Ti.UI.createButton({
		title:'Gevleugelde Woorden insturen',
		height:70,
		width:170,
		backgroundColor: '#dc006d',
		color: '#fff'
	});

	gwbutton.addEventListener('click',function(e){
	   	var emailDialog = Ti.UI.createEmailDialog();
		emailDialog.subject = "Gevleugelde Woorden via PJ Info";
		emailDialog.toRecipients = ['mennohellinga@zoho.com'];	// CHANGE BEFORE RELEASE!
		emailDialog.open();
	});

	label1.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview1);
	});
	label2.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview2);
	});

	stentorview.add(gwbutton);
	mainview.add(stentorview);
});

win.open();
<commit_msg>Infoscreen has white bg, lost redundancies<commit_after>var schedulechanges;
var infoScreen;

function getHTML(URL) {
var client = Ti.Network.createHTTPClient({
	onload: function(){
		Ti.API.info("Received HTML!");
		return this.responseText;
	},
	onerror: function(e){
		Ti.API.debug(e.error);
		alert('Internetverbinding mislukt. Probeer het later opnieuw.');
	},
	timeout : 5000
});
client.open("GET", URL);
client.send();
}

function loadschedule(){
	var subst = 1;
	var tables = [];
	// EDIT THIS!
	var schoollink = 'gym';
	var link = 'http://www3.pj.nl/' + schoollink + '_info_leerlingen/subst_00';
	while (1) {
		parselink = link + subst + '.htm';
		var html = getHTML(parselink);
		var regex = /Pagina (\d) \/ (\d)/;
		var paginas = regex.exec(html);
		if ((paginas !== null && paginas[0] <= paginas[1]) || subst == 1){
			tables.push(/(<tr.*<\/tr>)/mg.exec(html));
			subst = subst + 1;
		}
		if (paginas == null || paginas[0] == paginas[1]){
			break;
		}
	}
	Ti.API.info(tables);
	schedulechanges = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory(),'schedulechanges.html');
	var template = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'schedulechangestemplate.html');
	//Enter year filtering here
	tablesString = tables.join(" ");
	var templateString = template.read();
	schedulechanges.write(templateString + tablesString + '

');
}

function loadInfoscreen (){
	// EDIT THIS!
	var HTMLSource = getHTML ('www3.pj.nl/infoschermgymnasium/');
	var infoScreenWhite = HTMLSource.replace ('FFFBA4', 'FFFFFF');
	var infoScreenPrevSpaceGone = infoScreenWhite.replace ('
<o:p> </o:p>
', ' ');
	var infoScreenFinal = infoScreenPrevSpaceGone.replace (/
Einde bericht<o:p><\/o:p><\/span><\/b><\/p>.*<\/div>/img, '
');
	infoScreen = Titanium.Filesystem.getFile (Titanium.Filesystem.applicationDataDirectory(), 'infoScreen.html');
	infoScreen.write (infoScreenFinal);
}

var win = Titanium.UI.createWindow({
	backgroundColor: 'white',
	exitOnClose: true
});

var mainview = Titanium.UI.createView({
	height:'81%',
	top:'10%'
});

win.add(mainview);

loadschedule();
loadInfoscreen ();

var webview1 = Titanium.UI.createWebView({
	url: schedulechanges.nativePath
});

var webview1EventListener = function(){
	webview1.reload();
};

mainview.add(webview1);

var webview2 = Titanium.UI.createWebView({
	url: infoScreen.nativePath
});

var webview2EventListener = function(){
	webview2.reload();
};

var actionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'10%'
});

var titlelabel = Titanium.UI.createLabel({
	text:'PJ Info',
	textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
	color:'#fff',
	font:{fontSize:24}
});

actionbar.add(titlelabel);

var settingsbutton = Titanium.UI.createImageView({
	image:'settings.png',
	height:'80%',
	left:'3%'
});

var settingsactionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'10%'
});

settingsbutton.addEventListener('click',function(){
	var settingswin = Titanium.UI.createWindow({
		backgroundColor:'#fff'
	});

	var backbutton = Titanium.UI.createImageView({
		image:'back.png',
		height:'80%',
		left:'3%'
	});

	backbutton.addEventListener('click',function(e){
		settingswin.close();
	});

	settingsactionbar.add(backbutton);

	var titlelabel = Titanium.UI.createLabel({
		text:'Instellingen',
		textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
		color:'#fff',
		font:{fontSize:24}
	});

	var setschoolbutton = Titanium.UI.createButton({
		title:'Kies je school...',
		top:'35%',
		height:60,
		width:150,
		borderWidth:2,
		borderColor:'#003c6d',
		backgroundColor:'#fff',
		color:'#003c6d'
	});

	var schools = ['!mpulse', '!mpulse Kollum', 'Dalton Dokkum', 'De Brêge', 'De Dyk', 'De Foorakker',
	'ISK', 'Leeuwarder Lyceum', 'Montessori High School', 'Stedelijk Gymnasium', 'YnSicht'];

	setschoolbutton.addEventListener('click',function(){
		var schooloptions = {
		title:'School selecteren',
		options:schools
		};
		var setschool = Ti.UI.createOptionDialog(schooloptions);
		setschool.show();
		setschool.addEventListener('click', onSelectOptionDialog);
		function onSelectOptionDialog(event){
		    var selectedIndex = event.source.selectedIndex;
		    if (schools[selectedIndex] != null) {
		    	settingswin.remove(setschoolbutton);
			    setschoolbutton.title=schools[selectedIndex];
			    settingswin.add(setschoolbutton);
		    }
		}
	});

	var years = ['Leerjaar 1', 'Leerjaar 2', 'Leerjaar 3', 'Leerjaar 4', 'Leerjaar 5', 'Leerjaar 6'];

	var setyearbutton = Titanium.UI.createButton({
		title:'Kies je leerjaar...',
		top:'65%',
		height:60,
		width:150,
		borderWidth:2,
		borderColor:'#003c6d',
		backgroundColor:'#fff',
		color:'#003c6d'
	});

	setyearbutton.addEventListener('click',function(){
		var yearoptions = {
		title:'Leerjaar selecteren',
		options:years
		};
		var setyear = Ti.UI.createOptionDialog(yearoptions);
		setyear.show();
		setyear.addEventListener('click', onSelectOptionDialog);
		function onSelectOptionDialog(event){
		    var selectedIndex = event.source.selectedIndex;
		    if (years[selectedIndex] != null) {
		    	settingswin.remove(setyearbutton);
			    setyearbutton.title=years[selectedIndex];
			    settingswin.add(setyearbutton);
		    }
		}
	});

	Ti.Gesture.addEventListener('orientationchange', function(e){
		if(e.source.isPortrait()) {
			settingsactionbar.applyProperties({
				height:'10%'
			});
		} else if(e.source.isLandscape()) {
			settingsactionbar.applyProperties({
				height:'15%'
			});
		};
	});

	settingsactionbar.add(titlelabel);

	settingswin.add(settingsactionbar);
	settingswin.add(setschoolbutton);
	settingswin.add(setyearbutton);
	settingswin.open();
});

actionbar.add(settingsbutton);

var refreshbutton = Titanium.UI.createImageView({
	image:'refresh.png',
	height:'80%',
	right:'3%'
});

actionbar.add(refreshbutton);
win.add(actionbar);

var tabsview = Titanium.UI.createView({
	bottom:0,
	height:'10%',
	left:0,
	right:0
});

win.add(tabsview);

var label1 = Titanium.UI.createLabel({
	text:'Roosterwijzigingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'10%',
	bottom:0,
	left:0,
	width:'43%',
	color:'#003c6d',
	backgroundColor:'#fff'
});

var label2 = Titanium.UI.createLabel({
	text:'Mededelingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'10%',
	bottom:0,
	left:'44%',
	width:'34%',
	color:'#fff',
	backgroundColor:'#003c6d'
});

var imageview = Titanium.UI.createView({
	top:'10%',
	bottom:0,
	left:'79%',
	height:'90%',
	width:'21%',
	backgroundColor:'#003c6d'
});

var image = Titanium.UI.createImageView({
	image:'stentor.png'
});

imageview.add(image);

var divisionborder1 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'10%',
    bottom:0,
    width:'1%',
    left:'43%',
    right:'55%'
});

var divisionborder2 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'10%',
    bottom:0,
    width:'1%',
    left:'78%',
    right:'21%'
});

tabsview.add(divisionborder1);
tabsview.add(divisionborder2);

tabsview.add(label1);
tabsview.add(label2);
tabsview.add(imageview);

Ti.Gesture.addEventListener('orientationchange', function(e){
	if(e.source.isPortrait()) {
		mainview.applyProperties({
			height:'81%',
			top:'10%'
		});
		actionbar.applyProperties({
			height:'10%'
		});
		tabsview.applyProperties({
			height:'10%'
		});
		label1.applyProperties({
			top:'10%'
		});
		label2.applyProperties({
			top:'10%'
		});
		imageview.applyProperties({
			height:'90%',
			top:'10%'
		});
		divisionborder1.applyProperties({
			top:'10%'
		});
		divisionborder2.applyProperties({
			top:'10%'
		});
		settingsbutton.addEventListener('click',function(e){
			settingsactionbar.applyProperties({
				height:'10%'
			});
		});
	} else if(e.source.isLandscape()) {
		mainview.applyProperties({
			height:'72.5%',
			top:'15%'
		});
		actionbar.applyProperties({
			height:'15%'
		});
		tabsview.applyProperties({
			height:'15%'
		});
		label1.applyProperties({
			top:'15%'
		});
		label2.applyProperties({
			top:'15%'
		});
		imageview.applyProperties({
			height:'85%',
			top:'15%'
		});
		divisionborder1.applyProperties({
			top:'15%'
		});
		divisionborder2.applyProperties({
			top:'15%'
		});
		settingsbutton.addEventListener('click',function(e){
			settingsactionbar.applyProperties({
				height:'15%'
			});
		});
	};
});

label1.addEventListener('click',function(){
	label1.color = '#003c6d';
	label1.backgroundColor = '#fff';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview2EventListener);

	refreshbutton.addEventListener('click',webview1EventListener);

	mainview.remove(webview2);
	mainview.add(webview1);
});
label2.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#003c6d';
	label2.backgroundColor = '#fff';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview1EventListener);

	refreshbutton.addEventListener('click',webview2EventListener);

	mainview.remove(webview1);
	mainview.add(webview2);
});
imageview.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#fff';

	mainview.remove(webview1);
	mainview.remove(webview2);
	actionbar.remove(refreshbutton);

	var stentorview = Titanium.UI.createView({
    	backgroundColor: '#fff',
    	height:'81%',
    	top:'10%'
	});

	var gwbutton = Ti.UI.createButton({
		title:'Gevleugelde Woorden insturen',
		height:70,
		width:170,
		backgroundColor: '#dc006d',
		color: '#fff'
	});

	gwbutton.addEventListener('click',function(e){
	   	var emailDialog = Ti.UI.createEmailDialog();
		emailDialog.subject = "Gevleugelde Woorden via PJ Info";
		emailDialog.toRecipients = ['mennohellinga@zoho.com'];	// CHANGE BEFORE RELEASE!
		emailDialog.open();
	});

	label1.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview1);
	});
	label2.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview2);
	});

	stentorview.add(gwbutton);
	mainview.add(stentorview);
});

win.open();
<|endoftext|>


<commit_before>var tabs = Ti.UI.createTabGroup();
var win1 = Ti.UI.createWindow({
backgroundColor: '#D2B45B'
});
var tab1 = Ti.UI.createTab({
title: 'Dan's Info',
window: win1
});
var picofme = Ti.UI.createImageView({
height: '30%',
width: '30%',
top: '15%'
});
myPic.image = '\picofme.jpg';

var view1 = Ti.UI.createView({
backgroundColor: '#CCCCCC',
top: '40%',
width: '80%',
height: '15%'
});
var name = Ti.UI.createLabel({
color: '#000000',
font: {fontSize: '25dp'},
text: 'Dan Hart',
top: '5%'
});
var school = Ti.UI.createLabel({
color: '#000000',
font: { fontSize: '20dp'},
text: 'University of Idaho',
top: '33%'
});
var major = Ti.UI.createLabel({
color: '#000000',
font: { fontSize: '15dp'},
top: '66%',
text: 'Information Systems'
});
var contactData = [{ title: 'Phone: (208)320-8497', color: '#000000'}, {title:'E-mail: hart6069@vandals.uidaho.edu', color: '#000000'}];
var contactTable = Ti.UI.createTableView({
data: contactData,
headerTitle: 'Contact Info',
backgroundColor: '#CCCCCC,
top: '65%',
width: '80%',
height: '20%'
});
var win2 =Ti.UI.createWindow({
backgroundColor: '#D2B45B'
});
var tab2 = Ti.UI.createTab({
title: 'Portfolio',
window: win2
});
var view2 = Ti.UI.createView({
backgroundColor: '#CCCCCC',
height: '80%',
width: '80%'
});
var bio = Ti.UI.createLabel({
font: {fontSize: '20dp'},
text: 'Hi, My name is Dan Hart and I am currently a student at the University of Idaho, majoring in Information Systems. I will graduate in the Fall of 2015 and am currently looking for employment after I am done with school.'
});
win1.add(name);
win1.add(school);
win1.add(major);
win1.add(view1);
win1.add(picofme);
win1.add(contactTable);
win2.add(bio);
win2.add(view2);
tabs.addTab(tab1);
tabs.addTab(tab2);
tabs.open();
<commit_msg>Update app.js<commit_after>var tabs = Ti.UI.createTabGroup();
var win1 = Ti.UI.createWindow({
backgroundColor: '#D2B45B'
});
var tab1 = Ti.UI.createTab({
title: 'Dan's Info',
window: win1
});
var picofme = Ti.UI.createImageView({
height: '30%',
width: '30%',
top: '15%'
});
picofme.image = '\picofme.jpg';

var view1 = Ti.UI.createView({
backgroundColor: '#CCCCCC',
top: '40%',
width: '80%',
height: '15%'
});
var name = Ti.UI.createLabel({
color: '#000000',
font: {fontSize: '25dp'},
text: 'Dan Hart',
top: '5%'
});
var school = Ti.UI.createLabel({
color: '#000000',
font: { fontSize: '20dp'},
text: 'University of Idaho',
top: '33%'
});
var major = Ti.UI.createLabel({
color: '#000000',
font: { fontSize: '15dp'},
top: '66%',
text: 'Information Systems'
});
var contactData = [{ title: 'Phone: (208)320-8497', color: '#000000'}, {title:'E-mail: hart6069@vandals.uidaho.edu', color: '#000000'}];
var contactTable = Ti.UI.createTableView({
data: contactData,
headerTitle: 'Contact Info',
backgroundColor: '#CCCCCC,
top: '65%',
width: '80%',
height: '20%'
});
var win2 =Ti.UI.createWindow({
backgroundColor: '#D2B45B'
});
var tab2 = Ti.UI.createTab({
title: 'Portfolio',
window: win2
});
var view2 = Ti.UI.createView({
backgroundColor: '#CCCCCC',
height: '80%',
width: '80%'
});
var bio = Ti.UI.createLabel({
font: {fontSize: '20dp'},
text: 'Hi, My name is Dan Hart and I am currently a student at the University of Idaho, majoring in Information Systems. I will graduate in the Fall of 2015 and am currently looking for employment after I am done with school.'
});
win1.add(name);
win1.add(school);
win1.add(major);
win1.add(view1);
win1.add(picofme);
win1.add(contactTable);
win2.add(bio);
win2.add(view2);
tabs.addTab(tab1);
tabs.addTab(tab2);
tabs.open();
<|endoftext|>


<commit_before>var api = require('../controllers/api');

module.exports = function (server) {
    'use strict';

    // Posts
    server.resource('api/v1/posts', api.posts);
    server.resource('api/v1/posts/infos', api.postsinfo);
    server.resource('api/v1/labels', api.labels);
    server.resource('api/v1/themes/site', api.themes);
    server.resource('api/v1/themes/admin', api.adminthemes);

    server.resource('api/v1/config/redirects', api.redirects);
    server.resource('api/v1/settings', api.settings);

    // server.get('/api/v1/posts/archive', notImplemented);
    // server.get('/api/v1/posts/count', api.postCountInfo);
};<commit_msg>Comments removed<commit_after>var api = require('../controllers/api');

module.exports = function (server) {
    'use strict';

    // Posts
    server.resource('api/v1/posts', api.posts);
    server.resource('api/v1/posts/infos', api.postsinfo);
    server.resource('api/v1/labels', api.labels);
    server.resource('api/v1/themes/site', api.themes);
    server.resource('api/v1/themes/admin', api.adminthemes);

    server.resource('api/v1/config/redirects', api.redirects);
    server.resource('api/v1/settings', api.settings);
};<|endoftext|>


<commit_before>//将来的にxmlにパスワードとusernameを保存する
//他のwindowへのアクセス方法　Ti.App.scrollview.views[index]

(function(){
	Ti.App.disableNetworkActivityIndicator = true; //ネットワークインジゲータを消す
	///////////
	// require('lib/vineAPI').vineNewLogin('e.takumi.89@gmail.com','techcamptech','TechcampTakumi');
	// require('lib/vineAPI').vineNewLogin('higezizii-tansoku-choko-about@about-hiroppy.com','about19920429','about_hiroppy_test');
	// var b = require('com.HjAboutHiroppy.VineCamera');
	// var v = b.createView();
	// console.log(v);

	//require('lib/vineAPI').vineLogin('dreams.come.true.about@gmail.com','about19920429');
	// require('lib/vineAPI').vineLogin('e.takumi.89@gmail.com','8Gatu9Ka');

	tab_group = Ti.UI.createTabGroup();

	//一番下のベースLayer
	Ti.App.win_base = Ti.UI.createWindow({
		// backgroundImage: 'image/background.jpg',
		backgroundColor:"#eeeeee",
		navBarHidden: true,
		tabBarHidden: true,
		fullscreen : false,
	});

	var tab = Ti.UI.createTab({ window: Ti.App.win_base });
	tab_group.addTab(tab);
	tab_group.open();

		// Ti.App.Properties.removeProperty('username');
	    // Ti.App.Properties.removeProperty('password');

	start();
	if(!Ti.App.Properties.hasProperty('username')){
		var signSelectView = require('UI/signSelect').signSelect();
		Ti.App.win_base.add(signSelectView);
		Ti.App.win_base.loginSelectView = signSelectView;
	}
	else{
		// Ti.App.Properties.removeProperty('username');
	    // Ti.App.Properties.removeProperty('password');
		// console.log(Ti.App.Properties.getString('username'));
		require('lib/vineAPI').vineLogin(Ti.App.Properties.getString('username'),Ti.App.Properties.getString('password'));
	}

	function start(){
				var dummyWindow = [];

	    //この個数は変動
	    for(var i=0;i<4;i++){
		    var w = Ti.UI.createWindow({
			    width:"100%",
			    height:Ti.UI.FILL,
			    backgroundColor:"#ddd",
		    });
		    dummyWindow.push(w);
	    }

	    //スクロールビューの挿入
	    Ti.App.scrollview = Ti.UI.createScrollableView({
		    // left:"10%",
		    top:"10%",
		    width:"100%",
		    height:"80%",
		    // left:"20%",
		    views:dummyWindow,
		    horizontalBounce:false,
		    cacheSize:6,
		    // showPagingControl: true,
            // pagingControlHeight: 30,
	    });

	    Ti.App.win_base.add(Ti.App.scrollview);

	    //Button の　追加
	    createImages = function(image,size){
		    var button = Ti.UI.createButton({
			    color : "#ffffff",
			    backgroundImage : image,
			    left:size,
			    width:20,
		        height:20,
		    });
		    return button;
	    };

	    var homeButton = createImages("images/uniF489_.png",17);
	    var listButton = createImages("images/list.png",17);
	    var cameraButton = createImages("images/videocamera.png",153);
	    var searchButton = createImages("images/search.png",285);

	    listButton.addEventListener('singletap',function(){
		    require('UI/leftList').list();
	    });

	    cameraButton.addEventListener('singletap',function(){
		    require('UI/post').postWindow();
	    });

	    //可視化用
	    var buttonBar = Ti.UI.createView({
		    width:"100%",
		    height:"10%",
		    bottom:0,
		    backgroundColor:"#00a478",
		    color:"#fff",
		    textAlign:'center'
	    });

	    //buttonBar.add(homeButton);
	    buttonBar.add(listButton);
	    buttonBar.add(cameraButton);
	    buttonBar.add(searchButton);

	    var homebuttonBar = Ti.UI.createView({
		    width:"20%",
		    height:"100%",
		    top:0,
		    left:0,
		    image:"images/home2.png",
		    bubbleParent:false
	    });

	    homebuttonBar.addEventListener('singletap',function(){
		    Ti.App.scrollview.scrollToView(0);
	    });

	    // homebuttonBar.add(homeButton);

	    //上部ラベル
	    var topLabel = Ti.UI.createLabel({//Label
		    width:"100%",
		    height:"10%",
		    top:0,
		    backgroundColor:"#00a478",
		    text:"TIMELINE",
		    font:{
			    fontWeight: "normal",
			    fontSize: 25,
			    fontFamily: 'AppleGothic'
		    },
		    color:"#fff",
		    textAlign:'center',
		    bubbleParent:false
	    });

	    topLabel.add(homebuttonBar);
	    homebuttonBar.add(homeButton);

	    homebuttonBar.addEventListener('singletap',function(e){

		    //Ti.UI.ScrollableView. scrollToView(dummyWindow = [0]);
	    });

	    topLabel.addEventListener('singletap',function(e){
	    });

	    ///////////////////////////////////////////////
	    //Labelとscrollableview
	    var topLabelNameArray = [];
	    topLabelNameArray[0]= "TIMELINE";
	    topLabelNameArray[1]= "ACTIVITY";
	    topLabelNameArray[2]= "EXPLOPE";
	    topLabelNameArray[3]= "PROFILE";

	    Ti.App.scrollview.addEventListener('scroll',function(e){
		    if(e.currentPage != undefined){
			    topLabel.text = topLabelNameArray[e.currentPage];
		    }
	    });

	    ///////////////////////////////////////////////

        //
	    Ti.App.win_base.add(buttonBar);
	    Ti.App.win_base.add(topLabel);
	    // require('lib/camera').camera();
	    //これに入ったら各処理させる

	    Ti.App.addEventListener('loginComplete',function(){
	    	Ti.App.Properties.removeProperty('username');
	    	Ti.App.Properties.removeProperty('password');
	    	Ti.App.Properties.setString('username',Ti.App.email);
	    	Ti.App.Properties.setString('password',Ti.App.password);
	    	console.log(Ti.App.email);

	    	console.log(Ti.App.Properties.getString('username'));
	    	if(Ti.App.win_base.loginSelectView != undefined){
	    		// Ti.App.win_base.remove(Ti.App.win_base.loginSelectView);
	    		var animation = Ti.UI.createAnimation({
	    			delay:100,
	    			opacity:0,
	    			duration:300
	    		});
	    		Ti.App.win_base.loginSelectView.animate(animation);
	    		var cnt=0;
	    		Ti.App.win_base.loginView.animate(animation);
	    		animation.addEventListener('complete',function(){
	    			if(cnt == 0){
	    				animation = null;
	    			}
	    			if(cnt == 1){
	    				Ti.App.win_base.loginSelectView = null;
	    				Ti.App.win_base.loginView = null;
	    			}
	    			cnt++;
	    		});
	    	}
		    console.log('login');

		    // require('lib/vineAPI').vinePopularTimeLine();

		    // Ti.App.scrollview.views[0].add(require('UI/myTimeline').myTimeline());
		    //test
		    //require('UI/newLogin').newLogin();

		    // require('UI/signIn').signIn();
		    // require('UI/myProfile').myProfile();
		    // require('lib/vineAPI').myProfile();
		    // require('lib/vineAPI').vineGraphTimeLine();

		    //require('lib/vineAPI').userData();
		    //require('lib/vineAPI').vineLogin();

		    require('UI/myProfile').myProfile();
		    require('lib/vineAPI').myProfile();

		    require('lib/vineAPI').vineGraphTimeLine();
		    //require('lib/vineAPI').userData();
	    });
	}
})();
<commit_msg>connection post<commit_after>//将来的にxmlにパスワードとusernameを保存する
//他のwindowへのアクセス方法　Ti.App.scrollview.views[index]

(function(){
	Ti.App.disableNetworkActivityIndicator = true; //ネットワークインジゲータを消す
	///////////
	// var v = b.createView();
	// console.log(v);

	tab_group = Ti.UI.createTabGroup();

	//一番下のベースLayer
	Ti.App.win_base = Ti.UI.createWindow({
		// backgroundImage: 'image/background.jpg',
		backgroundColor:"#eeeeee",
		navBarHidden: true,
		tabBarHidden: true,
		fullscreen : false,
	});

	var tab = Ti.UI.createTab({ window: Ti.App.win_base });
	tab_group.addTab(tab);
	tab_group.open();

		// Ti.App.Properties.removeProperty('username');
	    // Ti.App.Properties.removeProperty('password');

	start();
	if(!Ti.App.Properties.hasProperty('username')){
		var signSelectView = require('UI/signSelect').signSelect();
		Ti.App.win_base.add(signSelectView);
		Ti.App.win_base.loginSelectView = signSelectView;
	}
	else{
		// Ti.App.Properties.removeProperty('username');
	    // Ti.App.Properties.removeProperty('password');
		// console.log(Ti.App.Properties.getString('username'));
		require('lib/vineAPI').vineLogin(Ti.App.Properties.getString('username'),Ti.App.Properties.getString('password'));
	}

	function start(){
		var dummyWindow = [];

	    //この個数は変動
	    for(var i=0;i<4;i++){
		    var w = Ti.UI.createWindow({
			    width:"100%",
			    height:Ti.UI.FILL,
			    backgroundColor:"#ddd",
		    });
		    dummyWindow.push(w);
	    }

	    //スクロールビューの挿入
	    Ti.App.scrollview = Ti.UI.createScrollableView({
		    // left:"10%",
		    top:"10%",
		    width:"100%",
		    height:"80%",
		    // left:"20%",
		    views:dummyWindow,
		    horizontalBounce:false,
		    cacheSize:6,
		    // showPagingControl: true,
            // pagingControlHeight: 30,
	    });

	    Ti.App.win_base.add(Ti.App.scrollview);

	    //Button の　追加
	    createImages = function(image,size){
		    var button = Ti.UI.createButton({
			    color : "#ffffff",
			    backgroundImage : image,
			    left:size,
			    width:20,
		        height:20,
		    });
		    return button;
	    };

	    var homeButton = createImages("images/uniF489_.png",17);
	    var listButton = createImages("images/list.png",17);
	    var cameraButton = createImages("images/videocamera.png",153);
	    var searchButton = createImages("images/search.png",285);

	    listButton.addEventListener('singletap',function(){
		    require('UI/leftList').list();
	    });

	    cameraButton.addEventListener('singletap',function(){
		    require('UI/post').postWindow();
	    });

	    //可視化用
	    var buttonBar = Ti.UI.createView({
		    width:"100%",
		    height:"10%",
		    bottom:0,
		    backgroundColor:"#00a478",
		    color:"#fff",
		    textAlign:'center'
	    });

	    //buttonBar.add(homeButton);
	    buttonBar.add(listButton);
	    buttonBar.add(cameraButton);
	    buttonBar.add(searchButton);

	    var homebuttonBar = Ti.UI.createView({
		    width:"20%",
		    height:"100%",
		    top:0,
		    left:0,
		    image:"images/home2.png",
		    bubbleParent:false
	    });

	    homebuttonBar.addEventListener('singletap',function(){
		    Ti.App.scrollview.scrollToView(0);
	    });

	    // homebuttonBar.add(homeButton);

	    //上部ラベル
	    var topLabel = Ti.UI.createLabel({//Label
		    width:"100%",
		    height:"10%",
		    top:0,
		    backgroundColor:"#00a478",
		    text:"TIMELINE",
		    font:{
			    fontWeight: "normal",
			    fontSize: 25,
			    fontFamily: 'AppleGothic'
		    },
		    color:"#fff",
		    textAlign:'center',
		    bubbleParent:false
	    });

	    topLabel.add(homebuttonBar);
	    homebuttonBar.add(homeButton);

	    homebuttonBar.addEventListener('singletap',function(e){

		    //Ti.UI.ScrollableView. scrollToView(dummyWindow = [0]);
	    });

	    topLabel.addEventListener('singletap',function(e){
	    });

	    ///////////////////////////////////////////////
	    //Labelとscrollableview
	    var topLabelNameArray = [];
	    topLabelNameArray[0]= "TIMELINE";
	    topLabelNameArray[1]= "ACTIVITY";
	    topLabelNameArray[2]= "EXPLOPE";
	    topLabelNameArray[3]= "PROFILE";

	    Ti.App.scrollview.addEventListener('scroll',function(e){
		    if(e.currentPage != undefined){
			    topLabel.text = topLabelNameArray[e.currentPage];
		    }
	    });

	    ///////////////////////////////////////////////

        //
	    Ti.App.win_base.add(buttonBar);
	    Ti.App.win_base.add(topLabel);
	    // require('lib/camera').camera();
	    //これに入ったら各処理させる

	    Ti.App.addEventListener('loginComplete',function(){
	    	Ti.App.Properties.removeProperty('username');
	    	Ti.App.Properties.removeProperty('password');
	    	Ti.App.Properties.setString('username',Ti.App.email);
	    	Ti.App.Properties.setString('password',Ti.App.password);
	    	console.log(Ti.App.email);

	    	console.log(Ti.App.Properties.getString('username'));
	    	if(Ti.App.win_base.loginSelectView != undefined){
	    		// Ti.App.win_base.remove(Ti.App.win_base.loginSelectView);
	    		var animation = Ti.UI.createAnimation({
	    			delay:100,
	    			opacity:0,
	    			duration:300
	    		});
	    		Ti.App.win_base.loginSelectView.animate(animation);
	    		var cnt=0;
	    		Ti.App.win_base.loginView.animate(animation);
	    		animation.addEventListener('complete',function(){
	    			if(cnt == 0){
	    				animation = null;
	    			}
	    			if(cnt == 1){
	    				Ti.App.win_base.loginSelectView = null;
	    				Ti.App.win_base.loginView = null;
	    			}
	    			cnt++;
	    		});
	    	}
		    console.log('login');

		    // require('lib/vineAPI').vinePopularTimeLine();

		    // Ti.App.scrollview.views[0].add(require('UI/myTimeline').myTimeline());
		    //test
		    //require('UI/newLogin').newLogin();

		    // require('UI/signIn').signIn();
		    // require('UI/myProfile').myProfile();
		    // require('lib/vineAPI').myProfile();
		    // require('lib/vineAPI').vineGraphTimeLine();

		    //require('lib/vineAPI').userData();
		    //require('lib/vineAPI').vineLogin();

		    require('UI/myProfile').myProfile();
		    require('lib/vineAPI').myProfile();

		    require('lib/vineAPI').vineGraphTimeLine();
		    //require('lib/vineAPI').userData();
	    });
	}
})();
<|endoftext|>


<commit_before>import React from 'react';

class Dom2React {

  constructor(tests) {
    this.tests = tests || [];
  }

  prepareChildren(childNodeList, level) {
    const children = Array.prototype.slice.call(childNodeList).map((node, index) =>
      this.prepareNode(node, level + 1, index)
    ).filter(Boolean);
    if (!children.length) return null;
    return children;
  }

  prepareAttributes(node, reactKey) {
    const attributes = {
      key: reactKey,
    };
    if (node.className) attributes.className = node.className;

    Array.prototype.slice.call(node.attributes).map((att) => {
      switch (att.name) {
        case 'class':
        case 'style':
          break;
        case 'checked':
        case 'selected':
        case 'disabled':
        case 'autoplay':
        case 'controls':
          attributes[att.name] = att.name;
          break;
        default:
          attributes[att.name] = att.value;
      }
      return null;
    });
    return attributes;
  }

  prepareNode(_node, level, index) {
    if (!_node) return null;
    let node = _node;
    const key = `${level}-${index}`;
    const result = [];

    this.tests.forEach((test) => {
      if (test.condition(node, key, level, this)) {
        if (typeof test.modify === 'function') {
          node = test.modify(node, key, level, this);
          if (!(node instanceof Node)) {
            node = _node;
            console.warn('The `modify`-method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `action`-method instead)');
          }
        }
        if (typeof test.action === 'function') {
          result.push(test.action(node, key, level, this));
        }
      }
    });

    if (result.length) return result;

    switch (node.nodeType) {
      case 1: // regular dom-node
        return React.createElement(
          node.nodeName,
          this.prepareAttributes(node, key),
          this.prepareChildren(node.childNodes, level)
        );

      case 3: // textnode
        if (!node.parentNode) return node.nodeValue.toString();
        switch (node.parentNode.nodeName.toLowerCase()) {
          case 'table':
          case 'thead':
          case 'tbody':
          case 'tfoot':
          case 'tr':
            return null;
          default:
            return node.nodeValue.toString();
        }

      case 8: // html-comment
        // console.info(node.nodeValue.toString());
        return null;

      default:
        // console.warn(`unhandled nodetype ${node.nodeType}`);
        return null;
    }
  }

}

export default Dom2React;
<commit_msg>Fix up some attribute errors: * Make the style attributes work by translating style strings to a style object. * Make a map of attributes that are not name the same in dom vs react, and always look up the correct attribute. * Trim the text nodes before inserting, as react may not allow whitespace as text nodes for certain kinds of nodes (like colspan in a table - very odd...).<commit_after>import React from 'react';

const hyphen2CamelCase = (str) =>  str.replace(/-([a-z])/gi,(s, group) =>  group.toUpperCase());
const style2object = (styleString) => styleString.split(';').filter(s => s.length).reduce((a, b) => {
  const keyValue = b.split(':');
  a[hyphen2CamelCase(keyValue[0])] = keyValue[1];
  return a;
}, {});

const poorlyNamedAttributes = {
  "tabindex" : "tabIndex",
  "accesskey" : "accessKey",
  "autocomplete" : "autoComplete",
  "text-anchor" : "textAnchor",
  "datetime" : "dateTime",
  "colspan" : "colSpan" ,
  "rowspan" : "rowSpan" ,
  "for" : "htmlFor",
};

class Dom2React {

  constructor(tests) {
    this.tests = tests || [];
  }

  prepareChildren(childNodeList, level) {
    const children = Array.prototype.slice.call(childNodeList).map((node, index) =>
      this.prepareNode(node, level + 1, index)
    ).filter(Boolean);
    if (!children.length) return null;
    return children;
  }

  prepareAttributes(node, reactKey) {
    const attributes = {
      key: reactKey,
    };
    if (node.attributes["class"]) attributes.className = node.attributes["class"].value;
    //since styles must be an object, we have to parse and generate it for react (rather than disgard it)
    if (node.attributes["style"] && node.attributes["style"].value) attributes.style = style2object(node.attributes["style"].value);

    Array.prototype.slice.call(node.attributes).map((att) => {
      switch (att.name) {
        //these are manually handled above, so break;
        case 'class':
        case 'style':
          break;
        case 'checked':
        case 'selected':
        case 'disabled':
        case 'autoplay':
        case 'controls':
          attributes[att.name] = att.name;
          break;
        default:
        if (poorlyNamedAttributes[att.name]) {
          attributes[poorlyNamedAttributes[att.name]] = att.value;
        } else {
          attributes[att.name] = att.value;
        }

      }
      return null;
    });
    return attributes;
  }

  prepareNode(_node, level, index) {
    if (!_node) return null;
    let node = _node;
    const key = `${level}-${index}`;
    const result = [];

    this.tests.forEach((test) => {
      if (test.condition(node, key, level, this)) {
        if (typeof test.modify === 'function') {
          node = test.modify(node, key, level, this);
          if (!(node instanceof Node)) {
            node = _node;
            console.warn('The `modify`-method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `action`-method instead)');
          }
        }
        if (typeof test.action === 'function') {
          result.push(test.action(node, key, level, this));
        }
      }
    });

    if (result.length) return result;

    switch (node.nodeType) {
      case 1: // regular dom-node
        return React.createElement(
          node.nodeName.toLowerCase(),
          this.prepareAttributes(node, key),
          this.prepareChildren(node.childNodes, level)
        );

      case 3: // textnode
        if (!node.parentNode) return node.nodeValue.toString();
        switch (node.parentNode.nodeName.toLowerCase()) {
          case 'table':
          case 'thead':
          case 'tbody':
          case 'tfoot':
          case 'tr':
            return null;
          default:
            return node.nodeValue.trim().toString();
        }

      case 8: // html-comment
        // console.info(node.nodeValue.toString());
        return null;

      default:
        // console.warn(`unhandled nodetype ${node.nodeType}`);
        return null;
    }
  }

}

export default Dom2React;
<|endoftext|>


<commit_before>  /*-------------------------- HTML ELEMENT: CREATE --------------------------*/

  (function() {

    var ELEMENT_INNER_HTML_IGNORES_SCRIPTS =
      envTest('ELEMENT_INNER_HTML_IGNORES_SCRIPTS'),

    ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY =
      envTest('ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY'),

    CONTEXT_TYPES = (function() {
      var T = { };
      T[ELEMENT_NODE] =
      T[DOCUMENT_NODE] = 1;
      return T;
    })(),

    FROM_STRING_PARENT_WRAPPERS = (function() {
      var T = {
        'COLGROUP': ['
<colgroup>',      '<\/colgroup>
<\/tbody><\/table>', 2],
        'FIELDSET': ['<form><fieldset>',       '<\/fieldset><\/form>',                  2],
        'LEGEND':   ['<form>',                 '<\/form>',                              1],
        'MAP':      ['<map>',                  '<\/map>',                               1],
        'SELECT':   ['<form><select>',         '<\/select><\/form>',                    2],
        'TABLE':    ['
',                '<\/table>',                             1],
        'TBODY':    ['

',         '<\/tbody><\/table>',                    2],
        'TR':       ['

',     '<\/tr><\/tbody><\/table>',              3],
        'TD':       ['

', '<\/td><\/tr><\/tbody><\/table>',        4]
      };

      // TODO: Opera fails to render optgroups when set with innerHTML
      T.TH = T.TD;
      T.OPTGROUP = T.SELECT;
      T.TFOOT = T.THEAD = T.TBODY;
      return T;
    })(),

    FROM_STRING_CHILDREN_PARENTS = (function() {
      var T = {
        'AREA':     'MAP',
        'COL':      'COLGROUP',
        'FIELDSET': 'FORM',
        'LEGEND':   'FIELDSET',
        'OPTION':   'SELECT',
        'TD':       'TR',
        'TR':       'TBODY',
        'TBODY':    'TABLE'
      };

      T.TH = T.TD;
      T.OPTGROUP = T.OPTION;
      T.TFOOT = T.THEAD = T.TBODY;
      T.CAPTION = T.COLGROUP = T.TBODY;
      return T;
    })(),

    doc              = window.fuse._doc,
    reSimpleTag      = /^<([A-Za-z0-9]+)\/?>$/,
    reTagStart       = /^\s*</,
    reTBody          = /<tbody /i,
    reExtractTagName = /^<([^> ]+)/,
    reStartsWithTR   = /^<tr/i,

    HTMLElement = function HTMLElement(tagName, context) {
      var attrs, element, options, result;
      if (!tagName || tagName.raw) {
        return tagName;
      }
      if (tagName.nodeType) {
        result = fromElement(tagName, context);
      } else {
        result = (tagName.charAt(0) == '<' ? fromHTML : fromTagName)(tagName, context);
      }
      options = !CONTEXT_TYPES[context && context.nodeType] && context;
      return (attrs = options && options.attrs)
        ? Element.plugin.setAttribute.call(result, attrs)
        : result;
    };

    function Decorator(element) {
      this.raw = element;
      this.style = element.style;
      this.nodeType = ELEMENT_NODE;
      this.childNodes = element.childNodes;
      this.tagName = this.nodeName = element.nodeName;
      this.initialize && this.initialize();
    }

    function Element(tagName, context) {
      // pass to HTMLElement until we have a non-html element solution
      return HTMLElement(tagName, context);
    }

    function extendByTag(tagName, plugins, mixins, statics) {
      var i = -1;
      if (isArray(tagName)) {
        while (tagName[++i]) {
          extendByTag(tagName[i], plugins, mixins, statics);
        }
      } else {
        getOrCreateTagClass(tagName).extend(plugins, mixins, statics);
      }
    }

    function from(element, context) {
      return window.fuse(element, context);
    }

    function fromElement(element, options) {
      var data, isCached, isDecorated, raw, result = element;
      if (options && !CONTEXT_TYPES[options.nodeType]) {
        isCached = options.cache;
        isDecorated = options.decorate;
      }
      isDecorated = isDecorated == null || isDecorated;
      if (raw = element.raw) {
        result = isDecorated ? element : raw;
      }
      else if (isDecorated) {
        Decorator.prototype = getOrCreateTagClass(element.tagName).plugin;
        if (isCached == null || isCached) {
          data = domData[getFuseId(element)];
          result = data.decorator || (data.decorator = new Decorator(element));
        } else {
          result = new Decorator(element);
        }
      }
      return result;
    }

    function fromHTML(html, context) {
      // support `<div>` format
      var element, fragment, isCached, isDecorated, length, match, result;
      if (match = html.match(reSimpleTag)) {
        return fromTagName(match[1], context);
      }
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }

      isCached    = isCached == null || isCached;
      isDecorated = isDecorated == null || isDecorated;
      fragment    = getFragmentFromHTML(html, context);

      // multiple elements return a NodeList
      if (fragment.nodeType == DOCUMENT_FRAGMENT_NODE) {
        result = NodeList();
        length = fragment.childNodes.length;
        if (isDecorated) {
          while (length--) {
            element = fragment.removeChild(fragment.lastChild);
            Decorator.prototype = getOrCreateTagClass(element.nodeName).plugin;
            if (isCached) {
              result[length] = domData[getFuseId(element)].decorator = new Decorator(element);
            } else {
              result[length] = new Decorator(element);
            }
          }
        } else {
          while (length--) {
            result[length] = fragment.removeChild(fragment.lastChild);
          }
        }
      }
      // single element return decorated element
      else {
        result = fragment.parentNode.removeChild(fragment);
        if (isDecorated) {
          element = result;
          Decorator.prototype = getOrCreateTagClass(element.nodeName).plugin;
          result = new Decorator(element);

          if (isCached) {
            domData[getFuseId(element)].decorator = result;
          }
        }
      }
      return result;
    }

    function fromId(id, context) {
      var element, isCached, isDecorated;
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }
      element = (context || doc).getElementById(id || uid);
      return isDecorated == null || isDecorated
        ? element && fromElement(element, isCached)
        : element;
    }

    function fromTagName(tagName, context) {
      // support simple tagNames
      var attrs, element, isCached, isDecorated, nodes, result;
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }

      // for a tidy cache stick to all upper or all lower case tagNames
      context || (context = doc);

      nodes = context === doc ? domData['1'].nodes :
        domData[getFuseId(getDocument(context))].nodes;

      result = (nodes[tagName] ||
        (nodes[tagName] = context.createElement(tagName))).cloneNode(false);

      if (isDecorated == null || isDecorated) {
        element = result;
        Decorator.prototype = getOrCreateTagClass(tagName).plugin;
        result = new Decorator(element);
        if (isCached == null || isCached) {
          domData[getFuseId(element)].decorator = result;
        }
      }
      return result;
    }

    function getFragmentFromHTML(html, context) {
      context || (context = doc);
      var match, node, nodeName, tbody, times, wrapping,
       ownerDoc = context.ownerDocument || context,
       data = domData[ownerDoc == doc ? '1': getFuseId(ownerDoc)],
       cache = data.fragments || (data.fragments = {
         'node': ownerDoc.createElement('div'),
         'fragment': ownerDoc.createDocumentFragment()
       });

      if (html == '') {
        return cache.fragment;
      }
      if (context.nodeType == DOCUMENT_NODE && (match = html.match(reExtractTagName))) {
        nodeName = FROM_STRING_CHILDREN_PARENTS[match[1].toUpperCase()];
      }
      if (!nodeName) {
        nodeName = getNodeName(context);
      }
      // skip auto-inserted tbody
      if (nodeName == 'TABLE' && ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY &&
          reStartsWithTR.test(html)) {
        nodeName = 'TBODY';
      }

      node = cache.node;
      wrapping = FROM_STRING_PARENT_WRAPPERS[nodeName];

      // Fix IE rendering issue with innerHTML and script
      // and link elements by prefixing the html with text
      if (!wrapping && ELEMENT_INNER_HTML_IGNORES_SCRIPTS && reTagStart.test(html)) {
        node.innerHTML = 'x' + html;
        node.removeChild(node.firstChild);
      }
      else if (wrapping) {
        times = wrapping[2];
        node.innerHTML= wrapping[0] + html + wrapping[1];
        while (times--) node = node.firstChild;
      }
      else {
        node.innerHTML = html;
      }

      // exit early for single elements
      if (node.childNodes.length == 1) {
        return node.firstChild;
      }
      // remove auto-inserted tbody
      if (nodeName == 'TABLE' && ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY &&
          !reTBody.test(html) && (tbody = node.getElementsByTagName('tbody')[0])) {
        tbody.parentNode.removeChild(tbody);
      }
      return getFragmentFromChildNodes(node, cache);
    }

    function getFragmentFromChildNodes(parentNode, cache) {
      var fragment = cache.fragment,
       nodes = parentNode.childNodes, length = nodes.length;
      while (length--) {
        fragment.insertBefore(nodes[length], fragment.firstChild);
      }
      return fragment;
    }

    function fuse(object, context) {
      var isCached, isDecorated;
      if (isString(object)) {
        return object.charAt(0) == '<'
          ? HTMLElement(object, context)
          : fromId(object, context);
      }
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
      }
      return isDecorated == null || isDecorated
        ? Node(Window(object, isCached), isCached)
        : object;
    }

    // IE7 and below need to use the sTag of createElement to set the `name` attribute
    // http://msdn.microsoft.com/en-us/library/ms536389.aspx
    //
    // IE fails to set the BUTTON element's `type` attribute without using the sTag
    // http://dev.rubyonrails.org/ticket/10548
    if (envTest('NAME_ATTRIBUTE_IS_READONLY')) {
      var __HTMLElement = HTMLElement;
      HTMLElement = function HTMLElement(tagName, context) {
        var attrs, match, name, type;
        if (isString(tagName) && context &&
            !CONTEXT_TYPES[context.nodeType] && (attrs = context.attrs) &&
            ('name' in attrs || 'type' in attrs) &&
            (tagName.charAt(0) != '<' || (match = tagName.match(reSimpleTag)))) {

          name = attrs.name;
          type = attrs.type;
          tagName = match && match[1] || tagName;

          tagName = '<' + tagName +
            (name == null ? '' : ' name="' + name + '"') +
            (type == null ? '' : ' type="' + type + '"') + '>';

          delete attrs.name; delete attrs.type;
          return plugin.setAttribute.call(fromHTML(tagName, context), attrs);
        }
        return __HTMLElement(tagName, context);
      };
    }

    if (envTest('ELEMENT_REMOVE_NODE')) {
      getFragmentFromChildNodes = function(parentNode, cache) {
        var fragment = cache.fragment;
        fragment.appendChild(parentNode).removeNode();
        return fragment;
      };
    }

    // copy old fuse properties to new window.fuse
    eachKey(window.fuse, function(value, key) {
      if (hasKey(window.fuse, key)) fuse[key] = value;
    });

    // add class sugar
    fuse.Class({ 'constructor': fuse });
    fuse.Class(Node, { 'constructor': Element });
    fuse.Class(Element, { 'constructor': HTMLElement });

    // expose
    Element.extendByTag =
    HTMLElement.extendByTag = extendByTag;

    Element.from =
    HTMLElement.from = from;

    Element.fromElement =
    HTMLElement.fromElement = fromElement;

    Element.fromId =
    HTMLElement.fromId = fromId;

    Element.fromTagName =
    HTMLElement.fromTagName = fromTagName;

    Element.fromHTML =
    HTMLElement.fromHTML = fromHTML;

    Element.updateGenerics =
    HTMLElement.updateGenerics = Node.updateGenerics;

    window.fuse = fuse;
    fuse.dom.Element = Element;
    fuse.dom.HTMLElement = HTMLElement;
    fuse.dom.getFragmentFromHTML = getFragmentFromHTML;
  })();

  /*--------------------------------------------------------------------------*/

  // define private vars shared by primary closure

  Element = fuse.dom.Element;

  HTMLElement = fuse.dom.HTMLElement;

  extendByTag = Element.extendByTag;

  fromElement = Element.fromElement;

  getFragmentFromHTML = fuse.dom.getFragmentFromHTML;

  getOrCreateTagClass = (function() {

    var TAG_NAME_CLASSES = (function() {
      var i, T = { }, temp = {
        'A':        'Anchor',
        'CAPTION':  'TableCaption',
        'COL':      'TableCol',
        'DEL':      'Mod',
        'DIR':      'Directory',
        'DL':       'DList',
        'H1':       'Heading',
        'IFRAME':   'IFrame',
        'IMG':      'Image',
        'INS':      'Mod',
        'FIELDSET': 'FieldSet',
        'FRAMESET': 'FrameSet',
        'OL':       'OList',
        'OPTGROUP': 'OptGroup',
        'P':        'Paragraph',
        'Q':        'Quote',
        'TBODY':    'TableSection',
        'TD':       'TableCell',
        'TEXTAREA': 'TextArea',
        'TR':       'TableRow',
        'UL':       'UList'
      };

      temp.TH = temp.TD;
      temp.COLGROUP = temp.COL;
      temp.TFOOT = temp.THEAD =  temp.TBODY;
      temp.H2 = temp.H3 = temp.H4 = temp.H5 = temp.H6 = temp.H1;

      for (i in temp) {
       T[i] = T[i.toLowerCase()] = 'HTML' + temp[i] + 'Element';
      }
      return T;
    })(),

    reTagName = /^[A-Z0-9]+$/;

    return function(tagName) {
      var upperCased, TagClass,
       tagClassName = TAG_NAME_CLASSES[tagName];

      if (!tagClassName) {
        if (tagClassName = TAG_NAME_CLASSES[upperCased = tagName.toUpperCase()]) {
          TAG_NAME_CLASSES[tagName] = tagClassName;
        } else {
          tagClassName =
          TAG_NAME_CLASSES[tagName] =
          TAG_NAME_CLASSES[upperCased] = 'HTML' +
            (reTagName.test(upperCased)
              ? capitalize(tagName.toLowerCase())
              : 'Unknown') + 'Element';
        }
      }
      if (!(TagClass = fuse.dom[tagClassName])) {
        TagClass =
        fuse.dom[tagClassName] = fuse.Class(HTMLElement, {
          'constructor': Function('fn',
            'function ' + tagClassName + '(element,options){' +
            'return element&&(element.raw?element:fn(element,options))' +
            '}return ' + tagClassName)(fromElement)
        });

        TagClass.addMixins = Node.addMixins;
        TagClass.addPlugins = Node.addPlugins;
        TagClass.updateGenerics = Node.updateGenerics;
      }
      return TagClass;
    };
  })();

  extendByTag('button');
  extendByTag('form');
  extendByTag('input');
  extendByTag('option');
  extendByTag('select');
  extendByTag('textarea');

  HTMLFormElement = fuse.dom.HTMLFormElement;

  CONTROL_PLUGINS = {
    'BUTTON':   (HTMLButtonElement   = fuse.dom.HTMLButtonElement).plugin,
    'INPUT':    (HTMLInputElement    = fuse.dom.HTMLInputElement).plugin,
    'OPTION':   (HTMLOptionElement   = fuse.dom.HTMLOptionElement).plugin,
    'SELECT':   (HTMLSelectElement   = fuse.dom.HTMLSelectElement).plugin,
    'TEXTAREA': (HTMLTextAreaElement = fuse.dom.HTMLTextAreaElement).plugin
  };
<commit_msg>fusejs: Fixed setAttribute call when creating an HTMLElement from HTML. [Joe Gornick]<commit_after>  /*-------------------------- HTML ELEMENT: CREATE --------------------------*/

  (function() {

    var ELEMENT_INNER_HTML_IGNORES_SCRIPTS =
      envTest('ELEMENT_INNER_HTML_IGNORES_SCRIPTS'),

    ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY =
      envTest('ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY'),

    CONTEXT_TYPES = (function() {
      var T = { };
      T[ELEMENT_NODE] =
      T[DOCUMENT_NODE] = 1;
      return T;
    })(),

    FROM_STRING_PARENT_WRAPPERS = (function() {
      var T = {
        'COLGROUP': ['
<colgroup>',      '<\/colgroup>
<\/tbody><\/table>', 2],
        'FIELDSET': ['<form><fieldset>',       '<\/fieldset><\/form>',                  2],
        'LEGEND':   ['<form>',                 '<\/form>',                              1],
        'MAP':      ['<map>',                  '<\/map>',                               1],
        'SELECT':   ['<form><select>',         '<\/select><\/form>',                    2],
        'TABLE':    ['
',                '<\/table>',                             1],
        'TBODY':    ['

',         '<\/tbody><\/table>',                    2],
        'TR':       ['

',     '<\/tr><\/tbody><\/table>',              3],
        'TD':       ['

', '<\/td><\/tr><\/tbody><\/table>',        4]
      };

      // TODO: Opera fails to render optgroups when set with innerHTML
      T.TH = T.TD;
      T.OPTGROUP = T.SELECT;
      T.TFOOT = T.THEAD = T.TBODY;
      return T;
    })(),

    FROM_STRING_CHILDREN_PARENTS = (function() {
      var T = {
        'AREA':     'MAP',
        'COL':      'COLGROUP',
        'FIELDSET': 'FORM',
        'LEGEND':   'FIELDSET',
        'OPTION':   'SELECT',
        'TD':       'TR',
        'TR':       'TBODY',
        'TBODY':    'TABLE'
      };

      T.TH = T.TD;
      T.OPTGROUP = T.OPTION;
      T.TFOOT = T.THEAD = T.TBODY;
      T.CAPTION = T.COLGROUP = T.TBODY;
      return T;
    })(),

    doc              = window.fuse._doc,
    reSimpleTag      = /^<([A-Za-z0-9]+)\/?>$/,
    reTagStart       = /^\s*</,
    reTBody          = /<tbody /i,
    reExtractTagName = /^<([^> ]+)/,
    reStartsWithTR   = /^<tr/i,

    HTMLElement = function HTMLElement(tagName, context) {
      var attrs, element, options, result;
      if (!tagName || tagName.raw) {
        return tagName;
      }
      if (tagName.nodeType) {
        result = fromElement(tagName, context);
      } else {
        result = (tagName.charAt(0) == '<' ? fromHTML : fromTagName)(tagName, context);
      }
      options = !CONTEXT_TYPES[context && context.nodeType] && context;
      return (attrs = options && options.attrs)
        ? Element.plugin.setAttribute.call(result, attrs)
        : result;
    };

    function Decorator(element) {
      this.raw = element;
      this.style = element.style;
      this.nodeType = ELEMENT_NODE;
      this.childNodes = element.childNodes;
      this.tagName = this.nodeName = element.nodeName;
      this.initialize && this.initialize();
    }

    function Element(tagName, context) {
      // pass to HTMLElement until we have a non-html element solution
      return HTMLElement(tagName, context);
    }

    function extendByTag(tagName, plugins, mixins, statics) {
      var i = -1;
      if (isArray(tagName)) {
        while (tagName[++i]) {
          extendByTag(tagName[i], plugins, mixins, statics);
        }
      } else {
        getOrCreateTagClass(tagName).extend(plugins, mixins, statics);
      }
    }

    function from(element, context) {
      return window.fuse(element, context);
    }

    function fromElement(element, options) {
      var data, isCached, isDecorated, raw, result = element;
      if (options && !CONTEXT_TYPES[options.nodeType]) {
        isCached = options.cache;
        isDecorated = options.decorate;
      }
      isDecorated = isDecorated == null || isDecorated;
      if (raw = element.raw) {
        result = isDecorated ? element : raw;
      }
      else if (isDecorated) {
        Decorator.prototype = getOrCreateTagClass(element.tagName).plugin;
        if (isCached == null || isCached) {
          data = domData[getFuseId(element)];
          result = data.decorator || (data.decorator = new Decorator(element));
        } else {
          result = new Decorator(element);
        }
      }
      return result;
    }

    function fromHTML(html, context) {
      // support `<div>` format
      var element, fragment, isCached, isDecorated, length, match, result;
      if (match = html.match(reSimpleTag)) {
        return fromTagName(match[1], context);
      }
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }

      isCached    = isCached == null || isCached;
      isDecorated = isDecorated == null || isDecorated;
      fragment    = getFragmentFromHTML(html, context);

      // multiple elements return a NodeList
      if (fragment.nodeType == DOCUMENT_FRAGMENT_NODE) {
        result = NodeList();
        length = fragment.childNodes.length;
        if (isDecorated) {
          while (length--) {
            element = fragment.removeChild(fragment.lastChild);
            Decorator.prototype = getOrCreateTagClass(element.nodeName).plugin;
            if (isCached) {
              result[length] = domData[getFuseId(element)].decorator = new Decorator(element);
            } else {
              result[length] = new Decorator(element);
            }
          }
        } else {
          while (length--) {
            result[length] = fragment.removeChild(fragment.lastChild);
          }
        }
      }
      // single element return decorated element
      else {
        result = fragment.parentNode.removeChild(fragment);
        if (isDecorated) {
          element = result;
          Decorator.prototype = getOrCreateTagClass(element.nodeName).plugin;
          result = new Decorator(element);

          if (isCached) {
            domData[getFuseId(element)].decorator = result;
          }
        }
      }
      return result;
    }

    function fromId(id, context) {
      var element, isCached, isDecorated;
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }
      element = (context || doc).getElementById(id || uid);
      return isDecorated == null || isDecorated
        ? element && fromElement(element, isCached)
        : element;
    }

    function fromTagName(tagName, context) {
      // support simple tagNames
      var attrs, element, isCached, isDecorated, nodes, result;
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
        context     = context.context;
      }

      // for a tidy cache stick to all upper or all lower case tagNames
      context || (context = doc);

      nodes = context === doc ? domData['1'].nodes :
        domData[getFuseId(getDocument(context))].nodes;

      result = (nodes[tagName] ||
        (nodes[tagName] = context.createElement(tagName))).cloneNode(false);

      if (isDecorated == null || isDecorated) {
        element = result;
        Decorator.prototype = getOrCreateTagClass(tagName).plugin;
        result = new Decorator(element);
        if (isCached == null || isCached) {
          domData[getFuseId(element)].decorator = result;
        }
      }
      return result;
    }

    function getFragmentFromHTML(html, context) {
      context || (context = doc);
      var match, node, nodeName, tbody, times, wrapping,
       ownerDoc = context.ownerDocument || context,
       data = domData[ownerDoc == doc ? '1': getFuseId(ownerDoc)],
       cache = data.fragments || (data.fragments = {
         'node': ownerDoc.createElement('div'),
         'fragment': ownerDoc.createDocumentFragment()
       });

      if (html == '') {
        return cache.fragment;
      }
      if (context.nodeType == DOCUMENT_NODE && (match = html.match(reExtractTagName))) {
        nodeName = FROM_STRING_CHILDREN_PARENTS[match[1].toUpperCase()];
      }
      if (!nodeName) {
        nodeName = getNodeName(context);
      }
      // skip auto-inserted tbody
      if (nodeName == 'TABLE' && ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY &&
          reStartsWithTR.test(html)) {
        nodeName = 'TBODY';
      }

      node = cache.node;
      wrapping = FROM_STRING_PARENT_WRAPPERS[nodeName];

      // Fix IE rendering issue with innerHTML and script
      // and link elements by prefixing the html with text
      if (!wrapping && ELEMENT_INNER_HTML_IGNORES_SCRIPTS && reTagStart.test(html)) {
        node.innerHTML = 'x' + html;
        node.removeChild(node.firstChild);
      }
      else if (wrapping) {
        times = wrapping[2];
        node.innerHTML= wrapping[0] + html + wrapping[1];
        while (times--) node = node.firstChild;
      }
      else {
        node.innerHTML = html;
      }

      // exit early for single elements
      if (node.childNodes.length == 1) {
        return node.firstChild;
      }
      // remove auto-inserted tbody
      if (nodeName == 'TABLE' && ELEMENT_TABLE_INNER_HTML_INSERTS_TBODY &&
          !reTBody.test(html) && (tbody = node.getElementsByTagName('tbody')[0])) {
        tbody.parentNode.removeChild(tbody);
      }
      return getFragmentFromChildNodes(node, cache);
    }

    function getFragmentFromChildNodes(parentNode, cache) {
      var fragment = cache.fragment,
       nodes = parentNode.childNodes, length = nodes.length;
      while (length--) {
        fragment.insertBefore(nodes[length], fragment.firstChild);
      }
      return fragment;
    }

    function fuse(object, context) {
      var isCached, isDecorated;
      if (isString(object)) {
        return object.charAt(0) == '<'
          ? HTMLElement(object, context)
          : fromId(object, context);
      }
      if (context && !CONTEXT_TYPES[context.nodeType]) {
        isCached    = context.cache;
        isDecorated = context.decorate;
      }
      return isDecorated == null || isDecorated
        ? Node(Window(object, isCached), isCached)
        : object;
    }

    // IE7 and below need to use the sTag of createElement to set the `name` attribute
    // http://msdn.microsoft.com/en-us/library/ms536389.aspx
    //
    // IE fails to set the BUTTON element's `type` attribute without using the sTag
    // http://dev.rubyonrails.org/ticket/10548
    if (envTest('NAME_ATTRIBUTE_IS_READONLY')) {
      var __HTMLElement = HTMLElement;
      HTMLElement = function HTMLElement(tagName, context) {
        var attrs, match, name, type;
        if (isString(tagName) && context &&
            !CONTEXT_TYPES[context.nodeType] && (attrs = context.attrs) &&
            ('name' in attrs || 'type' in attrs) &&
            (tagName.charAt(0) != '<' || (match = tagName.match(reSimpleTag)))) {

          name = attrs.name;
          type = attrs.type;
          tagName = match && match[1] || tagName;

          tagName = '<' + tagName +
            (name == null ? '' : ' name="' + name + '"') +
            (type == null ? '' : ' type="' + type + '"') + '>';

          delete attrs.name; delete attrs.type;
          return fuse.dom.Element.plugin.setAttribute.call(fromHTML(tagName, context), attrs);
        }
        return __HTMLElement(tagName, context);
      };
    }

    if (envTest('ELEMENT_REMOVE_NODE')) {
      getFragmentFromChildNodes = function(parentNode, cache) {
        var fragment = cache.fragment;
        fragment.appendChild(parentNode).removeNode();
        return fragment;
      };
    }

    // copy old fuse properties to new window.fuse
    eachKey(window.fuse, function(value, key) {
      if (hasKey(window.fuse, key)) fuse[key] = value;
    });

    // add class sugar
    fuse.Class({ 'constructor': fuse });
    fuse.Class(Node, { 'constructor': Element });
    fuse.Class(Element, { 'constructor': HTMLElement });

    // expose
    Element.extendByTag =
    HTMLElement.extendByTag = extendByTag;

    Element.from =
    HTMLElement.from = from;

    Element.fromElement =
    HTMLElement.fromElement = fromElement;

    Element.fromId =
    HTMLElement.fromId = fromId;

    Element.fromTagName =
    HTMLElement.fromTagName = fromTagName;

    Element.fromHTML =
    HTMLElement.fromHTML = fromHTML;

    Element.updateGenerics =
    HTMLElement.updateGenerics = Node.updateGenerics;

    window.fuse = fuse;
    fuse.dom.Element = Element;
    fuse.dom.HTMLElement = HTMLElement;
    fuse.dom.getFragmentFromHTML = getFragmentFromHTML;
  })();

  /*--------------------------------------------------------------------------*/

  // define private vars shared by primary closure

  Element = fuse.dom.Element;

  HTMLElement = fuse.dom.HTMLElement;

  extendByTag = Element.extendByTag;

  fromElement = Element.fromElement;

  getFragmentFromHTML = fuse.dom.getFragmentFromHTML;

  getOrCreateTagClass = (function() {

    var TAG_NAME_CLASSES = (function() {
      var i, T = { }, temp = {
        'A':        'Anchor',
        'CAPTION':  'TableCaption',
        'COL':      'TableCol',
        'DEL':      'Mod',
        'DIR':      'Directory',
        'DL':       'DList',
        'H1':       'Heading',
        'IFRAME':   'IFrame',
        'IMG':      'Image',
        'INS':      'Mod',
        'FIELDSET': 'FieldSet',
        'FRAMESET': 'FrameSet',
        'OL':       'OList',
        'OPTGROUP': 'OptGroup',
        'P':        'Paragraph',
        'Q':        'Quote',
        'TBODY':    'TableSection',
        'TD':       'TableCell',
        'TEXTAREA': 'TextArea',
        'TR':       'TableRow',
        'UL':       'UList'
      };

      temp.TH = temp.TD;
      temp.COLGROUP = temp.COL;
      temp.TFOOT = temp.THEAD =  temp.TBODY;
      temp.H2 = temp.H3 = temp.H4 = temp.H5 = temp.H6 = temp.H1;

      for (i in temp) {
       T[i] = T[i.toLowerCase()] = 'HTML' + temp[i] + 'Element';
      }
      return T;
    })(),

    reTagName = /^[A-Z0-9]+$/;

    return function(tagName) {
      var upperCased, TagClass,
       tagClassName = TAG_NAME_CLASSES[tagName];

      if (!tagClassName) {
        if (tagClassName = TAG_NAME_CLASSES[upperCased = tagName.toUpperCase()]) {
          TAG_NAME_CLASSES[tagName] = tagClassName;
        } else {
          tagClassName =
          TAG_NAME_CLASSES[tagName] =
          TAG_NAME_CLASSES[upperCased] = 'HTML' +
            (reTagName.test(upperCased)
              ? capitalize(tagName.toLowerCase())
              : 'Unknown') + 'Element';
        }
      }
      if (!(TagClass = fuse.dom[tagClassName])) {
        TagClass =
        fuse.dom[tagClassName] = fuse.Class(HTMLElement, {
          'constructor': Function('fn',
            'function ' + tagClassName + '(element,options){' +
            'return element&&(element.raw?element:fn(element,options))' +
            '}return ' + tagClassName)(fromElement)
        });

        TagClass.addMixins = Node.addMixins;
        TagClass.addPlugins = Node.addPlugins;
        TagClass.updateGenerics = Node.updateGenerics;
      }
      return TagClass;
    };
  })();

  extendByTag('button');
  extendByTag('form');
  extendByTag('input');
  extendByTag('option');
  extendByTag('select');
  extendByTag('textarea');

  HTMLFormElement = fuse.dom.HTMLFormElement;

  CONTROL_PLUGINS = {
    'BUTTON':   (HTMLButtonElement   = fuse.dom.HTMLButtonElement).plugin,
    'INPUT':    (HTMLInputElement    = fuse.dom.HTMLInputElement).plugin,
    'OPTION':   (HTMLOptionElement   = fuse.dom.HTMLOptionElement).plugin,
    'SELECT':   (HTMLSelectElement   = fuse.dom.HTMLSelectElement).plugin,
    'TEXTAREA': (HTMLTextAreaElement = fuse.dom.HTMLTextAreaElement).plugin
  };
<|endoftext|>