/* User interaction for FE pages */

/**
* Loads/updates nearest resources list
*
* @param mixed element to update
* @param string nearest_base_url base url for nearest resources
* @param integer buffer_size
* @param string loading animation element
*
*/
function ui_nearest_resources(element, nearest_base_url, buffer_size, loading_element){
    try { jQuery(loading_element).show();} catch (e) {};
    jQuery(element).load(nearest_base_url + buffer_size + '/', null, function(){
        try { jQuery(loading_element).hide();} catch (e) {};
    });
}

var olcontext = {
    getIcon: function(feature) {
        return feature.attributes["icon_url"] || '';
    },
    getHeight: function(feature) {
        return feature.attributes["height"] || 32;
    },
    getWidth: function(feature) {
        return feature.attributes["width"] || 32;
    },
    getStrokeColor: function(feature) {
        return feature.attributes["color"] || 'red';
    },
    getFillColor: function(feature) {
        return feature.attributes["fill_color"] || 'green';
    },
    getStrokeWidth: function(feature) {
        return feature.attributes["strike_width"] || 2;
    },
    getLabel: function(feature) {
        return feature.attributes["label"] || '';
    },
    getDashStyle: function(feature) {
        return feature.attributes["dash_style"] || 'solid';
    }
};

var oltemplate = {
    externalGraphic: "${getIcon}",
    graphicWidth :  "${getWidth}",
    graphicHeight : "${getHeight}",
    graphicOpacity : 1,
    fillColor: "${getFillColor}",
    fillOpacity: 1,
    strokeColor: "${getStrokeColor}",
    strokeWidth : "${getStrokeWidth}",
    strokeDashstyle : "$getDashStyle",
    graphicXOffset : -10,
    graphicYOffset : -32,
    label : "${getLabel}",
    fontColor: "black",
    fontSize: "12px",
    fontFamily: "Verdana,Arial,sans-serif",
    fontWeight: "bold",
    labelAlign: "rt",
    labelXOffset: "10",
    labelYOffset: "10"
};


/**
* Loads/updates nearest photo list
*
* @param mixed element to update
* @param string nearest_base_url base url for nearest resources
* @param integer buffer_size
* @param object map var
* @param string loading animation element
*
*/
function ui_nearest_photos(nearest_photo_url, buffer_size, olmap, loading_element){
    try { jQuery(loading_element).show();} catch (e) {};
    // Creates a new layer if not exists and adds photos to the map
    vector = ui_map_add_geojson_layer(olmap, nearest_photo_url + buffer_size + '/', gettext('Photo'));
    try { jQuery(loading_element).hide();} catch (e) {};
    return vector;
}

function ui_map_add_geojson_layer(olmap, url, layer_name) {
    var style = new OpenLayers.Style(oltemplate, {context: olcontext});
    var styleMap = new OpenLayers.StyleMap({'default': style});

    // Create polygon layer as vector features
    vectors = new OpenLayers.Layer.GML( layer_name, url,
                                        { format: OpenLayers.Format.GeoJSON,
                                          styleMap: styleMap,
                                          isBaseLayer: false,
                                          projection: new OpenLayers.Projection("EPSG:4326"),
                                          attribution: "" } );

    olmap.addLayer(vectors);
    // Get existing Vector layers, bug fix for Mozilla FF
    vlayers = [vectors];
    jQuery(olmap.layers).each(function(k,l){
        if (l instanceof OpenLayers.Layer.Vector){
            vlayers.push(l);
        }
    })
    select = new OpenLayers.Control.SelectFeature(vlayers, { clickout: true, hover: false });
    select.events.register("featurehighlighted", olmap,
            function(evt) { olmap.createPopup(evt); });
    select.events.register("featureunhighlighted", olmap,
            function(evt) { olmap.deletePopup(); });

    olmap.addControl(select);
    select.activate();
    return vectors;
}

/**
* JSON RPC
*/
function jrpc(method, payload, success_fn, failure_fn){
    typeof payload != 'undefined' || (payload = []);
    var params = {
        "id": "djangorpc",
        "method": method,
        "params": payload
    };

    jQuery.ajax({
        url : '/RPC2',
        type : 'post',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        processData: false,
        data : jQuery.toJSON(params),
        success : function(jsonData, textStatus, xhr) {
            if(jsonData.error){
                if(typeof failure_fn == 'function') {
                    console.log('1');
                    failure_fn(jsonData.error, textStatus, xhr);
                }
            } else {
                if(typeof success_fn == 'function') {
                    success_fn(jsonData.result, textStatus, xhr);
                }
            }
        },
        error : function(xhr, textStatus, exception ) {
            if(typeof failure_fn == 'function') {
                    console.log(textStatus);
                failure_fn(exception, textStatus, xhr);
            }
        }
    });
}

/**
* Add a new object to the guide
* only add_object is supported from FE
*/
function vguide_new_item(params) {
    if( params.model_name && params.object_id) {
        var result;
        params = [params.model_name, params.object_id];
        jrpc('vguide.check_object', params, function(r) {
                result = r;
            }
            , function(r){
                notify(gettext('Error checking object before trying to add an item to the guide.') + '<br />' + r.message, gettext('Error'));
            }
        );
        if(!result){
            // Error
            return notify(gettext('The item is too far from the nearest node of the track network.'), gettext('Error adding item to the virtual guide'));
        }
        method = 'vguide.add_object';
    } else {
        // Error
        return notify(gettext("The function parameters were wrong."), gettext('Errormsg'));
    }
    jrpc(method, params, function(r, textStatus, xhr) {
            notify(r.fields['description'] + ' ' + gettext("has been added to your virtual guide"), gettext('Information'));
        }
        , function(r, textStatus, xhr){
            if(!r || !r.message){
                r = { message : gettext("You must be registered to use the virtual guide function, please login or register an account.") }
            }
            notify(gettext("Error adding item to the guide.") + '<br />' + r.message);
        }
    );
}

/**
* Strategy: notify
*/
function notify(text, title){
    if(typeof title == 'undefined') {
        title = gettext('Information');
    }
    jQuery.jGrowl(text, { header: title , life: 10000 });
}

/**
* Adds an alert
*/
function add_alert() {
    jQuery.jGrowl(gettext('Click on the map to add an alert.'), { header: gettext('Add alert activated.') });
    alert_ctrl.activate();
}

/**
* Adds a tree behaviour to .vmenu ul
*/
function vmenu_scan(){
    jQuery(".vmenu ul").hide();
    jQuery(".vmenu .ctrl").unbind('click');
    jQuery(".vmenu .ctrl").click(function(){
        jQuery(this).siblings().toggle("slow");
        return false;
    });
}

