var form_submit = false;
var IE = false;

jQuery(document).ready(function()
{
    // jQuery('#container').find('form.validate').set_validate();
    
    jQuery('body.viikko-ohjelma, body.weekly-program, body.weeklyprogram, body.wochenprogramm').each(function()
    {
        var url = String(window.location);
        
        if (url.match(/(update|edit)/i))
        {
            return;
        }
        
        jQuery(this).find('input#fi_salla_calendar_display_in_weekly_program').attr('checked', 'checked');
    });
    
    if (typeof swfobject != 'undefined')
    {
        jQuery('.flash_replace')
            .each(function()
            {
               
                jQuery('#fi_salla_imageswapper, .flash_replace').css('height', '300px');
                
                var id = jQuery(this).attr('id');
                
                if (!id)
                {
                    do
                    {
                        id = 'fi_salla_imageswapper_' + Math.round(Math.random() * 10000);
                    }
                    while (jQuery('#' + id).size());
                    
                    jQuery(this).attr('id', id);
                }
                
                var images = jQuery(this).find('a[rel]');
                image_string = '';
                
                for (var i = 0; i < images.size(); i++)
                {
                    var rel = images.eq(i).attr('rel');
                    if (!rel)
                    {
                        continue;
                    }
                    
                    if (image_string.length > 0)
                    {
                        image_string += ',';
                    }
                    
                    image_string += rel;
                }
                
                if (image_string)
                {
                    var vars =
                    {
                        images: image_string
                    }
                    
                    var params =
                    {
                        bgcolor:'#eeece5',
                        wmode: 'transparent',
                        allowFullScreen: 'true',
                    };
                    
                    var attributes =
                    {
                        id:'obj',
                        name:'obj'
                    };
                    
                    swfobject.embedSWF
                    (
                        "/flash/pictures/gallery.swf",
                        id,
                        "100%",
                        350,
                        "9.0.0",
                        "/flash/expressInstall.swf",
                        vars,
                        params,
                        attributes
                    );
                }
            });
    }
    
    jQuery('#fi_salla_imageswapper').find('ul li a')
        .click(function()
        {
            var href = jQuery(this).attr('href');
            
            if (!href)
            {
                return false;
            }
            
            if (href.match(/\?/))
            {
                href += '&ajax';
            }
            else
            {
                href += '?ajax';
            }
            
            jQuery(this).parent().siblings('li.selected').removeClass('selected');
            jQuery(this).parent().addClass('selected');
            
            jQuery('#content_image').load
            (
                href + ' #content_image',
                null,
                function()
                {
                    // Probably no need for the callback
                }
            );
            return false;
        });
    
    // Draw the map if applicable
    if (   jQuery('#fi_salla_google_map').size()
        && jQuery('span.geolocation').size()
        && typeof(google) !== 'undefined')
    {
        var latitude = 66.824;
        var longitude = 28.6686;
        var zoom_level = 11;
        
        var points = {}
        var markers = {}
        var windows = {}
        
        var min_latitude = 66.824;
        var max_latitude = 66.824;
        var min_longitude = 28.6686;
        var max_longitude = 28.6686;
        
        var bounds = null;
        
        for (var i = 0; i < jQuery('span.geolocation').size(); i++)
        {
            var latitude = Number(jQuery('span.geolocation').eq(i).find('span.latitude').text());
            var longitude = Number(jQuery('span.geolocation').eq(i).find('span.longitude').text());
            
            // Get the bounding points for creating map bound to the correct locations
            if (latitude < max_latitude)
            {
                min_latitude = latitude;
            }
            
            if (latitude > max_latitude)
            {
                max_latitude = latitude;
            }
            
            if (longitude < max_longitude)
            {
                min_longitude = longitude;
            }
            
            if (longitude > max_longitude)
            {
                max_longitude = longitude;
            }
            
            var latlng = new google.maps.LatLng(latitude, longitude);
            points[i] = latlng;
        }
        
        if (   min_latitude != max_latitude
            && min_longitude != max_longitude
            && i > 1)
        {
            var bounds = new google.maps.LatLngBounds
            (
                new google.maps.LatLng(min_latitude, min_longitude),
                new google.maps.LatLng(max_latitude, max_longitude)
            );
        }
        
        var options = 
        {
            zoom: zoom_level,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        
        var map = new google.maps.Map(document.getElementById('fi_salla_google_map'), options);
        
        for (var i in points)
        {
            markers[i] = new google.maps.Marker
            (
                {
                    position: points[i],
                    map: map,
                    title: jQuery('span.geolocation').eq(i).find('a').text(),
                    href: jQuery('span.geolocation').eq(i).find('a').attr('href'),
                    readmore: jQuery('span.geolocation').eq(i).find('span.readmore').text(),
                    abstract: jQuery('span.geolocation').eq(i).find('.abstract').html(),
                    reserve: jQuery('span.geolocation').eq(i).find('.reserve').html(),
                    index: i
                }
            );
            
            google.maps.event.addListener
            (
                markers[i],
                'click',
                function()
                {
                    var html_content = '';
                    
                    if (this.href)
                    {
                        html_content += '<p><b><a href="' + this.href + '">' + this.title + '</a></b></p>';
                    }
                    else
                    {
                        html_content += '<p><b>' + this.title + '</b></p>';
                    }
                    
                    if (this.abstract)
                    {
                       html_content += '<div class="abstract">' + this.abstract + '</div>';
                    }
                    
                    if (this.reserve)
                    {
                        var href = jQuery('span.geolocation').eq(this.index).find('span.reserve').attr('href');
                        var title = jQuery('span.geolocation').eq(this.index).find('span.reserve').text();
                        
                        html_content += '<p class="more-info"><a href="' + href + '" onclick="jQuery(this).reserve_click(); return false;">' + title + '</a></p>';
                    }
                    else if (this.href)
                    {
                        html_content += '<p class="more-info"><a href="' + this.href + '">' + this.readmore + ' »</a></p>';
                    }
                    
                    var infowindow = new google.maps.InfoWindow
                    (
                        {
                            content: html_content
                        }
                    );
                    
                    infowindow.open(map, this);
                }
            );
        }
        
        if (bounds)
        {
            map.fitBounds(bounds);
        }
    }
    
    // Delete the HTML refresh
    jQuery('#webcam_refresh').remove();
    
    // Initialize Javascript-enabled refresh
    jQuery('ul.webcam-thumbs li a').click(function()
    {
        jQuery('ul.webcam-thumbs li a').removeClass('selected');
        
        var d = new Date();
        var image_href = jQuery(this).attr('rel') + '?'+'time='+d.getMilliseconds();
        
        jQuery('div.webcam img').attr('src', image_href);
        
        jQuery(this).addClass('selected');
        
        return false;
    });
    
    jQuery('div.webcam img').everyTime(10000, 'webcam_picture_swap', function()
    {
        var d = new Date();
        href_data = jQuery(this).attr('src');
        
        var result = href_data.replace(/\?.*/, '');
        result = result+'?'+d.getTime(); 
        
        jQuery(this).attr('src', result);
    });

    
    jQuery('ul.webcam-thumbs li a').click(function()
    {
        return false;
    });
    
    jQuery('#content-text table.row-highlight').find('tbody tr:odd').addClass('odd');
    jQuery('#content-text table.row-highlight').find('tbody tr:even').addClass('even');
    
    var language = 'fi';
    
    jQuery('ul.language li').click(function()
    {
        language = jQuery(this).attr('title');
        
        jQuery(this).parent().find('li[title!="' + language + '"]').removeClass('selected');
        jQuery(this).addClass('selected');
        
        jQuery('div.datamanager-languages fieldset.language').each(function(i)
        {
            if (jQuery(this).hasClass(language))
            {
                if (jQuery(this).css('display') == 'none')
                {
                    jQuery(this).slideDown('slow');
                }
                
                return;
            }
            
            jQuery(this).slideUp('slow');
        });
    });
    
    if (IE)
    {
        // return;
    }
    
    jQuery('a.reservations_link')
        .click(function()
        {
            jQuery(this).reserve_click();
            return false;
        });
});

jQuery.fn.open_popup = function(options)
{
    var date = new Date().getTime();
    
    var blankets = jQuery('.popup_blanket').size();
    var z_index_root = 3000 + 100 * blankets;
    
    jQuery('<div class="popup_blanket"></div>')
        .attr('rel', date)
        .attr('id', 'popup_blanket_' + date)
        .css
        (
            {
                zIndex: z_index_root
            }
        )
        .fadeTo(0, 0.5)
        .prependTo('body');
    
    var source = options.url;
    
    max_width = jQuery(window).width() - 40;
    max_height = jQuery(window).height() - 40;
    
    if (!options)
    {
        var options =
        {
            width: 640,
            height: 480
        }
    }
    
    if (!options.height)
    {
        options.height = max_height;
    }
    
    // Check that popup isn't going over the borders
    if (options.width > max_width)
    {
        console.log('trim width');
        options.width = max_width;
    }
    
    if (options.height > max_height)
    {
        console.log('trim height');
        options.height = max_height;
    }
    
    if (source.match(/\.(png|jpe?g|gif)$/i))
    {
        jQuery('<div class="popup_image"><img src="' + source + '" /></div>')
            .attr('rel', date)
            .css
            (
                {
                    zIndex: (z_index_root + 10)
                }
            )
            .insertBefore(jQuery('.popup_blanket:first'))
            .click(function()
            {
                jQuery(this).remove();
                jQuery(this).next('.popup_blanket').remove();
            });
        
        if (options.width)
        {
            jQuery('.popup_image:first')
                .css
                (
                    {
                        marginTop: '-' + Math.round(options.width / 2) + 'px !important',
                        width: Math.round(options.width) + 'px !important'
                    }
                );
        }
        
        if (options.height)
        {
            jQuery('.popup_image:first')
                .css
                (
                    {
                        marginLeft: '-' + Math.round(options.height / 2) + 'px !important',
                        height: Math.round(options.height) + 'px !important'
                    }
                );
        }
    }
    else
    {
        var wrapper = jQuery('<div class="popup_wrapper"></div>')
            .attr('rel', date)
            .css
            (
                {
                    zIndex: (z_index_root + 10),
                    top: (50 - (blankets * 2)) + '%',
                    left: (50 - (blankets * 2)) + '%'
                }
            )
            .addClass('loading')
            .insertAfter(jQuery('div.popup_blanket:first'));
        
        jQuery('<span class="popup_close"></span>')
            .attr('rel', date)
            .attr('id', 'popup_wrapper_' + date)
            .text('X')
            .appendTo(jQuery('div.popup_wrapper:first'));
        
        var content_area = jQuery('<div class="popup_content"></div>')
            .attr('rel', date)
            .addClass('loading')
            .appendTo(jQuery('div.popup_wrapper:first'));
        
        jQuery(window).bind('resize', function()
        {
            if (!jQuery('div.popup_wrapper').size())
            {
                return;
            }
            
            var wrapper = jQuery('div.popup_wrapper');
            var height = wrapper.height();
            
            // Determine if the height should be returned to
            // original or decreased
            if (height < jQuery(window).height())
            {
                if (wrapper.attr('originalheight'))
                {
                    height = wrapper.attr('originalheight');
                    margin_top = Math.round(height / 2);
                    
                    wrapper
                        .css
                        (
                            {
                                height: height + 'px',
                                marginTop: '-' + margin_top + 'px'
                            }
                        );
                }
            }
            else
            {
                // Store the initial (max) height
                if (!wrapper.attr('originalheight'))
                {
                    wrapper.attr('originalheight', height);
                }
                
                new_height = jQuery(window).height();
                margin_top = Math.round(new_height / 2);
                
                wrapper
                    .css
                    (
                        {
                            height: new_height + 'px',
                            marginTop: '-' + margin_top + 'px'
                        }
                    );
            }
            
            var content = jQuery('div.popup_content');
            var height = content.height();
            
            if (height < jQuery(window).height() - 60)
            {
                if (content.attr('originalheight'))
                {
                    content.css('height', content.attr('originalheight') + 'px');
                }
            }
            else
            {
                // Store the initial (max) height
                if (!content.attr('originalheight'))
                {
                    content.attr('originalheight', height);
                }
                
                new_height = jQuery(window).height() - 60;
                
                content
                    .css
                    (
                        {
                            height: new_height + 'px'
                        }
                    );
            }
        });
        
        if (options.height)
        {
            wrapper
                .css
                (
                    {
                        height: options.height + 'px',
                        marginTop: '-' + Math.round(options.height / 2) + 'px'
                    }
                );
            
            content_area
                .css
                (
                    {
                        height: (options.height - 60) + 'px'
                    }
                );
        }
    }
    
    jQuery('.popup_close[rel="' + date + '"], .popup_blanket[rel="' + date + '"], .popup_image[rel="' + date + '"]')
        .bind('click', function()
        {
            var rel = jQuery(this).attr('rel');
            
            jQuery('div[rel="' + rel + '"]')
                .fadeOut(200, function()
                {
                    jQuery(this).remove();
                });
        })
    
    if (source.match(/\.(png|jpe?g|gif)$/i))
    {
        return;
    }
    
    if (options.css)
    {
        jQuery('<link />')
            .attr
            (
                {
                    rel: 'stylesheet',
                    type: 'text/css',
                    href: options.css
                }
            )
            .appendTo('head');
    }
    
    if (options.dom_source)
    {
        source += ' ' + options.dom_source;
    }
    
    if (!options.callback)
    {
        options.callback = function()
        {
        }
    }
    
    if (options.jscript)
    {
        jQuery.getScript
        (
            options.jscript,
            function()
            {
                jQuery(jQuery('div.popup_content:first'))
                    .load
                    (
                        source,
                        null,
                        function()
                        {
                            jQuery(jQuery('div.popup_wrapper:first'))
                                .removeClass('loading')
                                .initialize_reservations_form_controls();
                            
                            options.callback();
                        }
                    );
            }
        )
    }
    else
    {
        jQuery(jQuery('div.popup_content:first'))
            .load
            (
                source,
                null,
                function()
                {
                    jQuery(jQuery('div.popup_wrapper:first'))
                        .removeClass('loading')
                        .initialize_reservations_form_controls();
                    
                    options.callback();
                }
            );
    }
}

jQuery(window).load(function()
{
    jQuery('#container').find('div.ie6hidden').css({visibility: 'visible'});
});

jQuery.fn.reserve_click = function()
{
    var options =
    {
        jscript: '/midcom-static/fi.salla.reservations/jquery.reservations.js',
        dom_source: '#fi_salla_reservations',
        url: jQuery(this).attr('href') + '?ajax',
        css: '/midcom-static/fi.salla.reservations/reservations.css'
    }
    
    jQuery(this).open_popup(options);
}

if (typeof console == 'undefined')
{
    console =
    {
        log: function(input){},
        error: function(input){},
        warn: function(input){}
    }
}

// Set validation code for HTML5 incompatible browsers
jQuery.fn.set_validate = function()
{
    if (('placeholder' in document.createElement('input')))
    {
        return;
    }
    
    jQuery(this).find('input, select, textarea')
       .bind('focus', function()
       {
           jQuery(this)
               .removeClass('ok')
               .removeClass('error');
               
           if (jQuery(this).attr('value') == jQuery(this).attr('placeholder'))
           {
               jQuery(this).attr('value', '');
           }
       })
       .bind('blur', function()
       {
           if (jQuery(this).hasClass('required'))
           {
               if (!jQuery(this).val())
               {
                   jQuery(this).addClass('error');
               }
           }
           
           if (jQuery(this).attr('type') == 'email')
           {
               var email = jQuery(this).val();
               
               if (!email.match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i))
               {
                   jQuery(this).addClass('error');
                   return;
               }
           }
           
           if (jQuery(this).attr('value') == '')
           {
               jQuery(this).attr('value', jQuery(this).attr('placeholder'));
           }
       })
       .each(function()
       {
           if (jQuery(this).attr('value') == '')
           {
               jQuery(this).attr('value', jQuery(this).attr('placeholder'));
           }
       });
    
    jQuery(this).bind('submit', function()
    {
        var inputs = jQuery(this).find('input, select, textarea');
        
        for (i = 0; i < inputs.size(); i++)
        {
            if (inputs.eq(i).val() == inputs.eq(i).attr('placeholder'))
            {
                if (inputs.eq(i).attr('required'))
                {
                    inputs.eq(i).addClass('error');
                }
                
                inputs.eq(i).val('');
            }
        }
        
        // No errors found, allow submit
        if (jQuery(this).find('input.error, select.error, textarea.error').size() == 0)
        {
            return true;
        }
        
        inputs.trigger('blur');
        return false;
    });
}

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