// ==UserScript==
//
// If you can read this, you need to enable or install the Greasemonkey add-on for firefox
// If you are using Chrome, download this file and drag it to the extensions tab
// Other browsers, use the bookmarklet
//
// @name        CouchPotato UserScript
// @description Add movies like a real CouchPotato
// @grant       none
// @version     {{version}}

// @match       {{host}}/*
{% for include in includes %}
// @match       {{include}}{% end %}
{% for exclude in excludes %}
// @exclude     {{exclude}}{% end %}
// @exclude     {{host}}{{api.rstrip('/')}}*

// ==/UserScript==

{% autoescape None %}
if (window.top == window.self){  // Only run on top window

var version = {{version}},
    host = '{{host}}',
    api = '{{api}}';

function create() {
    switch (arguments.length) {
    case 1:
        var A = document.createTextNode(arguments[0]);
        break;
    default:
        var A = document.createElement(arguments[0]), B = arguments[1];
        for ( var b in B) {
            if (b.indexOf("on") == 0){
                A.addEventListener(b.substring(2), B[b], false);
            }
            else if (",style,accesskey,id,name,src,href,which".indexOf(","
                    + b.toLowerCase()) != -1){
                A.setAttribute(b, B[b]);
            }
            else{
                A[b] = B[b];
            }
        }
        for ( var i = 2, len = arguments.length; i < len; ++i){
            A.appendChild(arguments[i]);
        }
    }
    return A;
}

var addStyle = function(css) {
    var head = document.getElementsByTagName('head')[0],
        style = document.createElement('style');
    if (!head)
        return;

    style.type = 'text/css';
    style.textContent = css;
    head.appendChild(style);
}

// Styles
addStyle('\
    #cp_popup { font-family: "Helvetica Neue", Helvetica, Arial, Geneva, sans-serif; -moz-border-radius: 6px 0px 0px 6px; -webkit-border-radius: 6px 0px 0px 6px; border-radius: 6px 0px 0px 6px; -moz-box-shadow: 0 0 20px rgba(0,0,0,0.5); -webkit-box-shadow: 0 0 20px rgba(0,0,0,0.5); box-shadow: 0 0 20px rgba(0,0,0,0.5); position:fixed; z-index:9999; bottom:0; right:0; font-size:15px; margin: 20px 0; display: block; background:#4E5969; } \
    #cp_popup.opened { width: 492px; } \
    #cp_popup a#add_to { cursor:pointer; text-align:center; text-decoration:none; color: #000; display:block; padding:5px 0 5px 5px; } \
    #cp_popup a#close_button { cursor:pointer; float: right; padding:120px 10px 10px; } \
    #cp_popup a img { vertical-align: middle; } \
    #cp_popup a:hover { color:#000; } \
    #cp_popup iframe{ background:#4E5969; margin:6px 0 2px 6px; height:140px; width:450px; overflow:hidden; border:none; } \
');

var cp_icon = 'data:image/png;base64, ';
var close_img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAA5ElEQVR42tRTQYoEIQwsl/2Bl3gQoY9eBKEf5kvyG8G7h4Z+S38gIu5lp5lZ2R7YPm1BDhZJSFWiGmPgDj5wE7cbfD4/mBkAHprUj9yTTyn9OsGIMSLG+Fxwxc8SiAi9d4QQHskjhIDeO4jorQcq5wwiQmsN3nt479FaAxEh5zxJmyZIKalSClprL1FKQUpJXZr4DBH52xqZeRhjICKw1sJaCxGBMQbMPN41GFpriAicc6i1otYK5xxEBFrraQuThGVZAADbtp2amXms6woAOI7j0gO17/t5MN+HNfEvBf//M30NAKe7aRqUOIlfAAAAAElFTkSuQmCC';

var osd = function(){
    var navbar, newElement;

    var createApiUrl = function(url){
        return host + api + "?url=" + escape(url)
    };

    var iframe = create('iframe', {
        'src': createApiUrl(document.location.href),
        'frameborder': 0,
        'scrolling': 'no'
    });

    var popup = create('div', {
        'id': 'cp_popup'
    });

    var onclick = function(){

        // Try and get imdb url
        try {
            var regex = new RegExp(/tt(\d{7})/);
            var imdb_id = document.body.innerHTML.match(regex)[0];
            if (imdb_id)
                iframe.setAttribute('src', createApiUrl('http://imdb.com/title/'+imdb_id+'/'))
        }
        catch(e){}

        popup.innerHTML = '';
        popup.setAttribute('class', 'opened');
        popup.appendChild(create('a', {
            'innerHTML': '<img src="' + close_img + '" />',
            'id': 'close_button',
            'onclick': function(){
                popup.innerHTML = '';
                popup.appendChild(add_button);
                popup.setAttribute('class', '');
            }
        }));
        popup.appendChild(iframe)
    }

    var add_button = create('a', {
        'innerHTML': '<img src="' + cp_icon + '" />',
        'id': 'add_to',
        'onclick': onclick
    });
    popup.appendChild(add_button);

    document.body.parentNode.insertBefore(popup, document.body);

    // Auto fold open
    if(document.body.getAttribute('cp_auto_open'))
    	onclick()
};

var setVersion = function(){
    document.body.setAttribute('data-userscript_version', version)
};

if(document.location.href.indexOf(host) == -1)
    osd();
else
    setVersion();

}