// Copyright 2008 Elegant Technologies, LLC	
//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load()
{
    dashcode.setupParts();
    jLookup('elegant');
}

//
// Function: flipToFront(event)
// Flip to the front view to show the normal utility view
//
function flipToFront(event)
{
    var views = document.getElementById('views');
    var front = document.getElementById('front');
    if (views && views.object && front) {
        views.object.setCurrentView(front, true);
    }
}

//
// Function: flipToSettings(event)
// Flip to the back view to present user customizable settings
//
function flipToSettings(event)
{
    var views = document.getElementById('views');
    var settings = document.getElementById('settings');
    if (views && views.object && settings) {
        views.object.setCurrentView(settings);
    }
}

/*function flipToDetails(event)
{
    var views = document.getElementById('views');
    var settings = document.getElementById('detailLevel');
    if (views && views.object && settings) {
        views.object.setCurrentView(settings);
    }
}
*/

function mySearchHandler(event)
{
    // What are we looking for?
    var ObjInputSearch = document.getElementById("InputSearch");	// replace with ID of text field
    textFieldValue = ObjInputSearch.value; //wanted to remove this for the also saw
    jLookup(textFieldValue);
    
}



function Word2Screen(StrWord,IdTarget){
    var ObjTitle = document.getElementById(IdTarget);
    ObjTitle.innerHTML = "<span style='color:gray'>"+'('+"</span>"+StrWord+"<span style='color:gray'>"+')'+"</span>";
}


function jLookup(StrWord){
    document.StrWord = StrWord;
// Tell user what we are looking for
    // Update the header to match the word
    Word2Screen(StrWord,'LblTitle');
    
    //ObjTitle2 = $("LblTitle");
    //alert("The title via prototype =>"+ObjTitle.innerText);
    
    // Look it up
    //alert("About to look up '"+textFieldValue+"'");
    //[ ] Handle empty field
    
    // Look up the word from server if I don't already know it
    if (StrWord  != 'elegant')  {
        var feedURL = "DictJson.php?action=define&input="+StrWord;
        //alert(feedURL);
        var onloadHandler = function() { jHasLoaded(xmlRequest); };	// The function to call when the feed is loaded; 
        var xmlRequest = new XMLHttpRequest();
        xmlRequest.onload = onloadHandler;
        xmlRequest.open("GET", feedURL,false);
        xmlRequest.setRequestHeader("Cache-Control", "no-cache");
        xmlRequest.send(null);    
        
        // Pass the word to the list controller???
    } else {
        var _rowData = [];
         _rowData = jJson2rowData('{"ArrAsrDefinitions":[{"type":"adj","definition":"refined and tasteful in appearance or behavior or style","samples":["elegant handwriting","an elegant dark suit","she was elegant to her fingertips","small churches with elegant white spires","an elegant mathematical solution--simple and precise and lucid"],"synonyms":[]},{"type":"adj","definition":"suggesting taste, ease, and wealth","samples":"","synonyms":["graceful","refined"]},{"type":"adj","definition":"displaying effortless beauty and simplicity in movement or execution","samples":["an elegant dancer","an elegant mathematical solution -- simple and precise"],"synonyms":[]}],"IntRank":39,"IntNumLookups":1}');
          RowData2Screen(_rowData);
    }
}


function jHasLoaded(data){
    //alert(data.responseText);
    var _rowData = [];
    if (!data.responseText) {
        //alert("no response from the server");
        _rowData['ArrAsrDefinitions'][0] = "No Matches Found";
        //return
    } else {    
        //[ ] Todo: handle couldn't connect to server (permission denied, etc)
        //[ ] Todo : handle no-match from server (zero length?)
        _rowData = jJson2rowData(data.responseText);
               //alert("Row 0 is " + _rowData[0]);
    }
    RowData2Screen(_rowData);
    
    // Show Popularity
    // Rank
    ObjT = document.getElementById("LblRank");
    ObjT.innerText = _rowData['IntRank'];
    //alert("rank=>");
    // NumLookups
    ObjT = document.getElementById("LblNumLookups");
    ObjT.innerText = _rowData['IntNumLookups'];
    
    // NumLookupsMe (# of times I have looked up this word before)
    ObjT = document.getElementById("LblNumLookupsMe");
    ObjT.innerText = _rowData['IntNumLookupsMe'];
    
    // Also Saw
    ObjT = document.getElementById("AlsoSaw");
    //document.forms['testform'].testselect.options[i] = null; //delte
    //document.forms['testform'].testselect.options[i] = new Option('new text','new value'); // new option
    //document.forms['testform'].testselect.options.length = 0; //To completely clear a select box, do
    ObjT.options.length = 0; //Clear out what was there
    ObjT[0] = new Option('Also Saw','-1');  //Add defaault item
    ObjT[1] = new Option('bob','bob');  //Add defaault item
    ObjT[2] = new Option('alice','alice');  //Add defaault item
    ObjT[3] = new Option('hank','hank');  //Add defaault item
   
}

function RowData2Screen(_rowData){
    //alert("About to reload" + _rowData['ArrAsrDefinitions'].length);
    var ObjList =  document.getElementById("list");
    if (_rowData['ArrAsrDefinitions'].length > 0 ) {
        listController._rowData = _rowData['ArrAsrDefinitions'];    
        ObjList.style.display = "block";
    } else {
        //alert("No Defs");
        ObjList.style.display = "none";
        var ArrEmpty = new Array();
        ArrEmpty[0] = new Array();
        ArrEmpty[0]['type'] = 'msg';
        ArrEmpty[0]['definition'] = 'No Defenitions Found';
        listController._rowData = ArrEmpty;
    }
    var ObjList =  document.getElementById("list");
    ObjList.object.reloadData();
    //alert("hi"+_rowData['Rank']);
    //alert("Just reloaded");
   }

function jJson2rowData(JsonData){
    var _rowData = [];
    ArrAsrDict = JSON.parse(JsonData);
    return ArrAsrDict;//return ArrAsrDict['ArrAsrDefinitions'];
        /*for ( Slot in ArrAsrDict ) {
            var CharType = ArrAsrDict[Slot]['type'];
            var StrDefinition = ArrAsrDict[Slot]['definition'];
            //alert('('+ CharType + ') '+ StrDefinition);
            _rowData[Slot] = "<span style='text-size:90%'>("+ CharType + ')</span> <i>'+ StrDefinition + "</i>"	;
            _rowData[Slot].ArrAsrDict = ArrAsrDict;
    return _rowData;
        }*/
}



var listController = {

    // This object acts as a controller for the list UI.
    // It implements the dataSource methods for the list.
    
    // This dataSource uses fixed data for the content of the list.  Some applications may have such static data for their lists, others will want to replace this with information fetched remotely via XMLHttpRequest.
    _rowData: [
        "Alta",
        "Aspen",
        "Big Bear",
        "Boreal",
        "Big Mountain",
    ],
    
    numberOfRows: function() {
        // The List calls this dataSource method to find out how many rows should be in the list.
//alert("Just entered listController/numberOfRows");
        return this._rowData.length;
    },
    
        
    prepareRow: function(rowElement, rowIndex, templateElements) {
        
        // The List calls this dataSource method for every row.  templateElements contains references to all elements inside the template that have an id. We use it to fill in the text of the rowTitle element.
        if (templateElements.rowTitle) {
            //templateElements.rowTitle.innerText = rowIndex + ')' +this._rowData[rowIndex];
            //templateElements.rowTitle.innerHTML = "<span style='color:gray;font-size:90%'>"+rowIndex + '</span> ' +this._rowData[rowIndex];
            //templateElements.rowTitle.innerHTML = this._rowData[rowIndex];
            //alert ("In prepare row" + this._rowData[rowIndex].length);
            if ( this._rowData[rowIndex]['type'] == 'msg') {
                // state: this is just a simple string, probably a message
                templateElements.rowTitle.innerHTML = "<i>"+this._rowData[rowIndex]['definition']+"</i>";
            } else {
                // state: I have a full associative array to work with

                // Type (adj, noun, etc)
                var PureType = this._rowData[rowIndex]['type'];
                if (PureType != '?') {
                    // state: I know the speech type
                    var CharType = PureType;
                    var HtmlType = "<span style='text-size:90%'>("+ CharType + ")</span>";
                } else {
                    // state: I don't have usefule type info
                    var HtmlType = '';
                } // OUTPUT: HtmlType                 

                
                // Def
                var StrDefinition = this._rowData[rowIndex]['definition'];
                
                // Write the row with the formatted def
                templateElements.rowTitle.innerHTML = HtmlType + ' <i>'+ StrDefinition + "</i>"	;
            }
        }
    
        // We also assign an onclick handler that will cause the browser to go to the detail page.
       var self = this;
       var handler = function() {
            //   var resort = self._rowData[rowIndex];  
            detailController.setRepresentedObject(listController._rowData[rowIndex],rowIndex);//detailController.setRepresentedObject(self._rowData[rowIndex],rowIndex); // tell the controller what it is working on
            var views = document.getElementById('views');
            var view = document.getElementById('detailLevel');
            if (views && views.object && view) {
                views.object.setCurrentView(view);
            }
        };
        rowElement.onclick = handler; // set this dynamically(?) generated function to be the handler for this particular row

    }
};

var detailController = {
    // This object acts as a controller for the detail UI.
    
    setRepresentedObject: function(representedObject,SlotCurrentDef) {//setRepresentedObject: function(representedObject) {
        // Update Page X of YY
        var CountCurrentDef = SlotCurrentDef + 1;
        var CountMax = listController._rowData.length;
        var SlotMax = CountMax -1;
        //alert("Top of set: SlotCurrentDef=>" + SlotCurrentDef + ", CountCurrentDef=> " + CountCurrentDef + ", CountMax=>" + CountMax + ", SlotMax=>" + SlotMax);

        // Update label
        var ObjLblDetailsPage = document.getElementById('LblDetailsPage');
        TextPage = CountCurrentDef + " of " + CountMax;
        ObjLblDetailsPage.innerHTML = TextPage
        
        // Update Previous
        var ObjButtonPrevious = document.getElementById('ButtonPrevious'); //INPUT
        var SlotGotoPrevious = SlotCurrentDef -1 ;// INPUT
        if (SlotGotoPrevious < 0) { // INPUT
           SlotGotoPrevious = SlotMax; // INPUT
        }
       // alert ("Goto slot for prev is " + SlotGotoPrevious);
        var handlerPrevious = function() {
            detailController.setRepresentedObject(listController._rowData[SlotGotoPrevious],SlotGotoPrevious); // tell the controller what it is working on
            var viewsPrevious = document.getElementById('views');
            var viewPrevious = document.getElementById('detailLevel');
            if (viewsPrevious && viewsPrevious.object && viewPrevious) {
                viewsPrevious.object.setCurrentView(viewPrevious);
            }
        };
        ObjButtonPrevious.onclick = handlerPrevious; // set this dynamically(?) generated function to be the handler for this particular row
        
        
       // Update Next
        var ObjButtonNext = document.getElementById('ButtonNext'); //INPUT
        var SlotGotoNext = SlotCurrentDef + 1;
        if (SlotGotoNext > SlotMax) { // INPUT
           SlotGotoNext = 0; // INPUT
        }
        //alert ("Goto slot for next is " + SlotGotoNext);
        var handlerNext = function() {
            detailController.setRepresentedObject(listController._rowData[SlotGotoNext],SlotGotoNext); // tell the controller what it is working on
            var viewsNext = document.getElementById('views');
            var viewNext = document.getElementById('detailLevel');
            if (viewsNext && viewsNext.object && viewNext) {
                viewsNext.object.setCurrentView(viewNext);
            }
        };
        ObjButtonNext.onclick = handlerNext; // set this dynamically(?) generated function to be the handler for this particular row
    

       
        // To start, the represented object of our detail controller is simply a string, the title of the list row that the user chose.  You may want to make the represented object any kind of object when you customize the template.
        this._representedObject = representedObject;
        
        // When the represented object is set, this controller also updates the DOM for the detail page appropriately.  As you customize the design for the detail page, you will want to extend this code to make sure that the correct information is populated into the detail UI.
        var ObjDetailedText = document.getElementById('detailText');

        // which word
        var StrWord = document.StrWord;
         Word2Screen(StrWord,'LblTitle1');
         
        // type + def
        ObjDetailedText.innerHTML = "<h3>Definition</h3>";	



        //type
        var PureType = this._representedObject['type'];
        // Type (adj, noun, etc)
        if (PureType != '?') {
            // state: I know the speech type
            var CharType = PureType;
            var HtmlType = "<span style='text-size:90%'>("+ CharType + ")</span>";
        } else {
            // state: I don't have usefule type info
            var HtmlType = '';
        } // OUTPUT: HtmlType                 

        // Def
        ObjDetailedText.innerHTML += HtmlType + ' ' + this._representedObject['definition'];

        // Source
        var StrSource = 'Wordnet';
        if (this._representedObject['EnumSource']) {
            StrSource = this._representedObject['EnumSource'];
        }
        ObjDetailedText.innerHTML += "<br/>&nbsp;(Source: " + StrSource + ")";
        ObjDetailedText.innerHTML += "<ul>";

        
        // samples
        ObjDetailedText.innerHTML += "<h3>Samples</h3>";	
        if (this._representedObject['samples']==0) {
            ObjDetailedText.innerHTML += "<span style='color:gray:'>&nbsp;&nbsp;No samples</span>";
        } else {
            for (Slot in this._representedObject['samples']) {
                ObjDetailedText.innerHTML += "<li>&nbsp;&nbsp;" + this._representedObject['samples'][Slot]+ "</li>";
            }            
            ObjDetailedText.innerHTML += "</ul>";
        }
        // synonyms
        ObjDetailedText.innerHTML += "<h3>Synonyms (Touch to Define)</h3>";	
        if (this._representedObject['synonyms']==0) {
            ObjDetailedText.innerHTML += "<span style='color:gray:'>&nbsp;&nbsp;No synonyms</span>";
        } else {
            for (Slot in this._representedObject['synonyms']) {
                ObjDetailedText.innerHTML += "&nbsp;&nbsp;&nbsp;<span style='font-size:110%;' onclick='jLookup(\""+this._representedObject['synonyms'][Slot]+"	\");flipToFront()'>" + this._representedObject['synonyms'][Slot] + "</span>";    
            }
        }
    }
    
};

function GoToEt(){
    location.href='http://www.eleganttechnologies.com';
}

