/* Calendar support */

function calendar_expand(event) {
    var effects = $(this).effects({duration: 100});
    widget = $(this).getElement('a img');
    if (!widget) {
        widget = $(this).getElement('a');
        widget.getElement('span.tagline').setStyle('display','block');
    }
    var effects2 = widget.effects({duration: 100});
    effects.start({
        'top': [0,-40],
        'height': [46,125],
        'width': [125,204]
    });
    effects2.start({
        'width': [46,125],
        'height': [46,125]
    })
    this.setStyle('z-index', 100);
}

function calendar_contract(event) {
    var effects = $(this).effects({duration: 100});
    widget = $(this).getElement('a img');
    if (!widget) {
        widget = $(this).getElement('a');
        widget.getElement('span.tagline').setStyle('display','none');
    }
    var effects2 = widget.effects({duration: 100});
    effects.start({
        'top': [-40,0],
        'height': [125,46],
        'width': [204,125]
    });
    effects2.start({
        'width': [125, 46],
        'height': [125,46]
    })
    this.setStyle('z-index', 0);
}

function calendar_init() {
    $$('div.advert').each(
        function (el) {
            el.addEvent('mouseenter', calendar_expand.bindWithEvent(el))
            el.addEvent('mouseleave', calendar_contract.bindWithEvent(el))
        }
    )
}

/* Dashboard advert approval/cancel support */

current_ad_id = null;

function get_reason(advert_id) {
    current_ad_id = advert_id;
    var ad_position = $('pending_' + advert_id).getPosition();
    $('reason_popup').setStyle('top', ad_position.y);
    $('reason_popup').setOpacity(1);
}

function cancel_reason() {
    $('reason_popup').setOpacity(0);
}

function perform_reject() {
    var reason = $('reason_popup_auto_reason').getValue();
    if (reason == 'Other') {
        reason = $('reason_popup_reason').getValue();
    }
    pending_advert_action(current_ad_id, 'reject', reason);
    $('reason_popup').setOpacity(0);
}

function pending_advert_action(advert_id, action, reason) {
    /* Get div */
    var ad_box = $('pending_' + advert_id);
    /* Update box with working.. */
    ad_box.getElement('div.foot').setHTML("Working...");
    /* Do ajax call to approve/cancel */
    var request = new Json.Remote("json_advert", {
        method: 'post',
        onComplete: function (data) {
            if (data.error) {
                ad_box.getElement('div.foot').setHTML(data.error);
                return;
            }
            if (action == 'approve') {
                ad_box.getElement('div.foot').setHTML("-");
                move_advert_to_running(advert_id);
            } else {
                remove_advert_from_pending(advert_id);
            }
        },
        onFailure: function (data) {
            ad_box.getElement('div.foot').setHTML("Failed");
            return;
        }
    }).send({advert_id: advert_id, action: action, reason: reason});
}

function remove_advert_from_pending(advert_id) {
    var ad_box = $('pending_' + advert_id);
    var slide = new Fx.Slide(ad_box);
    slide.slideOut();
}

function move_advert_to_running(advert_id) {
    var ad_box = $('pending_' + advert_id);
    var clone_ad_box = ad_box.clone();
    var slide = new Fx.Slide(ad_box);
    var your_ads = $("on_your_widget");
    var trigger = function () {
            if (your_ads.getElement("div.inbox_empty")) {
                your_ads.getElement("div.inbox_empty").remove();
            }
            clone_ad_box.injectBefore($("on_your_widget_last"));
            
        };
    slide.addEvent("onComplete", trigger);
    slide.slideOut();
}


/* paid ad management */

function paid_advert_action(advert_id, action) {
    /* Get div */
    var ad_box = $('paid_' + advert_id);
    /* Update box with working.. */
    ad_box.getElement('div.foot').setHTML("Working...");
    /* Do ajax call to approve/cancel */
    var request = new Json.Remote("json_paid_advert", {
        method: 'post',
        onComplete: function (data) {
            if (data.error) {
                ad_box.getElement('div.foot').setHTML(data.error);
                return;
            }
            if (action == 'approve') {
                remove_paid_from_pending(advert_id);
            } else {
                remove_paid_from_pending(advert_id);
            }
        },
        onFailure: function (data) {
            ad_box.getElement('div.foot').setHTML("Failed");
            return;
        }
    }).send({advert_id: advert_id, action: action});
}

function remove_paid_from_pending(advert_id) {
    var ad_box = $('paid_' + advert_id);
    var slide = new Fx.Slide(ad_box);
    slide.slideOut();
}



/* Dropped detection for cards */

function highlight_dropped() {
    $$('a.entrecard_only').each(
        function (el) {
            ecard_user_id = el.getProperty('ecard_id');
            if (ecard_user_id && (ecard_user_id.toInt() in entrecard_dropped_cards)) {
                el.getParent().getParent().addClass('dropped_on');
            }
        }
    )
}
window.addEvent('domready', function() { highlight_dropped(); });

entrecard_user_balance = null;
entrecard_dropped_cards = [];

function update_balance(uid) {
    var request = new Json.Remote("/user/" + uid + "/get_balance?rand=" + (Math.random()*100000) , {
        method: 'GET',
        onComplete: function (data) {
            entrecard_user_balance = data['balance'];
            entrecard_dropped_cards = data['dropped_cards'];
            $('user_balance').innerHTML = data['email'] + ' (<a href="/user/' + uid + '/switch">switch</a>), ' + data['balance'] + "ec (<small><a href=\"/r/buy_credits\">buy more</a></small>), " + data['drops'] + " drops";
            
            if ($('chat_status')) {
                if (data['chat_status'] == "open") {
                    $('chat_status').innerHTML = '<a href="/page/chat">Chat is currently open</a>';
                } else {
                    $('chat_status').innerHTML = '<span>Chat is currently closed</span>';
                }
            }
        }}).send()
}

function render_details_rss(card_id) {
    var request = new Json.Remote("/details/" + card_id + "/rss",
        {
            onComplete: function(data) {
                var rss = data['rss'];
                var result = '<div class="rss_feed"><h4>Most recent posts</h4>';
                for (var i=0; i<rss.length; i++) {
                    result += '<div class="entry"><span class="date">' + rss[i].date + '</span><a href="' + rss[i].link + '">' + rss[i].title + '</a></div>';
                }
                result += '</div>';
                $('rss_content').innerHTML = result;
            }
        }).send();
}

function render_details_rss_init(card_id) {
    window.addEvent('domready', function() { render_details_rss(card_id); });
}

function inbox_filter_set(mode) {
    if (mode == "all") {
        $('inbox_filter').selectedIndex = 0;
        dropped_display = "block";
        undropped_display = "block";
    } else if (mode == "dropped") {
        $('inbox_filter').selectedIndex = 1;
        dropped_display = "block";
        undropped_display = "none";
    } else if (mode == "undropped") {
        $('inbox_filter').selectedIndex = 2;
        dropped_display = "none";
        undropped_display = "block";
    }
    
    $$('div.browse_ecard').each(
        function (el) {
            if (el.hasClass("dropped")) {
                el.setStyle('display', dropped_display);
            } else {
                el.setStyle('display', undropped_display);
            }
        }
    )
    
    Cookie.set('entrecard_inbox_filter', mode);
}

function inbox_filter_change() {
    inbox_filter_set($('inbox_filter').getValue());
}

function inbox_filter_init() {
    /* Get cookie for current inbox filter setting */
    var filter_mode = Cookie.get('entrecard_inbox_filter');
    if (!filter_mode) {
        filter_mode = "all";
    }
    window.addEvent('domready', function() { inbox_filter_set(filter_mode) });
}

var ec_cookie = Cookie.get('entrecard');
var ec_user_id = 0;
var ec_user = {};

if (ec_cookie) {
    /* Get user details from cookie */
    ec_user_id = ec_cookie.split('|')[0];
    if (ec_user_id == 'delete') {
        ec_user_id = 0;
    } else {
        if (!ec_user_id || ((ec_user_id+'') == 'undefined')) {
            ec_user_id = 0;
        } else {
            window.addEvent('domready', function() { update_balance(ec_user_id); });
        }
    }
}


function generate_menu() {
    /* Generate the menu html */
    var result = "";
    
    if (ec_user_id) {
        menu = Array(
            Array( 'Dashboard', '/user/' + ec_user_id + '/', '/user/\d+/(?!statistics|widget_code)'),
            Array( 'Get code', '/user/' + ec_user_id + '/widget_code', 'widget_code'),
            Array( 'Campaign', '/category/', 'category|recent|popular|lowest_wait|recommended|favorites|nearest|unseen'),
            Array( 'Market', '/market/', 'market'),
            Array( 'Blog', '/blog/', '/blog'),
            Array( 'Forums', '/forums/', '/forums/'),
            Array( 'Statistics', '/user/' + ec_user_id + '/statistics', 'statistics'),
            Array( 'Help', '/docs/', '/docs')
        );
    } else {
         menu = Array(
            Array( 'Login', '/login', '/login'),
            Array( 'Signup', '/signup', '/signup'),
            Array( 'Browse', '/category/', 'category|recent|popular|lowest_wait|recommended|favorites|nearest|unseen'),
            Array( 'Market', '/market/', 'market'),
            Array( 'Blog', '/blog/', '/blog'),
            Array( 'Forums', '/forums/', '/forums/'),
            Array( 'Help', '/docs/', '/docs')
        )
    }
    for (i=0; i<menu.length; i++) {
        var item_class = "";
        try {
            var regex = new RegExp( menu[i][2] );
            var results = regex.exec( top.window.location.href );
            if (results) {
                item_class = "selected";
            }
        } catch (e) {}
        result += '<li class="menuitem"><a target="_top" class="' + item_class + '" href="' + menu[i][1] + '">' + menu[i][0] + '</a></li>';
    }
    return result;
}

function generate_details() {
    var result = "";
    
    if (ec_user_id) {
        /* Get user details from cookie */
        result = 'Welcome <span id="user_balance"></span> <a href="/logout">Logout</a>';
    } else {
        result = '<form style="display: inline" method="post" action="/login">Email: <input type="text" name="email_address" /> Password: <input type="password" name="password" /><input type="submit" value="Login" /></form><form style="display: inline; margin-left: 10px;" method="get" action="/signup"><input type="submit" value="Signup" /></form>';
    }
    return result;
}

function generate_category_tabs() {
    /* Generate the menu html */
    var result = "";
    
    menu = Array(
        Array( 'By Category', '/category/', '/category/$|/category/browser\\?category='),
        Array( 'Popular', '/category/browser?order_by=popular', '/category/browser\\?order_by=popular'),
        Array( 'New', '/category/browser?order_by=newest', '/category/browser\\?order_by=newest'),
        Array( 'Cheap', '/category/browser?order_by=cheapest', '/category/browser\\?order_by=cheapest'),
        Array( 'Random', '/category/browser?order_by=random', '/category/browser\\?order_by=random'),
        Array( 'Search', '/category/browser', '/category/browser$')
    );
    
    if (ec_user_id) {
        user_menu = Array(
        );
    } else {
        user_menu = Array();
    }
    
    menu = menu.concat(user_menu);
    
    for (i=0; i<menu.length; i++) {
        var item_class = "";
        try {
            var regex = new RegExp( menu[i][2] );
            var results = regex.exec( window.location.href );
            if (results) {
                item_class = "selected";
            }
        } catch (e) {}
        result += '<li class="' + item_class + '"><a href="' + menu[i][1] + '">' + menu[i][0] + '</a></li>';
    }
    return result;
}

function generate_advert_link(user_id) {
    if (ec_user_id) {
        return '<a href="/user/' + ec_user_id + '/advertise?seller_id=' + user_id + '">Advertise</a>';
    }
    return '<a href="/signup">Advertise</a>';
}