WALLY = {};

WALLY.Snippet = {};
WALLY.Snippet.Create = {
    editarea_is_initialized: false,
    language_map: {},
    
    doCheckTitle: function() {
        $('#ajax_error').hide();
        $('.ajax_related').hide();
        $.getJSON('/snippet/ajaxPreAdd', { 'title': $('#snippet_title').val() },
            function(data) {
                if(data.error == 'title_null') {
                    //$('#ajax_error').html('Title was empty').fadeIn(150);
                } else if(data.error == 'title_exists') {
                    $('#ajax_error').html('A snippet already exists by this title').show(200);
                    
                    $.each(data.related, function(key, val) {
                        html = '<div class="item"><a href="/s/' + val.url_name + '/view/latest">' + val.name + '</a></div>';
                        $('.ajax_related > .related').append(html);
                    });
                    
                    $('.ajax_related').show(200);
                    
                    
                } else {
                    
                    $('.ajax_related .related').empty();
                    
                    // success
                    $.each(data.related, function(key, val) {
                        html = '<div class="item"><a href="/s/' + val.url_name + '/view/latest" target="_blank">' + val.name + '</a></div>';
                        $('.ajax_related > .related').append($(html));
                    });
                    
                    if($.makeArray(data.related).length > 0) { $('.ajax_related').show(); }
                    //$('.bottom_form').show(150);
                    //$('#top_prefill_button').hide();
                    $('#add_snippet_form').unbind('submit').submit(function() { return true; });
                    
                    // bind language change event to editarea and initialize
                    /*$('#snippet_language').bind('change', function() { 
                        if($('#snippet_language').val() != 0) {
                            //WALLY.Snippet.Create.initEditArea($('#snippet_language').val());
                            //WALLY.Snippet.Create.editareaChangeLanguage($('#snippet_language').val());
                        }
                    });*/
                    //WALLY.Snippet.Create.initEditArea();
                }
            }
        );
    },
    
    initEditArea: function() {
        
        editAreaLoader.init({
            id : "snippet_snippet",
            //syntax: WALLY.Snippet.Create.language_map[language],
            start_highlight: false,
            replace_tab_by_spaces: 4,
            allow_resize: 'y',
            
            toolbar: "search,go_to_line,fullscreen,|,undo,redo,|,change_smooth_selection,word_wrap"
        });
        
        /*if(language == false || WALLY.Snippet.Create.language_map[language] == '') { 
            // editarea is buggy when you reinit, and doesn't have a destroy function...
            // do it the hard way: remove the existing element, and replace with a new, undecorated textarea
            if(WALLY.Snippet.Create.editarea_is_initialized) {
                current_value = $('#snippet_snippet').val();
                html_textarea = '<textarea name="snippet[snippet]" id="snippet_snippet">' + current_value + '</textarea>';
                EditAreaLoader.toggle_off();
                WALLY.Snippet.Create.editarea_is_initialized = false;
            }
            
            editAreaLoader.execCommand('snippet_snippet', 'change_highlight', !editAreaLoader.execCommand('snippet_snippet', 'change_highlight'));
        } else {
            
            
            WALLY.Snippet.Create.editarea_is_initialized = true;
        }*/
    },
    
    editareaChangeLanguage: function(language) {
        //alert(language + ' - ' + WALLY.Snippet.Create.language_map[language]);
        
        if(language == false || WALLY.Snippet.Create.language_map[language] == '') {
            editAreaLoader.execCommand('snippet_snippet', 'change_highlight', false);
        } else {
            editAreaLoader.execCommand('snippet_snippet', 'change_syntax', WALLY.Snippet.Create.language_map[language]);
            editAreaLoader.execCommand('snippet_snippet', 'change_highlight', true);
        }
    }
    
};

WALLY.Snippet.Star = {
	toggleStarSnippet: function(snippet_id, revision, img_selector) {
		$(img_selector).attr('src', '/images/loading_snake.gif');
		$.getJSON('/user/ajaxToggleStarSnippet', { snippet_id: snippet_id, revision: revision }, function(data) {
			if(data.error) {
				alert('error!');
			} else {
				$(img_selector).attr('src', (data.starred ? '/images/star.png' : '/images/star_gray.png'));
			}
		});
	}
};

WALLY.UI = {
    hideGlobalMessage: function() {
        $('#head_intro_wrapper').hide();
        $.getJSON('/user/change_user_setting/ajax/hide_global_message/1', {}, function() {});
    },
    
    toggleSnippetCopyTextarea: function(id) {
    	$('#snippet_copy_wrapper_'+id).toggle();
    	$('#snippet_copy_wrapper_'+id+' textarea').select();
    },
    
    hideSnippetCopyTextarea: function(id) {
    	$('#snippet_copy_wrapper_'+id).hide();
    },
    
    toggleTagHighlight: function(options) {
    	if(options.tag_category === undefined) { return false; }
    	
    	
    	if(WALLY.UI.tag_options[options.tag_category+'_highlight'] == 1) {
    		WALLY.UI.tag_options[options.tag_category+'_highlight'] = 0;
    		$('.tag_list.tag_list_'+options.tag_category).removeClass('tag_list_colored');
    		$('#og_'+options.tag_category+'_highlight a').removeClass('og_selected');
    	} else {
    		WALLY.UI.tag_options[options.tag_category+'_highlight'] = 1;
    		$('.tag_list.tag_list_'+options.tag_category).addClass('tag_list_colored');
    		$('#og_'+options.tag_category+'_highlight a').addClass('og_selected');
    	}
    	
    	$.post('/user/change_user_setting/ajax', { setting: 'tag_display_'+options.tag_category+'_highlight', value: WALLY.UI.tag_options[options.tag_category+'_highlight'] });
    	
    	return false;
    },
    
    setTagSort: function(options) {
    	if(options.tag_category === undefined || options.sort === undefined) { return false; }
    	
    	if(options.sort == 'alpha') {
    		WALLY.UI.tag_options[options.tag_category+'_sort'] = 'alpha';
    		$('.tag_list.tag_list_'+options.tag_category+'_all .tag_list_tag').tsort();
    		$('#og_'+options.tag_category+'_sort_pop').removeClass('og_selected');
    		$('#og_'+options.tag_category+'_sort_alpha').addClass('og_selected');
    	} else if (options.sort == 'pop') {
    		WALLY.UI.tag_options[options.tag_category+'_sort'] = 'pop';
    		$('.tag_list.tag_list_'+options.tag_category+'_all .tag_list_tag').tsort({ attr: 'item_count', order: 'desc' });
    		$('#og_'+options.tag_category+'_sort_alpha').removeClass('og_selected');
    		$('#og_'+options.tag_category+'_sort_pop').addClass('og_selected');
    	} else {
    		return false;
    	}
    	
    	if(options.saveServerSide) {
    		$.post('/user/change_user_setting/ajax', { setting: 'tag_display_'+options.tag_category+'_sort', value: WALLY.UI.tag_options[options.tag_category+'_sort'] });
    	}
    	
    	return false;
    },
    
    setTagMinRank: function(options) {
    	if(options.tag_category === undefined || options.min_rank === undefined) { return false; }
    	
    	
    	if(options.min_rank == 0) {
    		$('.tag_list.tag_list_'+options.tag_category+' .tag_list_tag').show();
    	} else {
    		for(i=6; i>options.min_rank; i--) {
    			$('.tag_list.tag_list_'+options.tag_category+' .tag_list_tag_color_'+i).show();
    		}
    		
    		for(i=options.min_rank; i>=1; i--) {
    			$('.tag_list.tag_list_'+options.tag_category+' .tag_list_tag_color_'+i).hide();
    		}
    	}
    	
    	$('#og_'+options.tag_category+'_filter_'+WALLY.UI.tag_options[options.tag_category+'_min_rank']).removeClass('og_selected');
    	$('#og_'+options.tag_category+'_filter_'+options.min_rank).addClass('og_selected');
    	
    	
    	WALLY.UI.tag_options[options.tag_category+'_min_rank'] = options.min_rank;
    	
    	if(options.saveServerSide) {
    		$.post('/user/change_user_setting/ajax', { setting: 'tag_display_'+options.tag_category+'_min_rank', value: WALLY.UI.tag_options[options.tag_category+'_min_rank'] });
    	}
    	
    	return false;
    }
    
};

WALLY.UI.DropdownMenu = {
    
    menu_timeout_ms:    500,
    menu_open_timer:    null,
    menu_close_timer:   null,
    active_menu_id:     null,
    
    open: function(div_id) {
        
        if(WALLY.UI.DropdownMenu.active_menu_id != div_id) {
            WALLY.UI.DropdownMenu.closeNow();
            WALLY.UI.DropdownMenu.active_menu_id = div_id;
	        $('#' + div_id + ' .dropdown').show();
	        //$(document).bind('click', WALLY.UI.DropdownMenu.close);
	        $('#clickable_background_layer').show().click(function() { WALLY.UI.DropdownMenu.close(); });
        }
        
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .top_most').css({'background-color': '#B7C6E9'});
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .dropdown').css({'background-color': '#D8DFEA'});
        
        WALLY.UI.DropdownMenu.cancelCloseTimeout();
        WALLY.UI.DropdownMenu.menu_open_timeout = null;
    },
    
    closeNow: function() {
        if(WALLY.UI.DropdownMenu.active_menu_id) {
            $('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .dropdown').hide();
        }
        WALLY.UI.DropdownMenu.cleanup();
    },
    
    close: function() {
        if(WALLY.UI.DropdownMenu.active_menu_id) {
            $('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .dropdown').hide(150); //.css({'background-color': '#DBE1EC'});
        }
        WALLY.UI.DropdownMenu.cleanup();
    },
    
    cleanup: function() {
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .top_most').css({'background-color': '#768FCA'});
        WALLY.UI.DropdownMenu.cancelCloseTimeout();
        WALLY.UI.DropdownMenu.active_menu_id = null;
        $(document).unbind('click', WALLY.UI.DropdownMenu.close);
        $('#clickable_background_layer').hide();
    },
    
    beginCloseTimeout: function() {
        WALLY.UI.DropdownMenu.menu_close_timer = window.setTimeout(WALLY.UI.DropdownMenu.close, WALLY.UI.DropdownMenu.menu_timeout_ms);
    },
    
    cancelCloseTimeout: function() {
        if(WALLY.UI.DropdownMenu.menu_close_timer) {
            window.clearTimeout(WALLY.UI.DropdownMenu.menu_close_timer);
            WALLY.UI.DropdownMenu.menu_close_timer = null;
        }
    },
    
    bindEvents: function(div_id) {
        $('#' + div_id + ' #header_button').bind('mouseover', function() {
            //WALLY.UI.DropdownMenu.menu_open_timeout = window.setTimeout(function(){WALLY.UI.DropdownMenu.open(div_id)}, 200);
        });
        
        $('#' + div_id + ' #header_button').bind('click', function() {
            //$(document).unbind();
            WALLY.UI.DropdownMenu.open(div_id);
            //$(document).bind('click', WALLY.UI.DropdownMenu.close);
        });
        
        $('#' + div_id + ' #header_button').bind('mouseout', function() {
            if(WALLY.UI.DropdownMenu.menu_open_timeout != null) {
                window.clearTimeout(WALLY.UI.DropdownMenu.menu_open_timeout);
                WALLY.UI.DropdownMenu.menu_open_timeout = null;
            } else {
                WALLY.UI.DropdownMenu.beginCloseTimeout();
            }
        });
        
        $('#' + div_id + ' .dropdown').bind('mouseover', function() {
            WALLY.UI.DropdownMenu.cancelCloseTimeout();
        });
        $('#' + div_id + ' .dropdown').bind('mouseout', function() {
            WALLY.UI.DropdownMenu.beginCloseTimeout();
        });
    }
};

WALLY.UI.Snippet = {
    
    current_showing: false,
    
    showInline: function(id) {
		var el_snippet = $('#snippet_'+id+' .snippet_rendered');
		var el_expand = $('#snippet_'+id+' .expand_link');
		
		if(el_snippet.css('display') == 'block') {
			el_snippet.hide(100);
			//el_expand.text('+');
		} else {
			
			var el_loader = $('#snippet_'+id+' .sli_star img');
			
			var el_loader_original_src = el_loader.attr('src');
			el_loader.attr('src', '/images/loading_snake.gif');
            
            var real_url = $('#snippet_'+id+' .title_link').attr('href');
			
			el_snippet.load('/ajax_snippet', { id: id }, function() {
				el_snippet.show(100);
                // trigger google analytics
                pageTracker._trackPageview(real_url);
                                
				//el_expand.text('-');
				el_loader.attr('src', el_loader_original_src);
				
			});
		}
    }
};

WALLY.UI.Activity = {
	showInline: function(revision_id, snippet_id, rev1, rev2) {
		
		el_rendered = $('#act_item_'+revision_id+' .diff_rendered');
		el_expand = $('#act_item_'+revision_id+' .expand_link');
	
		if(el_expand.text() == '-') {
			el_rendered.hide(100);
			el_expand.text('+');
		} else {
			el_rendered.load('/ajax_diff', { id: snippet_id, revision1: rev1, revision2: rev2  }, function() {
				el_rendered.show(100);
				el_expand.text('-');
			});
		}
	}
};