$(document).ready(function() {
    // enable fancybox for viewing css for style
    $('.post_css_link').fancybox({
        'width': '75%',
        'height': '75%'
    });
    
    // initialize height for css-containers
    $('.post_css').css('height', $(window).height() * 0.75);
    $('.post_css').css('width', $(window).width() * 0.75);
    
    // tipsy for post comment links
    $('.post_comment').tipsy({
        delayIn: 500,
        gravity: 's'
    });
    
    // tipsy for user avatars
    $('.user_avatar a').tipsy({
        gravity: 's'
    });
    
    // initialize prettyprint (for syntax highlighting)
    prettyPrint();
    
    // initialize zeroclipboard
    initZero();
    
    initFavoriteLinks();

    initFeatureLinks();
    
    initInstallation();
});


// Copy to clipboard
//
function initZero() {
    ZeroClipboard.setMoviePath(SITE_URL + 'public/swf/ZeroClipboard.swf');
        
    $('.post_copy_link').each(function() {
        $this = $(this);
        var css = $this.closest('.post').find('.stylebot_install_div').html();
        var clip = new ZeroClipboard.Client();
        clip.setText(css);
        var html = clip.getHTML(110, 20);
        $this.append(html);
        // return the keyboard focus back to document
        $this.bind('mouseup', function(e) {
            this.focus();
            // prepend some text
            $(this).closest('.post_css_header').find('.post_copy_status').text('Copied!');
        });
        $this.click(function(e) {
            e.preventDefault();
        });
    });
}


// Favorites

function initFavoriteLinks() {
    $('.post_star').click(function(e) {
        e.preventDefault();
        $this = $(this);
        if ($this.hasClass('disabled'))
            return;
        if ($this.hasClass('favorited'))
            unfavorite($this);
        else
            favorite($this);
    })

    .tipsy({
        gravity: 's',
        delayIn: 500
    });
}

function favorite($el) {
    
    $el
    .addClass('favorited')
    .attr('title', 'Remove as favorite');
    
    // increment favorite count
    var $post = $el.closest('.post');
    var $count_el = $post.find('.post_likes_count');
    var current_count = parseInt($count_el.text());
    
    $count_el
    
    .text(current_count + 1);
    
    // send request
    $.post(SITE_URL + 'style/favorite', { id: $post.attr('id').substring(4) }, function(data) {});
}

function unfavorite($el) {
    
    $el
    .removeClass('favorited')
    .attr('title', 'Add as favorite');
    
    // decrement favorite count
    var $post = $el.closest('.post');
    var $count_el = $post.find('.post_likes_count');
    var current_count = parseInt($count_el.text());

    $count_el
    .text( current_count - 1 );
    
    // send request
    $.post(SITE_URL + 'style/unfavorite', { id: $post.attr('id').substring(4) }, function(data) {});
}

function initFeatureLinks() {
    $('.post_feature_link').click(function(e) {
        e.preventDefault();

        $this = $(this);

        if ($this.hasClass('featured'))
            unfeature($this);

        else
            feature($this);
    })
    
    .tipsy({
        gravity: 's',
        delayIn: 500
    });
}

function feature($el) {
    var $post = $el.closest('.post');

    $el
    .addClass('featured')
    .attr('title', 'Remove as featured')
    .text('UF');
    
    // send request
    $.post(SITE_URL + 'style/feature', { id: $post.attr('id').substring(4) }, function(data) {});
}

function unfeature($el) {
    var $post = $el.closest('.post');
    
    $el
    .removeClass('featured')
    .attr('title', 'Add as featured')
    .text('F');
    
    // send request
    $.post(SITE_URL + 'style/unfeature', { id: $post.attr('id').substring(4) }, function(data) {});
}

// Installation process

function initInstallation() {
    // setup tipsy
    $('.post_userscript_link')
    .tipsy({
        gravity: 's',
        delayIn: 500
    });
    
    // the communication channels between the extension and stylebot social
    var $channels = $('.stylebot_install_div');
    
    // bind the listeners
    $channels
    
    // stylebot is installed
    .bind('stylebotIsAvailableEvent', function(e) {
        
        // initialize install links (converting userscript links into install links)
        
        $('.post_userscript_link')
        
        .removeClass('post_userscript_link')
        
        .addClass('post_install_link')
        
        .bind('click', install)

        .text('Install')

        .attr('title', 'Install style in Stylebot');
    })

    // installation was successful
    .bind('stylebotInstallationSuccessfulEvent', onInstallSuccess)
    
    // installation failed
    .bind('stylebotInstallationErrorEvent', onInstallFail)
    
    // style already exists
    .bind('stylebotStyleExistsEvent', onStyleExists);
}

// install style in stylebot
function install(e) {
    e.preventDefault();
    
    var $target = $(e.target);

    // link is disabled? return
    if ($target.hasClass('disabled'))
        return;
    
    // get the communication channel div between stylebot extension and site
    var channel = $target.closest('.post').find('.stylebot_install_div').get(0);

    // send out request to stylebot
    sendInstallMessage(channel);
}

// Installation was successful
function onInstallSuccess(e) {
    var $link = $(e.target).closest('.post').find('.post_install_link');
    
    $link
    
    .text("Installed!")
    
    .attr('title', 'Style installed in stylebot')
    
    .addClass('disabled');
}

// Installation failed
function onInstallFail(e) {
    var $link = $(e.target).closest('.post').find('.post_install_link');
    
    $link
    
    .text("CSS Syntax Error")
    
    .addClass('disabled');
}

// Style already exists for the URL. Display warning
function onStyleExists(e) {
    var site = $(e.target).closest('.post').find('.post_site').text();
    displayInstallationWarning(e.target, site);
}


// display the overwrite warning message
function displayInstallationWarning(channel, site) {
    var $msg = $("<div>", {
        className: 'warning'
    });
    
    $("<div>", {
        html: "You have an existing style for <strong>'" + site + "'</strong>. This will overwrite it. <br><br>Do you want to continue installing?"
    })
    .appendTo($msg);
    
    var buttons = $("<div>", {
        className: 'actions'
    });
    
    // yes button
    $("<input>", {
        type: 'button',
        value: 'Yes',
        className: 'warning_button',
        style: 'margin-right: 10px',
        tabIndex: 1
    })
    .click(function(e) {
        $.fancybox.close();
        sendOverwriteMessage(channel);
    })
    .appendTo(buttons);
    
    // no button
    $("<input>", {
        type: 'button',
        className: 'warning_button',
        value: 'No',
        tabIndex: 2
    })
    .click(function(e) {
        $.fancybox.close();
    })
    .appendTo(buttons);
    
    $msg.append(buttons);
    
    $.fancybox({
        content: $msg,
        modal: true,
        speedIn: 0,
        speedOut: 0,
        transitionIn: 'none',
        transitionOut: 'none',
        padding: 0
    });
}

function sendOverwriteMessage(channel) {
    var customEvent = document.createEvent('Event');
    customEvent.initEvent('stylebotOverwriteEvent', true, true);
    channel.dispatchEvent(customEvent);
}

function sendInstallMessage(channel) {
    var customEvent = document.createEvent('Event');
    customEvent.initEvent('stylebotInstallEvent', true, true);
    channel.dispatchEvent(customEvent);
}
