var ajax_utils = {}
ajax_utils.data = []

ajax_utils.get_message_handler = function ( message_container, timeout ) {
	
	var message_container = message_container,
		sticky_messages = [],
		expiring_messages = [],
		timeout = timeout,
		timer = {};
	//var is_timer_running = false;
	
	function write_out () {
	
		var html = '';
		
		sticky_messages.concat( expiring_messages ).forEach( function ( message ) {
		
			html += "<div>";
			html += message;
			html += "</div>";
			
		});
	
		message_container.innerHTML = html;
	
	}
	
	return {
	
		add_sticky_message : function ( message ) {
		
			sticky_messages.push( message );
			
			write_out();
			
			message_container.setStyle( 'display', 'block' );
			
		},
		
		add_expiring_message : function ( message ) {
		
			expiring_messages.push( message );
			
			write_out();
			
			this.pop_expiring_messages(false); // do not pop the first time
			
			//if ( !is_timer_running ) {
			//	this.timerId = setTimeout ( this.pop_expiring_messages, timeout );
			//}
			
			message_container.setStyle( 'display', 'block' );
			
		},
		
		pop_expiring_messages : function (do_pop) {
		
			//console.log( expiring_messages );
			
			if (expiring_messages.length > 0) {
				
				if (do_pop) {
				
					expiring_messages.shift();
					
					if ( expiring_messages.length === 0 ) {
						if( sticky_messages.length === 0 ) {
				    		message_container.setStyle( 'display', 'none' );
						}
					}
					
					write_out();
				}
				
				if( this.timerId )
				    this.timerId = setTimeout( this.pop_expiring_messages, timeout, true ); // next time, do pop
				
			} else {
				
				clearTimeout(this.timerId);
				delete this.timerId;
				//is_timer_running = false;
				
			}

			
		},
		
		clear : function () {
		
			sticky_messages = [];
			expiring_messages = [];
			
			if (this.timerId !== undefined) {
				clearTimeout(this.timerId);
			}
			
			write_out();
			
			message_container.setStyle( 'display', 'none' );
		}
		
	
	}

}

ajax_utils.get_page_link = function ( n, is_current,  change_page) {
    
    var link;
    
    if( is_current ){
    
        link = new Element( 'span', { 'html' : '<'+n+'>' } );
    
    }else{
        
        link = new Element( 'a', { 'href' : '#', 'html' : n } );
        
        link.addEvent( 'click', function (e) {
            
            e.stop();
            change_page( n );
        
        } );
    
    }

    return link;
    
};

ajax_utils.stripslashes = function (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
};

/* 
Function: $get 
    This function provides access to the "get" variable scope + the element anchor 
 
Version: 1.3 
 
Arguments: 
    key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor) 
    url - url; optional; the url to check for "key" in, location.href is default 
 
Example: 
    >$get("foo","http://example.com/?foo=bar"); //returns "bar" 
    >$get("foo"); //returns the value of the "foo" variable if it's present in the current url(location.href) 
    >$get("#","http://example.com/#moo"); //returns "moo" 
    >$get("#"); //returns the element anchor if any, but from the current url (location.href) 
    >$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:'bar',bar:'foo'} 
    >$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:'bar',bar:'foo',hash:'moo'} 
    >$get(); //returns same as above, but from the current url (location.href) 
    >$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href) 
 
Returns: 
    Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any) 
    Returns "" if the variable is not present in the given query string 
 
Credits: 
        Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url] 
        Function by Jens Anders Bakke, webfreak.no 
*/  
ajax_utils.$get = function (key,url){  
    if(arguments.length < 2) url =location.href;  
    if(arguments.length > 0 && key != ""){  
        if(key == "#"){  
            var regex = new RegExp("[#]([^$]*)");  
        } else if(key == "?"){  
            var regex = new RegExp("[?]([^#$]*)");  
        } else {  
            var regex = new RegExp("[?&]"+key+"=([^&#]*)");  
        }  
        var results = regex.exec(url);  
        return (results == null )? "" : results[1];  
    } else {  
        url = url.split("?");  
        var results = {};  
            if(url.length > 1){  
                url = url[1].split("#");  
                if(url.length > 1) results["hash"] = url[1];  
                url[0].split("&").each(function(item,index){  
                    item = item.split("=");  
                    results[item[0]] = item[1];  
                });  
            }  
        return results;  
    }  
};  

ajax_utils.generate_option = function ( value, label, selected ){

    var opt = new Element( 'option', {
    
        value : value,
        html : label
    
    } );
    
    if ( selected )
        opt.set( 'selected', 'true' );
    
    return opt;

};

ajax_utils.ophelia_request = function( page, action, params, callback, error_handler, error_callback ){

    new Request.JSON({
    
        url : ajax_utils.generateUrl( page, action ),
        onComplete: function ( response ) {
        
            if( response.err ){
            
                response.err.forEach( function( e ){
                
                    error_handler.add_sticky_message( e );
                
                } );
                
                if( error_callback ){
                
                    error_callback();
                
                }
            
            }else{
            
              callback( response.data );  
            
            }
        
        }
        
    }).post( { params : JSON.encode( params ) } );

}