<commit_before>'use strict';

const OPTIONS_PAGE = 'html/options.html';

/**
 * @exports newtaboverride
 */
const newtaboverride = {
  /**
   * Fired when the extension is first installed, when the extension is updated to a new version or when the browser
   * is updated to a new version. We want to show a badge on our toolbar icon when the extension is first installed
   * or if an older version is detected.
   *
   * @param {runtime.OnInstalledReason} details - details.reason contains the reason why this event is being dispatched
   *
   * @returns {void}
   */
  onInstalledHandler (details) {
    if (details.reason === 'install' || details.reason === 'update') {
      browser.browserAction.setBadgeText({ text : '★' });
    }

    if (details.reason === 'update') {
      browser.storage.local.set({ show_compat_notice : true });
    }
  },

  /**
   * Fired whenever the user changes the input, after the user has started interacting with the add-on by entering
   * its keyword in the address bar and then pressing the space key.
   *
   * @param {string} input - user input in the address bar, not including the add-on's keyword itself or the space
   *                 after the keyword

   *                 Supported value: settings
   * @param {function} suggest - a callback function that the event listener can call to supply suggestions for the
   *                   address bar's drop-down list
   *
   * @returns {void}
   */
  showOmniboxSuggestions (input, suggest) {
    const availableCommands = ['settings'];
    const suggestions = [];

    for (const command of availableCommands) {
      if (command.indexOf(input) !== -1) {
        suggestions.push({
          content : command,
          description : browser.i18n.getMessage('omnibox_command_' + command)
        });
      }

      if (suggestions.length === 0) {
        suggestions.push({
          content : 'settings',
          description : browser.i18n.getMessage('omnibox_command_settings')
        });
      }
    }

    suggest(suggestions);
  },

  /**
   * Fired when the user has selected one of the suggestions the add-on has added to the address bar's drop-down list.
   *
   * @param {string} input - this is the value that the user selected
   *
   * @returns {void}
   */
  callOmniboxAction (input) {
    switch (input) {
      case 'settings':
      default:
        newtaboverride.openUserInterfaceInCurrentTab();
    }
  },

  /**
   * Fired when the toolbar icon is clicked. This method is used to open the user interface in a new tab or to switch
   * to the tab with the user interface if the user interface is already opened.
   *
   * @returns {void}
   */
  openUserInterface () {
    const url = browser.extension.getURL(OPTIONS_PAGE);

    browser.browserAction.setBadgeText({ text : '' });
    browser.tabs.query({}, (tabs) => {
      let tabId = null;

      for (const tab of tabs) {
        if (tab.url === url) {
          tabId = tab.id;
          break;
        }
      }

      if (tabId) {
        browser.tabs.update(tabId, { active : true });
      }
      else {
        browser.tabs.create({ url });
      }
    });
  },

  /**
   * This method is used to open the user interface in the current tab. It's used for the omnibox suggestions.
   *
   * @returns {void}
   */
  openUserInterfaceInCurrentTab () {
    browser.tabs.update(null, { url : browser.extension.getURL(OPTIONS_PAGE) });
  }
};

browser.browserAction.onClicked.addListener(newtaboverride.openUserInterface);
browser.omnibox.onInputChanged.addListener(newtaboverride.showOmniboxSuggestions);
browser.omnibox.onInputEntered.addListener(newtaboverride.callOmniboxAction);
browser.omnibox.setDefaultSuggestion({ description : browser.i18n.getMessage('omnibox_default_description') });
browser.runtime.onInstalled.addListener(newtaboverride.onInstalledHandler);
<commit_msg>show compat notice and update badge only after update from previous version than 7<commit_after>'use strict';

const OPTIONS_PAGE = 'html/options.html';

/**
 * @exports newtaboverride
 */
const newtaboverride = {
  /**
   * Fired when the extension is first installed, when the extension is updated to a new version or when the browser
   * is updated to a new version. We want to show a badge on our toolbar icon when the extension is first installed
   * or if an older version is detected.
   *
   * @param {runtime.OnInstalledReason} details - details.reason contains the reason why this event is being dispatched
   *
   * @returns {void}
   */
  onInstalledHandler (details) {
    if (details.reason === 'install') {
      browser.browserAction.setBadgeText({ text : '★' });
    }

    if (details.reason === 'update' && parseFloat(details.previousVersion) < 7) {
      browser.browserAction.setBadgeText({ text : '★' });
      browser.storage.local.set({ show_compat_notice : true });
    }
  },

  /**
   * Fired whenever the user changes the input, after the user has started interacting with the add-on by entering
   * its keyword in the address bar and then pressing the space key.
   *
   * @param {string} input - user input in the address bar, not including the add-on's keyword itself or the space
   *                 after the keyword

   *                 Supported value: settings
   * @param {function} suggest - a callback function that the event listener can call to supply suggestions for the
   *                   address bar's drop-down list
   *
   * @returns {void}
   */
  showOmniboxSuggestions (input, suggest) {
    const availableCommands = ['settings'];
    const suggestions = [];

    for (const command of availableCommands) {
      if (command.indexOf(input) !== -1) {
        suggestions.push({
          content : command,
          description : browser.i18n.getMessage('omnibox_command_' + command)
        });
      }

      if (suggestions.length === 0) {
        suggestions.push({
          content : 'settings',
          description : browser.i18n.getMessage('omnibox_command_settings')
        });
      }
    }

    suggest(suggestions);
  },

  /**
   * Fired when the user has selected one of the suggestions the add-on has added to the address bar's drop-down list.
   *
   * @param {string} input - this is the value that the user selected
   *
   * @returns {void}
   */
  callOmniboxAction (input) {
    switch (input) {
      case 'settings':
      default:
        newtaboverride.openUserInterfaceInCurrentTab();
    }
  },

  /**
   * Fired when the toolbar icon is clicked. This method is used to open the user interface in a new tab or to switch
   * to the tab with the user interface if the user interface is already opened.
   *
   * @returns {void}
   */
  openUserInterface () {
    const url = browser.extension.getURL(OPTIONS_PAGE);

    browser.browserAction.setBadgeText({ text : '' });
    browser.tabs.query({}, (tabs) => {
      let tabId = null;

      for (const tab of tabs) {
        if (tab.url === url) {
          tabId = tab.id;
          break;
        }
      }

      if (tabId) {
        browser.tabs.update(tabId, { active : true });
      }
      else {
        browser.tabs.create({ url });
      }
    });
  },

  /**
   * This method is used to open the user interface in the current tab. It's used for the omnibox suggestions.
   *
   * @returns {void}
   */
  openUserInterfaceInCurrentTab () {
    browser.tabs.update(null, { url : browser.extension.getURL(OPTIONS_PAGE) });
  }
};

browser.browserAction.onClicked.addListener(newtaboverride.openUserInterface);
browser.omnibox.onInputChanged.addListener(newtaboverride.showOmniboxSuggestions);
browser.omnibox.onInputEntered.addListener(newtaboverride.callOmniboxAction);
browser.omnibox.setDefaultSuggestion({ description : browser.i18n.getMessage('omnibox_default_description') });
browser.runtime.onInstalled.addListener(newtaboverride.onInstalledHandler);
<|endoftext|>


<commit_before>/* global document, chrome, fetch, chrome, Worker, getSelection, localStorage */

let extensionReady, copiedPath, copiedValue, copyPathMenuEntryId, copyValueMenuEntryId, settings;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	onmessage(message, sender, sendResponse);
	return true;
});
init();

async function init() {
	extensionReady = migrateSettings();
	settings = await getSettings();
	if (settings.options && typeof settings.options.addContextMenu == "undefined") {
		settings.options.addContextMenu = true;
		await setSetting("options", settings.options);
	}
	if (!settings.theme) {
		const theme = await getDefaultTheme();
		await setSetting("theme", theme);
		await refreshMenuEntry();
	} else {
		await refreshMenuEntry();
	}
}

async function migrateSettings() {
	const promises = [];
	if (localStorage.options) {
		promises.push(new Promise(resolve => {
			chrome.storage.local.set({ options: JSON.parse(localStorage.options) }, () => resolve());
			delete localStorage.options;
		}));
	}
	if (localStorage.theme) {
		promises.push(new Promise(resolve => {
			chrome.storage.local.set({ theme: localStorage.theme }, () => resolve());
			delete localStorage.theme;
		}));
	}
	await Promise.all(promises);
}

async function onmessage(message, sender, sendResponse) {
	const json = message.json;
	let workerFormatter, workerJSONLint;
	if (message.setSetting) {
		await setSetting(message.name, message.value);
	}
	if (message.getSettings) {
		const settings = await getSettings();
		sendResponse(settings);
	}
	if (message.refreshMenuEntry) {
		await refreshMenuEntry();
	}
	if (message.init)
		sendResponse({
			options: (await getSettings()).options || {}
		});
	if (message.copyPropertyPath) {
		copiedPath = message.path;
		copiedValue = message.value;
	}
	if (message.jsonToHTML) {
		workerFormatter = new Worker("js/worker-formatter.js");
		workerFormatter.addEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.postMessage({
			json: json,
			fnName: message.fnName
		});
	}

	function onWorkerJSONLintMessage(event) {
		const message = JSON.parse(event.data);
		workerJSONLint.removeEventListener("message", onWorkerJSONLintMessage, false);
		workerJSONLint.terminate();
		sendResponse({
			error: message.error,
			loc: message.loc,
			offset: message.offset || 0
		});
	}

	async function onWorkerFormatterMessage(event) {
		const message = event.data;
		workerFormatter.removeEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.terminate();
		if (message.html)
			sendResponse({
				html: message.html,
				theme: (await getSettings()).theme
			});
		if (message.error) {
			workerJSONLint = new Worker("js/worker-JSONLint.js");
			workerJSONLint.addEventListener("message", onWorkerJSONLintMessage, false);
			workerJSONLint.postMessage(json);
		}
	}
}

async function refreshMenuEntry() {
	const options = (await getSettings()).options;
	if (options.addContextMenu && !copyPathMenuEntryId) {
		copyPathMenuEntryId = chrome.contextMenus.create({
			title: "Copy path",
			contexts: ["page", "link"],
			onclick: () => copy(copiedPath)
		});
		copyValueMenuEntryId = chrome.contextMenus.create({
			title: "Copy value",
			contexts: ["page", "link"],
			onclick: () => copy(copiedValue)
		});
	}
	if (!options.addContextMenu && copyPathMenuEntryId) {
		chrome.contextMenus.remove(copyPathMenuEntryId);
		chrome.contextMenus.remove(copyValueMenuEntryId);
		copyPathMenuEntryId = null;
	}
}

async function getDefaultTheme() {
	return (await fetch("css/jsonvue.css")).text();
}

function copy(value) {
	const selElement = document.createElement("span");
	const selRange = document.createRange();
	selElement.innerText = value;
	document.body.appendChild(selElement);
	selRange.selectNodeContents(selElement);
	const selection = getSelection();
	selection.removeAllRanges();
	selection.addRange(selRange);
	document.execCommand("Copy");
	document.body.removeChild(selElement);
}

async function getSettings() {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.get(["options", "theme"], result => resolve(result)));
}

async function setSetting(name, value) {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.set({ [name]: value }, result => resolve(result)));
}<commit_msg>move variable declaration<commit_after>/* global document, chrome, fetch, chrome, Worker, getSelection, localStorage */

let extensionReady, copiedPath, copiedValue, copyPathMenuEntryId, copyValueMenuEntryId;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	onmessage(message, sender, sendResponse);
	return true;
});
init();

async function init() {
	extensionReady = migrateSettings();
	const settings = await getSettings();
	if (settings.options && typeof settings.options.addContextMenu == "undefined") {
		settings.options.addContextMenu = true;
		await setSetting("options", settings.options);
	}
	if (!settings.theme) {
		const theme = await getDefaultTheme();
		await setSetting("theme", theme);
		await refreshMenuEntry();
	} else {
		await refreshMenuEntry();
	}
}

async function migrateSettings() {
	const promises = [];
	if (localStorage.options) {
		promises.push(new Promise(resolve => {
			chrome.storage.local.set({ options: JSON.parse(localStorage.options) }, () => resolve());
			delete localStorage.options;
		}));
	}
	if (localStorage.theme) {
		promises.push(new Promise(resolve => {
			chrome.storage.local.set({ theme: localStorage.theme }, () => resolve());
			delete localStorage.theme;
		}));
	}
	await Promise.all(promises);
}

async function onmessage(message, sender, sendResponse) {
	const json = message.json;
	let workerFormatter, workerJSONLint;
	if (message.setSetting) {
		await setSetting(message.name, message.value);
	}
	if (message.getSettings) {
		const settings = await getSettings();
		sendResponse(settings);
	}
	if (message.refreshMenuEntry) {
		await refreshMenuEntry();
	}
	if (message.init)
		sendResponse({
			options: (await getSettings()).options || {}
		});
	if (message.copyPropertyPath) {
		copiedPath = message.path;
		copiedValue = message.value;
	}
	if (message.jsonToHTML) {
		workerFormatter = new Worker("js/worker-formatter.js");
		workerFormatter.addEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.postMessage({
			json: json,
			fnName: message.fnName
		});
	}

	function onWorkerJSONLintMessage(event) {
		const message = JSON.parse(event.data);
		workerJSONLint.removeEventListener("message", onWorkerJSONLintMessage, false);
		workerJSONLint.terminate();
		sendResponse({
			error: message.error,
			loc: message.loc,
			offset: message.offset || 0
		});
	}

	async function onWorkerFormatterMessage(event) {
		const message = event.data;
		workerFormatter.removeEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.terminate();
		if (message.html)
			sendResponse({
				html: message.html,
				theme: (await getSettings()).theme
			});
		if (message.error) {
			workerJSONLint = new Worker("js/worker-JSONLint.js");
			workerJSONLint.addEventListener("message", onWorkerJSONLintMessage, false);
			workerJSONLint.postMessage(json);
		}
	}
}

async function refreshMenuEntry() {
	const options = (await getSettings()).options;
	if (options.addContextMenu && !copyPathMenuEntryId) {
		copyPathMenuEntryId = chrome.contextMenus.create({
			title: "Copy path",
			contexts: ["page", "link"],
			onclick: () => copy(copiedPath)
		});
		copyValueMenuEntryId = chrome.contextMenus.create({
			title: "Copy value",
			contexts: ["page", "link"],
			onclick: () => copy(copiedValue)
		});
	}
	if (!options.addContextMenu && copyPathMenuEntryId) {
		chrome.contextMenus.remove(copyPathMenuEntryId);
		chrome.contextMenus.remove(copyValueMenuEntryId);
		copyPathMenuEntryId = null;
	}
}

async function getDefaultTheme() {
	return (await fetch("css/jsonvue.css")).text();
}

function copy(value) {
	const selElement = document.createElement("span");
	const selRange = document.createRange();
	selElement.innerText = value;
	document.body.appendChild(selElement);
	selRange.selectNodeContents(selElement);
	const selection = getSelection();
	selection.removeAllRanges();
	selection.addRange(selRange);
	document.execCommand("Copy");
	document.body.removeChild(selElement);
}

async function getSettings() {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.get(["options", "theme"], result => resolve(result)));
}

async function setSetting(name, value) {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.set({ [name]: value }, result => resolve(result)));
}<|endoftext|>


<commit_before>/**
 * No Coin - Stop coin miners in your browser
 **
 * @author      Rafael Keramidas <ker.af>
 * @license     MIT
 * @source      https://github.com/keraf/NoCoin
 */

// Config
const defaultConfig = {
    toggle: true,
    whitelist: [{
        domain: 'cnhv.co',
        expiration: 0,
    }],
};

const localConfig = JSON.parse(localStorage.getItem('config'));
let config = {
    ...defaultConfig,
    ...localConfig,
};

/**
 * Variables
 */
let domains = [];
let detected = [];

/**
 * Functions
 */
const saveConfig = () => {
    localStorage.setItem('config', JSON.stringify(config));
};

const changeToggleIcon = (isEnabled) => {
    chrome.browserAction.setIcon({
        path: `img/${isEnabled ? 'logo_enabled' : 'logo_disabled'}.png`,
    });
};

const getDomain = (url) => {
    const match = url.match(/:\/\/(.[^/]+)/);

    return match ? match[1] : '';
};

const getTimestamp = () => {
    return Math.floor(Date.now() / 1000);
};

const isDomainWhitelisted = (domain) => {
    if (!domain) return false;

    const domainInfo = config.whitelist.find(w => w.domain === domain);

    if (domainInfo) {
        if (domainInfo.expiration !== 0 && domainInfo.expiration <= getTimestamp()) {
            removeDomainFromWhitelist(domain);

            return false;
        }

        return true;
    }

    return false;
};

const addDomainToWhitelist = (domain, time) => {
    if (!domain) return;

    // Make sure the domain is not already whitelisted before adding it
    if (!isDomainWhitelisted(domain)) {
        config.whitelist = [
            ...config.whitelist,
            {
                domain: domain,
                expiration: time === 0 ? 0 : getTimestamp() + (time * 60),
            },
        ];
        saveConfig();
    }
};

const removeDomainFromWhitelist = (domain) => {
    if (!domain) return;

    config.whitelist = config.whitelist.filter(w => w.domain !== domain);
    saveConfig();
};

const runBlocker = (blacklist) => {
    const blacklistedUrls = blacklist.split('\n');

    chrome.webRequest.onBeforeRequest.addListener(details => {
        chrome.browserAction.setBadgeBackgroundColor({
            color: [200, 0, 0, 100],
            tabId: details.tabId,
        });

        chrome.browserAction.setBadgeText({
            text: '!',
            tabId: details.tabId,
        });

        detected[details.tabId] = true;

        // Globally paused
        if (!config.toggle) {
            return { cancel: false };
        }

        // Is domain white listed
        if (isDomainWhitelisted(domains[details.tabId])) {
            chrome.browserAction.setIcon({
                path: 'img/logo_enabled_whitelisted.png',
                tabId: details.tabId,
            });

            return { cancel: false };
        }

        chrome.browserAction.setIcon({
            path: 'img/logo_enabled_blocked.png',
            tabId: details.tabId,
        });

        return { cancel: true };
    }, {
        urls: blacklistedUrls
    }, ['blocking']);
};

const runFallbackBlocker = () => {
    fetch(chrome.runtime.getURL('blacklist.txt'))
        .then(resp => {
            resp.text().then(text => runBlocker(text));
        });
};

/**
 * Main
 */

// Updating domain for synchronous checking in onBeforeRequest
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    domains[tabId] = getDomain(tab.url);

    // Set back to normal when navigating
    if (changeInfo === 'loading') {
        if (config.toggle) {
            chrome.browserAction.setIcon({
                path: 'img/logo_enabled.png',
                tabId,
            });
        }

        detected[details.tabId] = false;

        chrome.browserAction.setBadgeText({
            text: '',
            tabId,
        });
    }
});

chrome.tabs.onRemoved.addListener((tabId) => {
    delete domains[tabId];
});

// Run with the right icon
if (!config.toggle) {
    changeToggleIcon(false);
}

// Load the blacklist and run the blocker
const blacklist = 'https://raw.githubusercontent.com/keraf/NoCoin/master/src/blacklist.txt';
fetch(blacklist)
    .then(resp => {
        if (resp.status !== 200) {
            throw 'HTTP Error';
        }

        resp.text().then((text) => {
            if (text === '') {
                throw 'Empty response';
            }

            runBlocker(text);
        });
    })
    .catch(err => {
        runFallbackBlocker();
    });

// Communication with the popup and content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    switch (message.type) {
        case 'GET_STATE':
            sendResponse({
                version: chrome.runtime.getManifest().version,
                whitelisted: isDomainWhitelisted(domains[message.tabId]),
                domain: domains[message.tabId],
                detected: detected[message.tabId] || false,
                toggle: config.toggle,
            });
            break;
        case 'TOGGLE':
            config.toggle = !config.toggle;
            saveConfig();

            changeToggleIcon(config.toggle);
            sendResponse(config.toggle);
            break;
        case 'WHITELIST': {
            if (message.whitelisted) {
                removeDomainFromWhitelist(domains[message.tabId], message.time);
            } else {
                addDomainToWhitelist(domains[message.tabId], message.time);
            }

            sendResponse(!message.whitelisted);
            break;
        }
    }
});
<commit_msg>convert time to number (fixes issue #52)<commit_after>/**
 * No Coin - Stop coin miners in your browser
 **
 * @author      Rafael Keramidas <ker.af>
 * @license     MIT
 * @source      https://github.com/keraf/NoCoin
 */

// Config
const defaultConfig = {
    toggle: true,
    whitelist: [{
        domain: 'cnhv.co',
        expiration: 0,
    }],
};

const localConfig = JSON.parse(localStorage.getItem('config'));
let config = {
    ...defaultConfig,
    ...localConfig,
};

/**
 * Variables
 */
let domains = [];
let detected = [];

/**
 * Functions
 */
const saveConfig = () => {
    localStorage.setItem('config', JSON.stringify(config));
};

const changeToggleIcon = (isEnabled) => {
    chrome.browserAction.setIcon({
        path: `img/${isEnabled ? 'logo_enabled' : 'logo_disabled'}.png`,
    });
};

const getDomain = (url) => {
    const match = url.match(/:\/\/(.[^/]+)/);

    return match ? match[1] : '';
};

const getTimestamp = () => {
    return Math.floor(Date.now() / 1000);
};

const isDomainWhitelisted = (domain) => {
    if (!domain) return false;

    const domainInfo = config.whitelist.find(w => w.domain === domain);

    if (domainInfo) {
        if (domainInfo.expiration !== 0 && domainInfo.expiration <= getTimestamp()) {
            removeDomainFromWhitelist(domain);

            return false;
        }

        return true;
    }

    return false;
};

const addDomainToWhitelist = (domain, time) => {
    if (!domain) return;
    time = +time || 0;

    // Make sure the domain is not already whitelisted before adding it
    if (!isDomainWhitelisted(domain)) {
        config.whitelist = [
            ...config.whitelist,
            {
                domain: domain,
                expiration: time === 0 ? 0 : getTimestamp() + (time * 60),
            },
        ];
        saveConfig();
    }
};

const removeDomainFromWhitelist = (domain) => {
    if (!domain) return;

    config.whitelist = config.whitelist.filter(w => w.domain !== domain);
    saveConfig();
};

const runBlocker = (blacklist) => {
    const blacklistedUrls = blacklist.split('\n');

    chrome.webRequest.onBeforeRequest.addListener(details => {
        chrome.browserAction.setBadgeBackgroundColor({
            color: [200, 0, 0, 100],
            tabId: details.tabId,
        });

        chrome.browserAction.setBadgeText({
            text: '!',
            tabId: details.tabId,
        });

        detected[details.tabId] = true;

        // Globally paused
        if (!config.toggle) {
            return { cancel: false };
        }

        // Is domain white listed
        if (isDomainWhitelisted(domains[details.tabId])) {
            chrome.browserAction.setIcon({
                path: 'img/logo_enabled_whitelisted.png',
                tabId: details.tabId,
            });

            return { cancel: false };
        }

        chrome.browserAction.setIcon({
            path: 'img/logo_enabled_blocked.png',
            tabId: details.tabId,
        });

        return { cancel: true };
    }, {
        urls: blacklistedUrls
    }, ['blocking']);
};

const runFallbackBlocker = () => {
    fetch(chrome.runtime.getURL('blacklist.txt'))
        .then(resp => {
            resp.text().then(text => runBlocker(text));
        });
};

/**
 * Main
 */

// Updating domain for synchronous checking in onBeforeRequest
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    domains[tabId] = getDomain(tab.url);

    // Set back to normal when navigating
    if (changeInfo === 'loading') {
        if (config.toggle) {
            chrome.browserAction.setIcon({
                path: 'img/logo_enabled.png',
                tabId,
            });
        }

        detected[details.tabId] = false;

        chrome.browserAction.setBadgeText({
            text: '',
            tabId,
        });
    }
});

chrome.tabs.onRemoved.addListener((tabId) => {
    delete domains[tabId];
});

// Run with the right icon
if (!config.toggle) {
    changeToggleIcon(false);
}

// Load the blacklist and run the blocker
const blacklist = 'https://raw.githubusercontent.com/keraf/NoCoin/master/src/blacklist.txt';
fetch(blacklist)
    .then(resp => {
        if (resp.status !== 200) {
            throw 'HTTP Error';
        }

        resp.text().then((text) => {
            if (text === '') {
                throw 'Empty response';
            }

            runBlocker(text);
        });
    })
    .catch(err => {
        runFallbackBlocker();
    });

// Communication with the popup and content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    switch (message.type) {
        case 'GET_STATE':
            sendResponse({
                version: chrome.runtime.getManifest().version,
                whitelisted: isDomainWhitelisted(domains[message.tabId]),
                domain: domains[message.tabId],
                detected: detected[message.tabId] || false,
                toggle: config.toggle,
            });
            break;
        case 'TOGGLE':
            config.toggle = !config.toggle;
            saveConfig();

            changeToggleIcon(config.toggle);
            sendResponse(config.toggle);
            break;
        case 'WHITELIST': {
            if (message.whitelisted) {
                removeDomainFromWhitelist(domains[message.tabId], message.time);
            } else {
                addDomainToWhitelist(domains[message.tabId], message.time);
            }

            sendResponse(!message.whitelisted);
            break;
        }
    }
});
<|endoftext|>


<commit_before>import utils from './utils';
import Thumbnails from './thumbnails';
import Icons from './icons';

class Controller {
    constructor (player) {
        this.player = player;

        this.autoHideTimer = 0;
        if (!utils.isMobile) {
            this.player.container.addEventListener('mousemove', () => {
                this.setAutoHide();
            });
            this.player.container.addEventListener('click', () => {
                this.setAutoHide();
            });
            this.player.on('play', () => {
                this.setAutoHide();
            });
            this.player.on('pause', () => {
                this.setAutoHide();
            });
        }

        this.initPlayButton();
        this.initThumbnails();
        this.initPlayedBar();
        this.initFullButton();
        this.initQualityButton();
        this.initScreenshotButton();
        this.initSubtitleButton();
        if (!utils.isMobile) {
            this.initVolumeButton();
        }
    }

    initPlayButton () {
        this.player.template.playButton.addEventListener('click', () => {
            this.player.toggle();
        });

        if (!utils.isMobile) {
            this.player.template.videoWrap.addEventListener('click', () => {
                this.player.toggle();
            });
            this.player.template.controllerMask.addEventListener('click', () => {
                this.player.toggle();
            });
        }
        else {
            this.player.template.videoWrap.addEventListener('click', () => {
                this.toggle();
            });
            this.player.template.controllerMask.addEventListener('click', () => {
                this.toggle();
            });
        }
    }

    initThumbnails () {
        if (this.player.options.video.thumbnails) {
            this.thumbnails = new Thumbnails({
                container: this.player.template.barPreview,
                barWidth: this.player.template.barWrap.offsetWidth,
                url: this.player.options.video.thumbnails,
                events: this.player.events
            });

            this.player.on('loadedmetadata', () => {
                this.thumbnails.resize(160, this.player.video.videoHeight / this.player.video.videoWidth * 160);
            });
        }
    }

    initPlayedBar () {
        const thumbMove = (e) => {
            let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.playedBarWrap)) / this.player.template.playedBarWrap.clientWidth;
            percentage = Math.max(percentage, 0);
            percentage = Math.min(percentage, 1);
            this.player.bar.set('played', percentage, 'width');
            this.player.template.ptime.innerHTML = utils.secondToTime(percentage * this.player.video.duration);
        };

        const thumbUp = (e) => {
            document.removeEventListener(utils.nameMap.dragEnd, thumbUp);
            document.removeEventListener(utils.nameMap.dragMove, thumbMove);
            let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.playedBarWrap)) / this.player.template.playedBarWrap.clientWidth;
            percentage = Math.max(percentage, 0);
            percentage = Math.min(percentage, 1);
            this.player.bar.set('played', percentage, 'width');
            this.player.seek(this.player.bar.get('played') * this.player.video.duration);
            this.player.timer.enable('progress');
        };

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragStart, () => {
            this.player.timer.disable('progress');
            document.addEventListener(utils.nameMap.dragMove, thumbMove);
            document.addEventListener(utils.nameMap.dragEnd, thumbUp);
        });

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragMove, (e) => {
            if (this.player.video.duration) {
                const px = utils.cumulativeOffset(this.player.template.playedBarWrap).left;
                const tx = (e.clientX || e.changedTouches[0].clientX) - px;
                if (tx < 0 || tx > this.player.template.playedBarWrap.offsetWidth) {
                    return;
                }
                const time = this.player.video.duration * (tx / this.player.template.playedBarWrap.offsetWidth);
                if (utils.isMobile) {
                    this.thumbnails && this.thumbnails.show();
                }
                this.thumbnails && this.thumbnails.move(tx);
                this.player.template.playedBarTime.style.left = `${(tx - 20)}px`;
                this.player.template.playedBarTime.innerText = utils.secondToTime(time);
                this.player.template.playedBarTime.classList.remove('hidden');
            }
        });

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragEnd, () => {
            if (utils.isMobile) {
                this.thumbnails && this.thumbnails.hide();
            }
        });

        if (!utils.isMobile) {
            this.player.template.playedBarWrap.addEventListener('mouseenter', () => {
                if (this.player.video.duration) {
                    this.thumbnails && this.thumbnails.show();
                    this.player.template.playedBarTime.classList.remove('hidden');
                }
            });

            this.player.template.playedBarWrap.addEventListener('mouseleave', () => {
                if (this.player.video.duration) {
                    this.thumbnails && this.thumbnails.hide();
                    this.player.template.playedBarTime.classList.add('hidden');
                }
            });
        }
    }

    initFullButton () {
        this.player.template.browserFullButton.addEventListener('click', () => {
            this.player.fullScreen.toggle('browser');
        });

        this.player.template.webFullButton.addEventListener('click', () => {
            this.player.fullScreen.toggle('web');
        });
    }

    initVolumeButton () {
        const vWidth = 35;

        const volumeMove = (event) => {
            const e = event || window.event;
            const percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.volumeBarWrap) - 5.5) / vWidth;
            this.player.volume(percentage);
        };
        const volumeUp = () => {
            document.removeEventListener(utils.nameMap.dragEnd, volumeUp);
            document.removeEventListener(utils.nameMap.dragMove, volumeMove);
            this.player.template.volumeButton.classList.remove('dplayer-volume-active');
        };

        this.player.template.volumeBarWrapWrap.addEventListener('click', (event) => {
            const e = event || window.event;
            const percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.volumeBarWrap) - 5.5) / vWidth;
            this.player.volume(percentage);
        });
        this.player.template.volumeBarWrapWrap.addEventListener(utils.nameMap.dragStart, () => {
            document.addEventListener(utils.nameMap.dragMove, volumeMove);
            document.addEventListener(utils.nameMap.dragEnd, volumeUp);
            this.player.template.volumeButton.classList.add('dplayer-volume-active');
        });
        this.player.template.volumeButtonIcon.addEventListener('click', () => {
            if (this.player.video.muted) {
                this.player.video.muted = false;
                this.player.switchVolumeIcon();
                this.player.bar.set('volume', this.player.volume(), 'width');
            }
            else {
                this.player.video.muted = true;
                this.player.template.volumeIcon.innerHTML = Icons.volumeOff;
                this.player.bar.set('volume', 0, 'width');
            }
        });
    }

    initQualityButton () {
        if (this.player.options.video.quality) {
            this.player.template.qualityList.addEventListener('click', (e) => {
                if (e.target.classList.contains('dplayer-quality-item')) {
                    this.player.switchQuality(e.target.dataset.index);
                }
            });
        }
    }

    initScreenshotButton () {
        if (this.player.options.screenshot) {
            this.player.template.camareButton.addEventListener('click', () => {
                const canvas = document.createElement('canvas');
                canvas.width = this.player.video.videoWidth;
                canvas.height = this.player.video.videoHeight;
                canvas.getContext('2d').drawImage(this.player.video, 0, 0, canvas.width, canvas.height);

                let dataURL;
                canvas.toBlob((blob) => {
                    dataURL = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = dataURL;
                    link.download = 'DPlayer.png';
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(dataURL);
                });

                this.player.events.trigger('screenshot', dataURL);
            });
        }
    }

    initSubtitleButton () {
        if (this.player.options.subtitle) {
            this.player.events.on('subtitle_show', () => {
                this.player.template.subtitleButton.dataset.balloon = this.player.tran('Hide subtitle');
                this.player.template.subtitleButtonInner.style.opacity = '';
                this.player.user.set('subtitle', 1);
            });
            this.player.events.on('subtitle_hide', () => {
                this.player.template.subtitleButton.dataset.balloon = this.player.tran('Show subtitle');
                this.player.template.subtitleButtonInner.style.opacity = '0.4';
                this.player.user.set('subtitle', 0);
            });

            this.player.template.subtitleButton.addEventListener('click', () => {
                this.player.subtitle.toggle();
            });
        }
    }

    setAutoHide () {
        this.show();
        clearTimeout(this.autoHideTimer);
        this.autoHideTimer = setTimeout(() => {
            if (this.player.video.played.length && !this.player.paused && !this.disableAutoHide) {
                this.hide();
            }
        }, 3000);
    }

    show () {
        this.player.container.classList.remove('dplayer-hide-controller');
    }

    hide () {
        this.player.container.classList.add('dplayer-hide-controller');
        this.player.setting.hide();
        this.player.comment && this.player.comment.hide();
    }

    isShow () {
        return !this.player.container.classList.contains('dplayer-hide-controller');
    }

    toggle () {
        if (this.isShow()) {
            this.hide();
        }
        else {
            this.show();
        }
    }

    destroy () {
        clearTimeout(this.autoHideTimer);
    }
}

export default Controller;
<commit_msg>Update controller.js<commit_after>import utils from './utils';
import Thumbnails from './thumbnails';
import Icons from './icons';

class Controller {
    constructor (player) {
        this.player = player;

        this.autoHideTimer = 0;
        if (!utils.isMobile) {
            this.player.container.addEventListener('mousemove', () => {
                this.setAutoHide();
            });
            this.player.container.addEventListener('click', () => {
                this.setAutoHide();
            });
            this.player.on('play', () => {
                this.setAutoHide();
            });
            this.player.on('pause', () => {
                this.setAutoHide();
            });
        }

        this.initPlayButton();
        this.initThumbnails();
        this.initPlayedBar();
        this.initFullButton();
        this.initQualityButton();
        this.initScreenshotButton();
        this.initSubtitleButton();
        this.initHighlights();
        if (!utils.isMobile) {
            this.initVolumeButton();
        }
    }

    initPlayButton () {
        this.player.template.playButton.addEventListener('click', () => {
            this.player.toggle();
        });

        if (!utils.isMobile) {
            this.player.template.videoWrap.addEventListener('click', () => {
                this.player.toggle();
            });
            this.player.template.controllerMask.addEventListener('click', () => {
                this.player.toggle();
            });
        }
        else {
            this.player.template.videoWrap.addEventListener('click', () => {
                this.toggle();
            });
            this.player.template.controllerMask.addEventListener('click', () => {
                this.toggle();
            });
        }
    }

    initHighlights () {
        this.player.on('durationchange', () => {
            if (this.player.video.duration !== 1 && this.player.video.duration !== Infinity) {
                if (this.player.options.highlight) {
                    const highlights = document.querySelectorAll('.dplayer-highlight');
                    [].slice.call(highlights, 0).map((item) => {
                        this.player.template.playedBarWrap.removeChild(item);
                    });
                    for (let i = 0; i < this.player.options.highlight.length; i++) {
                        if (!this.player.options.highlight[i].text || !this.player.options.highlight[i].time) {
                            continue;
                        }
                        const p = document.createElement('div');
                        p.classList.add('dplayer-highlight');
                        p.style.left = ( (this.player.options.highlight[i].time / this.player.video.duration) * 100) + '%';
                        p.innerHTML = '' + this.player.options.highlight[i].text + '';
                        this.player.template.playedBarWrap.insertBefore(p, this.player.template.playedBarTime);
                    }
                }
            }
        });
    }

    initThumbnails () {
        if (this.player.options.video.thumbnails) {
            this.thumbnails = new Thumbnails({
                container: this.player.template.barPreview,
                barWidth: this.player.template.barWrap.offsetWidth,
                url: this.player.options.video.thumbnails,
                events: this.player.events
            });

            this.player.on('loadedmetadata', () => {
                this.thumbnails.resize(160, this.player.video.videoHeight / this.player.video.videoWidth * 160);
            });
        }
    }

    initPlayedBar () {
        const thumbMove = (e) => {
            let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.playedBarWrap)) / this.player.template.playedBarWrap.clientWidth;
            percentage = Math.max(percentage, 0);
            percentage = Math.min(percentage, 1);
            this.player.bar.set('played', percentage, 'width');
            this.player.template.ptime.innerHTML = utils.secondToTime(percentage * this.player.video.duration);
        };

        const thumbUp = (e) => {
            document.removeEventListener(utils.nameMap.dragEnd, thumbUp);
            document.removeEventListener(utils.nameMap.dragMove, thumbMove);
            let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.playedBarWrap)) / this.player.template.playedBarWrap.clientWidth;
            percentage = Math.max(percentage, 0);
            percentage = Math.min(percentage, 1);
            this.player.bar.set('played', percentage, 'width');
            this.player.seek(this.player.bar.get('played') * this.player.video.duration);
            this.player.timer.enable('progress');
        };

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragStart, () => {
            this.player.timer.disable('progress');
            document.addEventListener(utils.nameMap.dragMove, thumbMove);
            document.addEventListener(utils.nameMap.dragEnd, thumbUp);
        });

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragMove, (e) => {
            if (this.player.video.duration) {
                const px = utils.cumulativeOffset(this.player.template.playedBarWrap).left;
                const tx = (e.clientX || e.changedTouches[0].clientX) - px;
                if (tx < 0 || tx > this.player.template.playedBarWrap.offsetWidth) {
                    return;
                }
                const time = this.player.video.duration * (tx / this.player.template.playedBarWrap.offsetWidth);
                if (utils.isMobile) {
                    this.thumbnails && this.thumbnails.show();
                }
                this.thumbnails && this.thumbnails.move(tx);
                this.player.template.playedBarTime.style.left = `${(tx - 20)}px`;
                this.player.template.playedBarTime.innerText = utils.secondToTime(time);
                this.player.template.playedBarTime.classList.remove('hidden');
            }
        });

        this.player.template.playedBarWrap.addEventListener(utils.nameMap.dragEnd, () => {
            if (utils.isMobile) {
                this.thumbnails && this.thumbnails.hide();
            }
        });

        if (!utils.isMobile) {
            this.player.template.playedBarWrap.addEventListener('mouseenter', () => {
                if (this.player.video.duration) {
                    this.thumbnails && this.thumbnails.show();
                    this.player.template.playedBarTime.classList.remove('hidden');
                }
            });

            this.player.template.playedBarWrap.addEventListener('mouseleave', () => {
                if (this.player.video.duration) {
                    this.thumbnails && this.thumbnails.hide();
                    this.player.template.playedBarTime.classList.add('hidden');
                }
            });
        }
    }

    initFullButton () {
        this.player.template.browserFullButton.addEventListener('click', () => {
            this.player.fullScreen.toggle('browser');
        });

        this.player.template.webFullButton.addEventListener('click', () => {
            this.player.fullScreen.toggle('web');
        });
    }

    initVolumeButton () {
        const vWidth = 35;

        const volumeMove = (event) => {
            const e = event || window.event;
            const percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.volumeBarWrap) - 5.5) / vWidth;
            this.player.volume(percentage);
        };
        const volumeUp = () => {
            document.removeEventListener(utils.nameMap.dragEnd, volumeUp);
            document.removeEventListener(utils.nameMap.dragMove, volumeMove);
            this.player.template.volumeButton.classList.remove('dplayer-volume-active');
        };

        this.player.template.volumeBarWrapWrap.addEventListener('click', (event) => {
            const e = event || window.event;
            const percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.volumeBarWrap) - 5.5) / vWidth;
            this.player.volume(percentage);
        });
        this.player.template.volumeBarWrapWrap.addEventListener(utils.nameMap.dragStart, () => {
            document.addEventListener(utils.nameMap.dragMove, volumeMove);
            document.addEventListener(utils.nameMap.dragEnd, volumeUp);
            this.player.template.volumeButton.classList.add('dplayer-volume-active');
        });
        this.player.template.volumeButtonIcon.addEventListener('click', () => {
            if (this.player.video.muted) {
                this.player.video.muted = false;
                this.player.switchVolumeIcon();
                this.player.bar.set('volume', this.player.volume(), 'width');
            }
            else {
                this.player.video.muted = true;
                this.player.template.volumeIcon.innerHTML = Icons.volumeOff;
                this.player.bar.set('volume', 0, 'width');
            }
        });
    }

    initQualityButton () {
        if (this.player.options.video.quality) {
            this.player.template.qualityList.addEventListener('click', (e) => {
                if (e.target.classList.contains('dplayer-quality-item')) {
                    this.player.switchQuality(e.target.dataset.index);
                }
            });
        }
    }

    initScreenshotButton () {
        if (this.player.options.screenshot) {
            this.player.template.camareButton.addEventListener('click', () => {
                const canvas = document.createElement('canvas');
                canvas.width = this.player.video.videoWidth;
                canvas.height = this.player.video.videoHeight;
                canvas.getContext('2d').drawImage(this.player.video, 0, 0, canvas.width, canvas.height);

                let dataURL;
                canvas.toBlob((blob) => {
                    dataURL = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = dataURL;
                    link.download = 'DPlayer.png';
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(dataURL);
                });

                this.player.events.trigger('screenshot', dataURL);
            });
        }
    }

    initSubtitleButton () {
        if (this.player.options.subtitle) {
            this.player.events.on('subtitle_show', () => {
                this.player.template.subtitleButton.dataset.balloon = this.player.tran('Hide subtitle');
                this.player.template.subtitleButtonInner.style.opacity = '';
                this.player.user.set('subtitle', 1);
            });
            this.player.events.on('subtitle_hide', () => {
                this.player.template.subtitleButton.dataset.balloon = this.player.tran('Show subtitle');
                this.player.template.subtitleButtonInner.style.opacity = '0.4';
                this.player.user.set('subtitle', 0);
            });

            this.player.template.subtitleButton.addEventListener('click', () => {
                this.player.subtitle.toggle();
            });
        }
    }

    setAutoHide () {
        this.show();
        clearTimeout(this.autoHideTimer);
        this.autoHideTimer = setTimeout(() => {
            if (this.player.video.played.length && !this.player.paused && !this.disableAutoHide) {
                this.hide();
            }
        }, 3000);
    }

    show () {
        this.player.container.classList.remove('dplayer-hide-controller');
    }

    hide () {
        this.player.container.classList.add('dplayer-hide-controller');
        this.player.setting.hide();
        this.player.comment && this.player.comment.hide();
    }

    isShow () {
        return !this.player.container.classList.contains('dplayer-hide-controller');
    }

    toggle () {
        if (this.isShow()) {
            this.hide();
        }
        else {
            this.show();
        }
    }

    destroy () {
        clearTimeout(this.autoHideTimer);
    }
}

export default Controller;
<|endoftext|>


<commit_before>/**
 * Created by BreakPoint on 19.05.17.
 */
function initFirstBlock(page, worktype, clients, keyword) {

    pageGlobal = page;

    if (!(page || worktype || clients || keyword)) {
        gridInit();
        return false;
    } else if (page && worktype && clients && !keyword) {

        try {
            if (contentGlobal[pageGlobal][worktype][clients] === undefined) {
                redirectNotFound();
                return false;
            }

            $.each(contentGlobal[pageGlobal][worktype][clients], function (index, val) {
                vertical.push(val);
                //console.log(data);
            });
            $.each(contentGlobal[pageGlobal][worktype], function (key) {
                $.each(contentGlobal[pageGlobal][worktype][key], function (index, val) {
                    //console.log(key);
                    if (key != clients) {
                        vertical.push(val);
                        //console.log(val);
                    }
                });
            });
        } catch (err) {
            redirectNotFound();
            return false;
        }

    } else if (page && !worktype && clients && !keyword) {

        try {

            $.each(contentGlobal[pageGlobal], function (key) {
                $.each(contentGlobal[pageGlobal][key][clients], function (index, val) {
                    if (contentGlobal[pageGlobal][key][clients] !== undefined) {
                        horizontal.push(val);
                        //console.log(val);
                    }
                });
            });

            if (horizontal.length == 0){
                redirectNotFound();
                return false;
            }

            currentImgH = horizontal.length - 1;
            currentClient = clients;
            changeType(true);
            return false;

        } catch (err) {
            console.log(err);
            redirectNotFound();
            return false;
        }

    } else if (page && !worktype && !clients && !keyword) {

        if ( page == 'portfolio') {
            gridInit();
            return false;
        } else {
            try {

                $.each(contentGlobal[pageGlobal][pageGlobal][pageGlobal], function (index, val) {
                    vertical.push(val);
                    //console.log(val);
                });

            } catch (err) {
                redirectNotFound();
                return false;
            }

        }

    } else if (page && worktype && clients && keyword) {

        try {
            if (contentGlobal[pageGlobal][worktype][clients][keyword] !== undefined) {
                console.log("Верный ключ");
                trueKey = true;
                vertical.push(contentGlobal[pageGlobal][worktype][clients][keyword]);
            } else {
                trueKey = false;
            }
            if (contentGlobal[pageGlobal][worktype] === undefined) {
                redirectNotFound();
                return false;
            }
            $.each(contentGlobal[pageGlobal][worktype][clients], function (index, val) {
                if (vertical.length == 0) {
                    vertical.push(val);
                    //console.log(val);
                }
                if (vertical.length != 0 && val != vertical[0]) {
                    vertical.push(val);
                    //console.log(val);
                }
            });
            $.each(contentGlobal[pageGlobal][worktype], function (key) {
                $.each(contentGlobal[pageGlobal][worktype][key], function (index, val) {
                    if (key != clients) {
                        //console.log(key);
                        vertical.push(val);
                    }
                });
            });
        } catch (err) {
            redirectNotFound();
            return false;
        }

    } else {

        gridInit();
        return false;

    }

    currentImgV = vertical.length - 1;
    getContent(true);

}

function changeType(next) {

    lenCurrent = horizontal.length;

    if (next) {
        if (currentImgH == lenCurrent - 1) {
            currentImgH = 0;
            $('.container').html(horizontal[currentImgH]);
        } else {
            currentImgH += 1;
            $('.container').html(horizontal[currentImgH]);
        }
        //console.log(currentImg);
        //console.log(lenCurrent);
    } else {
        if (currentImgH == 0) {
            currentImgH = lenCurrent - 1;
            $('.container').html(horizontal[currentImgH]);
        } else {
            currentImgH -= 1;
            $('.container').html(horizontal[currentImgH]);
        }
        //console.log(currentImg);
        //console.log(lenCurrent);
    }

    currentImgV = 0;

    if (currentType != $('.container').children().data('type')) {
        vertical = [];
        currentType = $('.container').children().data('type');
        vertical.push(contentGlobal[pageGlobal][currentType][currentClient][counterType]);
        $.each(contentGlobal[pageGlobal][currentType], function (key) {
            $.each(contentGlobal[pageGlobal][currentType][key], function (index, val) {
                if (vertical[0] != val) {
                    vertical.push(val);
                }
                //console.log(val);
            });
        });
        counterType = 0;
    } else {
        counterType += 1;
    }

    window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType);
    document.title = currentClient + " | " + currentType;

    if (vertical.length == 1) {
        $('.navTB').hide();
    } else {
        $('.navTB').show();
    }

}

function getContent(next) {

    lenCurrent = vertical.length;

    if (next) {
        if (currentImgV == lenCurrent - 1) {
            currentImgV = 0;
            $('.container').html(vertical[currentImgV]);
        } else {
            currentImgV += 1;
            $('.container').html(vertical[currentImgV]);
        }
        console.log(currentImgV);
        console.log(lenCurrent);
    } else {
        if (currentImgV == 0) {
            currentImgV = lenCurrent - 1;
            $('.container').html(vertical[currentImgV]);
        } else {
            currentImgV -= 1;
            $('.container').html(vertical[currentImgV]);
        }
        console.log(currentImgV);
        console.log(lenCurrent);
    }

    currentImgH = 0;
    currentType = $('.container').children().data('type');

    if (currentClient != $('.container').children().data('client')) {
        horizontal = [];
        currentClient = $('.container').children().data('client');
        horizontal.push(contentGlobal[pageGlobal][currentType][currentClient][counterClient]);
        $.each(contentGlobal[pageGlobal], function(key) {
            if (contentGlobal[pageGlobal][key][currentClient] !== undefined) {
                $.each(contentGlobal[pageGlobal][key][currentClient], function(index, val) {
                    if (horizontal[0] != val) {
                        horizontal.push(val);
                        //console.log(contentGlobal[key][currentClient][0]);
                    }
                });
            }
        });
        counterClient = 0;
    } else {
        counterClient += 1;
    }

    if (trueKey) {
        window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType + "/" + locKeyword);
        document.title = currentClient + " | " + currentType;
    } else {
        window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType);
        document.title = currentClient + " | " + currentType;
    }

    if (horizontal.length == 1) {
        $('.navLR').hide();
    } else {
        $('.navLR').show();
    }

}<commit_msg>fix #2<commit_after>/**
 * Created by BreakPoint on 19.05.17.
 */
function initFirstBlock(page, worktype, clients, keyword) {

    pageGlobal = page;

    if (!(page || worktype || clients || keyword)) {
        gridInit();
        return false;
    } else if (page && worktype && clients && !keyword) {

        try {
            if (contentGlobal[pageGlobal][worktype][clients] === undefined) {
                redirectNotFound();
                return false;
            }

            $.each(contentGlobal[pageGlobal][worktype][clients], function (index, val) {
                vertical.push(val);
                //console.log(data);
            });
            $.each(contentGlobal[pageGlobal][worktype], function (key) {
                $.each(contentGlobal[pageGlobal][worktype][key], function (index, val) {
                    //console.log(key);
                    if (key != clients) {
                        vertical.push(val);
                        //console.log(val);
                    }
                });
            });
        } catch (err) {
            redirectNotFound();
            return false;
        }

    } else if (page && !worktype && clients && !keyword) {

        try {

            $.each(contentGlobal[pageGlobal], function (key) {
                $.each(contentGlobal[pageGlobal][key][clients], function (index, val) {
                    if (contentGlobal[pageGlobal][key][clients] !== undefined) {
                        horizontal.push(val);
                        //console.log(val);
                    }
                });
            });

            if (horizontal.length == 0){
                redirectNotFound();
                return false;
            }

            currentImgH = horizontal.length - 1;
            currentClient = clients;
            changeType(true);
            return false;

        } catch (err) {
            console.log(err);
            redirectNotFound();
            return false;
        }

    } else if (page && !worktype && !clients && !keyword) {

        if ( page == 'portfolio') {
            gridInit();
            return false;
        } else {
            try {

                $.each(contentGlobal[pageGlobal][pageGlobal][pageGlobal], function (index, val) {
                    vertical.push(val);
                    //console.log(val);
                });

            } catch (err) {
                redirectNotFound();
                return false;
            }

        }

    } else if (page && worktype && clients && keyword) {

        try {
            if (contentGlobal[pageGlobal][worktype][clients][keyword] !== undefined) {
                console.log("Верный ключ");
                trueKey = true;
                vertical.push(contentGlobal[pageGlobal][worktype][clients][keyword]);
            } else {
                trueKey = false;
            }
            if (contentGlobal[pageGlobal][worktype] === undefined) {
                redirectNotFound();
                return false;
            }
            $.each(contentGlobal[pageGlobal][worktype][clients], function (index, val) {
                if (vertical.length == 0) {
                    vertical.push(val);
                    //console.log(val);
                }
                if (vertical.length != 0 && val != vertical[0]) {
                    vertical.push(val);
                    //console.log(val);
                }
            });
            $.each(contentGlobal[pageGlobal][worktype], function (key) {
                $.each(contentGlobal[pageGlobal][worktype][key], function (index, val) {
                    if (key != clients) {
                        //console.log(key);
                        vertical.push(val);
                    }
                });
            });
        } catch (err) {
            redirectNotFound();
            return false;
        }

    } else {

        gridInit();
        return false;

    }

    currentImgV = vertical.length - 1;
    getContent(true);

}

function changeType(next) {

    lenCurrent = horizontal.length;

    if (next) {
        if (currentImgH == lenCurrent - 1) {
            currentImgH = 0;
            $('.container').html(horizontal[currentImgH]);
        } else {
            currentImgH += 1;
            $('.container').html(horizontal[currentImgH]);
        }
        //console.log(currentImg);
        //console.log(lenCurrent);
    } else {
        if (currentImgH == 0) {
            currentImgH = lenCurrent - 1;
            $('.container').html(horizontal[currentImgH]);
        } else {
            currentImgH -= 1;
            $('.container').html(horizontal[currentImgH]);
        }
        //console.log(currentImg);
        //console.log(lenCurrent);
    }

    currentImgV = 0;

    if (currentType != $('.container').children().data('type')) {
        vertical = [];
        currentType = $('.container').children().data('type');
        vertical.push(contentGlobal[pageGlobal][currentType][currentClient][counterType]);
        $.each(contentGlobal[pageGlobal][currentType], function (key) {
            $.each(contentGlobal[pageGlobal][currentType][key], function (index, val) {
                if (vertical[0] != val) {
                    vertical.push(val);
                }
                //console.log(val);
            });
        });
        counterType = 0;
    } else {
        counterType += 1;
    }

    window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType);
    document.title = currentClient + " | " + currentType;

    if (vertical.length == 1) {
        $('.navTB').hide();
    } else {
        $('.navTB').show();
    }

}

function getContent(next) {

    lenCurrent = vertical.length;

    if (next) {
        if (currentImgV == lenCurrent - 1) {
            currentImgV = 0;
            $('.container').html(vertical[currentImgV]);
        } else {
            currentImgV += 1;
            $('.container').html(vertical[currentImgV]);
        }
        console.log(currentImgV);
        console.log(lenCurrent);
    } else {
        if (currentImgV == 0) {
            currentImgV = lenCurrent - 1;
            $('.container').html(vertical[currentImgV]);
        } else {
            currentImgV -= 1;
            $('.container').html(vertical[currentImgV]);
        }
        console.log(currentImgV);
        console.log(lenCurrent);
    }

    currentImgH = 0;
    currentType = $('.container').children().data('type');

    if (currentClient != $('.container').children().data('client')) {
        horizontal = [];
        currentClient = $('.container').children().data('client');
        horizontal.push(contentGlobal[pageGlobal][currentType][currentClient][counterClient]);
        $.each(contentGlobal[pageGlobal], function(key) {
            if (contentGlobal[pageGlobal][key][currentClient] !== undefined) {
                $.each(contentGlobal[pageGlobal][key][currentClient], function(index, val) {
                    if (horizontal[0] != val) {
                        horizontal.push(val);
                        //console.log(contentGlobal[key][currentClient][0]);
                    }
                });
            }
        });
        counterClient = 0;
    } else {
        counterClient += 1;
    }

    if (trueKey) {
        window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType + "/" + locKeyword);
        document.title = currentClient + " | " + currentType;
    } else if (pageGlobal != currentType){
        window.history.pushState(currentClient + " | " + currentType, currentClient + " | " + currentType, "/" + pageGlobal + "/" + currentClient + "/" + currentType);
        document.title = currentClient + " | " + currentType;
    } else {
        window.history.pushState(currentType, currentType, "/" + pageGlobal);
        document.title = currentType;
    }

    if (horizontal.length == 1) {
        $('.navLR').hide();
    } else {
        $('.navLR').show();
    }

}<|endoftext|>


<commit_before>/*global angular, DocumentTouch*/

(function () {
  'use strict';

  var magnify = angular.module('ngMagnify', []);

  magnify.directive('ngMagnify', function () {
    return {
      restrict: 'EA',
      replace: true,
      template: '
' +
                  '

' +
                  '' +
                '
',
      scope: {
        imageSrc: '@',
        imageWidth: '=',
        imageHeight: '=',
        glassWidth: '=',
        glassHeight: '='
      },
      link: function (scope, element) {
        var glass = element.find('div'),
          image = element.find('img'),
          el, nWidth, nHeight, magnifyCSS;

        // if touch devices, do something
        if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
          return;
        }
        element.on('mouseenter', function () {
          el = angular.extend(scope.getOffset(element[0]), {
            width: element[0].offsetWidth,
            height: element[0].offsetHeight,
            imageWidth: image[0].offsetWidth,
            imageHeight: image[0].offsetHeight,
            glassWidth: glass[0].offsetWidth,
            glassHeight: glass[0].offsetHeight
          });
        })
        .on('mousemove', function (evt) {
          magnifyCSS = scope.magnify(evt);

          if (magnifyCSS) {
            glass.css( magnifyCSS );
          }
        })
        .on('mouseout', function () {
          glass.on('mouseleave', function () {
            glass.css({
              opacity: 0,
              filter: 'alpha(opacity=0)'
            });
          });
        });

        scope.magnify = function (evt) {
          var mx, my, rx, ry, px, py, bgp, img;

          if (!nWidth && !nHeight) {
            img = new Image();
            img.onload = function () {
              nWidth = img.width;
              nHeight = img.height;
            };
            img.src = scope.imageSrc;
          } else {
            // IE8 uses evt.x and evt.y
            mx = (evt.pageX) ? (evt.pageX - el.left) : evt.x;
            my = (evt.pageY) ? (evt.pageY - el.top) : evt.y;

            if (mx < el.width && my < el.height && mx > 0 && my > 0) {
              glass.css({
                opacity: 1,
                'z-index': 1,
                filter: 'alpha(opacity=100)'
              });
            } else {
              glass.css({
                opacity: 0,
                'z-index': -1,
                filter: 'alpha(opacity=0)'
              });
              return;
            }

            rx = Math.round(mx/el.imageWidth*nWidth - el.glassWidth/2)*-1;
            ry = Math.round(my/el.imageHeight*nHeight - el.glassHeight/2)*-1;
            bgp = rx + 'px ' + ry + 'px';

            px = mx - el.glassWidth/2;
            py = my - el.glassHeight/2;

            return { left: px+'px', top: py+'px', backgroundPosition: bgp };
          }
          return;
        };

        scope.getOffset = function (el) {
          var offsetLeft = 0,
            offsetTop = 0;

          while (el) {
            if (!isNaN(el.offsetLeft)) {
              offsetLeft += el.offsetLeft;
              offsetTop += el.offsetTop;
            }
            el = el.offsetParent;
          }

          return {
            left: offsetLeft,
            top: offsetTop
          };
        };

        scope.getContainerStyle = function () {
          return {
            width: (scope.imageWidth) ? scope.imageWidth + 'px' : '',
            height: (scope.imageHeight) ? scope.imageHeight + 'px' : ''
          };
        };

        scope.getGlassStyle = function () {
          return {
            background: 'url(' + scope.imageSrc + ') no-repeat',
            width: (scope.glassWidth) ? scope.glassWidth + 'px' : '',
            height: (scope.glassHeight) ? scope.glassHeight + 'px' : ''
          };
        };
      }
    };
  });
})();
<commit_msg>fix getOffset() to take into account user scrolling via window page offset<commit_after>/*global angular, DocumentTouch*/

(function () {
  'use strict';

  var magnify = angular.module('ngMagnify', []);

  magnify.directive('ngMagnify', function () {
    return {
      restrict: 'EA',
      replace: true,
      template: '
' +
                  '

' +
                  '' +
                '
',
      scope: {
        imageSrc: '@',
        imageWidth: '=',
        imageHeight: '=',
        glassWidth: '=',
        glassHeight: '='
      },
      link: function (scope, element) {
        var glass = element.find('div'),
          image = element.find('img'),
          el, nWidth, nHeight, magnifyCSS;

        // if touch devices, do something
        if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
          return;
        }
        element.on('mouseenter', function () {
          el = angular.extend(scope.getOffset(element[0]), {
            width: element[0].offsetWidth,
            height: element[0].offsetHeight,
            imageWidth: image[0].offsetWidth,
            imageHeight: image[0].offsetHeight,
            glassWidth: glass[0].offsetWidth,
            glassHeight: glass[0].offsetHeight
          });
        })
        .on('mousemove', function (evt) {
          magnifyCSS = scope.magnify(evt);

          if (magnifyCSS) {
            glass.css( magnifyCSS );
          }
        })
        .on('mouseout', function () {
          glass.on('mouseleave', function () {
            glass.css({
              opacity: 0,
              filter: 'alpha(opacity=0)'
            });
          });
        });

        scope.magnify = function (evt) {
          var mx, my, rx, ry, px, py, bgp, img;

          if (!nWidth && !nHeight) {
            img = new Image();
            img.onload = function () {
              nWidth = img.width;
              nHeight = img.height;
            };
            img.src = scope.imageSrc;
          } else {
            // IE8 uses evt.x and evt.y
            mx = (evt.pageX) ? (evt.pageX - el.left) : evt.x;
            my = (evt.pageY) ? (evt.pageY - el.top) : evt.y;

            if (mx < el.width && my < el.height && mx > 0 && my > 0) {
              glass.css({
                opacity: 1,
                'z-index': 1,
                filter: 'alpha(opacity=100)'
              });
            } else {
              glass.css({
                opacity: 0,
                'z-index': -1,
                filter: 'alpha(opacity=0)'
              });
              return;
            }

            rx = Math.round(mx/el.imageWidth*nWidth - el.glassWidth/2)*-1;
            ry = Math.round(my/el.imageHeight*nHeight - el.glassHeight/2)*-1;
            bgp = rx + 'px ' + ry + 'px';

            px = mx - el.glassWidth/2;
            py = my - el.glassHeight/2;

            return { left: px+'px', top: py+'px', backgroundPosition: bgp };
          }
          return;
        };

        scope.getOffset = function (_el) {
          var de = document.documentElement;
          var box = _el.getBoundingClientRect();
          var top = box.top + window.pageYOffset - de.clientTop;
          var left = box.left + window.pageXOffset - de.clientLeft;
          return { top: top, left: left };
        };

        scope.getContainerStyle = function () {
          return {
            width: (scope.imageWidth) ? scope.imageWidth + 'px' : '',
            height: (scope.imageHeight) ? scope.imageHeight + 'px' : ''
          };
        };

        scope.getGlassStyle = function () {
          return {
            background: 'url(' + scope.imageSrc + ') no-repeat',
            width: (scope.glassWidth) ? scope.glassWidth + 'px' : '',
            height: (scope.glassHeight) ? scope.glassHeight + 'px' : ''
          };
        };
      }
    };
  });
})();
<|endoftext|>