function Ajax()
{
  this.requestObj = null;
  this.state      = 1;
  this.getRequestObj = function ()
  {
    if (window.XMLHttpRequest)
    {
         return new XMLHttpRequest;
    }
    else if (window.ActiveXObject)
    {
         return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else return null;
  }

  this.getReadyStateHandler = function (req, handler, p)
  {
    return function ()
    {
       handler(req,p);
    }
  }

  this.sendRequest = function (url, params, method, myFunc, p)
  {
    this.requestObj = this.getRequestObj();
      
    if (!this.requestObj) return false;

    if (!method || !method.length || method.length < 4) method = "POST";

    this.requestObj.onreadystatechange = this.getReadyStateHandler(this.requestObj,myFunc, p);

    this.requestObj.open(method,url,true);
    this.requestObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    this.requestObj.send(params);
  }
}

function ViewBlock(divId, rssLink, itemsLimit, textLimit, dirname, informerTitle , randomize, stripTags, design){
  this.textLimit      = 100;
  this.itemsLimit     = 5;
  this.randomize      = randomize;
  this.stripTags      = true;
  this.imageSTR       = 'style="padding: 0px 5px 0px 0px;" width="200" border="0" alt="Автовик: авто, подержанные авто, авто тюнинг, автосалоны, машины: [TITLE]" title="Автовик: каталог автомобилей, авто, подержанные авто, авто тюнинг, автосалоны, машины, новости: [TITLE]" align="left"';
  this.design         = 'default';
  this.headerTemplate = '';
  this.itemTemplate   = '';
  this.footerTemplate = '';
  this.itemsText      = '';
  this.divId          = false;
  this.ajax           = new Ajax;
  this.dirname        = 'scripts/';
  this.serverSide     = 'get.php';
  this.responses       = new Array();
  var obj             = this;
  
  this.parseRSS = function(divId, rssLink, itemsLimit, textLimit, dirname, informerTitle, randomize, stripTags, design)
  {
    if(!rssLink || !dirname) return false;

    this.headerTemplate = '';
    this.itemTemplate   = '';
    this.footerTemplate = '';
    this.itemsText      = '';
    obj                 = this;
    this.informerTitle = informerTitle;
    this.divId         = divId;
    this.dirname       = dirname;
    this.randomize     = randomize;
    
    if(stripTags == false)  this.stripTags = false;
    if(itemsLimit >= 0)     this.itemsLimit = itemsLimit;
    if(textLimit >= 0)      this.textLimit  = textLimit;
    if(typeof(design) != 'undefined')  this.design     = design;
    this.getTemplate('header', this.design);
    this.getTemplate('footer', this.design);
    this.getTemplate('item',   this.design);
    this.getRss(rssLink);
  }
  
  
  this.getTemplate = function(tempName,design, text)
  { 
    //this.responses[this.responses.length] = tempName;
    this.ajax.sendRequest(this.dirname+this.serverSide, 'template='+tempName+'&design='+design,'post', this.parseResponse, tempName);
  }

  this.getRss = function(link)
  {
    //this.responses[this.responses.length] = link;
    this.ajax.sendRequest(this.dirname+this.serverSide, 'link='+link, 'post', this.rssOut, link);
  }

  this.parseResponse = function(resp, tempName)
  {
    if (resp.readyState == 4)
    {
      switch(tempName)
      {
        case 'header': obj.headerTemplate = resp.responseText; break;
        case 'footer': obj.footerTemplate = resp.responseText; break;
        case 'item':   obj.itemTemplate   = resp.responseText; break;
      }
    }
  }

  this.rssOut = function(resp)
  {
    if (resp.readyState == 4)
    {
      data = obj.parseXML(resp.responseXML);
      for (var i in data.items)
      {
        var str = new String(obj.itemTemplate);
            str = str.replace(/\[IMAGE\]/g,       data.items[i].image);
            str = str.replace(/\[DESCRIPTION\]/g, data.items[i].description);
            str = str.replace(/\[LINK\]/g,        data.items[i].link);
            str = str.replace(/\[TITLE\]/g,       data.items[i].title);
        obj.itemsText += str;
      }
      obj.printOutput();
    }
  }

  this.printOutput = function()
  {
    if(this.headerTemplate != '' && this.itemsText != '' && this.footerTemplate != '')
    {
      var text = this.headerTemplate + this.itemsText + this.footerTemplate;
          text = text.replace(/\[INFORMERTITLE\]/g, this.informerTitle);
      if(this.divId != false){
        document.getElementById(this.divId).innerHTML = text;
      }else{
        document.writeln(text);
      }
      text = '';
      this.headerTemplate = '';
      this.itemsText      = '';
      this.footerTemplate = '';
      this.informerTitle  = '';
    }else{
      setTimeout("this.printOutput", 100);
    }
  }

  // Returns a random integer between min and max
  // Using Math.round() will give you a non-uniform distribution!
  this.getRandomInt = function(min, max)
  {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  this.getItems = function(ret, items, i){
    
    ret.items[i] = new Object();
    for (var j = 0; j < items.item(i).childNodes.length; j++)
    {
      var node = items.item(i).childNodes.item(j);
      if (node.firstChild)
      {
        var text = node.firstChild.nodeValue; 
        var picOld  = false;
        var picNew  = false;
		text = text.replace("\n",' ');
		text = text.replace("\r",' ');
		text = text.replace("\t",' ');
		//alert(text);
		
        if(text.match(/src=[\"|\'|](.*?)[\"|\'|]/i) != null)
        {
	      var picNew = new String(text.match(/src=[\"|\'|].*?[\"|\'|]/i));
		  picNew = '<img '+picNew+' '+this.imageSTR+'/>';
		}
		
		/*
        if(text.match(/<img.*?>/i) != null)
        {
          var picOld = new String(text.match(/<img.*?>/i));
		  
          //alert(picOld.match(/src=\"(.*?)\"/i))
          //var arr = picOld.match(/src=\"(.*?)\"/i);
          //ret.items[i]['image'] = arr[1];
          //alert(arr[1]);
          var picNew = new String(picOld.replace(/align=[\"|\'|].*?[\"|\'|]/i, ''));
          picNew = new String(picNew.replace(/width=[\"|\'|].*?[\"|\'|]/i,     ''));
          picNew = new String(picNew.replace(/border=[\"|\'].*?[\"|\'|]/i,    ''));
          picNew = new String(picNew.replace(/height=[\"|\'|].*?[\"|\'|]/i,    ''));
          picNew = new String(picNew.replace(/class=[\"|\'|].*?[\"|\'|]/i,     ''));
          picNew = new String(picNew.replace(/id=[\"|\'|].*?[\"|\'|]/i,        ''));
          picNew = new String(picNew.replace(/alt=[\"|\'|].*?[\"|\'|]/i,       ''));
          picNew = new String(picNew.replace(/title=[\"|\'|].*?[\"|\'|]/i,     ''));
          picNew = new String(picNew.replace(/hspace=[\"|\'|].*?[\"|\'|]/i,    ''));
          picNew = new String(picNew.replace(/vspace=[\"|\'|].*?[\"|\'|]/i,    ''));
          picNew = new String(picNew.replace(/style=[\"|\'|].*?[\"|\'|]/i,     ''));
		  picNew = new String(picNew.replace(/_base_href=[\"|\'|].*?[\"|\'|]/i,''));
          picNew = new String(picNew.replace(/\/>/i,               '>'));
          picNew = new String(picNew.replace(/>/i, ' '+this.imageSTR+'/>'));
          //alert([picOld,picNew])
          //alert(text.match(/<img.*?>/));
          text = text.replace(picOld,' ');
          //alert(text)
                    
        }
		*/
        if(this.stripTags)
        {
          text = text.replace(new RegExp("&lt;", "g"),  "<");
          text = text.replace(new RegExp("&gt;", "g"), ">");
          text = text.replace(new RegExp("<[^>]+>", "g"),   "");
        }

        if(obj.textLimit > 0 && text.length > obj.textLimit)
        {
          text = text.substr(0, obj.textLimit);
          text = text.substr(0, text.lastIndexOf(' '));
        }
        ret.items[i][node.nodeName] = text;
  
        
        if(picNew)ret.items[i]['image'] = picNew;
      }
    }
    return ret;
  }
 this.parseXML = function(doc) {
    var ret = new Object();
    ret.items = new Array();

    try
    {
      if (!doc) {
          return ret;
      }

      ret.title       = doc.getElementsByTagName("title").item(0).firstChild.nodeValue;
      ret.description = doc.getElementsByTagName("description").item(0).firstChild.nodeValue;
      ret.link        = doc.getElementsByTagName("link").item(0).firstChild.nodeValue;

      ret.pubDate     = doc.getElementsByTagName("pubDate").item(0).firstChild.nodeValue;

      var items       = doc.getElementsByTagName("item");
      var LIMIT       = obj.itemsLimit;

      if(items.length < obj.itemsLimit || obj.itemsLimit == 0)  LIMIT = items.length;
      
      if(obj.randomize == true)
      {
        //alert('aha');
        var rands = new Array;
        for (var i = 0; i < LIMIT; i++)
        {
          var num = obj.getRandomInt(0,items.length);
          if(!obj.in_array(num, rands) && typeof(items[num]) != 'undefined'  && items[num] != null)
          {
            if(rands.length < LIMIT)
            {
              rands[rands.length] = num;
            }
          }else{
           --i;
          }
        }
        for (var i = 0; i < rands.length; i++)
        {
          ret = obj.getItems(ret, items, rands[i]);
        }
        
      }else{
        for (var i = 0; i < LIMIT; i++)
        {
          ret = obj.getItems(ret, items, i);
        }
      }

    }
    catch(e)
    {
  
    }
    return ret;
}

  this.in_array = function(needle, hash){
    for(var i = 0; i < hash.length; ++i){
      if(hash[i] == needle) return true;
    }
    return false;
  }
  this.parseRSS(divId, rssLink, itemsLimit, textLimit, dirname, informerTitle, randomize, stripTags, design);

}
