jQuery(document).ready(function()
{
    jQuery('form#cc_kaktus_discussion input[type="text"]:first').focus();
    jQuery('#content-text div.content').rot13();
    
    href = window.location.href;
    if (href.match(/www.ihmistulva.fi\/#.+$/))
    {
        hash = window.location.hash;
        
        if (hash)
        {
            hash = hash.replace(/#/, '');
            href = href.replace(/#.+/, '');
            
            jQuery.post(
                href + 'hash/' + hash + '/'
            );
        }
    }
    
    jQuery('#facebook_link').click(function()
    {
        if (jQuery('#facebook_clicktrack').size() == 0)
        {
            jQuery('<input type="hidden" />')
                .attr({
                    id: 'facebook_clicktrack',
                    name: 'facebook_click',
                    value: 1
                })
                .insertAfter(jQuery(this));
        }
        
        return true;
    });
    
    jQuery('#tell_a_friend_name').keyup(function(e)
    {
        var value = jQuery(this).attr('value');
        
        // Only spaces or nothing at all
        if (value.match(/^\s*$/))
        {
            return;
        }
        
        // Get the previous value
        var rel = jQuery(this).attr('rel');
        
        // ...and if it wasn't found, use the default
        if (!rel)
        {
            rel = 'Neiti X';
        }
        
        // Create a new regular expression and replace the previously entered name
        var regexp = new RegExp(rel);
        var content = jQuery('#tell_a_friend_message').attr('value');
        content = content.replace(regexp, value);
        jQuery('#tell_a_friend_message').attr('value', content);
        
        // Store the current name here
        jQuery(this).attr('rel', jQuery(this).attr('value'));
        
        return true;
    });
    
    jQuery('a.thickbox').attr('target', '_self');
    
    jQuery('#tell_a_friend')
        .keypress(function(e)
        {
            switch (e.which)
            {
                case 0:
                case 8:
                case 13:
                case 32:
                case 64:
                    var text = jQuery(this).attr('value');
                    var count = Number(jQuery(this).attr('rel'));
                    
                    if (!count)
                    {
                        count = 0;
                    }
                    
                    var i = 0;
                    while (text.match(/@/)
                        && i < 100)
                    {
                        text = text.replace(/@/, '');
                        i++;
                    }
                    
                    var diff = i - count;
                    jQuery('#points').add_points(diff * 2);
                    jQuery(this).attr('rel', i);
            }
            return true;
        });
    

    // Prevent enter from submitting the form
    jQuery('#tell_a_friend_backend input.text')
        .keypress(function(e)
        {
            switch (e.which)
            {
                case 13:
                    jQuery(this).parents('div.login_form').find('a.fetch').click();
                    return false;
            }
            return true;
        })
        .focus(function()
        {
            jQuery(this).parents('form').submit(function()
            {
                return false;
            });
        })
        .blur(function()
        {
            jQuery(this).parents('form').unbind('submit');
        });
    
    jQuery('#tell_a_friend_backend').css({display: 'block'});
    jQuery('#tell_a_friend_backend').find('input[name="backend_username"]')
        .focus(function()
        {
            value = jQuery(this).attr('value');
            
            if (value.match(/^@/))
            {
                jQuery(this).attr('value', '');
                jQuery(this).attr('rel', value);
            }
        })
        .blur(function()
        {
            value = jQuery(this).attr('value');
            
            if (!value)
            {
                jQuery(this).attr('value', jQuery(this).attr('rel'));
                return;
            }
            
            if (!value.match(/@[a-z0-9\.\-_]+\.([a-z0-9])/i))
            {
                value += jQuery(this).attr('rel');
                jQuery(this).attr('value', value);
            }
        });
    
    jQuery('#tell_a_friend_backend ul li').click(
        function()
        {
            var backend = jQuery(this).attr('rel');
            
            if (   !backend
                || jQuery(this).hasClass('toggle'))
            {
                return;
            }
            
            jQuery(this).addClass('toggle');
            jQuery(this).oneTime(500, function()
            {
                jQuery(this).removeClass('toggle');
            });
            
            if (jQuery('#tell_a_friend_backend_' + backend).css('display') == 'block')
            {
                jQuery('#tell_a_friend_backend_' + backend).css({display: 'none'});
                jQuery(this).removeClass('active');
            }
            else
            {
                jQuery('#tell_a_friend_backend_' + backend).css({display: 'block'});
                jQuery(this).addClass('active');
            }
        }
    );
    
    jQuery('#tell_a_friend_backend .fetch').click(function()
    {
        var username = jQuery(this).parents('div.backend').find('input[name="backend_username"]').attr('value');
        var password = jQuery(this).parents('div.backend').find('input[name="backend_password"]').attr('value');
        
        if (   !username
            || !password)
        {
            alert('Kirjoitathan käyttäjätunnuksesi ja salasanasi');
            return false;
        }
        
        var backend = jQuery(this).parents('div.backend').attr('rel');
        
        jQuery('#tell_a_friend_backend_' + backend).addClass('loading');
        
        jQuery.getJSON(
            MIDCOM_PAGE_PREFIX + 'midcom-exec-cc.kaktus.address/ajax.php',
            {
                backend: backend,
                username: username,
                password: password
            },
            function(data, status)
            {
                jQuery('#tell_a_friend_backend_' + backend).removeClass('loading');
                if (data.error)
                {
                    alert('Tunnistus epäonnistui');
                    return;
                }
                
                jQuery('#tell_a_friend_backend_' + backend).find('div.login_form label, div.fetch').remove();
                
                var id = 'tell_a_friend_backend_' + backend + '_table';
                
                if (jQuery('#' + id).size() != 0)
                {
                    return;
                }
                
                // Create table
                jQuery('<table></table>')
                    .attr({
                        id: id
                    })
                    .appendTo(jQuery('#tell_a_friend_backend_' + backend).find('div.login_form'));
                
                // Create search tools
                jQuery('<thead></thead>')
                        .appendTo('#' + id);
                
                /*
                jQuery('<tr class="search_tool"></tr>')
                    .appendTo(jQuery('#' + id).find('thead'));
                
                jQuery('<th colspan="3">Hae: </th>')
                    .appendTo(jQuery('#' + id).find('thead tr:last'));
                
                jQuery('<input type="text" />')
                    .keyup(function()
                    {
                        var value = jQuery(this).attr('value');
                        
                        jQuery(this).oneTime(500, function()
                        {
                            if (value != jQuery(this).attr('value'))
                            {
                                return;
                            }
                            
                            jQuery('#' + id).find('tbody tr').each(function(i)
                            {
                                if (jQuery(this).find('input[type="checkbox"]').attr('checked'))
                                {
                                    return;
                                }
                                
                                var email = jQuery(this).find('td.email').html();
                                var name = jQuery(this).find('td.name').html();
                                
                                var regexp = new RegExp(value, 'i');
                                
                                if (   email.match(regexp)
                                    || name.match(regexp))
                                {
                                    jQuery(this).css('display', 'table-row');
                                } 
                                else
                                {
                                    jQuery(this).css('display', 'none');
                                }
                            });
                        });
                    })
                    .appendTo(jQuery('#' + id).find('thead tr:last th'));
                /**/
                
                // Add select all button
                jQuery('<tr class="select_all"></tr>')
                    .appendTo(jQuery('#' + id).find('thead'));
                
                jQuery('<th></th>')
                    .addClass('checkbox')
                    .appendTo(jQuery('#' + id).find('thead tr:last'));
                
                jQuery('<input type="checkbox" />')
                    .toggle(
                        function()
                        {
                            var cc_kaktus_address_points_diff = 0;
                            
                            jQuery(this).parents('table').find('tbody input[type="checkbox"]').each(function()
                            {
                                if (!jQuery(this).attr('checked'))
                                {
                                    jQuery(this).attr({
                                        checked: 'checked',
                                        rel: 'forced'
                                    });
                                    
                                    jQuery(this).parents('tr').addClass('selected');
                                    cc_kaktus_address_points_diff += 2;
                                }
                            });
                            
                            // Change points
                            jQuery('#points').add_points(cc_kaktus_address_points_diff);
                            return true;
                        },
                        function()
                        {
                            var cc_kaktus_address_points_diff = 0;
                            
                            jQuery(this).parents('table').find('tbody input[rel="forced"]').each(function()
                            {
                                if (jQuery(this).attr('rel') == 'forced')
                                {
                                    jQuery(this).attr({
                                        checked: '',
                                        rel: ''
                                    });
                                    jQuery(this).parents('tr').removeClass('selected');
                                    cc_kaktus_address_points_diff -= 2;
                                }
                            });
                            
                            // Change points
                            jQuery('#points').add_points(cc_kaktus_address_points_diff);
                            return true;
                        }
                    )
                    .appendTo(jQuery('#' + id).find('thead th:last'));
                /**/
                jQuery('<th></th>')
                    .html('Merkitse kaikki')
                    .click(function()
                    {
                        jQuery(this).parent().find('input[type="checkbox"]').click();
                    })
                    .css({cursor: 'pointer'})
                    .appendTo(jQuery('#' + id).find('thead tr:last'));
                
                jQuery('<th class="search_tool"> Hae » </th>')
                    .appendTo(jQuery('#' + id).find('thead tr:last'));
                
                jQuery('<input type="text" />')
                    .keyup(function()
                    {
                        var value = jQuery(this).attr('value');
                        
                        jQuery(this).oneTime(500, function()
                        {
                            if (value != jQuery(this).attr('value'))
                            {
                                return;
                            }
                            
                            jQuery('#' + id).find('tbody tr').each(function(i)
                            {
                                if (jQuery(this).find('input[type="checkbox"]').attr('checked'))
                                {
                                    return;
                                }
                                
                                var email = jQuery(this).find('td.email').html();
                                var name = jQuery(this).find('td.name').html();
                                
                                var regexp = new RegExp(value, 'i');
                                
                                if (   email.match(regexp)
                                    || name.match(regexp))
                                {
                                    jQuery(this).css('display', 'table-row');
                                } 
                                else
                                {
                                    jQuery(this).css('display', 'none');
                                }
                            });
                        });
                    })
                    .prependTo(jQuery('#' + id).find('thead tr:last th:last'));
                
                // Show results
                jQuery('<tbody></tbody>')
                        .appendTo('#' + id);
                
                var cc_kaktus_address_counter = 1;
                
                jQuery.each(data, function(email, name)
                {
                    jQuery('<tr></tr>')
                        .click(function()
                        {
                            var points = 2;
                            
                            if (jQuery(this).find('input[type="checkbox"]').attr('checked'))
                            {
                                jQuery(this).find('input[type="checkbox"]').attr('checked', '');
                                jQuery('#points').add_points(-1 * points);
                                jQuery(this).removeClass('selected');
                            }
                            else
                            {
                                jQuery(this).find('input[type="checkbox"]').attr('checked', 'checked');
                                jQuery('#points').add_points(points);
                                jQuery(this).addClass('selected');
                            }
                        })
                        .addClass('row_' + cc_kaktus_address_counter)
                        .appendTo(jQuery('#' + id).find('tbody'));
                    
                    cc_kaktus_address_counter++;
                    
                    jQuery('<td></td>')
                        .addClass('checkbox')
                        .appendTo(jQuery('#' + id).find('tbody tr:last'));
                    
                    jQuery('<input type="checkbox" />')
                        .css({display: 'none'})
                        .attr({
                            name: 'backend_email[]',
                            value: email
                        })
                        .appendTo(jQuery('#' + id).find('tbody tr:last td.checkbox'));
                    
                    jQuery('<td></td>')
                        .addClass('name')
                        .html(name)
                        .appendTo(jQuery('#' + id).find('tbody tr:last'));
                    
                    jQuery('<td></td>')
                        .addClass('email')
                        .html(email)
                        .appendTo(jQuery('#' + id).find('tbody tr:last'));
                });
            }
                
        );
        
        return false;
    });
    
    jQuery('.youtube a').each(function()
    {
        var href = jQuery(this).attr('href');
        
        if (   !href
            || href.match(/(\?|&)width=/))
        {
            return;
        }
        
        var rel = jQuery(this).attr('rel');
        
        if (   rel
            && (regs = rel.match(/embed:([0-9a-f]+)/)))
        {
            var href = '/embed/' + regs[1] + '/';
            jQuery(this).attr('rel', '');
        }
        
        if (href.match(/\?/))
        {
            href += '&';
        }
        else
        {
            href += '?';
        }
        
        if (jQuery(this).find('span.width').size() > 0)
        {
            width = jQuery(this).find('span.width').html();
        }
        else
        {
            width = 425;
        }
        
        if (jQuery(this).find('span.height').size() > 0)
        {
            height = jQuery(this).find('span.height').html();
        }
        else
        {
            height = 344;
        }
        
        href += 'width=' + width + '&height=' + height;
        jQuery(this).attr('href', href);
    });
    
    jQuery('#calendar_widget').month_loader();
    
    jQuery('#points div.points').css('height', 0);
    jQuery('#points div.points span.points').css('display', 'none');
    
    jQuery('#points').hover(
        function()
        {
            jQuery(this).find('div.points').addClass('hover');
            jQuery(this).addClass('mouseover');
        },
        function()
        {
            jQuery(this).removeClass('mouseover');
            jQuery(this).oneTime(1000, function()
            {
                if (jQuery(this).hasClass('mouseover'))
                {
                    return;
                }
                
                jQuery(this).find('div.points').removeClass('hover');
            });
        }
    );
    
    jQuery('#points').add_points(0, 500);
});

jQuery.fn.month_loader = function()
{
    jQuery(this).find('thead a').click(function()
    {
        var href = jQuery(this).attr('href');
        
        if (href.match(/\?/))
        {
            href += '&';
        }
        else
        {
            href += '?';
        }
        
        href += 'ajax';
        
        jQuery(this).parents('table').parent().fadeTo(250, 0.25);
        
        jQuery(this).parents('table').parent().load(href, {}, function()
        {
            jQuery(this).month_loader();
            jQuery(this).fadeTo(250, 1.0);
        });
        
        return false;
    });
    
    jQuery('#participate_with_friends, #spread_the_word, #facebook_invite_friends').change(function()
    {
        if (previous = Number(jQuery(this).attr('rel')))
        {
            var diff = Number(jQuery(this).attr('value')) - previous;
        }
        else
        {
            var diff = Number(jQuery(this).attr('value'));
        }
        
        // Store the previous value
        jQuery(this).attr('rel', Number(jQuery(this).attr('value')));
        
        jQuery('#points').add_points(diff * 8);
    });
    
    jQuery('div.participate input[type="checkbox"]').each(function()
    {
        if (!jQuery(this).attr('checked'))
        {
            return;
        }
        
        jQuery(this).parents('li').find('div.actions').css({display: 'block'});
    });
    
    jQuery('div.participate input[type="checkbox"]')
        .click(function()
        {
            var value = Number(jQuery(this).attr('value'));
            
            if (jQuery(this).attr('checked'))
            {
                jQuery('#points').add_points(value, 500);
                jQuery(this).parents('li').find('div.actions').css({display: 'block'});
                jQuery(this).parents('li').addClass('active');
            }
            else
            {
                jQuery('#points').add_points(-1 * value, 500);
                
                if (jQuery(this).hasClass('main'))
                {
                    jQuery(this).parents('li').find('div.actions').css({display: 'none'});
                    jQuery(this).parents('li').removeClass('active');
                }
            }
        });
        
    jQuery('div.participate .read-more a').click(function()
    {
        if (jQuery(this).hasClass('process'))
        {
            return;
        }
        
        if (jQuery(this).parents('li').find('div.content').css('display') == 'block')
        {
            jQuery(this).parents('li').find('div.content').css({display: 'none'});
        }
        else
        {
            jQuery(this).parents('li').find('div.content').css({display: 'block'});
        }
        
        jQuery(this).addClass('process');
        jQuery(this).oneTime(500, function()
        {
            jQuery(this).removeClass('process');
        });
        
        return false;
    });
}

jQuery.fn.add_points = function(points, speed)
{
    if (jQuery(this).find('div.points').is(':animated'))
    {
        return;
    }
    
    var current = Number(jQuery('#points div.points span.points').html());
    var total = current + points;
    
    if (!speed)
    {
        speed = 1000;
    }
    
    jQuery(this).find('div.points span.points')
        .css('display', 'block')
        .html(String(total));
    
    if (total > 176)
    {
        total = 176;
    }
    
    if (total < 0)
    {
        total = 0;
    }
    
    jQuery(this).find('span.points').stopTime();
    
    // Animation queue
    jQuery(this).find('div.points')
        .animate(
            {
                height: total + 'px'
            },
            speed,
            function()
            {
                jQuery(this).find('span.points').oneTime(3000, function()
                {
                    if (jQuery(this).parents('div.hover').size() == 0)
                    {
                        jQuery(this).hide(1000);
//                        jQuery(this).css('display', 'none');
                    }
                    else
                    {
                        jQuery(this).css('display', 'block');
                    }
                });
            }
        );
}

jQuery.fn.rot13 = function()
{
    jQuery(this).find('a').each(function(i)
    {
        var html = jQuery(this).html();
        
        var href = jQuery(this).attr('href');
        if (!href.match(/mailto:/))
        {
            return;
        }
        
        if ((regs = html.match(/([0-9a-z\.\-]+@)/i)))
        {
            tmp_rot13 = rot13(regs[1]);
            regexp = new RegExp(regs[1]);
            tmp = html.replace(regexp, tmp_rot13);
            
            if (html != tmp)
            {
                jQuery(this).html(tmp);
            }
        }
        
        if ((regs = href.match(/mailto:([0-9a-z\.\-]+@)/i)))
        {
            tmp_rot13 = rot13(regs[1]);
            regexp = new RegExp(regs[1]);
            tmp = href.replace(regexp, tmp_rot13);
            
            if (href != tmp)
            {
                jQuery(this).attr('href', tmp);
            }
        }
    });
}

var last="";
var rot13map;

function rot13init()
{
    var map = new Array();
    var s = "abcdefghijklmnopqrstuvwxyz";
    for (i = 0; i < s.length; i++)
    {
        map[s.charAt(i)] = s.charAt((i+13)%26);
    }
    
    for (i=0; i<s.length; i++)
    {
        map[s.charAt(i).toUpperCase()]	= s.charAt((i+13)%26).toUpperCase();
    }
    
    return map;
}

function rot13(a)
{
    if (!rot13map)
    {
        rot13map=rot13init();
    }
    
    s = "";
    for (i=0; i<a.length; i++)
    {
        var b = a.charAt(i);
        s += (b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' ? rot13map[b] : b);
    }
    return s;
}


jQuery(function()
{
    jQuery('#orders_form').find('h1, h2').each(function(i)
    {
        jQuery('input[type="checkbox"]')
            .click(function()
            {
                if (jQuery(this).attr('checked'))
                {
                    jQuery(this).parents('div.orders_section').find('div.details').css('display', 'none');
                }
                else
                {
                    jQuery(this).parents('div.orders_section').find('div.details').css('display', 'block');
                }
            })
            .change(function()
            {
                if (jQuery(this).attr('checked'))
                {
                    jQuery(this).parents('div.orders_section').find('div.details').css('display', 'block');
                }
                else
                {
                    jQuery(this).parents('div.orders_section').find('div.details').css('display', 'none');
                }
            });
        
        if (jQuery(this).parents('div.visible').size() > 0)
        {
            jQuery(this).find('input[type="checkbox"]').attr('checked', 'checked');
            jQuery(this).parents('div.orders_section').find('div.details').css('display', 'block');
        }
    });
    
    jQuery('h1 input[type="checkbox"]').attr('checked', 'checked');
    
    jQuery('#orders_form').find('h1 a, h2 a').click(function()
    {
        jQuery(this).parent().find('input[type="checkbox"]').click();
        return false;
    });
});