var Comic = Class.create({
  initialize: function(container, paper, department, page) {
    if (container && paper && department) {
      if (container && $(container)) {
        this.container = container;        
      } else {
        throw("'container' ei määritelty");
      } 
      if (typeof(paper) == 'number' && (parseInt(paper) >= 0)) {
        this.paper = paper;
      } else {
        throw("'paper' ei määritelty");
      }
      if (typeof(department) == 'number'  && (parseInt(department) >= 0)) {
        this.department = department;
      } else {
        throw("'department' ei määritelty");
      }
      if (typeof(page) == 'number' && (parseInt(page) >= 0)) {
        this.page = page;
      } else {
        throw("'page' ei määritelty");
      }
    } else {
      throw("käytä kutsua 'new Comic([containerId], [paperId], [departmentId], [page])'");
    }
  },
  
  load: function( d ) {
    var self = this;  
    var url = '/scripts/edoris/edoris.dll?tem=ts_sarjakuva&publishing=' + ((!d || typeof(d) != 'string')? '' : d) + '&paper=' + this.paper + '&department=' + this.department + '&page=' + this.page;

    new Ajax.Request(url, {
      method: 'get',
      onLoading: function() {
        $( this.container ).update("Haetaan tietoja ...");
      },
      onFailure: function() {
        $( this.container ).update("Käyttämäsi selain ei tue Ajaxia. Päivitä selainmesi uudempaan versioon.");
      },
      onSuccess: function(transport) {
    		var o = {};
    		var current = {};
      
    		var x = transport.responseText.replace(/^\s*/,'').replace(/\s*$/,'').split(';');
    		for(var i=0; i < x.length - 1; i++) {
    			var y = x[i].split(',');
    			try {
    				if (o[y[0]]) o[y[0]].push({ imgsrc : y[4], thumbsrc : y[4].replace(/(tem=.*)(&doc_id)/, '$1_thumb$2'), week : y[3], date : y[2] });
    				else o[y[0]] = new Array({ imgsrc : y[4], thumbsrc : y[4].replace(/(tem=.*)(&doc_id)/, '$1_thumb$2'), week : y[3], date : y[2] });
    				if (parseInt(y[1])) current = { imgsrc : y[4], thumbsrc : y[4].replace(/(tem=.*)(&doc_id)/, '$1_thumb$2'), week : y[3], date : y[2] };
    			} catch(e) { }
    		}
    		
        var currentPicContainer = new Element('fieldset', { 'class' : 'currentPicContainer' });
    		if (current && current.imgsrc) {
    		  currentPicContainer.update( new Element('legend', { 'class' : 'currentWeek' }).update(current.week) );
    		  currentPic = new Element('img', { 'src' : current.imgsrc });
    		  currentPicContainer.insert( currentPic );
    		} else {
          currentPicContainer.update("[Ei kuvaa]");
        }

    		$( self.container ).update( currentPicContainer );
   		
  	 		var thumbContainer = new Element('div', { 'class' : 'comicThumbContainer' });
        for(var i=0; i < o['0'].length; i++) {
  				var thumbLink = new Element('a', { 'href' : 'javascript://Set active picture' }).observe('click', function(event) {
            var element = Event.findElement( event, 'a' );
  					var m = /doc_id=(\d+)/.exec( element.down('img').src );
  					currentPic.src = currentPic.src.replace( /(doc_id=)\d+/, '$1' + m[1] );
  					element.up('td').select('a').invoke('removeClassName', 'selected');
            element.addClassName('selected'); 
          }).update( new Element('img', { 'src' : o['0'][i].thumbsrc }).wrap('span') );
          
          if ( thumbLink.down('img').src.replace(/^.*doc_id=(\d+).*$/, '$1') == currentPic.src.replace(/^.*doc_id=(\d+).*$/, '$1') ) {
            thumbLink.addClassName('selected');
          }
  				thumbContainer.insert(thumbLink);
  			}

    		var previousLink = new Element('a', {
          'class' : 'icon-prev' + (!o['-1']? '_d' : ''),
          'title' : o['-1'] && typeof(o['-1'][0].week) != 'undefined' ? o['-1'][0].week : '',
          'href' : 'javascript://Edellinen sarja'
        });
        if (o['-1']) previousLink.observe('click', function() { self.load( o['-1'][0].date ) }); 
    		var nextLink = new Element('a', {
          'class' : 'icon-next' + (!o['1']? '_d' : ''),
          'title' : o['1'] && typeof(o['1'][0].week) != 'undefined' ? o['1'][0].week : '',
          'href' : 'javascript://Seuraava sarja'
        });
        if (o['1']) nextLink.observe('click', function() { self.load( o['1'][0].date ) });
  			
  			var trBottom = new Element('tr');
  			trBottom.insert( $( previousLink ).wrap('td') );
  			trBottom.insert( $( thumbContainer ).wrap('td', { 'class' : 'comicThumbContainer', 'style' : 'width: 100%;' }) );
  			trBottom.insert( $( nextLink ).wrap('td') );
  			
  			$( self.container ).insert( trBottom.wrap('tbody').wrap('table', { 'class' : 'comicThumbContainer' }) );
      }
    });
  }
});
