

// ---------------------------- APIRequest Object -------------------------------------------------------------- //
//
//
//      Creates a Request Object that connects to the Yola JSON APIs
//
//
// ---------------------------- APIRequest Object -------------------------------------------------------------- //


    function APIRequest(args){

        args = args || {}

        this.post = args.post || {};
        this.onSuccess = args.success || function(){};
        this.onFailure = args.failure || function(){};
        this.url = args.url || {};
        this.async = args.async || {};

        this.send();
       
    }

    APIRequest.prototype = {

        abort : function(){
            
            try{
                if(this.xhr && this.xhr.abort){                             
                    if(this.readyState != 4){
                        this.xhr.abort();
                    }
                }else{
                    this.aborted = true;
                }               
            }catch(err){
                this.aborted = true;
            }
            
        },

        send : function(post){
            
            var self = this;
            
            if(!this.url || String(this.url).trim() == ""){
                
                this.onFailure({
                    code: 1, 
                    response : {
                        message : "NO API URL SPECIFIED"
                    }
                });
                
                return;
                
            }
            
            if(post) this.post = post;

            var scope = this;
            
            var startTime = new Date().valueOf();

            this.xhr = new XHR();
                
            this.xhr.onreadystatechange = function(){

                var xhr = self.xhr;
                
                self.readyState = xhr.readyState;
                
                if(xhr == null || xhr.readyState != 4) return;
                
                if(self.aborted == true) return;
                
                var endTime = new Date().valueOf();
                var response;
                                    
                switch(xhr.status){
                    
                    case 0:
                    
                        return;
                    
                    break;
                    
                    case 200: // success

                        try{ // Attempt to parse JSON response

                            response = eval("(" + xhr.responseText + ")");
                            
                            if(response.code && response.code == 1){
                                
                                response.systemError = true;
                                
                            }
                            
                        }catch(err){
                            
                            response = {
                                code: 1,
                                response : {
                                    message : "JSON CONVERSION FAILED - INVALID RESPONSE TEXT: " + err,
                                    detail : "RESPONSE TEXT:\n\n " + xhr.responseText 
                                } 
                            };
                        
                        }
                        break;

                    
                    case 12002: // trap for IE errors
                    case 12007:
                    case 12029:
                    case 12030:
                    case 12031:
                    case 12152:
                    case 12159:

                    default: // handle any other error
                    
                        try{
                        
                            var temp = xhr.statusText;
                        
                        }catch(everything){
                            
                            xhr = {
                                getAllResponseHeaders : function(){
                                    return "nothing";
                                }
                            };
                        
                        }
                    
                        response = {
                            code : 1,
                            response : {
                                message : xhr.statusText,
                                detail : xhr.responseText
                            }                       
                        };
                        
                }
                
                response.post = scope.post;
                
                response.url = scope.url;
                
                response.httpStatus = xhr.status;
                
                response.responseHeaders = xhr.getAllResponseHeaders();
                
                response.duration = endTime - startTime;
                
                if(!response.systemError){
                    
                    response.systemError = false;
                    
                }
                
                if(scope.validateSuccess(response, scope.suppressErrorReporting, scope.suppressErrors)){
                
                    try{
                
                        if(response.response){
                            scope.onSuccess(response.response);
                        }else{
                            scope.onSuccess(null);
                        }
        
                    }catch(everything){
                        
                        alert(everything.description)
                        
                    };
                
                }else{                      
            
                    switch(response.code){
                        
                        default :

                            scope.onFailure(response);
                        
                        break;
                        
                    }
                    
                }
                
            };
            
            this.xhr.open("POST", this.url, this.async);
            
            this.xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8;");
            
            // make sure we have a string
            if(String(typeof(this.post)).toLowerCase() != "string"){
                
                this.post = this.post.toJSON();
                
            }
            
            // get the length of the string and set the appropriate header
            this.xhr.setRequestHeader("Content-Length", this.post.length);

            this.xhr.send(this.post);

        },
        
        onSuccess : function(){},
        
        onFailure : function(response){},
        
        validateSuccess : function(response){

            switch(response.code){
            
                case 0 : // Success             
                    return true;
                break;
                
                default : // Any Other Error
                    return false;
                break;
            
            }

        }

    };


// ---------------------------- APIRequest Object -------------------------------------------------------------- //
    
    /**
     * 
     * XHR Object
     * 
     * @param {Object} post
     * 
     * @return Object 
     *   
     */
    function XHR(){
        try{
            return new XMLHttpRequest();
        }catch(tryMicrosoft){
            try{
                return new ActiveXObject("Msxml2.XMLHTTP");
            }catch(tryOtherMicrosoft){          
                try{
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }catch(failed){
                    alert("Error initializing XHR Object!");
                    return null;
                }           
            }       
        }       
    }

    