var Feedback = {
	'submitForm': function(f) {
		
		$.post('user.htm', $(f).serialize() );
		alert('Thank you for your feedback.');
		this.toggle();
		f.feedback.value = '';
	},
	'toggle': function() {
		$('#feedback_container').toggle();
		if ($('#feedback_container').css('display') != 'none' ) {
			window.scrollTo(0, WindowInfo.getPageY());
		}
	}
}


var Spot = {
    'getCategories': function(){
        var idArray = [];
        $('#category_list li').each(function(i){
            idArray.push(this.id.replace('category_', ''));
        });
        return idArray;
    },
    'getEngines': function(categoryId){
        var idArray = [];
        $('#' + categoryId + '_list li').each(function(i){
            idArray.push(this.id.replace(/^engine_[0-9]+_/, ''));
        });
        return idArray;
    },
	'initialize': function() {  
		/*$('#category_list li').each( function(i) {
			this.onmouseover = function() {  
				this.className += ' hover';  
			};  
			this.onmouseout = function() {  
				this.className = this.className.replace(' hover', '');  
			}  
		}); */
	},
    'showCategory': function(categoryId){
        $('.category_table .list ul').hide();
        $('#' + categoryId + '_list').show();
        $('#category_list li').each(function(i){
            this.className = 'hand';
        });
        $('#category_' + categoryId)[0].className = 'hand current';
        
        document.search_form.c.value = categoryId;
        
        if (this.categoryMemory['category_' + categoryId] !== undefined) {
            var selectedId = this.categoryMemory['category_' + categoryId];
            if ($('#radio_' + categoryId + '_' + selectedId)[0]) {
                $('#radio_' + categoryId + '_' + selectedId)[0].checked = true;
				this.selectEngine(categoryId, selectedId);
            }
        }
        else {
            if ($('#' + categoryId + '_list input')[0]) {
                $('#' + categoryId + '_list input')[0].checked = true;
				this.selectEngine(categoryId, $('#' + categoryId + '_list input')[0].id.replace(/^radio_[0-9]+_/,'') );
            }
        }
    },
    'selectEngine': function(categoryId, value){
        this.categoryMemory['category_' + categoryId] = value;
		Cookie.set('last_engine', categoryId + ',' + value, 1);
    },
	'toggleNav': function() {
		$('.nav .content').toggle();
		if (this.toggleNavMemory == 0) {
			this.toggleNavMemory = 1;
			$("#cl_container").load("ajax_cl.htm", null, function(responseText, textStatus, XMLHttpRequest) {
				if (Spot.cl) document.options_form.cl.value = Spot.cl;
			});
			
		}
	},
	'toggleNavMemory': 0,
    'categoryMemory': {}
}



var SpotEdit = {
    'removeCategory': function(categoryId){
        if ($('#category_' + categoryId)) {
            $('#category_' + categoryId).slideUp('fast', function(){
                $('#category_' + categoryId).remove();
                SpotEdit.saveCategories();
		        var nodes = Spot.getCategories();
		        if (nodes[0]) {
		            var id = nodes[0];
		            Spot.showCategory(id);
		        }				
            });
            $('#' + categoryId + '_list').remove();
			$('#top_category_checkbox_' + categoryId)[0].checked = false;
			$('#top_category_' + categoryId)[0].className = '';
        }

        
    },
    'removeEngine': function(categoryId, engineId){
        if ($('#engine_' + categoryId + '_' + engineId)) {
            $('#engine_' + categoryId + '_' + engineId).slideUp('fast', function(){
                $('#engine_' + categoryId + '_' + engineId).remove();
                var idArray = Spot.getEngines(categoryId);
                SpotEdit.saveEngines(categoryId, idArray);
            });
        }
    },
    'resetCategory': function(categoryId){
        this.saveEngines(categoryId, false, 'location = location;');
    },
    'saveEngines': function(categoryId, idArray, evalCodeWhenDone){
        var engineObject = {};
        if (Cookie.read('engines') !== false) {
            try {
                engineObject = eval('(' + Cookie.read('engines') + ')');
            } 
            catch (e) {
                engineObject = {};
            }
        }
        
        engineObject[categoryId] = idArray;
        
        engineStringArray = [];
        for (i in engineObject) {
            if (engineObject[i] !== false) 
                engineStringArray.push('"' + i + '": [ ' + engineObject[i].join(',') + ' ] ');
        }
        
        engineString = '{' + engineStringArray.join(',') + ' } ';
        
        Cookie.set('engines', engineString);
        //$('#debug').html(engineString);

		$.post('user.htm', 'post_submission=save_engines&value=' + engineString, function() {
			if (evalCodeWhenDone != null) {
				try {
					eval(evalCodeWhenDone);
				}
				catch(e) {
					
				}
			}
		} );
		
		
    },
    'saveCategories': function(){
        var idArray = Spot.getCategories();
        Cookie.set('categories', idArray.join(','))
		
		$.post('user.htm', 'post_submission=save_categories&value=' + idArray.join(',') );
    },
	'selectAll': function(f) {
		this.selectAllMemory = this.selectAllMemory == 0 ? 1 : 0;
		$('.top_category_checkbox').each(function(i) {
			this.checked = SpotEdit.selectAllMemory;
		})
	},
	'selectAllMemory' : 0,
    'sortCategories': function(){
        this.saveCategories();
    },
    'sortEngines': function(e, ui){
        var categoryId = ui.current.element.id.replace('_list', '');
        /*var node = $(ui.current.element.childNodes)[0];
        if ($('#' + node.id.replace('engine_', 'radio_'))) {
            $('#' + node.id.replace('engine_', 'radio_'))[0].checked = true;
        }*/
		Spot.showCategory(categoryId);
        
        var nodes = ui.current.element.childNodes;
        var idArray = Spot.getEngines(categoryId);
        this.saveEngines(categoryId, idArray);
    },
    'toggleCategory': function(){
        var categories = Spot.getCategories();
        
        if (this.editCategoryMemory == 1) { // turn off
            $('#edit_category_status').html('off');
            $('#edit_category_status')[0].className = 'edit_category_status_off';
            $('.remove_engine').hide();
            $('#remove_category').hide();
            this.editCategoryMemory = 0;
            for (var i = 0, j = categories.length; i < j; i++) {
                var categoryId = categories[i];
                $('#' + categoryId + '_list').sortableDestroy();
            }
            $('#category_list').sortableDestroy();
            
        }
        else { // turn on
            this.editCategoryMemory = 1;
            $('#edit_category_status').html('on');
            $('#edit_category_status')[0].className = 'edit_category_status_on';
            $('.remove_engine').show();
            $('#remove_category').show();
            var categoryId = 0;
            
            for (var i = 0, j = categories.length; i < j; i++) {
                categoryId = categories[i];
                
                $('#' + categoryId + '_list').sortable({
                    items: 'li',
                    update: function(e, ui){
                        SpotEdit.sortEngines(e, ui);
                    },
                    start: function(e, ui){
                        // cannot pass categoryId to func, get the id from ui object
                        $('.remove_engine').hide();
						$('.link_engine').hide();
						$('.rate_engine').hide();
                    },
                    stop: function(e, ui){
                        $('.remove_engine').show();
						$('.link_engine').show();
						$('.rate_engine').show();
                    }
                });
                
            }
            $('#category_list').sortable({
                items: 'li',
                update: function(e, ui){
                    SpotEdit.sortCategories(e, ui);
                }
            });
            
        }
        
        
    },
    'editCategoryMemory': 0
}




var User = {
	'rateEngine': function(id) {
		$(document.rate_form.s).show();
		document.rate_form.engine_id.value = id;
		document.rate_form.comments.value = '';
		document.rate_form.rating[2].checked = 1;
		$('#popup_rate_message').hide();
		Popup.show('popup_rate');
	},
	'rateSubmit': function(f) {
		$(document.rate_form.s).hide();
		$('#popup_rate_message').html('submitting ...');
		$('#popup_rate_message').fadeIn('fast');
		$.post('user.htm', $(f).serialize(), function(data, textStatus) {
			$('#popup_rate_message').html('thank you for your feedback');
		} );
		
	},
	'submitCategories': function(f) {
		$.post('user.htm', $(f).serialize(), function(data, textStatus){
			location = location;
		});
	},
	'submitLogin': function(f) {
		var message = '';
		if ( !_U.emailRE.test(f.email.value) ) {
			message += 'Please enter an email. \n';
		}
		if ( $.trim(f.password.value) < 4 ) {
			message += 'Please enter a password loner than 4 letters. \n';
		}
		
		if (message == '') {
			$.post('user.htm', $(f).serialize(), function(data, textStatus){
				if (data == 0) {
					$('#login_error').html('The email and password combination is invalid.');
					$('#login_error').fadeIn();
				}
				else {
					location = location;
				}
			});
		}
		else {
			$('#login_error').html(message);
			$('#login_error').fadeIn();
		}
	},
	'submitOptions': function(f) {
		var windowValue = 0;
		for (var i = 0, j = f.window_option.length; i < j; i++) {
			if (f.window_option[i].checked == true) {
				windowValue = f.window_option[i].value;
				break;
			}
		}
		
		$.post('user.htm', $(f).serialize() );
		
		
		$('#options_message').html('your choices have been saved');
		$('#options_message').fadeIn();
		
		if ( windowValue == 1) {
			document.search_form.target = '_blank';
		}
		else {
			document.search_form.target = '';
		}
	},
	'submitRegistration': function(f) {
		var message = '';
		if ( !_U.emailRE.test(f.email.value) ) {
			message += 'Please enter an email. \n';
		}
		if ( $.trim(f.password.value) < 4 ) {
			message += 'Please enter a password loner than 4 letters. \n';
		}
		if ( f.password.value != f.password_confirm.value ) {
			message += 'Please confirm your password. \n';
		}
		
		if (message == '') {
			$.post('user.htm', $(f).serialize(), function(data, textStatus){
				if (data == 0) {
					$('#registration_error').html('This email has already been registered.');
					$('#registration_error').fadeIn();
				}
				else {
					location = location;
				}
			});
		}
		else {
			$('#registration_error').html(message);
			$('#registration_error').fadeIn();
		}
	}
}







var _U = {
	'emailRE': /[\w-\.]+@([\w-]+\.)+/
}





/*
 var text = '';
 for (i in e) {
 text += i + ' ' + e[i] + '\\n';
 }
 alert(text);*/

