
// namespace: caliper
var caliper = {};

// utilities: console
var mconsole = {};

// html console appends messages to <div id="map_console"></div>	
// to clear the console: mconsole.clear();
mconsole.log = function(m, o){
    var c = jQuery("#map_console");
    if (!c || c.length == 0) 
        return;
    var h = c.html();
    if (o) {
        var s = str_replace(/,/g, "\,<br/>", toJsonString(o));
        m = m + "<br/><pre>" + s + "</pre>";
    }
    if (m == 'reset') {
        c.html("ready.<br/>");
    }
    else {
        c.html(h + m + "<br/>");
    }
	try  {
    console.log('%s %o', m, o);
	} catch (err) 
	{ /** handle missing console here ***/ };
}

mconsole.clear = function(){
    mconsole.log("reset");
}

// utilities: string functions
str_replace = function(search_regex, replacement, input_string){
    var obj = new String(input_string);
    return obj.replace(search_regex, replacement);
}


// utilities: dQuery
dQuery = function(pattern){
    var j = jQuery(pattern);
    if (j) {
        mconsole.log("jQuery('" + pattern + "') " + j.length + " matches");
    }
    else {
        mconsole.log("jQuery('" + pattern + "') not found");
    }
    return j;
}


// return a json-encoded string or the value "x.config"
caliper.get_json_string = function(request_data){
    if (typeof request_data == "string") {
        if (request_data.indexOf(".config") == request_data.length - 7) {
            return request_data;
        }
        if (request_data.indexOf("json:") != 0) {
            return "json:" + request_data;
        }
        return request_data;
    }
    return toJsonString(request_data);
}

caliper.mapService = {};
caliper.mapService.gisdk_request = {};
caliper.mapService.gisdk_response = {};

caliper.mapService.submit = function(callback_function){
    if (!callback_function) {
        callback_function = caliper.mapService.ajax_success;
    }
    mconsole.clear();
    mconsole.log("caliper.mapService.submit()");
    var target_service = jQuery("#__target").attr("value");
    var target_method = jQuery("#__event").attr("value");
    var request_data = jQuery("#__request").attr("value");
    var application_data = jQuery("#__application").attr("value");
    caliper.mapService.DoMethod(target_service + "." + target_method, request_data, application_data, callback_function);
}


// post an ajax request to the map server
// target_service: 			"MapService" , "Geocoder" , ...
// target_method: 			"RedrawMap"  , "GetDataView" , "FindAddress" , ...
// service_dot_method:  	"MapService.RedrawMap" , etc...
// request_data: 			javascript object: { "MapFile": ... , "Scope": ... }'
// application_config:		server-side application config file
// callback_function:		javascript function to execute when the method returns a response option array
caliper.mapService.DoMethod = function(service_dot_method, request_data, application_config, callback_function){
    mconsole.log("caliper.mapService.DoMethod()");
    if (!callback_function) {
        callback_function = caliper.mapService.ajax_success;
    }
    var __data = {};
    var words = service_dot_method.split(".");
    if (words.length < 2) {
        alert("caliper.mapService.DoMethod - invalid input service_dot_method - " + service_dot_method);
        return;
    }
    __data.__service = words[0];
    __data.__method = words[1];
    __data.__library = "caliper/applications/mapserver";
    __data.__application = caliper.get_json_string(application_config);
    __data.__user = {};
    __data.__request = caliper.get_json_string(request_data);
    __data.__format = "json"; // desired output format for mapserver.php
    var request = jQuery.ajax({
        url: "mapservice.php", // the ajax map server 
        type: 'POST',
        dataType: 'json', // return type
        timeout: 5000, // in milliseconds
        data: __data,
        error: caliper.ajax_error,
        success: callback_function
    });
    caliper.mapService.gisdk_request = __data;
    mconsole.clear();
    mconsole.log("caliper.mapService.DoMethod <br/>" + str_replace(/,/g, "\,<br/>", toJsonString(__data)));
}

// example callback function
// do something with the response from mapserver.php
caliper.mapService.ajax_success = function(response){
    caliper.mapService.gisdk_response = response;
    mconsole.clear();
    mconsole.log("<b>caliper.mapService.ajax_success</b><br/><pre>" + str_replace(/,/g, "\,<br/>", toJsonString(response)) + "</pre>");
    if (response.ImageFile) {
        jQuery("#map_image").attr("src", response.ImageFile);
    }
    if (response.MapScope) {
        jQuery("#map_scope").html(response.MapScope);
    }
}

// report a server-side error
caliper.mapService.ajax_error = function(request_obj, error_type, exception_obj){
    var error_message = "caliper.mapService.ajax_error: " + error_type;
    if (request_obj) {
        if (request_obj.responseText) {
            mconsole.log(request_obj.responseText);
            error_message = error_message + "<br/>" + request_obj.responseText;
        }
    }
    try {
        if (exception_obj) {
            if (exception_obj.description) {
                error_message = error_message + "<br/>" + exception_obj.description;
            }
        }
        if (request_obj) {
            if (request_obj.readyState) {
                error_message = error_message + "<br/>" + request_obj.readyState;
            }
            if (request_obj.responseText) {
                error_message = error_message + "<br/>" + request_obj.responseText;
            }
            if (request_obj.statusText) {
                error_message = error_message + "<br/>" + request_obj.statusText;
            }
        }
    } 
    catch (err) {
        if (typeof(err) == 'string') {
            error_message = error_message + "<br/>" + err;
        }
        else 
            if (err.description) {
                error_message = error_message + "<br/>" + err.description;
            }
    }
    caliper.mapService.gisdk_response = {
        "Error": true,
        "Message": error_message
    };
    mconsole.log(error_message);
}

