var fi_halti_products_cloudmade_maps_zoom = 4;
var fi_halti_products_cloudmade_api_key = null;
var fi_halti_products_cloudmade_style = null;

// Default location is - of course - Halti fell
var org_routamc_positioning_latitude = 69.307778;
var org_routamc_positioning_longitude = 21.272222;
var cm_map = null;

    // Initialize product dock
jQuery(function()
{
    // Browser matching. Now this is immoral...
    if (   jQuery.cookie('browser')
        && jQuery.cookie('version'))
    {
        var version = jQuery.cookie('version');
        if (   jQuery.cookie('browser') == 'Safari'
            && version.match(/4/))
        {
            jQuery('body').addClass('safari-4');
        }
    }
    else
    {
        jQuery.getJSON
        (
            MIDCOM_PAGE_PREFIX + 'browser/',
            {},
            function(data, status)
            {
                jQuery.cookie('browser', data.browser);
                jQuery.cookie('version', data.version);
                
                if (   data.browser == 'Safari'
                    && data.version == 4)
                {
                    jQuery('body').addClass('safari-4');
                }
            }
        );
    }
    
    // Quick-fix to prevent Asgard JavaScript errors
    url = String(window.location);
    if (url.match(/__mfa/))
    {
        return;
    }
    
    jQuery('body').initialize_thickbox();
    jQuery('div.fi_halti_products_product div.images').thumbnail_slider(380);
    jQuery('div.fi_halti_products_product div.info-items').info_slider(340);
    
    jQuery('#fi_halti_products_search div.freeform input[type="text"]')
        .focus(function()
        {
            if (jQuery(this).attr('value') == jQuery(this).attr('rel'))
            {
                jQuery(this).attr('value', '');
            }
            else
            {
                jQuery(this).select();
            }
        })
        .blur(function()
        {
            if (jQuery(this).attr('value') == '')
            {
                jQuery(this).attr('value', jQuery(this).attr('rel'));
            }    
        })
        .each(function()
        {
            if (jQuery(this).attr('value') == '')
            {
                jQuery(this).attr('value', jQuery(this).attr('rel'));
            }
        });
    
    jQuery('#fi_halti_products_search ul').addClass('jquery-enabled');
    
    jQuery('#fi_halti_products_search ul.sprite li label')
        .hover
        (
            function()
            {
                jQuery(this).addClass('hover');
            },
            function()
            {
                jQuery(this).removeClass('hover');
            }
        )
        .click(function()
        {
            jQuery(this).removeClass('hover');
            if (jQuery(this).hasClass('toggle'))
            {
                return true;
            }
            
            if (!jQuery(this).find('input').attr('checked'))
            {
                jQuery(this).addClass('selected');
            }
            else
            {
                jQuery(this).removeClass('selected');
            }
            
            jQuery(this).addClass('toggle');
            jQuery(this).sprite_toggle();
            
            if (jQuery(this).parents('form').hasClass('trigger'))
            {
                return true;
            }
            
            // Submit the form
            jQuery(this).parents('form').oneTime(500, function()
            {
                jQuery(this).removeClass('trigger');
                jQuery(this).submit();
            });
            
            jQuery(this).parents('form').addClass('trigger');
            
            return true;
        });
    
    jQuery('#fi_halti_products_search div.chooser label').click(function()
    {
        if (jQuery(this).parents('form').hasClass('trigger'))
        {
            return true;
        }
        
        if (!jQuery(this).find('input').attr('checked'))
        {
            jQuery(this).addClass('selected');
        }
        else
        {
            jQuery(this).removeClass('selected');
        }
        
        // Submit the form
        jQuery(this).parents('form').oneTime(500, function()
        {
            jQuery(this).removeClass('trigger');
            jQuery(this).submit();
        });
        
        jQuery(this).parents('form').addClass('trigger');
        
        return true;
    });
    
    jQuery('#fi_halti_products_search').submit(function()
    {
        if (jQuery(this).hasClass('trigger'))
        {
            return false;
        }
        
        jQuery(this).parents('form').addClass('trigger');
        var action = jQuery(this).attr('action');
        
        if (action.match(/\?/))
        {
            action += '&ajax';
        }
        else
        {
            action += '?ajax';
        }
        
        jQuery(this).ajaxSubmit(
        {
            url: action,
            target: jQuery('div.fi_halti_products_product_list'),
            beforeSubmit: function()
            {
                jQuery('div.fi_halti_products_product_list').addClass('loading');
                jQuery('ul.fi_halti_products_product_dock').fadeTo(500, 0.5);
            },
            success: function()
            {
                jQuery('.fi_halti_products_product_dock').initialize_dock();
                jQuery('div.recommended ul li a').initialize_loader();
                jQuery('div.fi_halti_products_product_list ul li a').initialize_loader();
                jQuery('div.fi_halti_products_product_list').removeClass('loading');
            }
        });
        
        return false;
    });
    
    jQuery('.fi_halti_products_product_dock').initialize_dock();
    jQuery('.fi_halti_products_product_dock li a').initialize_loader();
    jQuery('div.recommended ul li a').initialize_loader();
    
    var hash = String(window.location.hash);
    if (hash)
    {
        jQuery('a[rel="' + hash.replace(/#/, '') + '"]').click();
    }
    
    jQuery('#fi_halti_products_quick_search select')
        .change(function()
        {
            jQuery('ul.fi_halti_products_product_dock').fadeTo(500, 0.5);
            jQuery('<div class="loading"></div>')
                .prependTo('div.fi_halti_products_product_list');
            
            var query = jQuery('#fi_halti_products_quick_search').attr('action') + '?ajax';
            
            jQuery('#fi_halti_products_quick_search select').each(function()
            {
                if (jQuery(this).attr('value'))
                {
                    query += '&' + jQuery(this).attr('name') + '=' + jQuery(this).attr('value');
                }
            });
            
            jQuery('div.fi_halti_products_product_list').load
            (
                query,
                null,
                function()
                {
                    jQuery('.fi_halti_products_product_dock').initialize_dock();
                    jQuery('.fi_halti_products_product_dock li a').initialize_loader();
                    jQuery('div.recommended ul li a').initialize_loader();
                }
            );
        });
    
    // Allow entering directly to the correct view
    if (window.location.hash)
    {
        var hash = String(window.location.hash);
        
        if (regs = hash.match(/url=(.+)$/))
        {
            jQuery('#fi_halti_products_product_wrapper').load_product(regs[1]);
            
            // Reinitialize addThis
            var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
            if (window.addthis)
            {
                window.addthis = null;
            }
            
        }
    }
});

jQuery.fn.initialize_dock = function()
{
    if (jQuery('div.fi_halti_products_product_list').next('#fi_halti_products_product_wrapper').size() == 0)
    {
        jQuery('<div id="fi_halti_products_product_wrapper"></div>')
            .insertAfter(jQuery('div.fi_halti_products_product_list'));
    }
    
    var count = jQuery(this).attr('rel');
    
    // Center the dock by force, since it's impossible with CSS to center floating block-level items
    if (   count
        && (count = Number(count.replace(/^count:/, ''))))
    {
        var margin = (21 - count) * 20;
        jQuery(this).css('margin-left', margin + 'px');
    }
    
    
    jQuery(this).find('li').each
    (
        function()
        {
            var offset = jQuery(this).offset();
            jQuery(this).find('div.weather').css(
            {
                left: offset.left + 'px'
            });
            
            jQuery(this).find('.weather-title').remove();
        }
    );
    
    jQuery(this).find('li').hover
    (
        function()
        {
            jQuery(this).siblings('li').find('div.weather').css('display', 'none');
            jQuery(this).addClass('hover');
            jQuery(this).find('div.weather').css('display', 'block');
        },
        function()
        {
            jQuery(this).oneTime(750, function()
            {
                if (jQuery(this).hasClass('hover'))
                {
                    return;
                }
                
                jQuery(this).find('div.weather').fadeOut(750, function()
                {
                    jQuery(this).css('display', 'none');
                });
            });
            
            jQuery(this).removeClass('hover');
        }
    );
}

jQuery.fn.initialize_loader = function()
{
    jQuery(this).click
    (
        function()
        {
            if (jQuery(this).hasClass('navigation'))
            {
                jQuery('<div class="loading"></div>')
                    .prependTo('div.fi_halti_products_product_list');
                
                jQuery('div.fi_halti_products_product_list ul').fadeTo(500, 0.5);
                jQuery('div.fi_halti_products_product_list').load(
                    jQuery(this).attr('href') + '&ajax',
                    null,
                    function()
                    {
                        jQuery('.fi_halti_products_product_dock li a').initialize_loader();
                        jQuery('.fi_halti_products_product_dock')
                           .initialize_dock();
                    });
                return false;
            }
            
            var href = jQuery(this).attr('href');
            jQuery('#fi_halti_products_product_wrapper').load_product(href);
            
            if (jQuery(this).attr('rel'))
            {
                // Enable this to enable direct linking
                // window.location.hash = '#' + jQuery(this).attr('rel');
            }
            
            return false;
        }
    );
}

// Load a product
jQuery.fn.load_product = function(url)
{
    jQuery('#fi_halti_products_product_wrapper').addClass('loading');
    jQuery('div.fi_halti_products_product').remove();
    
    // Remove existing hash
    url = url.replace(/#.+$/, '');
    
    // Remove server part
    if (url.match(/^http:/))
    {
        url = url.replace(/http:\/\/.+?\//, '/');
    }
    
    if (url.match(/\?/))
    {
        href = url + '&ajax';
    }
    else
    {
        href = url + '?ajax';
    }
    
    jQuery(this).load
    (
        href,
        null,
        function()
        {
            var position = jQuery('div.fi_halti_products_product_list').offset();
            
            var product_title = jQuery('#fi_halti_products_product_wrapper h1').text();
            var page_title = String(document.title);
            
            if (page_title.match(/#/))
            {
                page_title = product_title;
            }
            else
            {
                page_title = page_title.replace(/^.+?\|/, product_title + ' |');
            }
            
            // Set the page title
            document.title = page_title;
            
            // Reinitialize addThis
            var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
            if (window.addthis)
            {
                window.addthis = null;
            }
            
            jQuery.getScript(script);
            // resetAddThis();
            
            sIFR.replace(plantijn,
            {
                selector: '#fi_halti_products_product_wrapper h1',
                wmode: 'transparent',
                fitExactly: true,
                css: '.sIFR-root { color: #000000; font-size: 32px; }'
            });
            
            jQuery('div.fi_halti_products_product div.images').thumbnail_slider(380);
            jQuery('div.fi_halti_products_product div.info-items').info_slider(340);
            jQuery('div.fi_halti_products_product div.images').initialize_thickbox();
            jQuery('div.recommended ul li a').initialize_loader();
            // jQuery(document).pngFix();

            jQuery('html, body').animate(
                {
                    scrollTop: position.top - 20
                },
                1000
            );
        }
    );
    
    window.location.hash = '#url=' + url;
}

// Initialize CloudMade Map
jQuery(function()
{
    var hash = String(window.location.hash);
    
    if (hash.match(/debug/))
    {
        return;
    }
    
    if (jQuery('#org_routamc_positioning_map_widget').size() == 0)
    {
        return;
    }
    
    jQuery('#org_routamc_positioning_map_widget').css('background-image', 'none');
    
    if (!fi_halti_products_cloudmade_style)
    {
        fi_halti_products_cloudmade_style = 10321;
    }
    
    // Get the map
    var cloudmade = new CM.Tiles.CloudMade.Web(
    {
        key: fi_halti_products_cloudmade_api_key,
        styleId: fi_halti_products_cloudmade_style
    });
    
    cm_map = new CM.Map('org_routamc_positioning_map_widget', cloudmade);
    
    if (   jQuery.cookie('latitude')
        && jQuery.cookie('longitude'))
    {
        org_routamc_positioning_latitude = jQuery.cookie('latitude');
        org_routamc_positioning_longitude = jQuery.cookie('longitude');
        cm_map.setCenter(new CM.LatLng(org_routamc_positioning_latitude, org_routamc_positioning_longitude), fi_halti_products_cloudmade_maps_zoom);
        
        // Set an icon to the current position
        open_info_window(org_routamc_positioning_latitude, org_routamc_positioning_longitude, 'you are here');
    }
    else if (navigator.geolocation)
    {
        cm_map.setCenter(new CM.LatLng(org_routamc_positioning_latitude, org_routamc_positioning_longitude), fi_halti_products_cloudmade_maps_zoom);
        navigator.geolocation.getCurrentPosition(update_current_location);
    }
    else
    {
        cm_map.setCenter(new CM.LatLng(org_routamc_positioning_latitude, org_routamc_positioning_longitude), fi_halti_products_cloudmade_maps_zoom);
        
        // Try to load latitude and longitude from uncached content
        jQuery.getJSON
        (
            MIDCOM_PAGE_PREFIX + 'location/',
            {},
            function(data, status)
            {
                org_routamc_positioning_latitude = data.latitude;
                org_routamc_positioning_longitude = data.longitude;
                
                // Set an icon to the current position
                open_info_window(org_routamc_positioning_latitude, org_routamc_positioning_longitude, 'you are here');
                // cm_map.setCenter(new CM.LatLng(org_routamc_positioning_latitude, org_routamc_positioning_longitude), fi_halti_products_cloudmade_maps_zoom);
                
                jQuery.cookie('latitude', data.latitude);
                jQuery.cookie('longitude', data.longitude);
            }
        );
    }
    
//    cm_map.addControl(new CM.ScaleControl());
    cm_map.addControl(new CM.LargeMapControl());
    cm_map.disableScrollWheelZoom();
});

function open_info_window(latitude, longitude, info_title, link, icon)
{
    if (!link)
    {
        link = null;
    }
    
    if (   link
        && (regs = link.match(/([0-9a-f]{32,})/)))
    {
        var guid = regs[1];
    }
    else
    {
        var guid = null;
    }
    
    var position = new CM.LatLng(latitude, longitude);
    
    // Define an icon
    var map_icon = new CM.Icon();
    
    if (icon)
    {
        map_icon.image = icon;
    }
    else
    {
        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);
    
    var position_marker = new CM.Marker(
        position,
        {
            title: info_title,
            icon: map_icon
        });
    
    if (!cm_map)
    {
        return;
    }
    
    
    cm_map.addOverlay(position_marker);
    
    CM.Event.addListener(position_marker, 'click', function(position)
    {
        var latitude = position._lat;
        var longitude = position._lng;
        
        var date = new Date();
        var id = 'fi_halti_products_map_marker_' + date.getTime();
        
        var url = MIDCOM_PAGE_PREFIX + 'weather/';
        
        if (guid)
        {
            url += guid + '/';
        }
        
        jQuery.get(
            url,
            {
                latitude: latitude,
                longitude: longitude,
                title: info_title,
                link: link
            },
            function(data)
            {
                cm_map.panTo(position);
                
                var size = new CM.Size(50,50);
                
                cm_map.openInfoWindow(
                    position,
                    data,
                    {
                        maxWidth: '200px',
                        pixelOffset: size
                    }
                );
        });
    });
    
    if (info_title.match(/you are here/i))
    {
        CM.Event.fire(position_marker, 'click', position);
    }
}

function update_current_location(location)
{
    org_routamc_positioning_latitude = location.coords.latitude;
    org_routamc_positioning_longitude = location.coords.longitude;
    
    jQuery.cookie('latitude', org_routamc_positioning_latitude);
    jQuery.cookie('longitude', org_routamc_positioning_longitude);
    
    jQuery.post
    (
        MIDCOM_PAGE_PREFIX + 'midcom-exec-org.routamc.positioning/geolocation-json.php',
        {
            accuracy: location.coords.accuracy,
            latitude: org_routamc_positioning_latitude,
            longitude: org_routamc_positioning_longitude
        }
    );
    
    cm_map.setCenter(new CM.LatLng(org_routamc_positioning_latitude, org_routamc_positioning_longitude), fi_halti_products_cloudmade_maps_zoom + 1);
    
    // Set an icon to the current position
    open_info_window(org_routamc_positioning_latitude, org_routamc_positioning_longitude, 'you are here');
}

jQuery.fn.thumbnail_slider = function(dimension)
{
    jQuery(this).find('div.wrapper div.item').css(
    {
        display: 'block',
        height: dimension + 'px'
    });
    
    jQuery(this).find('div.thumbnails a').click(function()
    {
        jQuery(this).parent().find('a').removeClass('selected');
        jQuery(this).addClass('selected');
        
        var count = jQuery(this).prevAll('a').size();
        var margin = -1 * dimension * count;
        
        jQuery(this).parents('div.thumbnails').find('a.clicked').removeClass('clicked');
        jQuery(this).addClass('clicked');
        
        jQuery(this).parents('div.slider').find('div.wrapper div.slide').animate
        (
            {
                marginLeft: margin + 'px'
            },
            500
        );
        
        return false;
    });
    
    jQuery(this).find('div.thumbnails a:first').click();
}

jQuery.fn.info_slider = function(width)
{
    var fade_level = 0.2;
    var fade_speed = 500;
    
    jQuery(this).find('div.item').css('display', 'block');
    
    // Center the position
    jQuery(this).find('div.item').each(function()
    {
        var offset = Math.round((100 - jQuery(this).height()) / 2);
        
        if (offset > 0)
        {
            jQuery(this).css('padding-top', offset + 'px');
        }
    });
    
    // Disable previous by default
    jQuery(this).find('div.navigation a.prev')
        .fadeTo(fade_speed, fade_level)
        .addClass('disabled');
        
    jQuery(this).find('div.navigation a').each(function()
    {
        var offset = jQuery(this).offset();
        
        jQuery(this).css(
        {
            top: offset.top + 'px',
            left: offset.left + 'px'
        });
    });
    
    jQuery(this).find('div.navigation a').click(function()
    {
        var fade_level = 0.2;
        var fade_speed = 500;
        
        if (jQuery(this).hasClass('disabled'))
        {
            return false;
        }
        
        width = 340;
        
        var index = Number(jQuery('span.indicator span.current:first').text());
        
        var max = Number(jQuery('span.indicator span.max').text());
        
        if (jQuery(this).hasClass('prev'))
        {
            index--;
        }
        else
        {
            index++;
        }
        
        if (   index < 1
            || index > max)
        {
            return false;
        }
        
        margin = width * (index - 1) * -1;
        
        jQuery('span.indicator span.current').text(index);
        
        jQuery(this).parents('div.slider').find('div.wrapper div.slide')
            .animate({
                marginLeft: margin + 'px'
            });
        
        if (index <= 1)
        {
            jQuery(this).parents('div.slider').find('a.prev')
                .fadeTo(fade_speed, fade_level)
                .addClass('disabled');
        }
        else
        {
            jQuery(this).parents('div.slider').find('a.prev')
                .fadeTo(fade_speed, 1.0)
                .removeClass('disabled');
        }
        
        if (index >= max)
        {
            jQuery(this).parents('div.slider').find('a.next')
                .fadeTo(fade_speed, fade_level)
                .addClass('disabled');
        }
        else
        {
            jQuery(this).parents('div.slider').find('a.next')
                .fadeTo(fade_speed, 1.0)
                .removeClass('disabled');
        }
        
        return false;
    });
}

jQuery.fn.sprite_toggle = function()
{
    if (jQuery(this).find('input').attr('checked'))
    {
        var position = 0;
    }
    else
    {
        var position = '-40px';
    }
    
    /*
    // This toggle will force maximum of one to be selected
    if (jQuery(this).parents('ul').hasClass('radio'))
    {
        jQuery(this).parent().siblings('li').find('label').each(function()
        {
            jQuery(this).find('input').attr('checked', '');
            // Move the sprite
            jQuery(this).animate
            (
                {
                    'background-position': '(0 0)'
                },
                200
            );
        });
    }
    /**/
    
    // Move the sprite
    jQuery(this).animate
    (
        {
            'background-position': '(0 ' + position + ')'
        },
        200,
        function()
        {
            jQuery(this).removeClass('toggle');
        }
    );
}

function resetAddThis()
{
    jQuery('.addthis_button').each(function()
    {
        jQuery(this).attr("onclick", "return addthis_open(this, '', '" + jQuery(this).attr('addthis:url') + "', '" + jQuery(this).attr('addthis:title') + "');");
    });
}