/************************************************************
** FaucetPVR Javascript library
** 
** Author: Luca Restagno
** 
** Libarary required
** webtoolkit.base64.js // for base64 encoding
** prototype.js // for the JSON support
**
** Faucet API Specification:
** http://www.vcast.it/TestS/?xml=api_specification.xml
**
** Usage:
** Faucet.method( [arguments] )
**
*************************************************************/

var Faucet = {
      
      // your proxy URL
      _proxy : "faucet_proxy.php",
      
      _AuthCode : "",
      
      getAuthorizationCode : function( user , password ) {
        var auth_code = Base64.encode( user + ':' + password )
        this._AuthCode = auth_code
        return auth_code
      },
      
      setAuthorizationCode : function( code ) {
        this._AuthCode = code
      },
      
      getRecordingsList : function( ) {
        var xhr = new XHR();
        xhr.open("GET", this._proxy+"?req=get_rec_list&authcode="+this._AuthCode ,false);
        xhr.send("");
        if(xhr.readyState  == 4){
          if(xhr.status  == 200){
              var code = parseHttpResponse(xhr.responseText)
              if(code == 200){
                return retrieveJSONfromHttpResponse( xhr.responseText )
              }
              else if(code  == 401){
                return "Unauthorized"
              }
          }
        }
      },
      
      /**********************************
      ** JSON object example
      **   {
      **    "from_time":"2008-02-04 11:00:00",
      **    "ch_name":"Mtv",
      **    "to_time":"2008-02-04 12:30:00",
      **    "ch_type":"video",
      **    "retention":"3",
      **    "repeat":"no_repeat",
      **    "format":"ipod",
      **    "title":"Into the music"
      **    }
      **
      ** The allowed value for the different field are:
      ** ch_type can be 'audio', 'video'
      ** format can be 'ipod', 'psp', '3gpp', 'divx', 'mp3', 'oggvorb', 'appletv'
      ** repeat can be 'no_repeat', 'daily', 'weekly', 'mon_fri', 'mon_sat'
      **
      **********************************/
      setRecordItem : function (from_time, ch_name, to_time, ch_type, retention, repeat, format, title){
        var JSONobj = {
                        "from_time":from_time,
                        "ch_name":ch_name,
                        "to_time":to_time,
                        "ch_type":ch_type,
                        "retention":retention,
                        "repeat":repeat,
                        "format":format,
                        "title": title
                      };
        var xhr = new XHR();
        xhr.open("POST", this._proxy+"?req=record&authcode="+this._AuthCode,false);
        xhr.send(Object.toJSON(JSONobj));
        if(xhr.readyState  == 4){
            xhr.responseText
            if(xhr.status  == 200){
              var code = parseHttpResponse(xhr.responseText)
              if(code == 201)
                return "Created"
              else if(code == 401)
                return "Unauthorized"
              else if(code == 400)
                return "Bad request"
            }
        }
      },
      
      deleteRecordItem : function ( id_rec ){
        var xhr = new XHR();
        xhr.open("GET", this._proxy+"?req=delete&authcode="+this._AuthCode+"&id_rec="+id_rec,false);
        xhr.send("");
        if(xhr.readyState  == 4){
            xhr.responseText
            if(xhr.status  == 200){
              var code = parseHttpResponse(xhr.responseText)
              if(code == 201)
                return "OK"
              else if(code == 401)
                return "Unauthorized"
              else if(code == 404)
                return "Not found"
            }
        }
      },
      
      getRssURL : function (){
        var xhr = new XHR();
        xhr.open("GET", this._proxy+"?req=rss&authcode="+this._AuthCode,false);
        xhr.send("");
        if(xhr.readyState  == 4){
            xhr.responseText
            if(xhr.status  == 200){
              var code = parseHttpResponse(xhr.responseText)
              if(code == 200){
                return retrieveJSONfromHttpResponse( xhr.responseText )
              }
              else if(code == 401)
                return "Unauthorized"
            }
        }
      },
      
      forwardDataToProxy : function ( data ){
        var xhr = new XHR();
        xhr.open("GET", this._proxy+"?"+data,false);
        xhr.send("");
        if(xhr.readyState  == 4){
            xhr.responseText
            if(xhr.status  == 200){
              return xhr.responseText
            }
        }
      },
}



function parseHttpResponse( response ){
  var array = response.split("\n")
  var firstLine = array[0]
  var els = firstLine.split(" ")
  return els[1]
}

function retrieveJSONfromHttpResponse( response ){
  var array = response.split("\n")
  return array[array.length-2] 
}

/*****************************
** retrieves the XML object
*****************************/
function XHR(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

