jQuery(function()
{
    jQuery('#fi_halti_retailers_freeform').submit(function()
    {
        return false;
    });
    
    url = MIDCOM_PAGE_PREFIX + 'retailers/closest/?l=3';
    current = String(window.location);
    
    if (regs = current.match(/[\?&](cq=.+?)(&|$)/))
    {
        url += '&' + regs[1];
    }
    
    jQuery('#closest_retailers').load
    (
        url + ' div.retailers_list'
    )
    
    jQuery('#fi_halti_retailers_freeform input[type="text"]')
        .focus(function()
        {
            jQuery(this).removeClass('empty');
            if (jQuery(this).attr('value') == jQuery(this).attr('rel'))
            {
                jQuery(this).attr('value', '');
            }
        })
        .blur(function()
        {
            if (jQuery(this).attr('value') == '')
            {
                jQuery(this).attr('value', jQuery(this).attr('rel'));
                jQuery(this).addClass('empty');
            }
        })
        .keyup(function()
        {
            jQuery(this).attr('title', jQuery(this).attr('value'));
            
            // Short delay on the launch, prevents from multitude of responds
            jQuery(this).oneTime(500, function()
            {
                if (jQuery(this).attr('value') != jQuery(this).attr('title'))
                {
                    return;
                }
                
                // Emptry cached key
                jQuery(this).attr('title', '');
                
                url = MIDCOM_PAGE_PREFIX + 'retailers/closest/?l=3';
                
                if (jQuery(this).attr('value'))
                {
                    var value = jQuery(this).attr('value');
                    
                    while (value.match(/ /))
                    {
                        value = value.replace(/^\s*(.+?)\s*$/, '$1');
                        value = value.replace(/ /, '+');
                    }
                    
                    // Skip searching with a space only
                    if (value)
                    {
                        url += '&cq=' + value;
                    }
                }
                
                jQuery('#closest_retailers').load
                (
                    url + ' div.retailers_list'
                );
            });
        });
    
    jQuery('#content-right').initialize_thickbox();
    jQuery('#cloudmade_maps').show_map();
});

jQuery.fn.show_map = function()
{
    var rel = jQuery(this).attr('rel');
    
    if (!rel)
    {
        return;
    }
    
    regs = rel.match(/^(street|coords):(([\-0-9\.]+?);([\-0-9\.]+?)|.+?)($|;scope:[0-9]+)/)
    
    if (   !regs
        || !regs[1])
    {
        return;
    }
    
    // Get the map
    var cloudmade = new CM.Tiles.CloudMade.Web(
    {
        key: 'ed7aaaf3733444ea8dfd4cab0149ca70',
        styleId: 10321
    });
    
    // Get the ID of the element requested
    var id = jQuery(this).attr('id');
    
    cloudmade_maps_map = new CM.Map(id, cloudmade);
    
    // Define an icon
    var map_icon = new CM.Icon();
    map_icon.image = MIDCOM_STATIC_URL + '/fi.halti.products/map-marker.png';
    
    map_icon.iconSize = new CM.Size(20, 20);
    map_icon.iconAnchor = new CM.Point(10, 10);
    
    zoom_level = 9;
    
    // Get the zoom level
    for (i = 0; i < regs.length; i++)
    {
        if (   !regs
            || !regs[i])
        {
            continue;
        }
        
        if (!regs[i].match(/scope:([0-9]+)$/))
        {
            continue;
        }
        
        regs_2 = regs[i].match(/scope:([0-9]+)$/);
        zoom_level = Number(regs_2[1]);
    }
    
    switch (regs[1])
    {
        case 'street':
            var geocoder = new CM.Geocoder('ed7aaaf3733444ea8dfd4cab0149ca70');
            geocoder.getLocations
            (
                regs[2],
                function(response)
                {
                    for (var i = 0; i < response.features.length; i++)
                    {
                        var coords = response.features[i].centroid.coordinates;
                        cloudmade_maps_map.setCenter(new CM.LatLng(coords[0], coords[1]), zoom_level);
                        
                        var lat = coords[0];
                        var lng = coords[1];
                        var marker = new CM.Marker
                        (
                            new CM.LatLng(lat, lng),
                            {
                                icon: map_icon,
                                clickable: false
                            }
                        );
                        
                        cloudmade_maps_map.addOverlay(marker);
                        
                        break;
                    }
                }
            );
            break;
        
        case 'coords':
            var lat = Number(regs[3]);
            var lng = Number(regs[4]);
            
            cloudmade_maps_map.setCenter(new CM.LatLng(lat, lng), zoom_level);
            
            var marker = new CM.Marker
            (
                new CM.LatLng(lat, lng),
                {
                    icon: map_icon,
                    clickable: false
                }
            );
            
            cloudmade_maps_map.addOverlay(marker);
            break;
    }
    
    // Set controls
    cloudmade_maps_map.disableScrollWheelZoom();
    cloudmade_maps_map.addControl(new CM.SmallMapControl());
    cloudmade_maps_map.addControl(new CM.ScaleControl());
}

jQuery.fn.initialize_thickbox = function()
{
    jQuery(this).find('a.thickbox')
        .each(function()
        {
            // Switch the link on the fly to use Thickbox to load images only
            if (jQuery(this).attr('src'))
            {
                jQuery(this).attr('href', jQuery(this).attr('src'));
            }
            
            var href = jQuery(this).attr('href');
            
            if (href.match(/(jpe?g|png|gif)$/))
            {
            }
            else if (href.match(/\?/))
            {
                href += '&ajax';
            }
            else
            {
                href += '?ajax';
            }
            
            jQuery(this).attr('href', href);
        });
    
    tb_init('a.thickbox');
}
