jQuery(function( $ ){
	$("div.scrollable-vertical").scrollable({ 
	        vertical:true
	});
		
    $('#iphone_link').click(function() {
        ef__l(["","ne|","pho","|i"]);
    });
	
	/*

    */
	$("#search").prefilled_fields();
	
    
});

var POPUP = $(document.createElement('div')).hide().addClass('baro_popup');
var POPUP_VISIBLE = false;
var POPUP_SHOWING_ID = -1;
var EMPTY_CHOICE = '- - - - - - - - - - - - - - - - - - - - - -';

function popup_full(z) {
	var evolution = '';
    if (z.ev_value > 0) {
        evolution = z.ev + '<img src="' + IMG_UP + '" />';
    }
    else {
        evolution = z.ev + '<img src="' + IMG_DOWN + '" />';
    }
    if(z.pm[0] != "ND")
        bottom_limit = " " + z.pm[0] +" &lt ";
    else
        bottom_limit = "";
    if(z.pm[2] != "ND")
        upper_limit = " &lt " + z.pm[2];
    else
        upper_limit = "";
	var lines=[
		'<div class="ptitle">'+z.lbl+'</div>',
		'<div class="phead">Prix moyen du m2</div>',
		'<div>'+bottom_limit+'<span class="meanprice_small">'+z.pm[1]+'&nbsp;&euro;</span>'+upper_limit+'</div>',
		'<div class="phead">Prix moyen bien immobilier</div>',
		'<div>'+z.ap+' &euro;</div>',
		'<div class="phead">Evolution des prix au m2 (1mois)</div>',
		'<div>'+evolution+'</div>'
	];
	return lines;
}

function popup_light(z) {
	var lines=[
		'<div class="ptitle">'+z.lbl+'</div>',
		'<div class="phead">Prix moyen du m2</div>',
		'<div>'+z.pm+'&nbsp;&euro;</div>'
	];
	return lines;
}

function show_popup(sel){
	return function(e) {
		var offset = $(sel).offset();
		var zid = this.id.split('_')[1];
		var z = CHILDREN_INFOS[zid];
		x = e.pageX - offset.left;
		y = e.pageY - offset.top;
		POPUP.css('left', (x+4)+'px');
		POPUP.css('top', (y-30)+'px');
		if (POPUP_SHOWING_ID!=zid){
			var lines = [];
			if (z.kind=='full') {lines = popup_full(z);}
			if (z.kind=='light') {lines = popup_light(z);}
			POPUP.html(lines.join(''));
		}
		if (!POPUP_VISIBLE){
			POPUP.show();
			POPUP_VISIBLE = true;
		}
		POPUP_SHOWING_ID = zid;
	};
}

function hide_popup() {
	POPUP.hide();
	POPUP_VISIBLE = false;
}

function baro2_init_downer() {
	$("#search").keydown(handle_return);
	if (SHOW_MAP) {load_gmap('map_barometre');}
}

function baro2_init_address() {
	load_gmap('small_map');
	load_gmarker();
}



/* Functions for Label positionning */

function get_bbox(element) {
    // Return the element bounding box. Bounding box is a bit "larger" than the real one in order to avoir labels too close
    if(element.bbox)
        return element.bbox;
        
    offset_x = 8;
    offset_y = 5;
    var bbox = {};
    var el_pos = element.position();
    bbox.tl = {};    // Top-Left corner
    bbox.tl.x = el_pos.left - offset_x;
    bbox.tl.y = el_pos.top - offset_y;
    bbox.br = {};    // Bottom-right
    bbox.br.x = bbox.tl.x + element.width() + offset_x;
    bbox.br.y = bbox.tl.y + element.height() + offset_y;
    element.bbox = bbox;
    return bbox;
}

function get_surf(element) {
    // Compute the surface of an element
    if(element.surface)
        return element.surface;
    element.surface = element.width() * element.height();
    return element.surface;
}

function is_point_inside(rect, point) {
    // Check if point is inside rect
    if(point.x >= rect.tl.x && point.y >= rect.tl.y && point.x <= rect.br.x && point.y <= rect.br.y )
        return true;
    return false;
}

function elem_overlaps(elem1, elem2) {
    // Brute check : test if one of the 4 corners of the smallest elem are inside the biggest elem
    // Small optim : if the 2 labels are far "y" away skip the test
    if(get_surf(elem1) < get_surf(elem2)) {
        bbox1 = get_bbox(elem2);
        bbox2 = get_bbox(elem1);
    }
    else {
        bbox1 = get_bbox(elem1);
        bbox2 = get_bbox(elem2);
    }
    if(Math.abs(bbox1.tl.y - bbox2.tl.y) > 50) {
        return false;
    }
    
    tl2 = bbox2.tl;
    tr2 = {};
    tr2.x = bbox2.br.x; tr2.y = bbox2.tl.y;
    br2 = bbox2.br;
    bl2 = {};
    bl2.x = tl2.x; bl2.y = br2.y;
    to_check = [tl2, tr2, br2, bl2];
    for(var i=0; i< 4; i++) {
        if( is_point_inside(bbox1, to_check[i]) === true) {
            return true; 
        }
    }
    return false;
}

// Basicaly the 8 possible displacement and the initial position
BASE_DISPLACEMENT_MATRIX = [ [0, 0],
                        [0, 1],
                        [0, -1],
                        [1, 0],
                        [-1, 0],
                        [-1, -1],
                        [-1, 1],
                        [1, 1],
                        [1, -1]
                        ];
                        
DISPLACEMENT_MATRIX = Array();

function extend_matrix(coeff) {
    // Just an helper to extend the matrix with biggest distance
    for (var i=0; i < BASE_DISPLACEMENT_MATRIX.length; i++) {
        DISPLACEMENT_MATRIX.push([BASE_DISPLACEMENT_MATRIX[i][0]*coeff, BASE_DISPLACEMENT_MATRIX[i][1]*coeff]);
    }
}

function displace_element(elem, initial_position, displacement) {
    // The following 2 are the smallest possible displacement. They are mutiplied by a value from the matrix
    offset_x = 6;
    offset_y = 3;
    elem.bbox = null;   // as we are moving the element, invalidate previous bbox
    displ = DISPLACEMENT_MATRIX[displacement];
    elem.css("left", initial_position.left + displ[0] * offset_x);
    elem.css("top", initial_position.top + displ[1] * offset_y);
}


function check_overlaps(elem, city) {
    // Check if elem overlaps one of the displayed label, if so, try to move elem in a position where it doesn't overlaps any visible element
    var initial_position = elem.position();
    var backup_initial_position = $.extend({}, initial_position);
    
    var reverted = 0;   // A flag for the city, to know the position of the pin (left, right, top, bottom)
    if(city === true) {
        max_displacement = 1;   // Restrict movement for city
    } else {
        max_displacement = DISPLACEMENT_MATRIX.length;
    }
    for(var current_displacement = 0;current_displacement < max_displacement; current_displacement++) {
        displace_element(elem, initial_position, current_displacement);
        is_overlapping = false;
        
        for(var i=0; i < VISIBLE_LABELS.length; i++) {
            is_overlapping = elem_overlaps(elem, VISIBLE_LABELS[i]);
            if(is_overlapping === true) {
                if(current_displacement + 1 == max_displacement) {
                    if( city === true && reverted < 3) {
                        // For city there is A Last Hope, try to display the city name on the left of the pin
                        
                        current_displacement = -1;
                        i=0;
                        initial_position = $.extend({}, backup_initial_position);
                        elem.removeClass("lblk1").removeClass("lblk1-right").removeClass("lblk1-bottom").removeClass("lblk1-top");
                        if( reverted === 0 ) {
                            // Pin on the right
                            elem.addClass("lblk1-right");
                            initial_position.left = backup_initial_position.left - elem.width();
                        } else if (reverted == 1) {
                            // Pin on the bottom
                            elem.addClass("lblk1-bottom");
                            initial_position.left = backup_initial_position.left - parseInt(elem.width() / 2.0, 10) + 6;
                            initial_position.top = backup_initial_position.top - elem.height(); 
                        } else {
                            // Pin on top
                            elem.addClass("lblk1-top");
                            initial_position.left = backup_initial_position.left - parseInt(elem.width() / 2.0, 10) + 6;
                        }
                        reverted++;
                        break;
                    }
                    else {
                        // We have tried all the possible movment, sad, no ways to display the label
                        return true;
                    }
                }
                else {
                    // Overlapping, but hey ! There is still some movements to try, so there is still hope !
                    break;
                }
            }
        }   // End for each visible element
        if(is_overlapping === false) {
            // Groovy, found a place to put the label without overlapping :)
            break;
        }
    }
    return false;
}
VISIBLE_LABELS = [];

function add_labels() {
    visible_labels = [];
	$('#img_container').prepend(POPUP);
	for (var i=0; i<BARO_LABELS.length; i++) {
		var item = BARO_LABELS[i];
		if (item[3]) {
			// Creating div for labels :
			var label_div = $(document.createElement('div')).hide().addClass('map_label').addClass('carto_label').addClass('lblk'+item[4]).attr('id', 'zone_'+item[0]).html(item[3]);
			// Attaching to img_container :
			$('#img_container').prepend(label_div);
			if (item[4]===0) {
				var w = label_div.width();
				var h = label_div.height();
				ox = Math.floor(w/2);
				oy = Math.floor(h/2);
			}
			else {
				ox=0;
				oy=0;
			}
			label_div.css('left', parseInt(item[1], 10)-ox+'px');
			label_div.css('top', parseInt(item[2], 10)-oy+'px');
			label_div.show();
			if( check_overlaps(label_div, item[4]==1) === false) {
                VISIBLE_LABELS.push(label_div);
            }
            else {
                label_div.hide();
            }
		}
	}
	$("area, .map_label").mousemove(show_popup('#img_container')).mouseout(hide_popup).click(function() {document.location = CHILDREN_INFOS[this.id.split('_')[1]].url+'#pricemap';});
}

function handle_return(e) {
	e = e || window.event;
	if (e.keyCode == 13) {
		goto_address();
		return false;
	}
}

function baro2_init_upper() {
    if( IS_DEP_ARR === true) {
        // restrict movment for city
        extend_matrix(1.0);
        extend_matrix(2.0);
        extend_matrix(3.0);
    } else {
        extend_matrix(2.0);
        extend_matrix(5.0);
        extend_matrix(10.0);
    }
	add_labels();
	$('#id_region').change( function() {update_departments(this.value);});
	$('#id_dept').change( function() {update_cities(this.value);});
	update_cities($('#id_dept').val());
	$("#search").keydown(handle_return);
}

function pie_chart(div_id, datum, colors, decimals, suffix) {
	var c = new JSChart(div_id, 'pie');
	c.setDataArray(datum);
	c.colorizePie(colors);
    c.setTitle('');
	c.setTitleColor('#857D7D');
	//c.setPieUnitsColor('#9B9B9B');
	c.setPieUnitsColor('#000');
	c.setPieValuesColor('#111');
	c.setPiePosition(0,90);
	if (decimals !== null) c.setPieValuesDecimals(decimals);
    if (suffix !== null) c.setPieValuesSuffix(suffix);
    c.setPieRadius(66);
	c.setSize(280, 210);
	c.draw();
}

function bar_chart(div_id, datum, colors, decimals, suffix, y_name) {
	var c = new JSChart(div_id, 'bar');
	c.setDataArray(datum);
	c.colorizeBars(colors);
	c.setTitle('');
	c.setAxisNameX('');
	c.setAxisNameY('');
	c.setAxisNameFontSize(16);
	c.setAxisColor('#666');
	c.setAxisNameColor('#000');
	c.setAxisValuesColor('#000');
	c.setBarValuesColor('#333');
	if (decimals !== null) c.setBarValuesDecimals(decimals);
	if (suffix !== null) c.setBarValuesSuffix(suffix);
	if (y_name !== null) c.setAxisNameY(y_name);
	c.setAxisPaddingBottom(30);
	c.setAxisPaddingLeft(50);
	c.setAxisPaddingRight(30);
	c.setAxisPaddingTop(10);
	//c.setTextPaddingLeft(105);
	c.setBarValuesFontSize(7);
	c.setBarBorderWidth(1);
	c.setBarBorderColor('#C4C4C4');
	c.setBarSpacingRatio(5);
	c.setGrid(true);
	c.setSize(550, 220);
	c.draw();
}

function line_chart(div_id, datum, labels, decimals) {
	var c = new JSChart(div_id, 'line');
	c.setDataArray(datum);
	c.setAxisColor('#666');
	c.setAxisNameColor('#000');
	c.setAxisValuesColor('#000');
	c.setAxisNameFontSize(10);
	c.setAxisNameX('');
	c.setAxisNameY('');
	c.setAxisPaddingBottom(30);
	c.setAxisPaddingLeft(50);
	c.setAxisPaddingRight(30);
	c.setAxisPaddingTop(10);
    if (decimals !== null) c.setAxisValuesDecimals(decimals);
	c.setAxisValuesNumberX(6);
	c.setBackgroundColor('#FFF');
	for (var i = 0; i < labels.length; i++){ 
		c.setLabelX(labels[i]);
	}
	c.setLineColor('#F76015');
	c.setShowXValues(false);
	c.setShowYValues(true);
	c.setTitle('');
	c.setSize(550, 150);
	c.setTextPaddingBottom(20);
	c.setTextPaddingLeft(120);
	c.setTextPaddingTop(15);
	c.setFlagRadius(6);
	for (var i = 0; i < datum.length; i++){ 
		c.setTooltip(datum[i]);
	}
	c.draw();
}

function change_cities(res) {
	var select_city = $('#id_city');
	var content = [];
	for (var i = 0; i < res.option.length; i++){
		city = res.option[i];
		content[i] = '<option value="'+city[0]+'">'+city[1]+'</option>';
	}
	select_city.html('<option value="0" selected="1">'+EMPTY_CHOICE+'</option>'+content.join(''));
	select_city.attr('disabled',false);
    if ($("label[for='id_city']").text() != res.label) {
        $("label[for='id_city']").text(res.label);
    }
}

function update_cities(id) {
	var id = parseInt(id, 10);
	if (id>0) {
		var select_city = $('#id_city');
		select_city.attr('disabled',true);
		$.getJSON(BARO_URL+'/cities/'+id+'/', change_cities);
	}
	else {$('#id_city').html('<option value="0" selected="1">'+EMPTY_CHOICE+'</option>');}
}

function change_departments(depts) {
	var select_dept = $('#id_dept');
	var content = [];
	for (var i = 0; i < depts.length; i++){
		dept = depts[i];
		content[i] = '<option value="'+dept[0]+'">'+dept[1]+'</option>';
	}
	select_dept.html('<option value="0" selected="1">'+EMPTY_CHOICE+'</option>'+content.join(''));
	select_dept.attr('disabled',false);
	// Cascade change on departement to cities :
	sel = $('#id_dept').val();
	if (sel) {update_cities(sel);}
}

function update_departments(id) {
	var id = parseInt(id, 10);
	if (id>0) {
		var select_dept = $('#id_dept');
		select_dept.attr('disabled',true);
		$.getJSON(BARO_URL+'/departments/'+id+'/', change_departments);
	}
	else {
		$('#id_dept').html('<option value="0" selected="1">'+EMPTY_CHOICE+'</option>');
		$('#id_city').html('<option value="0" selected="1">'+EMPTY_CHOICE+'</option>');
	}
}

function goto_zone() {
	var val = parseInt($('#id_city').val(), 10);
	if (!val || val===0) {
		val = parseInt($('#id_dept').val(), 10);
	}
	if (!val || val===0) {
		val = parseInt($('#id_region').val(), 10);
	}
	if (val) {
		document.location = '/prix-immobiliers/id_z'+val+'/#pricemap';
	}
}

function goto_address() {
	$('#search_loading').show();
	$.post(BARO_URL+'/recherche/', { address: $('#search').val() }, 
		function(data){
			$('#search_loading').hide();
			if (data.redirect) {
				document.location = data.redirect+'#pricemap';
				return;
			}
			var lines = [];
			var links = [];
			if (data.msg) {lines[0] = '<strong>'+data.msg+'</strong>';}
			if (data.msg2) {lines[1] = data.msg2;}
			if (data.results) {
				var results = data.results;
				links[0]='<br/><ul>';
				for (var i = 0; i < results.length; i++){
					var res = results[i];
					links[links.length] = '<li><a href="'+res[0]+'">'+res[1]+'</a></li>';
				}
				links[links.length]='</ul>';
			}
			$('#search_results').html(lines.join('<br/>')+links.join(''));
		}, "json");
}


var myPano;
var panoClient; 
function init_streetview(lat,lng) {
	/*
	var geocoder = new GClientGeocoder();
	var coordinates = new GLatLng(lat,lng);
	panoramaOptions = { latlng:coordinates };
	panoClient = new GStreetviewClient();
	myPano = new GStreetviewPanorama(document.getElementById("streetview"), panoramaOptions);
	GEvent.addListener(myPano, "error", handleError);
	panoClient.getNearestPanorama(coordinates, function(tmp) {});
	*/
}


function handleError(errorCode) {
	if (errorCode == 603 || errorCode == 600){
		$("#sv_container").hide();
		return;
	}
}
