/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    server:new Array(),
    // Application Constructor
    initialize: function() {
        this.bindEvents();
         console.log("1");
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        console.log("2");
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        console.log("3");
        $('#searchVerbbtn').click(function(){
                                  $('#messagebox').hide();
                                  $('#resultbox').hide();
                                  $('#messagebox').html('');
                                  var verb = $('#query').val();
                                  console.log("search verb clicked");
                                  server.Search(verb, app.onSuccess);
                                  });
        
        app.InstallFunction(app.server, 'Search');
    },
    
    InstallFunction: function(obj, functionName) {
        obj[functionName] = function() { app.Request(functionName, arguments); }
    },
    
    Request: function(function_name, opt_argv) {
        if (!opt_argv)
            opt_argv = new Array();
        
        var callback = null;
        var len = opt_argv.length;
        if (len > 0 && typeof opt_argv[len-1] == 'function') {
            callback = opt_argv[len-1];
            opt_argv.length--;
        }
        var async = (callback != null);
        
        var query = 'action=' + encodeURIComponent(function_name);
        for (var i = 0; i < opt_argv.length; i++) {
            var key = 'arg' + i;
            var val = JSON.stringify(opt_argv[i]);
            query += '&' + key + '=' + encodeURIComponent(val);
        }
        query += '&time=' + new Date().getTime();
        
        var req = new XMLHttpRequest({mozSystem:true});
        req.open('GET', 'http://congifr.appspot.com/verb?' + query, async);
        console.log("sending request");
        if (async) {
            console.log("getting response");
            req.onreadystatechange = function() {
                if(req.readyState == 4 && req.status == 200) {
                    console.log("getting results");
                    var response = null;
                    try {
                        response = JSON.parse(req.responseText);
                    } catch (e) {
                        response = req.responseText;
                    }
                    callback(response);
                }
            }
        }
        
        req.send();
    },
    
    onSuccess: function(response) {
        console.log("4");
        switch(response['action']){
            case 'search':
                if(response['state']==1){
                    app.addContent(response['data']);
                    $('#messagebox').hide();
                    $('#resultbox').show();
                    
                }
                if(response['state']==0){
                    $('#messagebox').show();
                    $('#resultbox').hide();
                    $('#messagebox').html('<p>'+response['data']+'</p>');
                }
        }
    },
    
    addContent: function(data){
        var idindex=new Array("present", "presentPerfect","simplePast","pastPerfect","imperfect","pluperfect","future","pastFuture","subPresent","subPast","subImperfect","subPluperfect","conPresent","con1Past","con2Past","impPresent","impPast","infPresent","infPast","partPresent","partPast");
        for( var i=0; i < idindex.length; i++){
            $("#"+idindex[i]).html('<p>'+data[idindex[i]]+'</p>');
        }
    }
    
};
