document.observe('dom:loaded', function (e) {
    $$('a[rel~=external]').each(function (item) {
        item.writeAttribute('target', '_blank');
        item.observe('click', function (e) {
            var href = e.element().href;
            var url = (new RegExp('^http://(.+?)/?$')).exec(href)[1];
            
            pageTracker._trackPageview('/outgoing/' + url);
        });
    });
    
    if (Prototype.Browser.IE) {
    	$$('div.frequencies table tr').each(function (item) {
    		item.observe('mouseover', item.addClassName.bind(item, 'hover'));
    		item.observe('mouseout', item.removeClassName.bind(item, 'hover'));
    	});
    }
    
    if (document.location.pathname.startsWith('/radiokanavat/')) {
    	document.observe('starbox:rated', function (event) {
    		var uri = (new RegExp('^/radiokanavat/(.+?)$')).exec(document.location.pathname)[1];
    		new Ajax.Request('/ajax/radiokanavat/arvostele', {
    			postBody: $H({ 'uri': uri, 'rated': event.memo.rated.toFixed(0) }).toJSON(),
    			onSuccess: function (transport) {
    				var indicator = event.findElement('.starbox').down('.indicator');
    				var restore = indicator.innerHTML;
    				indicator.update('Kiitos arvostelusta');
    				(function () { indicator.update(restore); }).delay(5); 
    			}
    		});
    	});
    }
    
    if (document.location.pathname == '/radiokanavat') {
    	var sortby = $$('#content .sortby')[0];
    	if (sortby) {
    		sortby.down('.alphabet').observe('click', function (e) {
    			var stations = $('stations').cloneNode(false);
    			$$('#stations li').sortBy(function (item) {
    				return item.innerHTML;
    			}).each(function (item) {
    				stations.appendChild(item);
    			});
    			$('stations').replace(stations);
    			e.stop();
    		});
    		sortby.down('.rating').observe('click', function (e) {
    			var stations = $('stations').cloneNode(false);
    			$$('#stations li').sortBy(function (item) {
    				return 1000 - parseInt(item.down('.stars').style.width);
    			}).each(function (item) {
    				stations.appendChild(item);
    			});
    			$('stations').replace(stations);
    			e.stop();
    		});
    	}
    	$$('#stations li span').each(function (item) {
    		var value = parseFloat(item.innerHTML);
    		item.update('');
    		item.appendChild(new Element('span', {'class': 'bg'}).setStyle({'width': (80 / 5 * value).toFixed(0) + 'px'}));
    		item.appendChild(new Element('span', {'class': 'stars'}).setStyle({'width': (80 / 5 * value).toFixed(0) + 'px'}));
    	});
    }
    
    if (document.location.pathname == '/') {
        // highlight station from referer if there is any
        var keywords = [];
        if (document.referer && document.referer.length) {
            var referer = document.referer.toLowerCase();
            var param = '';
            if (referer.include('www.google.') || referer.include('live.com') || referer.include('search.msn.')) {
                param = 'q';
            } else if (referer.include('yahoo.com')) {
                param = 'p';
            }
            if (param.length) {
                var raw = referer.toQueryParams()[param];
                if (raw) {
                    keywords = $w(raw.replace(/[.+]/g, ' ')).without('radio', 'nettiradio', 'the');
                }
            }
        }
        keywords.each(function (keyword, index) {
            $('sidebar').select('ul li a').each(function (item) {
                if ($w(item.readAttribute('title').toLowerCase()).include(keyword)) {
                	item.highlight.bind(item, {
                        afterFinish: function (effect) { effect.element.setStyle({background: ''}); }
                    }).delay(index + 2);
                }
            });
        });
    }

    
    if (typeof frequencies != 'undefined') {
	    $A(frequencies).without(null).each(function (frequency) {
	        var container = new Element('div', {'class': 'onmap'});
	        container.setStyle({
	            position: 'absolute',
	            top: (45 + frequency[2][1]) + 'px',
	            left: (560 + frequency[2][0]) + 'px'
	        });
	
	        var title = new Element('span', {'class': 'title pngfix'});
	        title.update(frequency[0]);
	        
	        var hz = new Element('span', {'class': 'hz pngfix'});
	        hz.update(frequency[1] + ' MHz');
	        
	        $('content').appendChild(container.insert(title).insert(hz));
	    });
    }
    
    if (typeof region != 'undefined') {
    	var container = new Element('div', {'class': 'onmap'});
    	container.setStyle({
    		position: 'absolute',
    		top: (45 + region[1][1]) + 'px',
    		left: (560 + region[1][0]) + 'px'
    	});
    	
    	var title = new Element('span', {'class': 'title pngfix'});
    	title.update(region[0]);
    	
    	var hz = new Element('span', {'class': 'mock pngfix'});
    	hz.update(' ');
    	
    	$('content').appendChild(container.insert(title).insert(hz));
    }
    
    var player = $('player');
    if (player) {
        var href = player.down().readAttribute('href');
        var code = '';
        
        code += '<object classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" height="65" width="300" type="application/x-oleobject">';
        code += '<param name="AutoStart" value="1" />';
        code += '<param name="URL" value="' + href + '" />';
        code += '<param name="AnimationAtStart" value="0" />';
        code += '<param name="ShowStatusBar" value="1" />';
        code += '<param name="ShowControls" value="1" />';
        code += '<param name="ShowAudioControls" value="1" />';
        code += '<param name="ShowTracker" value="TRUE" />';
        code += '<param name="AllowScan" value="-1" />';
        code += '<param name="ClickToPlay" value="0" />';
        code += '<param name="TransparentAtStart" value="1" />';
        code += '<embed type="application/x-mplayer2" src="' + href + '" animationatstart="false" autostart="1" width="300" height="70" transparentatstart="0" showstatusbar="1" showcontrols="1" autosize="0" displaysize="0"></embed>';
        code += '</object>';
        
        player.update(code);
        
        new PeriodicalExecuter(function () {
            pageTracker._trackPageview(document.location.pathname + '/online');
        }, 300);
        
        (function () {
            window.onbeforeunload = function () {
                pageTracker._trackPageview(document.location.pathname + '/leave');
            }
        }).delay(20);
    }
});
