/**
 * This code was originally created by http://www.qloud.com/. Some of the code might have been added or changed.
 * You can view the original source here: http://www.qloud.com/js/Model/Request.js
 */

// JavaScript Document
function Request(cReff, url)
{
	var d = new Date();
	var mill=new Date(3001, 00, 01, 00, 00, 00)
	d = mill - d;
	var selfobj=this;  //reference to itself  
    //we create the XMLHttpRequest object.
	this.xmlRequestObject = null;
	this.urlString = url;
	if (this.urlString.lastIndexOf("process-favorite-tracks.php") != -1)
	{
		if (this.urlString.lastIndexOf("?") == -1) {
			this.urlString += "?tnow=" + d;
		}
		else {
			this.urlString += "&tnow="+ d;		
		}
	}
	this.callerReff = cReff;	
	this.reqMethod="GET";
	this.managerIndex=null;	
	this.rqStatus=Request.STATUS_IDLE;	
	this.startTime = 0;
	this.stopTime = 0;
	this.postData = "";

	
	/**
	*@param string ("GET" | "POST")
    *@desc set the method used for the request (GET/POST)
    */
    this.setRequestMethod=function(meth)
	{
        this.reqMethod=meth;
    }
    
    this.getRequestMethod=function()
    {
        return this.reqMethod;
    }
    
    /**
	*@param string     The url for the HTTP request
    *@desc set URL for the HTTP request
    */
    this.setURL=function(urlS)
    {
        this.urlString=urlS;    
    }
    
    this.getURL=function()
    {
        return this.urlString;
    }
    
    this.setPostData=function(data)
    {
        this.postData=data;    
    }
    
    this.getURL=function()
    {
        return this.postData;
    }
    
    /**
	* @desc Stop the current request
	*/
	this.abort = function ()
	{
		if(this.getReqStatus()==Request.STATUS_BUSY)
		{
            selfobj.xmlRequestObject.abort();
            this.setReqStatus(Request.STATUS_IDLE);
            if (Config.debug && _e("loading_debug") && _e("loading_debug_text"))
            {
            	if (!RequestManager.getInstance().activeRequests>0)
            	{
            		_e("loading_debug").style.visibility = "hidden";
            	}
            	_e("loading_debug_text").innerHTML=RequestManager.getInstance().activeRequests+" active requests";
            }
        }
	}	
	
	/**
	*@desc Starts the request, this is where the request is actually made to the server
	*@return boolean
	*/
	this.start = function ()
	{
		if(this.getReqStatus() == Request.STATUS_IDLE)
		{
            this.setReqStatus(Request.STATUS_BUSY)
            this.getHTTPObject();
            if (this.reqMethod=="POST")
            {

				selfobj.xmlRequestObject.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
				
            	selfobj.xmlRequestObject.send(this.postData);
            }
            else
            {
            	selfobj.xmlRequestObject.send(null);
            }
            RequestManager.getInstance().activeRequests++;
            selfobj.startTime=getUniqueValue();
            if (Config.debug && _e("loading_debug") && _e("loading_debug_text"))
            {
//            	RequestManager.getInstance().activeRequests++;
            	if (RequestManager.getInstance().activeRequests>0)
            	{
            		_e("loading_debug").style.visibility = "visible";
            	}
            	_e("loading_debug_text").innerHTML=RequestManager.getInstance().activeRequests+" active requests";
            }
            return true;
        }
        return false;
	}
	
	
	/**
	*@param number     See the constants of this class
    *@desc set the status of this request
    */
	this.setReqStatus=function (status)
	{
        this.rqStatus=status;
    }
    this.getReqStatus=function()
	{
        return this.rqStatus;
    }
    
    /**
	*@param number     The index from the que of the RequestManager
    *@desc set the index from the que of the RequestManager
    */
    this.setManagerIndex=function(index)
    {
        this.managerIndex=index;
    }
    this.getManagerIndex=function()
    {
        return this.managerIndex;
    }
	
	/**
	* @desc this function will return an instance to a new created XMLHttpRequest object
	* @return object
	*/
	this.getHTTPObject = function () 
	{ 
		if(selfobj.xmlRequestObject==null)
		{
            var xmlhttp; 
    		// IE7 supports native XMLHttpRequest, try to use that first
    		if (typeof XMLHttpRequest != 'undefined') 
    		{ 
    			try 
    			{ 
    				xmlhttp = new XMLHttpRequest(); 
    			} 
    			catch (e) 
    			{ 
    				xmlhttp = false; 
    			} 
    		} 
    		else
    		{
				try
				{
					xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0")
				}
				catch(e)
				{
	    			try 
    				{
						xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
					} 
					catch (e)
					{
						try
						{
							xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
						}
						catch (e){}
					}
				}
    		}
				
    		if (!xmlhttp)
    		{
    			alert("No XmlHttpRequest object could be found for your browser\nPlease use a fully supported browser (Firefox 1.0 or newer, IE6 or newer or Safari)");
    		}
    		selfobj.xmlRequestObject=xmlhttp;
		}
		
		selfobj.xmlRequestObject.open(selfobj.reqMethod, selfobj.urlString, true);				
		selfobj.xmlRequestObject.onreadystatechange = function()
        {          
		  if(selfobj.xmlRequestObject.readyState==Request.STATE_COMPLETED)
		  {
			if (selfobj.callerReff.name == "testObj"){ //final check
				
				selfobj.callerReff.handleResponse(selfobj);
				
			}
			else if (selfobj.callerReff.objType == "soundtrack"){ //objects
				
				selfobj.callerReff.handleResponse(selfobj);
				
			}
			else if (selfobj.callerReff.objType == "track"){ //objects
				
				selfobj.callerReff.handleResponse(selfobj);
				
			}				
			else if (selfobj.callerReff.objType == "artist"){ //objects
				
				selfobj.callerReff.handleResponse(selfobj);
				
			}	
			else if (selfobj.callerReff.objType == "album"){ //objects
				
				selfobj.callerReff.handleResponse(selfobj);
				
			}				
			else {
				selfobj.stopTime=getUniqueValue();
				selfobj.setReqStatus(Request.STATUS_IDLE);
				selfobj.callerReff.handleResponse(selfobj.getManagerIndex());            
				RequestManager.getInstance().activeRequests--;
				if(RequestManager.getInstance().activeRequests==0)
				{
					if(typeof RequestManager.getInstance().onAllRequestsEnd =="function")
					{
						RequestManager.getInstance().onAllRequestsEnd();
					}
				}
				if (Config.debug && _e("loading_debug") && _e("loading_debug_text"))
				{
					trace(selfobj.urlString+=": "+(selfobj.stopTime-selfobj.startTime)+"ms");
					if (!RequestManager.getInstance().activeRequests>0)
					{
						_e("loading_debug").style.visibility = "hidden";
					}            	
					_e("loading_debug_text").innerHTML=RequestManager.getInstance().activeRequests+" active requests";
				}
			}
          }
	   }
		return xmlhttp; 
	} 
	
	/**	
	* Get the error code (specific to the application) from the response 
	* @return	error code
	* @type number 
	*/
	this.getResponseErrorCode=function()
	{		
		if(selfobj.xmlRequestObject.responseText)
		{

			var rsp_arr=eval('('+selfobj.xmlRequestObject.responseText+')');
			return rsp_arr['errorCode'];
		}
		return null;
	}
	
	/**	
	*@return	string|object
	*@desc get the content from the response
	*/
	this.getResponseContent=function()
	{
		if(selfobj.xmlRequestObject.responseText)
		{
			var rsp_arr=eval('('+selfobj.xmlRequestObject.responseText+')');
			if (rsp_arr['results'] != null){
				return rsp_arr['results'];
			}
			else if (rsp_arr != null){
				return rsp_arr;
			}
			else {
				return "null";
			}
			//return rsp_arr['content'];
		}
		return "null";
	}	
}

Request.STATE_COMPLETED=4;

Request.STATUS_BUSY=1;
Request.STATUS_IDLE=2;
