/****** FUNCTIONS RELATED TO EVENTS *******/


/**
* @author Javier Millan
*
* Bind the plot hover and polot click events to control the highlighting
* and the visualization of point tags
*
* @param <placeholder> Placeholder of the flot
*
*/
function bindEvents(placeholder){	
	
    /**
     * Graph onHover hook
     */
    placeholder.bind("plothover", function (event, pos, item) {

            var identifier;
            var tagmode;
            if(item){

            //ident + tagmode of the serie
            identifier=item.series.raw_ident;
            tagmode = item.series.tagmode;

                if(tagmode !="none"){

                        //hide the last visible tag
                        if(last_selected_item)
                                last_selected_item.css("visibility", "hidden");

                        //makes visible the current tag
                        last_selected_item = $('#'+identifier+item.dataIndex);
                        last_selected_item.css("visibility", "visible");

                        /*if the current tag must always be visible,
                        it should not be hidden in the next event*/
                        if(tagmode =="visible")
                                last_selected_item = null;
                }
            }

            //it's hover a zone without series, hide the last one selected
            else{
                    if(last_selected_item)
                            last_selected_item.css("visibility", "hidden");
            }

    });
	
	
    placeholder.bind("plotclick", function (event, pos, item) {

        if(item){
            var product_id = item.series.ident;
            var hv = item.series.hv;
            var epoch = item.series.raw_data[item.dataIndex][0];
            if(item.series.now && item.series.now <= epoch){
                //call function to trigger the event EVENT_SET_PRODUCT_EPOCH
                triggerEventSetProductEpoch('meteogram',epoch/1000,product_id,hv)
            }
        }
    });
}


/**
* @author Javier Millan
*
* Makes the highlight of the item; (called from alert component) 
*
* @param <idElemTrigg>	ID of the element that has triggered the event
* @param <productId>	ID of the product to highlight
* @param <higherValues>			higer values of the product to highlight
* @param <epoch>	start epoch of the item to highlight
* @param <end_epoch>	end epoch of the item to highlight
*
* @return 0->process OK; -1-> invalid highlighting
*
*/
function meteogram_eventSetProductEpoch(idElemTrigg,epoch,productId,higherValues){

	var nplots = GLOBAL_PLOTS.length;
	var vindex,i;
        var plot_index = -1;
        var data_index = -1;
        
        epoch*=1000;//multiply epoch to obtain a milliepoch
	
	//unhighlight the previous item highlighted
	for(var j=0;j<nplots;j++){GLOBAL_PLOTS[j].unhighlight();}
	
	//find the correct flot
        for(i=0;i<nplots;i++){
		data_index = find_uuid_hv_in_plot(GLOBAL_PLOTS[i].getData(),productId,higherValues);
		if(data_index>-1){
			plot_index = i;
                        break;
                }
	}
	
	//invalid highlighting
	if(data_index==-1)
		return -1;
	
	//plot index->i;  product index -> pindex
	var dataarray = GLOBAL_PLOTS[plot_index].getData()[data_index].raw_data;
	var highlightmode = GLOBAL_PLOTS[plot_index].getData()[data_index].hmode;
	
	//TODO-> import this function from wicast_meteogram.js library
	vindex = find_epoch_in_product_array(dataarray,epoch,highlightmode);
	
	
	//finally highlight the correct item
	var series 	= GLOBAL_PLOTS[plot_index].getData()[data_index];
	var datapoint 	= [GLOBAL_PLOTS[plot_index].getData()[data_index].data[vindex][0],GLOBAL_PLOTS[plot_index].getData()[data_index].data[vindex][1],0];

	GLOBAL_PLOTS[plot_index].highlight(series,datapoint);
	
	return 0;		
}


function meteogram_eventSetPeriod(idElemTrigg,epoch_start,epoch_end,idPoint){

    //do an ajax call to obtain values from db
    var data2;
         $.ajax({
            async: false,
            type: "GET",
            dataType: 'json',
            url: '/frontend.php/es/query/meteogram?'+'START='+epoch_start+'&END='+epoch_end+'&id_point='+idPoint,
            success: function(data){
                data2 = data;
            }
        });

    meteo_data = new Object();
    meteo_data.options = data2.options;
    meteo_data.product_data = data2.product_data;
    //console.dir(meteo_data.product_data);
    meteo_config  = data2.config;
    GLOBAL_PLOTS = [];
    legends = [];
    var divs;

    //comprove if is generated to create divs
    if($('#meteogram').html() =='')
        divs = false;
        
     else
        divs = true;

    generateMeteogram(divs);
}


/**
* Searches for a specific epoch value in an array and returns
* the index holding the value
*
* @param data_array		array of data holding a product epoch and values [[epoch,val],[epoch,val].....]
* @param epoch			epoch to search
* @param searchmode		can be one of 	_H_FLOOR	returns the lowest nearest position
*										_H_CELINIG	returns the highest nearest position
*										_H_NEAREST	returns the nearest position
*
* @return integer holding the index of the desired item, -1 if nothing is found
*/
function find_epoch_in_product_array(data_array,epoch,hmod){

	switch(hmod){
		case _H_FLOOR:
			return find_epoch_in_parray_floor(data_array,epoch,hmod);
		break;
		case _H_CEILING:
			return find_epoch_in_parray_ceiling(data_array,epoch,hmod);
		break;
		case _H_NEAREST:
			return find_epoch_in_parray_nearest(data_array,epoch,hmod);
		break;
		default:
			return find_epoch_in_parray_floor(data_array,epoch,hmod);
		break;
	}
	return -1;
}

/**
* Returns the index of a searched epoch in a given array
* if the epoch is not in the array returns the lowest of
* the two nearest values
*
*	@param data_array	Array of pairs where the epoch must be searched
*	@param epoch		epoch to search
*/
function find_epoch_in_parray_floor(data_array,epoch){
	var ln = data_array.length;
	for(var i=0;i<ln;i++){
        if(data_array[i][0] == epoch) return i;
        else if(data_array[i][0] > epoch) return i-1;
    }
}

/**
* Returns the index of a searched epoch in a given array
* if the epoch is not in the array returns the highest of
* the two nearest values
*
*	@param data_array	Array of pairs where the epoch must be searched
*	@param epoch		epoch to search
*/
function find_epoch_in_parray_ceiling(data_array,epoch){
	var ln = data_array.length;
	for(var i=0;i<ln;i++){
        if(data_array[i][0] >= epoch) return i;
    }
	return 0;
}

/**
* Returns the index of a searched epoch in a given array
* if the epoch is not in the array returns the nearest
*
*	@param data_array	Array of pairs where the epoch must be searched
*	@param epoch		epoch to search
*/
function find_epoch_in_parray_nearest(data_array,epoch){
	var ln = data_array.length;
	var diff1,diff2;

	for(var i=0;i<ln;i++){
        if(data_array[i][0] == epoch) return i;
        else if(data_array[i][0] > epoch){
			if(i-1<0) return -1;
			diff1 = data_array[i][0] - epoch;
			diff2 = epoch - data_array[i-1][0];

			if(diff1<=diff2){return i}
			else{ return i-1}
		}
    }
}



/**
* @author Jordi Castells
*
* Loops through the objects array looking for a specific uuid value
* @param value						The uuid value to search
* @param hv							The higher values representing the product
* @param plot_data_objects_array	The array of products of one plot
*
* @return The index of the product in the array, -1 if the product is not found
*/
function find_uuid_hv_in_plot(plot_data_objects_array,value,hvalues){
	var ln = plot_data_objects_array.length;

	for(var i=0;i<ln;i++)
        {
            if(plot_data_objects_array[i].ident == value && plot_data_objects_array[i].hv == hvalues)
                return i;
        }
	return -1;
}


/*
 * 
 * EVENTS FUNCTIONS
 * 
 */

/*
 * Main function that stablish relation between bind functions and the specific one
 * First unbind all possible events, and then bind
 */
function meteogram_bindEvents(){
    //start with unbind all functions
    meteogram_unbindFunctions();
    //now bind it
    meteogram_bindFunctions();

}
/*
 * Simply unbind all events
 */
function meteogram_unbindFunctions(){

    $(document).unbind('EVENT_SET_PRODUCT_EPOCH', function(event,idElemTrigg,epoch,productId,higherValues){meteogram_eventSetProductEpoch(idElemTrigg,epoch,productId,higherValues)});
    $(document).unbind('EVENT_SET_PERIOD', function(event,idElemTrigg, startEpoch, endEpoch,idPoint){meteogram_eventSetPeriod(idElemTrigg, startEpoch, endEpoch,idPoint)});

}
/*
 * Simply bind all events
 */
function meteogram_bindFunctions(){

    $(document).bind('EVENT_SET_PRODUCT_EPOCH', function(event,idElemTrigg,epoch,productId,higherValues){meteogram_eventSetProductEpoch(idElemTrigg,epoch,productId,higherValues)});
    $(document).bind('EVENT_SET_PERIOD', function(event,idElemTrigg, startEpoch, endEpoch,idPoint){meteogram_eventSetPeriod(idElemTrigg, startEpoch, endEpoch,idPoint)});

}
