// Change this line to the domain you are using
// Ensure your project is set to use Static Ports. 
// In VSStudio Express, click the project directory (top of the solution explorer). 
// Click the properties. Under "Developer Web Server" click "Use Dynamic Ports" and set it to false.
// Change the port number to 1255 or whatever port matches the line in the gDomain variable below.
//var gDomain = "http://localhost:1255/BaeBo/";
var gDomain = "http://BaeBo.francisshanahan.com/";

var xml;
var researchDiv; 
var shopDiv;

var myProcessor;
var ownerDocument;
var myRequest;

var winW = 1016, winH = 768;

var statusCounter = 0;
var keyResults = new Array(21);
var keyWords = new Array(21);

var theQueueDivs = new Array(10);
var theQueueUrls = new Array(10);
var theQueueCaptions = new Array(10);
var theQueueStatus = new Array(10);
var theQueueXsl = new Array(10);
var theTimer;

var bDoingSomething = false;
var currentlyDoing = -1;

var myHistory; 

defaultResearchSearch
function defaultResearchSearch(e)
{
  if (e && e.which == 13)
    AddSomethingNewToDo('Google Web Search:' + GCRK(), 0, '', 'keywords=' + GCRK(), 7, 'g', 'searchResults');
  else
    return true;
}

function defaultSearch(e)
{
  if (e && e.which == 13)
    AS(1, GI());
  else
    return true;
}

function myOpen(strUrl) {
    window.open(strUrl)
}

function InitQueue(){ // set the queue contents to "done"
	for (var i = 0; i < theQueueStatus.length; i++) theQueueStatus[i]="done";
	// Nothing to do
	thingsToDoCounter = 0;
}

function PrintQueue(){
    return; // disable the queue
	var i=0;
	var strOutput="";
	for(i=0; i < theQueueStatus.length; i++) {
		strOutput += i + ". " + theQueueCaptions[i] + ": " + theQueueStatus[i] + "<br/>";
	}
	myQueue.innerHTML = strOutput;	
}

function DoSomething(){
	
	var i=0;
	if (thingsToDoCounter > -1) {
		// there's something in the queue
		var thingToDo = 0;
		while ((theQueueStatus[i] == "done") & ( i < theQueueStatus.length)) {
			i ++ ;	
		}
		
		if (i < theQueueStatus.length) {
			// Found something or ended
			currentlyDoing = i;
			//var currentUrl = theQueueUrls[i];
			printf("Found something to Do: "+ theQueueCaptions[currentlyDoing]);
			bDoingSomething = true;
			// show the loading gif
			document.getElementById('loading').style.visibility='visible';
			document.getElementById('loadingstatus').innerText= theQueueCaptions[currentlyDoing];
			
			GetData(currentlyDoing);
			PrintQueue();
		} else {
			//printf("Can't find something to do");
		}
		
	} else {
		//printf("nothing to do");
		bDoingSomething = false;
	}	
}

function GCK(){// Get Current Keywords
	return document.getElementById('txtKeywords').value;
}
function GCRK(){// Get Current Keywords (rESEARCH)
	return document.getElementById('txtResearch').value;
}
function SyncR() {document.getElementById('txtResearch').value = document.getElementById('txtKeywords').value;return;}
function SyncK() {document.getElementById('txtKeywords').value = document.getElementById('txtResearch').value;return;}

function SimulateComingBack () {
	if (currentlyDoing >= 0){
		theQueueStatus[currentlyDoing] = "done";
		document.getElementById(theQueueDivs[currentlyDoing]).innerHTML = "SOME DUMMY RESULTS";
		currentlyDoing = -1;
		bDoingSomething = false;		
	} else {
		printf("Not doing anything at the moment");
	}
	PrintQueue();
}

function GetQueryToUse(strParam, queryToUse){
	var url ="";
    var root = gDomain + "g.aspx";

	switch(queryToUse){
	
	case "yt": url= root + "?w=yt&j=" + GCRK() ; break; // youtube
	case "yp": url= root + "?w=yp&j=" + strParam ; break; // yahoo products
	case "n": url = root + "?w=n&j=" + GCRK() ; break; // yahoo news
	case "m": url = root + "?w=m&j=" + GCRK() ; break;  // yahoo movie
	case "a": url = root + "?w=a&j=&language=en&query=" + strParam ; break; // technorati
	case "b": url = root + "?w=b&j=" + GCK() ; break; // amazon no longer used
	case "e": url = root + "?w=e&j=" + strParam ; break; // ebay
	case "f": url = root + "?w=f&j=" + GCRK() ; break; // flickr
	case "g": url = root + "?w=g&j=&" + strParam;break; // google
	case "h": url = root + "?w=h&j=" + strParam;break; // yahoo audio artist
	case "i": url = root + "?w=i&j=" + GCRK() ; break; // yahoo images (not used)
	case "j": url = gDomain + "fs.aspx?SearchIndex=Blended&format=xml&Keywords=" + GCK(); break;
	case "app": url = root + "?w=app&j=&" + strParam;break; // amazon passthrough	
    case "ap": url = root + "?w=ap&j=" + escape("Operation=ItemSearch&SearchIndex=Blended&ResponseGroup=Medium&Keywords=" + GCK()) ; break;
	default: url = "unknown URL"; printf("unknown query:" + queryToUse);break;
	}	
	return url;
}

function AddToHistory(keyWord){
	//keyWords[statusCounter]= currentIdx + "["+currentWord+"]";
	keyWords[statusCounter]= keyWord;
	statusCounter ++;
	if (statusCounter >20) {statusCounter=1;myHistory.innerHTML= "";} 
}

function AddSomethingNewToDo(strCaption, iPage, strIndex, strStem, xslToUse, queryToUse, divToUse ) {
    theQueueDivs[thingsToDoCounter] = divToUse;
    var strQuery = strStem ;
    if (strIndex != "") strQuery += "&SearchIndex=" + strIndex;
    if (iPage != 0) strQuery += "&ItemPage=" + iPage;
    
    theQueueUrls[thingsToDoCounter] = GetQueryToUse(strQuery, queryToUse);
	theQueueStatus[thingsToDoCounter] = "todo";
	
	var strHistory = strCaption;
	if (iPage != 0) strHistory += ", Pg:" + iPage + "[ "+ strIndex + "]";
	
	theQueueCaptions[thingsToDoCounter] = strHistory;	
	theQueueXsl[thingsToDoCounter] = xslToUse;	
	
	thingsToDoCounter ++;
		
	if (thingsToDoCounter > 10) thingsToDoCounter=0;
	PrintQueue();		
}

function AddSomethingToDo(strParam, xslToUse, queryToUse, divToUse){
	theQueueDivs[thingsToDoCounter] = divToUse;
	theQueueUrls[thingsToDoCounter] = GetQueryToUse(strParam, queryToUse);
	theQueueStatus[thingsToDoCounter] = "todo";
	theQueueXsl[thingsToDoCounter] = xslToUse;
	printf("XSL To Use: " + xslToUse);
	
	thingsToDoCounter ++;
	if (thingsToDoCounter > 10) thingsToDoCounter=0;
		
	PrintQueue();	
}

function DoTimer(){
    if (currentlyDoing < 0) DoSomething();
    theTimer  = setTimeout("DoTimer()", 500);
}

// Credit where Credit's due: I did not write this function. 
// This function came from http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
   winW = myWidth;
   winH = myHeight;  
}

function SetPositions(){
    // Set the position of the "loading" img
    alertSize();

    document.getElementById("loading").style.left = (winW-200)/2 + 'px';
    document.getElementById("loading").style.top= (winH-100)/2 + 'px';
    
    //document.getElementById("amazonBrowse").style.left = (winW-600)/2 + 'px';
    //document.getElementById("amazonBrowse").style.top= '200px';
    // position the help
    document.getElementById("help").style.left = (winW-600)/2 + 'px';
    document.getElementById("help").style.top= '200px';
    
    document.getElementById("shopDiv").style.left = (winW-1016)/2 + 'px';
    document.getElementById("researchDiv").style.left = (winW-1016)/2 + 'px';
    document.getElementById("feedsDiv").style.left = (winW-1016)/2 + 'px';
    document.getElementById("browseDiv").style.left = (winW-1016)/2 + 'px';
    
}

function Init() {

    gCartId = ReadCookie('myCartId');
    gHMAC = ReadCookie('myHMAC');
   
    SetPositions();

    ShowMenu('menuShop', 'shopDiv', 50 );
    // Check for work every half second
    theTimer  = setTimeout("DoTimer()", 500);

	InitQueue();
	myHistory = document.getElementById('history');
	myQueue = document.getElementById('queue');

	// For IE based browsers:
	if (window.ActiveXObject)
	{
		try
		{
			xml = new ActiveXObject("Msxml2.DomDocument");			
			InitXslIE();			    
			xml.async = false;							
		}
		catch (e)
		{
			//alert(e.description)
		}
	}
	else
	{
		if (document.implementation && document.implementation.createDocument)
		{
		    InitXslFF();
			xml = document.implementation.createDocument("","xml",null);			
			xml.async=false;			
		}
		else
		{
			//alert("No XML/XSLT Support! This site is tested with IE6 and FireFox only. ");
		}
	}
	LoadCart('similar');
}

function printf(strString){
//	document.getElementById("status").innerHTML +=strString +"<br/>" ; 
}

function MyReplace(strSearch, strReplace, strString){ 
  var re = new RegExp(strSearch, "g");  
  return strString.replace(re, strReplace);
}

function transformContent()
{
	
	 //printf("Transforming...");
	// alert (xsl);
	 var Xsl = gXsl[theQueueXsl[currentlyDoing]];
	 
	 var strTmp;
	 
	 //alert (xsl);
     try
     {
          if (window.ActiveXObject)
          {
               //alert("Transforming")
               // only if we're browsing, pass in a parameter
               if (theQueueXsl[currentlyDoing] == 6) {               
               
                // Transform
                var template = new ActiveXObject("Msxml2.XSLTemplate.3.0");
                template.stylesheet = Xsl;
                
                var myProcessor = template.createProcessor();
                myProcessor.input = xml;
                myProcessor.addParameter("BrowseLevel", gBrowseLevel);
                myProcessor.transform();
               
                strTmp = myProcessor.output;
              }
               else {
                  //////////////////////////
                  strTmp = xml.transformNode(Xsl);
               } 
               
               var objB = document.getElementById(theQueueDivs[currentlyDoing]); 
               objB.innerHTML = strTmp; 
              
               var strBracketTmp = MyReplace('&lt;', '<', objB.innerHTML);
               strBracketTmp= MyReplace('&gt;', '>', strBracketTmp);
               objB.innerHTML = strBracketTmp;
          }
          else
          {
               // Create Processor
               myProcessor = new XSLTProcessor();
              // printf("importing sheet"); 
               myProcessor.importStylesheet(Xsl);
               
               // only if we're browsing, pass in a parameter
               if (theQueueXsl[currentlyDoing] == 6) myProcessor.setParameter(null, "BrowseLevel", gBrowseLevel);
               printf("stylesheet imported:" + Xsl); 
               
               ownerDocument = document.implementation.createDocument("", "", null);
               var xmlserial = new XMLSerializer();
               
               /////////////var newFragment = processor.transformToFragment(xml, ownerDocument);
               var newFragment = myProcessor.transformToFragment(xml, ownerDocument);
               //alert(newFragment);
               
               var objB = document.getElementById(theQueueDivs[currentlyDoing]); 
               
               // 6 = Browsing
               if ((theQueueDivs[currentlyDoing] != "bucket") ) objB.innerHTML = "";
              
               // Finally here's a little hack to get around the disable-output-escaping problem in Firefox
               objB.appendChild(newFragment);            
                              
               strTmp = MyReplace('&lt;', '<', objB.innerHTML);
               strTmp = MyReplace('&gt;', '>', strTmp);
               objB.innerHTML = strTmp;
                                    
          }
          if ((theQueueXsl[currentlyDoing] != 6) & (theQueueXsl[currentlyDoing] != 8) & (theQueueXsl[currentlyDoing] != 4)) AddSearchHistory(strTmp, currentlyDoing);
          //printf("Transforming...Complete");
     }
     catch (e)
     {
          //alert("Bug transforming: " + e.description)
     }
     
     if (currentlyDoing >= 0){
		theQueueStatus[currentlyDoing] = "done";
		currentlyDoing = -1;
		// hide the loading gif
		document.getElementById('loading').style.visibility='hidden';
		bDoingSomething = false;		
	} else {
		printf("Not doing anything at the moment");
	}
	PrintQueue();	
}

/////////////////////////////////////////////////////////////////////////////
function GetData(currentlyDoing) { // Actually calls the server
	// currently Doing is the thing we're currently doing
	
	printf("Preparing...");
	
	url = theQueueUrls[currentlyDoing];
								
	printf(url);
    if (window.XMLHttpRequest) {
        myRequest = new XMLHttpRequest();
        myRequest.onreadystatechange = processReqChange;
        myRequest.open("GET", url, true);
        myRequest.send(null);         
    } else if (window.ActiveXObject) {
        myRequest = new ActiveXObject("Microsoft.XMLHTTP");
        if (myRequest) {
            myRequest.onreadystatechange = processReqChange;
            myRequest.open("GET", url, true);
            myRequest.send();
        }       
    }
	printf("Sent it..." + url);
}

// Here's where the XML comes back
function processReqChange() {
    if (myRequest.readyState == 4) {
        if (myRequest.status == 200) {                       
            xml = myRequest.responseXML;
			
			printf("Sent...ResponseReceived");
			transformContent();
        } else {
            //alert("There was a problem retrieving the data:\n" + myRequest.statusText);
        }
    }
}

