'use strict';

function getViewerURL(fileUrl) {
    return chrome.extension.getURL('viewer/viewer.html') + '?file=' + encodeURIComponent(fileUrl);
}

function isRtfFile(details) {
    var contentType = details.responseHeaders.find(function(element){
        if(element.name.toLowerCase() === 'content-type'){
            return element;
        }
        return false;
    });

    if (contentType) {
        return (contentType.value === 'application/rtf' ||
            contentType.value === 'text/rtf' ||
            (contentType.value.indexOf('text/plain') > -1 && details.url.endsWith('.rtf')));
    }
}

chrome.webRequest.onHeadersReceived.addListener(
    function(details) {
        if (!isRtfFile(details)) {
            return;
        }
        return { redirectUrl: getViewerURL(details.url) };
    },
    {
        urls: ['<all_urls>'],
        types: ['main_frame', 'sub_frame']
    },
    ['blocking','responseHeaders']
);

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        return { redirectUrl: getViewerURL(details.url) };
    },
    {
        urls: ['ftp://*/*.rtf'],
        types: ['main_frame', 'sub_frame']
    },
    ['blocking']
);

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        return { redirectUrl: getViewerURL(details.url) };
    },
    {
        urls: ['file://*/*.rtf'],
        types: ['main_frame', 'sub_frame']
    },
    ['blocking']
);
@@ -143,16 +143,163 @@
 rl);%0A%7D%0A%0A
+function contentTypeContains(contentType, string)%7B%0A    if(contentType.value.indexOf(string) %3E -1)%7B%0A        return true;%0A    %7D%0A    return false;%0A%7D%0A%0A
 function
@@ -316,24 +316,24 @@
 (details) %7B%0A
-
     var cont
@@ -568,26 +568,37 @@
 tentType
-.value ===
+Contains(contentType,
  'applic
@@ -603,24 +603,25 @@
 ication/rtf'
+)
  %7C%7C%0A        
@@ -639,18 +639,29 @@
 Type
-.value ===
+Contains(contentType,
  'te
@@ -667,16 +667,17 @@
 ext/rtf'
+)
  %7C%7C%0A    
@@ -696,31 +696,38 @@
 tentType
-.value.indexOf(
+Contains(contentType, 
 'text/pl
@@ -731,21 +731,16 @@
 /plain')
- %3E -1
  && deta

make contentType validation more robust