/*!
 * @author Stephen Clay <steve@mrclay.org>
 * @copyright Copyright (c) 2012
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * Requires jQuery and element with id="street-view-link-widget" on the page.
 */
$(function () {
    $('#street-view-link-widget').each(function () {
        function embedToLink(embed, removeQuery) {
            embed = embed.match(/src="([^"]+)"/);
            if (embed) {
                embed = embed[1].replace(/\&amp;/g, '&').replace(/\&(?:source|output)=\w*/g, '');
                if (removeQuery) {
                    embed = embed.replace(/\&(?:q|oq)=[^\&]*/g, '');
                }
            }
            return embed;
        }
        $(this).html('<input value="paste embed HTML..."><br><input type="checkbox" checked> remove query<br><button>Convert</button> <span></span>');
        var i = $('input:first', this).css({color: '#999', width: '98%'}).
            one('focus', function() {
                $(this).css({color: '#000'}).val('');
            })[0],
            that = this;
        $('button', this).click(function () {
            var r = embedToLink(i.value, $('input[type="checkbox"]', that)[0].checked);
            i.value = r ? r : '';
            i.select();
            i.focus();
            $('span', that).html(r ? 'Success! <a target="_blank" href="#">Open in new window</a>' : ':( Conversion failed.');
            if (r) {
                $('a', that)[0].href = r;
            }
        });
    });
});
