var map;
var geocoder;
var marker;
function initializeGMaps() {
    
    if( !document.getElementById("map_canvas") )
        return;
    
    if( $('#map_canvas').attr('location') && $('#map_canvas').attr('location')!="" ) {
        var location = $('#map_canvas').attr('location');
        var loc = location.split(',');
        var lat = loc[0].substring(1, 100);
        var lng = loc[1].substring(1, (loc[1].length-1));
        var latlng = new google.maps.LatLng(lat, lng);
    } else {
        var latlng = new google.maps.LatLng(59.31212640236102, 18.06047910156251);
    }
    
    
    
    var myOptions = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        mapTypeControl: false
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    geocoder = new google.maps.Geocoder();

    placeMapMarker(latlng);
    google.maps.event.addListener(map, 'click', function(event) {
        /* Reverse geocode the zipcode */
        geocoder.geocode( { 'latLng': event.latLng}, function(results, status) {
            if( results[0] && results[0].address_components ) {
                for( var i = 0; i<results[0].address_components.length; i++ ) {
                    if( results[0].address_components[i].types[0]=='postal_code' ) {
                        $('#ads_location_zip>input').val(results[0].address_components[i].short_name);
                        break;
                    }
                }
            }
        });
        
        
        placeMapMarker(event.latLng);
        
    });
    
    //var image = 'images/beachflag.png';
    /*var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        //icon: image
    });*/
}

function placeMapMarker(location) {
  var clickedLocation = new google.maps.LatLng(location);
  
  if( marker && typeof(marker.setMap)!='undefined' ) {
	marker.setMap(null);
  }
	
    $('#map_canvas').attr('location', location.toString());
    
  marker = new google.maps.Marker({
      position: location, 
      map: map
  });
    $('#geo_pos').val(location.toString());
  //map.set_center(location);
}

function geocodeZipcode(zip) {
    
    if( zip.length==5 ) {
        geocoder.geocode( { 'address': zip+', Sweden'}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    //el.innerHTML+=','+results[0].geometry.location;
                    /*var marker = new google.maps.Marker({
                        position: results[0].geometry.location, 
                        map: map,
                        title:el.innerHTML
                    });   
                    bounds.extend(results[0].geometry.location);*/
                    placeMapMarker(results[0].geometry.location);
                    map.setCenter(results[0].geometry.location);
                }
                //$('#geo_counter').val(parseInt($('#geo_counter').val())+1);
                
                if( $('#geo_counter').val()>=$('.city').length ) {
                    map.fitBounds(bounds)
                }
            }
            
        });
    }    
    
    return zip;
}

function toggleSearch() {
    
    if( $('#search').hasClass('search_minimized') ) {

        $('#search').slideUp('normal', function () {
            $('#search').removeClass('search_minimized');
            $('#search').addClass('search_large');
            $('#search').slideDown('fast');
            
            
        });
        
    }else if( $('#search').hasClass('search_large') ) {
        $('#search').addClass('search_minimized');
        $('#search').removeClass('search_large');
    }
    return false;
}

function jsDate(format, timestamp) {
    var d = new Date();
    if( timestamp )
        d.setTime(timestamp*1000);

    format = format.replace("Y", d.getFullYear());

    var m = (d.getMonth()+1)+'';
    if( m.length==1 ) m = '0'+m;
    format = format.replace("m", m);
    
    var day = d.getDate()+'';
    if( day.length==1 ) day = '0'+day;
    format = format.replace("d", day);
    
    var hours = d.getHours()+'';
    if( hours.length==1 ) hours = '0'+hours;
    format = format.replace("H", hours);
    
    var minutes = d.getMinutes()+'';
    if( minutes.length==1 ) minutes = '0'+minutes;
    format = format.replace("i", minutes);
    
    return format;
}



/*
 * Based on javaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date(time);
	diff = (((new Date()).getTime() - date.getTime())/1000),
	day_diff = Math.floor(diff / 86400);
	
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) {
		return jsDate('Y-m-d', (time/1000));
    }
	diff = parseInt(diff);

    var r = '';
	if( day_diff == 0 && diff < 60 )
        r+="precis nu";
    else if( day_diff==0 && diff < 120 )
        r+="1 minut sedan";
    else if( diff < 3600 )
        r+=Math.floor( diff / 60 ) + " min sedan";
	else if( diff < 7200 )
        r+="1 timme sedan";
    else if( diff < 86400 )
        r+=Math.floor( diff / 3600 ) + " timmar sedan";
    else if( day_diff == 1 )
        r+="Igår "+jsDate('H:i', time);
    else if( day_diff < 7 )
        r+=day_diff + " dagar sedan";
    else if( day_diff==7 )
        r+=" 1 vecka sedan";
    else if( day_diff < 31 )
        r+=Math.ceil( day_diff / 7 ) + " veckor sedan";
    return r;
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
/* ----------------------------------------------------------------------------------- */


function showExtraSearchParams(section, settings) {
    /*if( section==0 ) {
        $('#search_params').html('');
        $('#search_params').slideUp('fast');
        return;
    }*/
    $.get('/ptm/ads/sproperties/section_id/'+section+'/settings/'+settings, function(resp) {
        $('#search_params').html(resp);
        if( $('#search_params').find('span').length==0 ) {
            $('#search_params').hide();
        }else{
            $('#search_params').slideDown('fast');
        }

        $('#search_selltype').find('option').hide();
        $('#search_params').find('input[name="selltypes"]').each(function () {
            
            var options = $('#search_selltype').find('option');
            for( var i = 0; i<options.length; i++ ) {
                if( $(options[i]).val()>0 ) {
                    if( $(options[i]).val()==$(this).val() )
                        $(options[i]).show();
                }else{
                    $(options[i]).show();
                }
            }
            
        });
        
    }); 
}

function showExtraParams(section, settings, type) {
    if( section==0 )
        return;
    $.get('/ptm/ads/properties/section_id/'+section+'/settings/'+settings+'/type/'+type, function(resp) {
       $('#extra_parameters').html(resp); 
    });
}



/* Search form helpers */



$(document).ready(function () {
    
    initializeGMaps();

    $('.prettydate').each(function() {
        $(this).text(prettyDate($(this).text()*1000));
    });

    /* Handle selection of counties */
    $('span.county').click(function () {

        var span_offset = $(this).offset();
        var county = $(this).attr('county');
        if( $('#qp_counties').val().indexOf(','+county)<0 && $('#qp_counties').val().indexOf(',*'+county)<0 ) {
            $('#qp_counties').val($('#qp_counties').val()+','+county);
            $(this).addClass('selected');
            
            $('#county_sub').attr('county', county);
            $('#county_sub').css('top', (span_offset.top-177)+'px');
            $('#county_sub').css('left', span_offset.left+'px');
            
            var select_box = $('#county_sub').find('select');
            select_box.empty();
            select_box.append('<option value="">Välj kommun</option>');
            $.getJSON('/ptm/ads/county/county/'+county, function (data) {
                $.each(data.kommuner, function(i,item){
                    select_box.append('<option value="'+item.Kommunkod+'">'+item.Kommun_klartext+'</option>');
                });
            })
            
            $('#county_sub').show();
        }else{

            var qp_counties = $('#qp_counties').val().split(',');
            for( var i = 0; i<qp_counties.length; i++ ) {
                if( qp_counties[i]==county || qp_counties[i]=='*'+county || qp_counties[i].substring(0,2)==county )
                    qp_counties[i]='';
            }
            $('#qp_counties').val(qp_counties.join(','));  

            $(this).removeClass('selected');
            $('#county_sub').hide();
        }
        return false;
    });

/*
    $(document).click(function () {
        console.log($(this));
        try {
            if( $(event.srcElement).attr('id')!='county_sub' && $(event.srcElement).parent('#county_sub').length==0 )
                $('#county_sub').hide();
        }catch( e ) {
            $('#county_sub').hide();
        }
       
    });
       */

    $('#county_sub>input,select').change(function() {
        var qp_counties = $('#qp_counties').val().split(',');
        for( var i = 0; i<qp_counties.length; i++ ) {
            if(
               $('#county_sub').attr('county')==qp_counties[i] ||
               '*'+$('#county_sub').attr('county')==qp_counties[i] ||
               $('#county_sub').attr('county')==qp_counties[i].substring(0,2)
               ) {
                if( $(this).attr('id')=='county_sub_surround' )
                    qp_counties[i] = '*'+$('#county_sub').attr('county');
                else if( $(this).attr('id')=='county_sub_all' )
                    qp_counties[i] = $('#county_sub').attr('county');
                else if( $(this).attr('id')=='county_sub_area' && $('#county_sub>select').val()!="" )
                    qp_counties[i] = $('#county_sub>select').val();
                else if( $(this).attr('name')=='county_sub_area' && $(this).val()!="" )
                    qp_counties[i] = $(this).val();
            }
        }
       
        $('#qp_counties').val(qp_counties.join(','));  
    });



    /* View a specific ad */
    $('.view_ad').find('.thumbnails > span').click(function() {
        $('.view_ad').find('.big_image').html('<img src="'+$(this).attr('original_image')+'" />');    
    });

    $('.view_ad').find('.big_image').click(function () {
        var current_src = $(this).find('img').attr('src');
        var thumbs = $('.view_ad').find('.thumbnails').find('span[original_image]');
        
        for( i=0; i<thumbs.length; i++ ) {
            if( current_src.indexOf($(thumbs[i]).attr('original_image'))>=0 ) {
                if( (i+1)==thumbs.length )
                    i = 0;
                else
                    i++;
                break;
            }
        }
        $('.view_ad').find('.big_image').html('<img src="'+$(thumbs[i]).attr('original_image')+'" />');    
    });


    
});

function cleanNr(val) {
    val = val.replace(',', '.');
	valid_chars = '00123456789.';
	var clean_val = '';
	for( var i = 0; i<val.length; i++ ) {
		if( valid_chars.indexOf(val.substring(i,i+1))>=0 )
			clean_val+=''+val.substring(i,i+1);
	}
	
	return clean_val;
}
