﻿// JScript File
var gRequest;
var gXsl = new Array;
var gCurrentXsl = 0;
var gTargetDiv = "results";
var gXml;
var gBrowseLevel=0;
var winW =0;
var winH = 0;

// Used to display the path of the chain
var gLinkedStories;
var gLinkedTags;

function PickIt(strObj, strTarget){
    var lbox = document.getElementById(strObj);
    document.getElementById(strTarget).innerHTML = lbox.options[lbox.selectedIndex].value;    
}

function GetStoryById(strId){
    GetData(0, "storyDetail", 'api=getStoryById&storyId=' + strId );
}

function GetStoriesByTag(strTag){
    GetData(0, "storiesDiv", 'api=getStoriesByTag&startTag=' + strTag );
}

function GetStoryTags(strId){
    GetData(0, "storyTags", 'api=getTagsByStory&storyId=' + strId );
}


function FindConnection(){
    var start = document.getElementById('txtStart').innerHTML;
    var end = document.getElementById('txtEnd').innerHTML;
    GetData(0, "connectionResults", 'api=findConnection&startTag='+ start +'&endTag='+ end );
    strRDF = '<a target="_blank" href="rdf.aspx?&startTag='+ start +'&endTag='+ end +'">RDF for this connection</a>';
    document.getElementById('rdf').innerHTML=strRDF;
    
}

function ShowStories(){
    var i;
    var strHTML = ""; 
    for(i=0; i < gLinkedStories.length; i++){
       strHTML += "Story ID: <a href='javascript:void(0)' onclick='GetStoryById(" + gLinkedStories[i] + ")'>" + gLinkedStories[i] + "</a><br/>";     
    }
    
    document.getElementById("storyChain").innerHTML = strHTML;
}
////////////////////////////////////////
function Lookup(ItemId){
    // Set the Xsl file to use when the data comes back
	GetData(2, "details", "api=amazon&operation=ItemLookup&ItemId=" + ItemId);
}

function ListSearch(){
    // Set the Xsl file to use when the data comes back    
    var FirstName = document.getElementById('txtFirstName').value;
	var LastName = document.getElementById('txtLastName').value;
	GetData(0, "results", "api=amazon&operation=ListSearch&ResponseGroup=ListInfo&ListType=WishList&FirstName="+ FirstName + "&LastName=" + LastName);
}

function ListLookup(ListId){
    // Set the Xsl file to use when the data comes back
	GetData(1, "lists", "api=amazon&operation=ListLookup&ResponseGroup=Large&ListType=WishList&ListId=" + ListId);
}

function DirectorSearch(keywords){
    // Set the Xsl file to use when the data comes back
    GetData(2, "results", "api=amazon&operation=ItemSearch&Director=" + keywords + "&SearchIndex=DVD");
}

function YouTube(keywords){
    // Set the Xsl file to use when the data comes back
    GetData(2, "results", "api=youtube&tag=" + keywords );
}

function EbaySearch(keywords){
    // Set the Xsl file to use when the data comes back
    GetData(5, "results", "api=ebay&query=" + keywords );
}

function ActorSearch(keywords){
    // Set the Xsl file to use when the data comes back    
	GetData(2, "results", "api=amazon&operation=ItemSearch&Actor=" + keywords + "&SearchIndex=DVD");
}

// this function actually performs the request for data. 
function GetData(myXslIndex, myTarget, myOperation) {
    

    // Set some variables used in the response handler   
    gCurrentXsl = myXslIndex; 
    gTargetDiv =  myTarget;//"results" + myTarget;
    gBrowseLevel = myTarget;
    
    // Show progress
    ShowProgress("<font color=red>Loading</font>");

    var myCacheBreaker = Math.floor(Math.random()*10000);
    // Break the caching by attaching a random number. 
	//var myUrl="rest.aspx?" + myOperation + "&cacheBreaker=" + myCacheBreaker;
	var myUrl="http://www.FrancisShanahan.com/sixdegrees/rest.aspx?" + myOperation + "&cacheBreaker=" + myCacheBreaker;
	
	// Is this a Microsoft browser?
	if (window.ActiveXObject) {
	    // Create a new request
        myRequest = new ActiveXObject("Microsoft.XMLHTTP");
        if (myRequest) {
            myRequest.onreadystatechange = HandleResponse;
            myRequest.open("GET", myUrl, true);
            myRequest.send();
            
        }  
    } else if (window.XMLHttpRequest) {
        // If this is Firefox or Safari...	
        myRequest = new XMLHttpRequest();
        myRequest.onreadystatechange = HandleResponse;
        myRequest.open("GET", myUrl, true);
        myRequest.send(null);             
    }
    myPrint(myUrl);
}

function myPrint(msg){
  document.getElementById('debug').innerHTML += "<br/>" + msg;
}

function HandleResponse() {

    // Readystate 4 means we're done
    if (myRequest.readyState == 4) {
    
        // If the server returned OK
        if (myRequest.status == 200) {       
         //alert(gXml);                  
            gXml = myRequest.responseXML;
            //alert(gXml);
            TransformResponse();
        } else {
            myPrint("<br/>Oops there was a problem, " + myRequest.statusText);
            myPrint("<br/>Try again later");
        }
    }
    
}

function Init(){
   
    // Branch the code to support either IE or Firefox
	if (window.ActiveXObject)
	{
        InitXslIE();
	}
	else
	{
        InitXslFF();
    }
    // Load all the stylesheets.
    LoadXsl();
}

// Load an array of XSL sheets
function LoadXsl(){
    gXsl[0].load('xml/SixDegrees.xsl');
    //gXsl[0].load('xml/AmazonListSearch.xsl');
   /* gXsl[1].load('xml/AmazonListLookup.xsl');   
    gXsl[2].load('xml/AmazonYouTube.xsl');
    gXsl[3].load('xml/AmazonCartCreate.xsl');
    gXsl[4].load('xml/AmazonCartGet.xsl');
    gXsl[5].load('xml/ebaySearch.xsl');*/
}

// Initialize the XSL objects in Firefox
function InitXslFF() {
   for (var i = 0; i< 6 ; i++ ){
      gXsl[i] = document.implementation.createDocument("","xsl",null);
   }
   
    // Finally the XML object
   gXml = document.implementation.createDocument("","xml",null);	
   gXml.async=false;
}

// Initialize the XSL in IE
function InitXslIE() {    
   for (var i = 0; i< 6 ; i++ ){   
       gXsl[i] = new ActiveXObject("MSXML2.FreeThreadedDOMDocument"); 
   }  // Msxml2.DomDocument
   // setup the xml object. 
   gXml = new ActiveXObject("Msxml2.DomDocument");
   gXml.async=false; 
}

function ShowProgress(strMsg){
    document.getElementById("progress").innerHTML = "<h2>" + strMsg + "...</h2>";
}

// Transform the XML data
function TransformResponse()
{	
    ShowProgress("Transforming");
    
    var myXsl = gXsl[gCurrentXsl];
    var myXml=gXml;
    var myResults;
    var myProcessor;     
    var myTarget = document.getElementById(gTargetDiv); 
         
    if (window.ActiveXObject)
    {               
       // IE specific transformation.    
       
       var template = new ActiveXObject("Msxml2.XSLTemplate.3.0");
       template.stylesheet = myXsl;
        
       var myProcessor = template.createProcessor();
       myProcessor.input = myXml;
       myProcessor.addParameter("BrowseLevel", gBrowseLevel);
       myProcessor.transform();
       
       myTarget.innerHTML = myProcessor.output;
    }
    else
    {
        // Create Processor
        myProcessor = new XSLTProcessor();
        myProcessor.importStylesheet(myXsl);                      
        
        //myProcessor.setParameter(null, "BrowseLevel", gBrowseLevel);
        myResults = myProcessor.transformToFragment(myXml, document);
        
        var newDiv = document.createElement('div');
        newDiv.style.float = "left";
        newDiv.appendChild(myResults);
        
        // Finally display the response
        myTarget.innerHTML = "";        
        myTarget.appendChild(newDiv);
    }       
    ShowProgress("Done");
}

