var contenttargeting = {
    hover_selected_topic: function(selected_topic_id) {
        var el = $('#' + selected_topic_id);
        el.css({background: '#ffffcc', border: '1px solid #ccccff'}); 
        el.children('div.remove-icon').css('display', 'block');
    },
    
    unhover_selected_topic: function(selected_topic_id) {
        var el = $('#' + selected_topic_id);
        el.css({background: 'white', border: '1px solid white'});
        el.children('div.remove-icon').css('display', 'none');
    },
    
    hover_selected_site: function(selected_site_id) {
        var el = $('#' + selected_site_id);
        el.css({background: '#ffffcc', border: '1px solid #ccccff'}); 
        el.children('div.remove-icon').css('display', 'block');
    },
    
    unhover_selected_site: function(selected_site_id) {
        var el = $('#' + selected_site_id);
        el.css({background: 'white', border: '1px solid white'});
        el.children('div.remove-icon').css('display', 'none');
    },
    
    site_click: function(target_id) {
        var site_id = target_id.substr('id_site_'.length, target_id.length);
        var target_div = $('#' + target_id);
        var site_name = target_div.find('a').text();
        
        if ($('#selected-sites input[@value=' + site_name +']').get().length)
            return;
        
        var get_site_name = function(el) {
            var name = $(el).find('.site_name').text();
            return name;
        };
        
        var existing_divs = $('#selected-sites').children('.selected_site');
        
        var last_greater = -1;
        
        for (var i = 0; i < existing_divs.length; i++) {
            if (site_name > get_site_name(existing_divs.get()[i])) {
                last_greater = i;
            }
        }
        
        var template = '<div class="selected_site" id="selected_site_${site_id}" style="border: 1px solid white;" ' +
                'onmouseover="contenttargeting.hover_selected_site(\'selected_site_${site_id}\')" onmouseout="contenttargeting.unhover_selected_site(\'selected_site_${site_id}\')">' +
                '<div class="remove-icon" title="Remove from selection"></div>' +
                '<a class="remove-link" title="Remove from selection">${site_name}</a><span style="display: none;" class="site_name">${site_name}</span>' +
            '<input type="hidden" name="selected_site" value="${site_name}"/></div>';
        
        var content = template.process({site_id: site_id, site_name: site_name});
        
        var s = '' + content;
        
        if (last_greater == -1) {
            $('#selected-sites').prepend(content);
            return false;
        }
        
        $(existing_divs.get()[last_greater]).after(content);
        return false;
    },

    topic_click: function(target_id) {
        var topic_id = target_id.substr('id_topic_'.length, target_id.length);
        var target = $('#' + target_id);
        var topic_name = target.text();
        
        var build_topic_name = function(el, pn) {
            var partial_name;
            if (!partial_name) {
                partial_name = '';
            }
            else {
                partial_name = pn;
            }
            
            var parent = $(el).parents('li.topic').get();
            
            if (!parent.length) {
                var cn = $(el).find('div.topic_div:first a.topic:first').text();
                return cn;
            }
            return build_topic_name(parent[0], partial_name) + '/' + $(el).find('div.topic_div:first a.topic:first').text();
        };
        
        var full_name = build_topic_name(target.parent().parent());
        
        var get_topic_name = function(el) {
            var name = $(el).children('.topic_name').text();
            return name;
        }
        
        var selected_topics = $('#selected-topics .selected_topic').get();
        for (var i = 0; i < selected_topics.length; i++) {
            if (full_name == get_topic_name(selected_topics[i]))
                return;
        }
        
        
        if (true) {
            var template = '<div class="selected_topic" id="selected_topic_${topic_id}" style="border: 1px solid white;" ' +
                    'onmouseover="contenttargeting.hover_selected_topic(\'selected_topic_${topic_id}\')" onmouseout="contenttargeting.unhover_selected_topic(\'selected_topic_${topic_id}\')">' +
                    '<div class="remove-icon" title="Remove from selection"></div>' +
                    '<a class="remove-link" title="Remove from selection">${full_name}</a><span style="display: none;" class="topic_name">${full_name}</span>' +
                '<input type="hidden" name="selected_topic" value="${topic_id}"/></div>';
            
            var content = template.process({topic_id: topic_id, full_name: full_name});
                
            if (!($('#selected-topics div.selected_topic').get().length)) {
                $('#selected-topics').append(content);
                return false;
            }
            
            var inserted = false;
            
            var elements = $('#selected-topics div.selected_topic').get()
            
            var last_lesser = 0;
            
            last_lesser = -1;
            for (var i = 0; i < elements.length; i++) {
                var element = elements[i];
                var name = get_topic_name(element);
                if (full_name > name)
                {
                  last_lesser = i;
                  if (last_lesser >= elements.length) {
                    last_lesser = elements.length - 1;
                  }
                }
            }
            
            last_lesser += 1;
            if (last_lesser >= elements.length) {
            }
            
            var last_element = elements[elements.length - 1];
            if (full_name > get_topic_name(last_element)) {
                $(last_element).after(content);
            }
            else {
                $(elements[last_lesser]).before(content);
            }
        }
        return false;
      },
      
    remove_selected_topic: function(event) {
        event.preventDefault();
        var el = $(this).parent();
        var next = el.next();
        el.remove();
        if (next.length){
            var next_id = next.get()[0].id;
            contenttargeting.hover_selected_topic(next_id);
        }
    },
    
    remove_selected_site: function(event) {
        event.preventDefault();
        var el = $(this).parent();
        var next = el.next();
        el.remove();
        if (next.length){
            var next_id = next.get()[0].id;
            contenttargeting.hover_selected_site(next_id);
        }
    },
    
    hover_topic: function(topic_id){
        $('#' + topic_id).css('background', '#ffffcc').css('border', '1px solid #ccccff'); 
        $('#' + topic_id + ' .add-topic').css('display', 'block');
        return true; 
    },
    
    unhover_topic: function(topic_id){
        $('#' + topic_id).css('background', 'white').css('border', '1px solid white'); 
        $('#' + topic_id + ' .add-topic').css('display', 'none');
        return true; 
    },
    
    hover_site: function(site_id){
        var el = $(document.getElementById(site_id));
        el.css('background', '#ffffcc').css('border', '1px solid #ccccff'); 
        el.find('.add-site').css('display', 'block');
        return true; 
    },
    
    unhover_site: function(site_id){
        var el = $(document.getElementById(site_id));
        el.css('background', 'white').css('border', '1px solid white'); 
        el.find('.add-site').css('display', 'none');
        return true; 
    },
    
    get_topics_str: function(){
        var topics = [];
        var topic_spans = $('.selected_topic .topic_name').get();
        
        for (var i = 0; i < topic_spans.length; i++){
            topics.push($(topic_spans[i]).text());
        } 
        
        var topics_str = topics.join('\r\n');
        return topics_str;
    },
    
    get_sites_str: function(){
        var sites = [];
        var site_spans = $('.selected_site .site_name').get();
        
        for (var i = 0; i < site_spans.length; i++){
            sites.push($(site_spans[i]).text());
        } 
        
        var sites_str = sites.join('\r\n');
        return sites_str;
    },
    
    init: function(){
        debug.log('contenttargeting.init: started');

        if (!$('#topic_search_result').css('overflow-y')) {
            $('#topic_search_result').css('overflow', 'scroll');
            $('#selected-objects').css('overflow', 'scroll');
        }
    
        $('div.selected_topic a.remove-link').livequery('click',
            contenttargeting.remove_selected_topic);
        
        $('div.selected_topic div.remove-icon').livequery('click',
            contenttargeting.remove_selected_topic);
        
        $('div.selected_site a.remove-link').livequery('click',
            contenttargeting.remove_selected_site);
        
        $('div.selected_site div.remove-icon').livequery('click',
            contenttargeting.remove_selected_site);
            
        $('#content-form').submit(function(event){
            var topics_str = contenttargeting.get_topics_str();
            
            var field_str = '<textarea style="display: none;" cols="30" rows="10" name="topics" class="vLargeTextField" id="id_topics">${topics}</textarea>'.process({topics: topics_str});
            $('#content-form').append(field_str);
            
            var sites_str = contenttargeting.get_sites_str();
            var field_str = '<textarea style="display: none;" cols="30" rows="10" name="manual_sites" class="vLargeTextField" id="id_manual_sites">${sites}</textarea>'.process({sites: sites_str});
            $('#content-form').append(field_str);
        });

        debug.log('bound events');
        
        var last_value = null;
        var ajax_request = null;
        var data_present = false;
        
        var update_topics = function() {
            debug.log('contenttargeting.update_topics: started');
            var query = $('#topic_search_query').get()[0].value;
            debug.log('query: "' + query + '"')
            if (query != last_value) {
                debug.log("that's something new");
                last_value = query;
                if (ajax_request) {
                    ajax_request.abort();
                    debug.log('aborted current request')
                    ajax_request = null;
                }
                debug.log("displaying 'loading...' message");
                $('#topic_search_result').html('<div class="topic-search-loading">Loading...</div>');
                debug.log('done');
                ajax_request = $.ajax({
                    type: 'POST',
                    url: '/ajax/topicsearch/',
                    data: {query: query},
                    timeout: 60000,
                    success: function(data){
                        debug.log('ajax success');
                        data_present = true;
                        $('#topic_search_result').html(data);
                        debug.log('search results updated');
                        ajax_request = null;
                    },
                    error: function(){
                        debug.log('ajax error');
                        ajax_request = null;
                        if (!data_present) {
                            $('#topic_search_result').html('');
                            debug.log('search results cleared');
                        }
                    }
                });
                debug.log('ajax request sent');
            };
        };
        
        var timeout_handler = setTimeout(update_topics, 500);
        debug.log('timeout set');
        
        $('#topic_search_query').keyup(function(){
            debug.log('#topic_search_query keyup');
            if (timeout_handler != null) {
                clearTimeout(timeout_handler);
                debug.log('timeout cleared');
            }
            if (ajax_request) {
                ajax_request.abort();
                debug.log('request aborted');
                ajax_request = null;
            }
            timeout_handler = setTimeout(update_topics, 500);
            debug.log('new timeout set');
        });
    },
    toggle_topic: function(topic_id){
        var hitarea = $('#' + topic_id);
        var topic_div = hitarea.parent();
        var topic_ul = topic_div.parent().children('.ul-container');
        var collapsable = $.className.has(topic_div.get(0).className, 'collapsable');
        
        var toggle_classes = function() {
            topic_div.toggleClass('collapsable').toggleClass('expandable');
            if (collapsable) {
                hitarea.attr('title', 'Expand topic');
            }
            else {
                hitarea.attr('title', 'Collapse topic');
            }
        };
        
        if (collapsable) {
            topic_ul.hide();
        }
        else {
            topic_ul.show();
        }
        toggle_classes();
    }
};

$(document).ready(contenttargeting.init);

