////////////////////////////////////////////////////////////////////////////////
//                            iSee
//                    Author: Hernan Amiune
//                          Copyright
////////////////////////////////////////////////////////////////////////////////
var req = null;        //xmlhttprequest
var webpage="";        //string with values "youtube" or "google"
var videoNumber=0;     //index of the video
var totalVideos=0;     //total number of videos from the feed
var videoLink="";      //string with the video link
var feedNumber=0;      //index of the feed
var feedTitles = null; //feed titles
var feedUrls = null;   //feed urls
var rssCache = null;   //cache of the rss feeds
////////////////////////////////////////////////////////////////////////////////
/**
* Initialize the gadget 
*/
function init(){
  System.Gadget.settingsUI = "settings.html";
  System.Gadget.Flyout.file = "flyout.html";
  System.Gadget.onSettingsClosed = settingsClosed;

  loadFeedsDatabase();
}
////////////////////////////////////////////////////////////////////////////////
/**
* Open the flyout window or load the video 
*/
function openFlyout(){
  if(System.Gadget.Flyout.show==false) System.Gadget.Flyout.show = true;
  else System.Gadget.Flyout.document.loadFlyout(); 
}
////////////////////////////////////////////////////////////////////////////////
/**
* Reload the feeds database
*/
function settingsClosed()
{
    loadFeedsDatabase();
}
////////////////////////////////////////////////////////////////////////////////
/**
* Show next feed
*/
function nextFeed(){
  videoNumber=0;
  feedNumber++;
  if(feedNumber>=feedTitles.length)feedNumber=0;
  var feedNameFull = feedTitles[feedNumber];
  var feedNameTrimmed = feedTitles[feedNumber];
  if(feedNameTrimmed.length > 20) feedNameTrimmed = feedNameTrimmed.substr(0,17) + "...";
  document.getElementById("feedName").innerHTML = '<div title="' + feedNameFull + '">' + feedNameTrimmed + '</div>';
  document.getElementById("videoTitle").innerHTML = "Loading...";
  loadRSS(feedUrls[feedNumber]);
}
////////////////////////////////////////////////////////////////////////////////
/**
* Show previus feed
*/
function previusFeed(){
  videoNumber=0;
  feedNumber--;
  if(feedNumber<0)feedNumber=feedTitles.length-1;
  var feedNameFull = feedTitles[feedNumber];
  var feedNameTrimmed = feedTitles[feedNumber];
  if(feedNameTrimmed.length > 20) feedNameTrimmed = feedNameTrimmed.substr(0,17) + "...";
  document.getElementById("feedName").innerHTML = '<div title="' + feedNameFull + '">' + feedNameTrimmed + '</div>';
  document.getElementById("videoTitle").innerHTML = "Loading...";
  loadRSS(feedUrls[feedNumber]);
}
////////////////////////////////////////////////////////////////////////////////
/**
* Show next video
*/
function nextVideo(){
  videoNumber++;
  if(videoNumber>totalVideos-1)videoNumber=0;
  document.getElementById("videoTitle").innerHTML = "Loading...";
  processRSS();
}
////////////////////////////////////////////////////////////////////////////////
/**
* Show previus video
*/
function previusVideo(){
  videoNumber--;
  if(videoNumber<0)videoNumber=totalVideos-1;
  document.getElementById("videoTitle").innerHTML = "Loading...";
  processRSS();
}
////////////////////////////////////////////////////////////////////////////////
/**
* Load the feeds database
*/
function loadFeedsDatabase(){
    try{
        if(window.ActiveXObject){
            var oFS = new ActiveXObject("Scripting.FileSystemObject") 

            var path = System.Gadget.path;
            path = path.replace(/\\/g,"\\\\");
            path = path + "\\databases\\feedsDB.xml";
            //path = "c:\\feedsDB.xml";
            
            if(oFS.FileExists(path) == true){
              var oFSFile = oFS.OpenTextFile(path,1);
              var strXML = oFSFile.readall();
              oFSFile.close();
              
              var xmlDoc;
              xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.loadXML(strXML);

              var node = xmlDoc.documentElement;
              var items = node.getElementsByTagName("item");

              feedTitles = new Array();
              feedUrls = new Array();
              for(var i=0; i<items.length; i++){
                  feedTitles[i] = items[i].getElementsByTagName("title").item(0).firstChild.data;
                  feedUrls[i] = items[i].getElementsByTagName("url").item(0).firstChild.data;
              }
              
            }
            
            if(feedTitles.length < 1){
              document.getElementById("videoTitle").innerHTML = "No feeds available";
              return;
            }
            if(feedNumber >= feedTitles.length)feedNumber=0;
            var feedNameFull = feedTitles[feedNumber];
            var feedNameTrimmed = feedTitles[feedNumber];
            if(feedNameTrimmed.length > 20) feedNameTrimmed = feedNameTrimmed.substr(0,17) + "...";
            document.getElementById("feedName").innerHTML = '<div title="' + feedNameFull + '">' + feedNameTrimmed + '</div>';
            loadRSS(feedUrls[feedNumber]);      
        }
    }catch(e){}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Load the rss feed from the url
* @param {string} url feed url
*/
function loadRSS(url){
    try{
        if(url.indexOf("google.com/")!=-1)webpage="google"; else webpage="youtube";
        if(window.ActiveXObject){
            req = new ActiveXObject("Microsoft.XMLHTTP");
            if(req){
                req.onreadystatechange = saveRSS;
                req.open("GET", url, true);
                req.setRequestHeader("Cache-Control", "no-cache");
                req.setRequestHeader("Pragma", "no-cache");
                req.send();
            }        
        }
    }catch(e){}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Save the rss feed on the rssCache variable
*/
function saveRSS(){
    try{
        if(req.readyState == 4 && req.status == 200 && req.responseText) {
          rssCache = req.responseText; 
          processRSS(); 
          req.send();  
        }else if(req.readyState == 4 && req.status == 404){
          document.getElementById("videoTitle").innerHTML = "Feed couldn't be loaded";
        }
    }catch(e){}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Parse the rss and show the videos
*/
function processRSS() {  
    try{

          var xmlDoc;
          if(window.ActiveXObject){
              xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.loadXML(rssCache);
          }

          var node = xmlDoc.documentElement;

          // clear non ascii characters
          if(node == null){

              var tmp = rssCache; 
              rssCache="";
              for(var i=0; i<tmp.length; i++){
                if(tmp.charCodeAt(i)>31 && tmp.charCodeAt(i)<128)
                  rssCache+=tmp.charAt(i);
              }

              xmlDoc.loadXML(rssCache);

              node = xmlDoc.documentElement;
              if(node == null){
                document.getElementById("videoTitle").innerHTML = "Feed couldn't be loaded";
                return;
              }
          }


          var channel = node.getElementsByTagName("channel").item(0);

          

          var items = channel.getElementsByTagName("item");
          totalVideos = items.length;
          if(totalVideos < 1){
              document.getElementById("videoTitle").innerHTML = "No videos on this feed";
              return;
          }
          if(videoNumber >= totalVideos)videoNumber=0;
          
          var videoTitle="";
          var videoAuthor="";
          var videoInfo="";
          var videoTag="";
          var videoImageTag="";
          var videoImage="";
          
          if(webpage == "youtube"){
              videoTitle = items[videoNumber].getElementsByTagName("title").item(0).firstChild.data;
              videoTitle = videoTitle.replace(/"/g,"''");
              videoAuthor = items[videoNumber].getElementsByTagName("author").item(0).text;
              videoInfo = 'Title: '+ videoTitle +'\nAuthor: '+ videoAuthor.substring(videoAuthor.indexOf('(')+1,videoAuthor.indexOf(')'));
              videoLink = items[videoNumber].getElementsByTagName("enclosure")[0].getAttribute("url");
              videoLink = videoLink.substring(0,videoLink.indexOf(".swf"));
              videoImage = items[videoNumber].getElementsByTagName("media:thumbnail")[0].getAttribute("url");
              
              videoTitle = (videoNumber+1).toString() + '. ' + videoTitle;
              if(videoTitle.length > 20) videoTitle = videoTitle.substr(0,17) + "...";
              
              document.getElementById("videoTitle").innerHTML = '<div title="' + videoInfo + '">' + videoTitle + '</div>';
              videoImageTag = '<a href="javascript:openFlyout()"><img width="120" height="90" border="0" src="'+ videoImage +'"/></a>';
              videoTag = '<object width="300" height="245"> ' +
              '<embed src="' + videoLink + '&autoplay=1" quality="high" type="application/x-shockwave-flash" ' +
              'pluginspage="http://www.macromedia.com/go/getflashplayer" width="300" height="245"> ' +
              '</embed> ' +
              '</object>';

              
          }else if(webpage == "google"){
              videoTitle = items[videoNumber].getElementsByTagName("title").item(0).firstChild.data;
              videoTitle = videoTitle.replace(/"/g,"'");
              videoAuthor = items[videoNumber].getElementsByTagName("author").item(0).text;
              videoInfo = 'Title: '+ videoTitle +'\nAuthor: '+ videoAuthor.substring(videoAuthor.indexOf('(')+1,videoAuthor.indexOf(')'));
              videoLink = items[videoNumber].getElementsByTagName("guid").item(0).firstChild.data;
              videoLink = "http://video.google.com/googleplayer.swf" + videoLink.substr(videoLink.indexOf("?"));
              videoImage = items[videoNumber].getElementsByTagName("media:thumbnail")[0].getAttribute("url");
              
              videoTitle = (videoNumber+1).toString() + '. ' + videoTitle;
              if(videoTitle.length > 20) videoTitle = videoTitle.substr(0,17) + "...";
              
              document.getElementById("videoTitle").innerHTML = '<div title="' + videoInfo + '">' + videoTitle + '</div>';
              videoImageTag = '<a href="javascript:openFlyout()"><img width="120" height="90" border="0" src="'+ videoImage +'"/></a>';
              videoTag = '<object width="300" height="245"> ' +
                         '<embed src="' + videoLink + '&autoplay=1" quality="high" ' +
                         'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="300" height="245"> ' +
                         '</embed> ' +
                         '</object>';
          }
          document.getElementById("videoTag").value = videoTag;
          document.getElementById("videoImageTag").innerHTML = videoImageTag;
          
          
    }catch(e){}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Toggle buttons
*/
function toggleButton(objToChange, newSRC)
{        
   eval("objToChange").src = "images/"+newSRC;
}
////////////////////////////////////////////////////////////////////////////////
window.onload = init;
////////////////////////////////////////////////////////////////////////////////
