Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(b,a){this.element=this.subject=$(b);
this.parent(a);var d=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=$(this.element.getDocument().body);}var c=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){c.addEvent("mousewheel",d);},true);this.addEvent("complete",function(){c.removeEvent("mousewheel",d);
},true);}},set:function(){var a=Array.flatten(arguments);this.element.scrollTo(a[0],a[1]);},compute:function(c,b,a){return[0,1].map(function(d){return Fx.compute(c[d],b[d],a);
});},start:function(c,h){if(!this.check(c,h)){return this;}var e=this.element.getSize(),f=this.element.getScrollSize();var b=this.element.getScroll(),d={x:c,y:h};
for(var g in d){var a=f[g]-e[g];if($chk(d[g])){d[g]=($type(d[g])=="number")?d[g].limit(0,a):a;}else{d[g]=b[g];}d[g]+=this.options.offset[g];}return this.parent([b.x,b.y],[d.x,d.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(b){var a=$(b).getPosition(this.element);return this.start(a.x,a.y);}});

  var tgt = null;
  var scrollr = null;
var autolink = function (string, options){
    if(!options) options = {};
    if(!options.limit) options.limit = 10;
    if(!options.tagFill) options.tagFill = '';
    
    var regex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!<\-\/]))?/gi;
    
    string = string.replace(regex, function(value){
        value = value.toLowerCase();
        var m = value.match(/^([a-z]+:\/\/)/);
        value = value.replace(/,/,'');
        //console.log(value);
        var nice;
        var url;
        
        if(m)
        {
            nice = value.replace(m[1],'');
            url = value;
        }
        else
        {
            nice = value;
            url = 'http://' + nice;
        }
        
        return '<a href="' + url + '">' + nice + '</a>';
    });
    
    return string;
};

  var containsUrl = function(s) {
    var rgxp = /((ftp|http|https):\/\/|www\.)(\w+:{0,1}\w)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/!<\/])|)/;
    return s.match(rgxp);
  }
  var stripUrl = function(data) {
    return data.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,
'<a href="$&" class="my_link" target="_blank">$&</a>').replace(/([^\/])(www[\S]+(\b|$))/gim,
'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
  }
  var populator = function(response) {
          var decoded = JSON.decode(response);
          decoded = decoded[0];
          //console.log(decoded);
          var kategoriat = '';
          $A(decoded.Kategoriat).each(function(kat,id) {
          kategoriat +='<a rel="kategoria" title="'+kat.id+'" href="kategoriat/selaa/kategoria/'+kat.id+'">'+kat.nimi+'</a><br/>';
          });
          //kategoriat +='</ul>';
          var ytbox = '<div class="boksit">'
                      +'<div class="yhteystietoboksihead">'
                      +'<strong> Kategoriat </strong>'
                      +'</div>'
                      +'<div class="yhteystietoboksi katit">'+kategoriat+'</div>'
                      +'<div class="yhteystietoboksihead">'
                      +'<strong> Yhteystiedot </strong></div>'
                      +'<div class="yhteystietoboksi">'+decoded.Julkaisija.yhteystietoboksi+'</div></div>';
          var tobe = '<div class="leipis"><h2>'+decoded.otsikko+'</h2>';
          var toend = '<br style="clear:both;"/></div>';
          //var nhtml = this.getParent().getElement('span');
          var toinject = autolink(ytbox.replace(/<br>/g,' <br> ').replace(/<br\/>/,' <br\/> ').replace(/<\/p>/,' <\/p>')) + tobe + autolink(decoded.content.replace(/<br>/g,' <br> ').replace(/<br\/>/,' <br\/> ').replace(/<\/p>/,' <\/p>')) + toend;
          //console.log(toinject);
          tgt.set('html', toinject);
          $(tgt).getElements('.yhteystietoboksi.katit a').addEvent('click',function(e) { e.stop();
          menuselect(this,'ajax');
          tgt.fireEvent('onContentChange');
          });

  };
  var menuselect = function(wat,who) {
   // console.log(wat);
    var t = wat.get('tag');
    var w = who;
    switch(w) {
    case 'tabnav':
    var tobe = '<h2>'+wat.get('text')+'</h2>';
    $$('.'+wat.title).each(function(x) { tobe = tobe + ''+x.get('html')+''; });
    //console.log(nhtml);
    tgt.empty().set('html', '<div class="leipis_wide">'+tobe+'</div>');
    //tgt.getElements('div').getElement('a').setStyle('font-weight','bold');
    tgt.getElements('span').each(function(el) {
    var toinject= el.get('html');
    new Element('div', {html:toinject}).replaces(el);
    });
    if(!Browser.Engine.trident) scrollr.toElement('content');
    else window.scrollTo(0,0);
    break;
    case 'kats':default:
     var tobe = '<h2>'+wat.get('text')+'</h2>';
      var toend = '';
      var nhtml = wat.getParent().getElement('span') || $('lmenu').getElement('span[title='+wat.get('title')+']');
      if(nhtml) {
      var toinject = tobe + nhtml.get('html') + toend;
      } else {
      $$('.cat_'+wat.title).each(function(x) { tobe = tobe + ''+x.get('html')+''; });
      var toinject = tobe;
      }
      //console.log(toinject);
      toinject = autolink(toinject);
      tgt.empty().set('html', '<div class="leipis_wide">'+toinject+'</div>');
      //tgt.getElement('div').getElements('a').setStyle('font-weight','bold');
      tgt.getElements('span').each(function(el) {
      var toinject= el.get('html');
      new Element('div', {html:toinject}).replaces(el);
      if(!Browser.Engine.trident) scrollr.toElement('content');
      else window.scrollTo(0,0);
      });
    break;
    }
  };
  var passReq = function(event) {
    event.stop();
    //console.log();
    var rel = event.target.get('rel');
    var ref = event.target.get('text');
    switch(rel) {
    case 'kategoria':
      menuselect(this,'ajax');
      tgt.fireEvent('onContentChange');
    break;
    case 'hakemisto':default:
    var fetch = new Hash({itemIds:[ref]});
    var req = new Request({
        url: 'ajax',
        method: 'post',
        data: fetch.toQueryString(),
        onComplete:populator
        }).send();
    if(!Browser.Engine.trident) scrollr.toElement('content');
    else window.scrollTo(0,0);
    break;
    }
  };
  window.addEvent('domready', function() { 
    scrollr = new Fx.Scroll(window);
    if($('kysely')) {
    $('kysely').getElements('a').setProperty('target','_blank');
    //sb.asset.addEvent('load', function(e) { if(window.console) console.log(e);  });
    }
    var AC = new Autocompleter.Request.JSON('searchservice', 'ajax', {
        'postVar': 'search'
    });

    $$('.email').each(function(el) { el.set('html', el.get('html').replace('::at::','@')); });
    tgt = $('content');
    tgt.addEvent('onContentChange', function() {
      var fetch = new Hash({itemIds:[]});
      this.getElements('li[class^=hakemisto]').each(function(el) {
       fetch.itemIds.push(el.get('class').replace("hakemisto_",""));
      });
        var req = new Request({
        url: 'ajax',
        method: 'post',
        data: fetch.toQueryString(),
        onComplete:function(response) {
          var decoded = JSON.decode(response);
          decoded.each(function(value,key) { 
             tgt.getElement('.hakemisto_'+value.id).getElement('.fillme').set('html',autolink(value.yhteystietoboksi.replace(/<br>/g,' <br> ').replace(/<br\/>/,' <br\/> ').replace(/<\/p>/,' <\/p>')));
             tgt.getElements('a[rel=hakemisto]').addEvent('click',passReq);
             
          });
        }
        }).send();
        if(!Browser.Engine.trident) scrollr.toElement('content');
        else window.scrollTo(0,0);
        //console.log(req,fetch);
    });
    $$('.kats a').set('morph', {'duration':800, transition: Fx.Transitions.Elastic.easeOut});
    $$('#tabnav li').addEvent('onToggleClass', function() {
      $$('#tabnav li').filter(function(elem) { return elem.hasClass('selected')}).removeClass('selected');
      this.addClass('selected');
    });
    $$('#tabnav li').each(function(el,id) { 
    if(id > 0) {
    //var tgt = $('content');
    el.addEvent('click',function(e) { 
    e.stop(); 
    el.fireEvent('onToggleClass');
    menuselect(this,'tabnav');
    tgt.fireEvent('onContentChange');
    });
    }
    }); 
    $$('.kats a').addEvents({
    'click':function(e) { 
      e.stop(); 
     // var tgt = $('content'); 
     menuselect(this,'kats');
     tgt.fireEvent('onContentChange');
      //new Element('div', {html:toinject}).inject(tgt);
    },
    'mouseenter':function() { this.get('morph').start({'padding-right': 20, 'background-color':['#ededede','#fff']}); },
    'mouseleave':function() { this.get('morph').start({'padding-right': 12, 'background-color':'#ededed'}); }
    });
    $$('.kats span li a,.boxed a').each(function(el) {
    el.removeEvents();
    var tx = (el.getParent().hasClass('boxed'))?'Eepinen OY':el.get('text');
    var fetch = new Hash({itemIds:[tx]});
    el.addEvent('click',function(e) {
    e.stop();
    var req = new Request({
        url: 'ajax',
        method: 'post',
        data: fetch.toQueryString(),
        onComplete:populator
        }).send();
    });
    });
    $('searchservice').addEvents({
      'focus':function(e) { if (this.value == 'Hae tästä') this.value=''; },
      'blur':function(e) { if (this.value == '') this.value='Hae tästä';  }
    });
    AC.addEvents({
     'onShow': function() { 
      var el = $$('ul.autocompleter-choices');
        el.morph({'margin-left':[0,-80],'width':[165,250]});
     },
     'onSelection': function(arg1,arg2,arg3,arg4) {
        var fetch = new Hash({itemIds:[arg3]});
        var req = new Request({
        url: 'ajax',
        method: 'post',
        data: fetch.toQueryString(),
        onComplete:populator
        }).send();
     }
    });
  });
