

function InvestorCalculator(frm,priceLayerName,divLayerName){
    this.frm=frm;
    this.priceLayer=document.getElementById(priceLayerName);
    this.divLayer=document.getElementById(divLayerName);

    this.ticker;
    this.amount;
    this.firstValue;
    this.start;
    this.stop;
    this.calcDiv;

    this.sc=null;
    this.first;
    this.last;
    this.nCurrency;

    this.init=function(){
        //
        this.fillYears(frm.elements['start.Year'],false);
        this.fillYears(frm.elements['stop.Year'],true);
        var cm, cd;
        cm=new Date();
        cd=cm.getDate();
        cd=cd>9?cd:"0"+cd;
        cm=cm.getMonth()+1;
        cm=cm>9?cm:"0"+cm;
        frm.elements["stop.Month"].value=cm;
        frm.elements["stop.Day"].value=cd;
    
    }
    
    this.fillYears=function(elem, current){
        var opt = elem.options;
        if(opt+""=="undefined") return;

        var maxs=0;
        for(var i=0; i<opt.length;i++){
            if(opt[i].value>maxs){
                maxs=opt[i].value;
            }
        }

        var year = (new Date()).getYear();
        year=year<1900?year+1900:year;

        while(maxs<year){
            maxs++;
            var op = document.createElement("OPTION");
            op.value=maxs;
            op.text=maxs;
            opt.add(op);
            if(current && maxs==year) op.selected=true;
        }
    }

    this.recalc=function(me){
        //hide
        this.priceLayer.style.display="none";
        this.divLayer.style.display="none";
        //read
//window.status='readfrm0';
        this.readForm();
        //load
        this.loadQuote(me);
    }

    this.afterLoad=function(){
        window.status='loaded';
        //calc
        var firstPrice=this.first;
        if(this.amount!=0 && this.firstValue!=0){
            firstPrice=this.firstValue/this.amount;
        } 
        this.firstValue=this.firstValue!=0?this.firstValue:this.first*this.amount;
        this.amount=this.amount!=0?this.amount:this.firstValue/firstPrice;

        var lastPrice=this.last;
        var lastValue=this.last*this.amount;
        
        var change   =lastValue-this.firstValue;

        var days=parseInt((this.stop.valueOf()-this.start.valueOf())/1000/60/60/24);
//        alert(days);

        var yield    =(change/this.firstValue)*100*365/days;
        if(isNaN(yield)) yield=0;

        var sumDiv=0;

        var stockCd=this.ticker.split('.')[this.ticker.split('.').length-1];
        var underStock=stocks[stockCd].split(',');
        var ratio=underStock[1];
        underStock=underStock[0];

        for(var i=0;i<dividend.length;i++){
            var divrow=dividend[i].split(',');
            if( divrow[0]<this.formatDate(this.start) || 
                divrow[0]>this.formatDate(this.stop)  ||
                underStock!=divrow[1]
              ){
                continue;
            }
            var rate=this.getRate(divrow[0],divrow[3],this.nCurrency);
            
            sumDiv+=(rate*parseFloat(divrow[2])*ratio);
        }

        var sumDivValue =sumDiv*this.amount;
        var divYield;   
        var totalYield;

        divYield =(sumDivValue/this.firstValue)*100*365/days;
        totalYield  =((change+sumDivValue)/this.firstValue)*100*365/days;

        if(yield<=(-100)) yield="-";
        if(totalYield<=(-100)) totalYield="-";
        
    if(days<=0) {
        divYield=0; totalYield=0; yield=0;
    }
        
        //fillup
        if(document.getElementById('firstPrice' )!=null) document.getElementById('firstPrice' ).innerHTML =  this.fmt(firstPrice );
        if(document.getElementById('lastPrice'  )!=null) document.getElementById('lastPrice'  ).innerHTML =  this.fmt(lastPrice  );
        if(document.getElementById('lastValue'  )!=null) document.getElementById('lastValue'  ).innerHTML =  this.fmt(lastValue  );
        if(document.getElementById('change'     )!=null) document.getElementById('change'     ).innerHTML =  this.fmt(change     );
        if(document.getElementById('yield'      )!=null) document.getElementById('yield'      ).innerHTML =  this.fmt(yield      );
                                                                       
        if(document.getElementById('sumDiv'     )!=null) document.getElementById('sumDiv'     ).innerHTML =  this.fmt(sumDiv     );
        if(document.getElementById('sumDivValue')!=null) document.getElementById('sumDivValue').innerHTML =  this.fmt(sumDivValue);
        if(document.getElementById('divYield'   )!=null) document.getElementById('divYield'   ).innerHTML =  this.fmt(divYield   );
        if(document.getElementById('totalYield' )!=null) document.getElementById('totalYield' ).innerHTML =  this.fmt(totalYield );

        //display
        this.priceLayer.style.display="";
        if(this.calcDiv) this.divLayer.style.display="";
        //document.body.removeChild(this.sc);
window.status='ready';
    }

    this.loadQuote=function(me){
window.status='loading';

        var query=  "http://chart.rsf.ru/calculator/getdata.phtml?sd="+
                    this.formatDate(this.start)+
                    "&ed="+
                    this.formatDate(this.stop)+
                    "&ticker="+
                    this.ticker+
                    "&me="+me;

//window.status=query;
        //alert(query);
        if(this.sc!=null) document.body.removeChild(this.sc);
        
        this.sc = document.createElement("SCRIPT");
        
        this.sc.setAttribute("language","javascript");
        
        this.sc.setAttribute("src",query);
        
        document.body.appendChild(this.sc);

    }
    
    this.readForm=function(){
window.status='readfrm1';
        this.ticker=null;
        var tickers=this.frm.elements['ticker'];
        for(var i=0;i<tickers.length;i++){
            if(tickers[i].checked ){
                this.ticker=tickers[i].value;
                break;
            }
        }
        if(this.ticker==null){
            this.ticker=tickers.value;
        }
window.status='readfrm2';

        this.amount=parseFloat(this.frm.elements['amount'].value);
        this.amount=isNaN(this.amount)?0:this.amount;
window.status='readfrm3';

        this.firstValue=parseFloat(this.frm.elements['firstValue'].value);
        this.firstValue=isNaN(this.firstValue)?0:this.firstValue;
window.status='readfrm4';

        this.start=this.readDate('start');
        this.stop=this.readDate('stop');

window.status='period '+this.start+' '+this.stop;

        this.calcDiv=this.frm.elements['dividend'].checked;
        
    }

    this.readDate=function(pref){
window.status='readdt1';

        var el=this.frm.elements;
        var ny=el[pref+'.Year'];
        var nm=el[pref+'.Month'];
        var nd=el[pref+'.Day'];
//window.status=pref+' '+ny.value+' '+nm.value+' '+nd.value;
        var result=new Date(0);
            result.setYear(ny.value);
            result.setMonth(nm.value-1);
            result.setDate(nd.value);
/* *
    var day=result.getDate();
    while(day!=dday)){
        result.setDate(
        
    }
/* */
        this.setDate(pref,result);
        return result;
    }
    
    this.setDate=function(pref,date){
//window.status=pref+' '+date;
        var ny=date.getFullYear();
        var nm=date.getMonth()+1;
        var nd=date.getDate();
        var el=this.frm.elements;

        el[pref+".Year"].value=ny;
        el[pref+".Month"].value=nm<10?"0"+nm:nm;    
        el[pref+".Day"].value=nd<10?"0"+nd:nd;    
    }

    this.formatDate=function(date){
//    window.status='formatDate '+date;
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        month=month<10?"0"+month:month;
        day=day<10?"0"+day:day;
        return year+""+month+""+day;
    }
    
    this.fmt=function(num){
        if(isNaN(num)) return "-";
        if(num==0) return 0;

        var prec=(3-Math.floor(Math.log(num>0?num:-num)/Math.log(10))) ;
        
        if(prec>20) return num;
/*
        if(prec<0){
            return Math.round(num);
        }
*/
        if(prec<2){
            prec=2;
        }

        if(num.toFixed){
            return res=num.toFixed(prec); 
        }

        return num;
    }
    
    this.getRate=function(dt,curIn,curOut){
        if(curIn==curOut) return 1;
        for(var i=0;i<rate.length;i++){
            var row=rate[i].split(',');
            if(parseInt(row[0])==parseInt(dt)){
                if(curCurrency==curOut && row[1]==curIn){
                    return parseFloat(row[2]);
                }
                
                if(curCurrency==curIn && row[1]==curOut){
                    return 1/parseFloat(row[2]);
                }
            }
        }
        return 0;
    }

    this.init();
}
