var IE = null;

var fi_cityshops_places_location_latitude = null;
var fi_cityshops_places_location_longitude = null;

var fi_cityshops_places_bounds =
{
    max_lat: 60.240,
    min_lat: 60.150,
    max_long: 25.00,
    min_long: 24.85
}

jQuery(function()
{
    // Add form tabs
    // jQuery('#fi_cityshops_places_editor form').tabbed();
    jQuery('#fi_cityshops_places_quick_filter').find('select')
        .bind('change', function()
        {
            var selected_genre = jQuery(this).val();
            var genres = new Array();
            var found = false;
            var options = jQuery(this).find('option');
            
            if (!selected_genre)
            {
                for (i in map_markers)
                {
                    map_markers[i].setMap(map);
                }
                
                return;
            }
            
            for (i = 0; i < options.size(); i++)
            {
                if (options.eq(i).attr('value') == selected_genre)
                {
                    found = true;
                    
                    if (options.eq(i).text().match(/^»/))
                    {
                        genres = new Array(options.eq(i).attr('value'));
                        break;
                    }
                    
                    genres.push(options.eq(i).attr('value'));
                    continue;
                }
                
                if (!found)
                {
                    continue;
                }
                
                if (options.eq(i).text().match(/^»/))
                {
                    genres.push(options.eq(i).attr('value'));
                }
                else
                {
                    break;
                }
            }
            
            var regexp_str = '';
            
            for (i in genres)
            {
                if (regexp_str)
                {
                    regexp_str += '|';
                }
                
                regexp_str += genres[i];
            }
            
            var reg = new RegExp('(' + regexp_str + ')');
            
            for (i in map_markers)
            {
                if (map_markers[i].memberships.match(reg))
                {
                    map_markers[i].setMap(map);
                }
                else
                {
                    map_markers[i].setMap(null);
                }
            }
        });
    
    if (jQuery('table.tablesorter').size())
    {
        jQuery('table.tablesorter').tablesorter
        (
            {
                widgets: ['zebra']
            }
        );
    }
    
    jQuery('div.fi_cityshops_shop_minilist').initialize_shop_dl_pager();
    
    jQuery('a.videochat')
        .bind('click', function()
        {
            var href = jQuery(this).attr('href');
            
            if (href.match(/\?/))
            {
                href += '&popup';
            }
            else
            {
                href += '?popup';
            }
            
            window.open(href, 'VideoChat', 'menubar=no,innerWidth=800,innerHeight=600,toolbar=no,status=no');
            return false;
        });
    
    if (typeof jQuery.fn.datepicker == 'function')
    {
        jQuery('input.datepicker')
            .datepicker
            (
                {
                    firstDay: 1,
                    dateFormat: 'dd.mm.yy',
                    showAnim: ''
                }
            );
    }
    
    jQuery('#fi_cityshops_places_metadata_editor')
        .bind('submit', function()
        {
            if (jQuery(this).find('.error'))
            {
                jQuery(this).find('.error').trigger('focus');
                
                // alert('Error');
                // return false;
            }
            
            return true;
        });
    
    // Metadata editor characters count
    jQuery('#fi_cityshops_places_metadata_editor').find('input[type="text"], textarea')
        .bind('keypress', function(e)
        {
            var char = String.fromCharCode(e.charCode)
            
            if (!char.match(/[a-zA-Z0-9åäö]/))
            {
                char = '';
            }
            
            var value = jQuery(this).val() + char;
            var length = value.length;
            var tmp = value.replace(/[^a-zA-Z0-9åäöÅÄÖ]+/gi, ' ').replace(/^[ ]+/, '').replace(/[ ]+$/, '');
            var words = tmp.split(' ').length;
            
            // Class name of the current field
            var classname = jQuery(this).attr('class');
            
            // Get maximum
            var max = Number(jQuery(this).parents('tr').find('span.maxlength.' + classname).text());
            
            // Word or character count
            if (classname == 'keywords')
            {
                if (max >= words)
                {
                    limit = true;
                }
                else
                {
                    limit = false;
                }
                
                jQuery(this).parents('tr').find('span.length.' + classname).text(words)
            }
            else
            {
                if (max >= length)
                {
                    limit = true;
                }
                else
                {
                    limit = false;
                }
                
                jQuery(this).parents('tr').find('span.length.' + classname).text(length)
            }
            
            // Toggle error class according to the limit
            if (limit)
            {
                jQuery(this).parents('tr').find('span.length.' + classname).removeClass('error');
            }
            else
            {
                jQuery(this).parents('tr').find('span.length.' + classname).addClass('error');
            }
            
            return true;
        });
    
    jQuery('#users_filter')
        .bind('keypress', function()
        {
            jQuery(this).oneTime(500, 'keypressed', function()
            {
                jQuery(this).stopTime('keypressed');
                
                var places = jQuery('table tr.place');
                
                var value = jQuery(this).val();
                
                if (   !value
                    || value.length < 3)
                {
                    jQuery('table tr.hidden').removeClass('hidden');
                    return;
                }
                
                for (i = 0; i < places.size(); i++)
                {
                    var text = places.eq(i).find('.name').text();
                    var regexp = new RegExp(value, 'i');
                    var rel = places.eq(i).attr('rel');
                    
                    if (!text.match(regexp))
                    {
                        jQuery('tr[rel="' + rel + '"]').addClass('hidden');
                    }
                    else
                    {
                        jQuery('tr[rel="' + rel + '"]').removeClass('hidden');
                    }
                }
            });
        });
    
    jQuery('body').everyTime(2000, 'eqheight', function()
    {
        jQuery('#container .fi_cityshops_places').find('div.info-items, div.description, > li.section').equalize_heights();
    });
    
    jQuery('.slideshow').slideshow();
    jQuery('.mainpage_slideshow').slideshow('li');
    
    jQuery('#mainpage_browser')
        .each(function()
        {
            if (jQuery(this).find('.slideshow img').size() == 0)
            {
                return;
            }
            
            jQuery(this)
                .addClass('_with-controller');
            
            
            var wrapper = jQuery('<div class="controller"></div>')
                .prependTo(jQuery(this));
            
            jQuery('<span class="previous"><img src=\"/images/browse-previous.png\" alt="«" width="49" height="106" class="controller previous" /></span>')
                .appendTo(wrapper);
            
            jQuery('<span class="next"><img src=\"/images/browse-next.png\" alt="»" width="49" height="106" class="controller next /></span>')
                .appendTo(wrapper);
            
            jQuery(wrapper).find('span img')
                .bind('click', function()
                {
                    jQuery(this).parents('._with-controller').find('._slideshow').stopTime('slideshow');
                    
                    var images = jQuery(this).parents('._with-controller')
                        .find('img._slideshow_image');
                    
                    var index = 0;
                    var count = images.size();
                    
                    for (i = 0; i < count; i++)
                    {
                        if (images.eq(i).hasClass('display'))
                        {
                            index = i;
                            break;
                        }
                    }
                    
                    if (jQuery(this).hasClass('next'))
                    {
                        next = index + 1;
                    }
                    else
                    {
                        next = index - 1;
                    }
                    
                    if (next >= count)
                    {
                        next = 0;
                    }
                    else if (next < 0)
                    {
                        next = count - 1;
                    }
                    
                    images.eq(index)
                        .css('z-index', 100 + count - 1)
                        .removeClass('display')
                        .oneTime(500, function()
                        {
                            jQuery(this).fadeOut(1000);
                        });
                    
                    images.eq(next)
                        .css('z-index', 100 + count + 1)
                        .fadeIn(1000)
                        .addClass('display');
                });
        });
    
    jQuery('div.flash ul li a')
        .bind('click', function()
        {
            var href = jQuery(this).attr('href');
            
            if (!href.match(/\?/))
            {
                href += '?ajax';
            }
            else
            {
                href += '&ajax';
            }
            
            jQuery.ajax
            (
                {
                    url: href,
                    dataType: 'html',
                    success: function(data)
                    {
                        jQuery('#container div.fi_cityshops_places div.flash_wrapper').remove();
                        jQuery(data).find('div.flash_wrapper').appendTo('#container div.fi_cityshops_places div.flash');
                        
                        var wrapper = jQuery('#container').find('div.fi_cityshops_places div.flash_wrapper');
                        var id = wrapper.attr('id');
                        
                        if (!id)
                        {
                            var date = new Date();
                            id = 'fi_cityshops_places_temporary_id_' + date.getTime();
                            
                            wrapper.attr('id', id);
                        }
                        
                        if (typeof swfobject != 'undefined')
                        {
                            wrapper.set_picture_viewer();
                        }
                        else
                        {
                            wrapper.find('a.thickbox')
                                .bind('click', function()
                                {
                                    popup(jQuery(this).attr('href'));
                                    return false;
                                });
                        }
                    }
                }
            );
            
            return false;
        });
});

function centralize_window()
{
    if (jQuery('#fi_cityshops_places_list_descriptor').size() == 0)
    {
        return;
    }
    
    jQuery(map_markers[map_marker_active]._image).oneTime(500, function()
    {
        var offset = jQuery(this).offset();
        var offset_parent = jQuery('#fi_cityshops_places_map').offset();
        
        jQuery('#fi_cityshops_places_list_descriptor')
            .css
            (
                {
                    marginTop: (offset.top - offset_parent.top + 11) + 'px',
                    marginLeft: (offset.left - offset_parent.left + 12) + 'px'
                }
            );
    });
}

jQuery.fn.initialize_shop_dl_pager = function()
{
    jQuery(this).find('a.pager')
        .bind('click', function()
        {
            jQuery.ajax
            (
                {
                    url: jQuery(this).attr('href'),
                    dataType: 'GET',
                    success: function(data)
                    {
                        var container = jQuery('#container').find('div.fi_cityshops_shop_minilist');
                        container.find('> *').remove();
                        
                        jQuery(data).find('div.fi_cityshops_shop_minilist > *').appendTo(container);
                        container.initialize_shop_dl_pager();
                    }
                }
            );
            
            return false;
        });
}

jQuery.fn.equalize_heights = function()
{
    height = 0;
    
    for (var i = 0; i < jQuery(this).size(); i++)
    {
        if (jQuery(this).eq(i).height() > height)
        {
            height = jQuery(this).eq(i).height();
        }
    }
    jQuery(this).css('min-height', height + 'px');
    
    if (typeof jQuery.fn.rounded_corners != 'undefined')
    {
        // jQuery(this).rounded_corners();
    }
}

var slideshow_count = 0;

jQuery.fn.slideshow = function(attribute)
{
    slideshow_count = jQuery(this).size();
    
    var attribute = attribute || 'img';
    
    jQuery(this).each(function(i)
    {
        if (jQuery(this).find(attribute).size() < 2)
        {
            return;
        }
        
        jQuery(this).attr('slideshow', attribute);
        
        jQuery(this).addClass('_slideshow');
        
        jQuery(this).find('img').addClass('_slideshow_image');
        jQuery(this).find('img').not(':first')
            .css('z-index', '-1');
        
        jQuery(this).oneTime(i * 500 + 50, function()
        {
            jQuery(this)
                .bind('mouseover', function()
                {
                    jQuery(this).addClass('hover');
                })
                .bind('mouseout', function()
                {
                    jQuery(this).removeClass('hover');
                })
                .everyTime(5000, 'slideshow', function()
                {
                    if (jQuery(this).hasClass('hover'))
                    {
                        return;
                    }
                    
                    var images = jQuery(this).find(jQuery(this).attr('slideshow'));
                    var index = 0;
                    
                    for (var i = 0; i < images.size(); i++)
                    {
                        if (images.eq(i).hasClass('display'))
                        {
                            index = i;
                            break;
                        }
                    }
                    
                    var count = images.size();
                    
                    if (index + 1 >= count)
                    {
                        next = 0;
                    }
                    else
                    {
                        next = index + 1;
                    }
                    
                    images.eq(index)
                        .css('z-index', 99)
                        .removeClass('display')
                        .oneTime(500, function()
                        {
                            jQuery(this).fadeOut(1000);
                        });
                    
                    images.eq(next)
                        .css('z-index', 101)
                        .fadeIn(1000, function()
                        {
                        })
                        .addClass('display');
                });
            
            jQuery(this).find(jQuery(this).attr('slideshow') + ':first')
                .addClass('display');
            
            jQuery(this).find(jQuery(this).attr('slideshow')).not(':first')
                .fadeOut(0);
        });
    });
}

jQuery.fn.tabbed = function()
{
    var fieldsets = jQuery(this).find('> div > fieldset');
    
    if (fieldsets.size() < 2)
    {
        return;
    }
    
    var tab_container = jQuery('<ul></ul>')
        .addClass('tabbed')
        .prependTo(jQuery(this));
    
    var first = false;
    
    for (i = 0; i < fieldsets.size(); i++)
    {
        var fieldset = fieldsets.eq(i);
        var legend = fieldset.find('> legend');
        
        var label = legend.text();
        
        if (!label)
        {
            continue;
        }
        
        fieldset.addClass('tabbed');
        
        legend.bind('click', function()
        {
            if (jQuery(this).parent().hasClass('hidden'))
            {
                jQuery(this).parent().removeClass('hidden');
            }
            else
            {
                jQuery(this).parent().addClass('hidden');
            }
        });
        
        var id = fieldset.attr('id');
        
        if (!id)
        {
            id = 'fieldset_' + Math.round(Math.random() * 1000) + i;
            fieldset.attr('id', id);
        }
        
        var li = jQuery('<li></li>')
            .text(label)
            .attr('rel', id)
            .bind('click', function()
            {
                var id = jQuery(this).attr('rel');
                
                jQuery('#' + id)
                    .removeClass('hidden');
                
                jQuery('#' + id).siblings('fieldset')
                    .addClass('hidden');
                
                window.location.hash = '#' + id;
            })
            .appendTo(tab_container);
        
        if (!first)
        {
            first = true;
        }
        else
        {
            fieldset.addClass('hidden');
        }
    }
}

if (typeof console == 'undefined')
{
    console =
    {
        log: function(input)
        {
           // alert(input);
        }
    }
}

