 var j=jQuery.noConflict();

function loadjscssfile(filename, filetype) {
     if (filetype=="js"){ //if filename is a external JavaScript file
          var fileref=document.createElement('script');
          fileref.setAttribute("type","text/javascript");
          fileref.setAttribute("src", filename);
     } else if (filetype=="css"){ //if filename is an external CSS file
          var fileref=document.createElement("link");
          fileref.setAttribute("rel", "stylesheet");
          fileref.setAttribute("type", "text/css");
          fileref.setAttribute("href", filename);
     }
     if (typeof fileref!="undefined") {
          document.getElementsByTagName("head")[0].appendChild(fileref);
     }
}

//if (BrowserDetect.browser=='Explorer' && BrowserDetect.version==6) { // needed for ie6 only
//     loadjscssfile('/_admin/js/DD_belatedPNG.js','js');
//}

        /* SETUP */

        j(window).load(function() {

            try {
                DD_belatedPNG.fix('#rounded_rect,#colVirt,#colPhys,#colVirtLabel,#colPhysLabel,#shadow,.pngFixRule2');
            } catch(err) {}

            Cufon.replace('.greenBtn .body, .ctaText',{ fontSize: '15.5px', lineHeight: '16px', letterSpacing: '-0.25px' });
            Cufon.replace('#top_text h3',{ fontSize: '27px', lineHeight: '30px', letterSpacing: '-0.25px' });

            j('.serv').each(function(ix,el) {
                switch (el.id) {
                    case 'emailServers':
                        el.value=1;
                        break;
                    case 'dbServers':
                        el.value=2;
                        break;
                    case 'fileshareServers':
                        el.value=1;
                        break;
                    case 'generalpurposeServers':
                        el.value=3;
                        break;
                    case 'otherServers':
                        el.value=1;
                        break;
                    default:
                        el.value=1;
                }
                j(el).bind('keyup',startUpdate);
            });
            j('.cap').each(function(ix,el) {
                switch (el.id) {
                    case 'emailCap':
                        el.value=200;
                        break;
                    case 'dbCap':
                        el.value=100;
                        break;
                    case 'fileshareCap':
                        el.value=300;
                        break;
                    case 'generalpurposeCap':
                        el.value=250;
                        break;
                    case 'otherCap':
                        el.value=100;
                        break;
                    default:
                        el.value=100;
                }
                j(el).bind('keyup',startUpdate);
            });

            j('#labels').append(function() {
                str='';
                for (i=0;i<numChartLabels*2;i++) {
                    str+='<div class="label">&nbsp;</div>';
                    oldLabels['label'+i]=0;
                    newLabels['label'+i]=0;
                }
                return str;
            });

            if (!j('#overlayContent').length) { // if not in an overlay page, otherwise overlay will do inits
                update();
            } else {
                registerOverlayInitScript('efficiencyCalcOverlay',update);
            }

        });

        var updateDelayInt=0;
        function startUpdate() {
            clearTimeout(updateDelayInt);
            updateDelayInt=setTimeout(update,250);
        }

        /* ANIMATION STORAGE -- objects for tweening display numbers */

        var oldVals={ v: 0, p: 0, cs: 0, roi: 0 }; // virtual, physical, cost savings, roi
        var newVals={ v: 0, p: 0, cs: 0, roi: 0 };
        var oldLabels={};
        var newLabels={};
        var numChartLabels=6; // this is a general target, actual number will be twice this, but only roughly half to 2/3 will show most of the time
        var animParams={
            easing: 'easeInOutQuad',
            duration: 1000,
            framerate: 20
        };

        /* DATA STORAGE  --  .b is before, .a is after */

        var d={}; // DATA

        d.b={ // BEFORE
            servers: -1, // calculated
            costsperserver: 5600,
            virtlicensecost: 0,
            operationscosts: -1, // calculated
            storagecostsgb: 1,
            growth: 0.3,
            protection: 2,
            dedupe: 0,
            raidcap: (600*0.7),
            adminsal: 71250,
            maxserversadmin: 40,
            admincostsperserver: -1 // calculated
        };
        d.a={ // AFTER
            servers: -1, // calculated
            costsperserver: 2900,
            virtlicensecost: 5750,
            operationscosts: -1, // calculated
            storagecostsgb: 1.5,
            growth: 0.3,
            protection: 1.5,
            dedupe: 0.7,
            raidcap: (600*5*0.7),
            adminsal: 71250,
            maxserversadmin: 8,
            admincostsperserver: -1 // calculated
        };

        var o={}; // CAPACITY OUTPUTS (all will have outputs for each app type plus a 'total' value)
        o.b={};
        o.a={};

        var c={}; // COSTS (all will have .b and .a properties)
        c.s={}; // server
        c.l={}; // license
        c.d={}; // datacenter
        c.st={}; // storage

        var t={}; // 3-YEAR TCO (will have properties 'v' (virtual), 'p' (physical), 'roi' (ROI))

        /* CALCS */

        function update() {

            caps=j('.cap');
            servs=j('.serv');

            caps.each(numsOnly);
            servs.each(numsOnly);

            d.b.servers=0;
            o.b.total=0;
            o.a.total=0;

            servs.each(function(ix,el) {
                d.b.servers+=Number(el.value);
                o.b[el.id]=(Number(servs[ix].value))?Math.round(Number(caps[ix].value)*(1+d.b.growth)*d.b.protection*100)/100:0;
                fsMod=(ix==2)?(1-d.a.dedupe):1; // special case for file share
                o.a[el.id]=(Number(servs[ix].value))?Math.round(Number(caps[ix].value)*(1+d.a.growth)*fsMod*d.a.protection*100)/100:0;
                o.b.total+=o.b[el.id];
                o.a.total+=o.a[el.id];
            });

            calc1=(d.b.servers)?(d.b.servers-Number(servs[2].value))/8:0;
            d.a.servers=(d.b.servers)?Math.max(2,Math.ceil(calc1)):0;

            d.b.admincostsperserver=d.b.adminsal/d.b.maxserversadmin;
            d.a.admincostsperserver=d.a.adminsal/d.a.maxserversadmin;

            d.b.operationscosts=(1500*d.b.servers)+(d.b.admincostsperserver*d.b.servers);
            d.a.operationscosts=(1500*d.a.servers)+(d.a.admincostsperserver*d.a.servers);

            c.s.b=d.b.servers*d.b.costsperserver;
            c.s.a=d.a.servers*d.a.costsperserver;

            c.l.b=d.b.servers*d.b.virtlicensecost;
            c.l.a=d.a.servers*d.a.virtlicensecost;

            c.d.b=d.b.operationscosts;
            c.d.a=d.a.operationscosts;

            c.st.b=o.b.total*d.b.storagecostsgb;
            c.st.a=o.a.total*d.a.storagecostsgb;

            t.v=c.s.a+c.l.a+c.d.a+c.st.a;
            t.p=c.s.b+c.l.b+c.d.b+c.st.b;
            t.roi=Math.round(((t.p-t.v)/t.v)*100);
            if (isNaN(t.roi)) { t.roi=0; }

            //try {
            //    console.clear();
            //    console.log(d.b);
            //    console.log(d.a);
            //    console.log(c.s);
            //    console.log(c.l);
            //    console.log(c.d);
            //    console.log(c.st);
            //    console.log(o.b.total);
            //    console.log(o.a.total);
            //} catch(err) { }

            //j('#debug').html('<div style="float: left; width: 250px;"><b><i>INTERNAL DATA:</i></b>'+
            //        '<br/><b>BEFORE:</b>'+
            //        '<br/>'+j.param(d.b).split('&').join('<br/>')+
            //        '</div><div style="float: left; width: 250px;"><br/><b>AFTER:</b>'+
            //        '<br/>'+j.param(d.a).split('&').join('<br/>')+
            //        '</div><div style="float: left; width: 250px;"><br/><b>COST (Servers before/after):</b>'+
            //        '<br/>'+j.param(c.s).split('&').join('<br/>')+
            //        '<br/><b>COST (License before/after):</b>'+
            //        '<br/>'+j.param(c.l).split('&').join('<br/>')+
            //        '<br/><b>COST (Data Center before/after):</b>'+
            //        '<br/>'+j.param(c.d).split('&').join('<br/>')+
            //        '<br/><b>COST (Storage before/after):</b>'+
            //        '<br/>'+j.param(c.st).split('&').join('<br/>')+
            //        '<br/><b>COST (Total before/after):</b>'+
            //        '<br/>'+o.b.total+
            //        '<br/>'+o.a.total+'</div>');

            chartScaleFactor=Math.max(t.p,t.v)/j('#chart').height();

            //j('#outputTCO').html('&nbsp;'+currencyIzeNumber(t.p-t.v));
            //j('#outputROI').html('&nbsp;'+t.roi+'%');
            j('#colVirt').stop().animate({
                height: (t.v/chartScaleFactor)+'px'
            },animParams);
            j('#colPhys').stop().animate({
                height: (t.p/chartScaleFactor)+'px'
            },animParams);
            j('#colVirtLabel').stop().animate({
                bottom: (t.v/chartScaleFactor)+'px'
            },animParams);
            j('#colPhysLabel').stop().animate({
                bottom: (t.p/chartScaleFactor)+'px'
            },animParams);
            chartLabels=getLabels(Math.max(t.p,t.v),numChartLabels);
            newLabels=chartLabels.labels;
            newVals={
                v: t.v,
                p: t.p,
                cs: t.p-t.v,
                roi: t.roi
            };
            chartLabelEls=j('#labels .label');
            j(chartLabelEls).each(function(ix,el){
                j(el).stop().animate({
                    bottom: (newLabels['label'+ix]/chartScaleFactor)+'px'
                },animParams);
            });
            j(oldLabels).stop().animate(newLabels, {
                duration: animParams.duration,
                easing: animParams.easing,
                step: function() {
                    j(chartLabelEls).each(function(ix,el) {
                        j(el).html(currencyIzeNumber(Math.round(oldLabels['label'+ix])));
                    });
                }
            });
            j(oldVals).stop().animate(newVals, {
                duration: animParams.duration,
                easing: animParams.easing,
                step: function() {
                    j('#outputTCO').html('&nbsp;'+currencyIzeNumber(oldVals.cs));
                    j('#outputROI').html('&nbsp;'+Math.round(oldVals.roi)+'%');
                    j('#colVirtLabel .colLabelBot').html(currencyIzeNumber(oldVals.v));
                    j('#colPhysLabel .colLabelBot').html(currencyIzeNumber(oldVals.p));
                }
            });

        }

        function randomizeInputs() {
            j('.serv').each(function(ix,el) {
                randomize(el,10,false);
            });
            j('.cap').each(function(ix,el) {
                randomize(el,1000,false);
            });
            update();
        }

        function randomize(el,baseVal,init) {
            el.value=(init)?baseVal:Math.round(Math.random()*baseVal);
        }

        /* LIMIT FORM INPUTS */

        function numsOnly(ix,el) {
            test=parseInt(el.value);
            if (isNaN(test)) {
                el.value=0;
            } else {
                if (j(el).hasClass('serv')) {
                    if (test>99) { test=99; }
                } else {
                    if (test>9999) { test=9999; }
                }
                if (test<0) { test=0; }
                el.value=test;
            }
        }

        /* DISPLAY */

        function currencyIzeNumber(inVal) {
            //defaults
            currSymPos=0;
            currSym='$';
            separator=',';
            decimalSeparator='.';
            interval=3;
            decimals=2;
            padDecimals=true;

            inDecimals=inVal%1;
            outDecimals='';
            if (padDecimals) {
                inDecimals=Math.round(roundTo(inDecimals,decimals)*(Math.pow(10,decimals)));
                if (inDecimals==Math.pow(10,decimals)) {
                    inDecimals=0;
                    inVal+=1;
                }
            } else {
                inDecimals=roundTo(inDecimals,decimals);
                inDecimalsTemp=inDecimals;
                while (inDecimalsTemp%1!=0 && String(Math.floor(inDecimalsTemp)).length<decimals) {
                    inDecimalsTemp*=10;
                }
                inDecimals=Math.round(inDecimalsTemp);
            }
            if (decimals>0) {
                if (padDecimals) {
                    outDecimals=padString(inDecimals,decimals,'0');
                } else {
                    outDecimals=String(Math.floor(inDecimals));
                }
            }
            inStr=String(Math.floor(inVal));
            strPieces=new Array();
            while (inStr.length>interval) {
                strPieces.push(inStr.slice(-interval));
                inStr=inStr.slice(0,inStr.length-interval);
            }
            strPieces.push(inStr);
            assembled=
                ((currSymPos==0)?currSym:'')+
                strPieces.join(separator)+
                ((currSymPos==0.5)?currSym:'')+
                ((decimals>0 && currSymPos!=0.5)?decimalSeparator:'')+
                outDecimals+
                ((currSymPos==1)?currSym:'')+
                '';
            return ((currSymPos==0)?currSym:'')+strPieces.reverse().join(separator)+((currSymPos==0.5)?currSym:'')+((decimals>0 && currSymPos!=0.5)?decimalSeparator:'')+outDecimals+((currSymPos==1)?currSym:'');
        }

        function padString(inVal) {
            newLength=2;
            fillChar='0';
            inValStr=String(inVal);
            while (inValStr.length<newLength) {
                inValStr=fillChar+inValStr;
            }
            return inValStr;
        }

        function roundTo(inVal,decimals) {
            places=Math.pow(10,decimals);
            inVal*=places;
            inVal=Math.round(inVal);
            inVal/=places;
            return inVal;
        }

        // label maker
        var acceptableIntervals=[
        0,
        0.1,
        0.25,
        0.5,
        0.75,
        1,
        1.25,
        1.5,
        2,
        2.5,
        5,
        7.5,
        10,
        12.5,
        15,
        20,
        25,
        50,
        75,
        100,
        125,
        150,
        200,
        250,
        500,
        750,
        1000,
        1250,
        1500,
        2000,
        2500,
        5000,
        7500,
        10000,
        12500,
        15000,
        20000,
        25000,
        50000,
        75000,
        100000,
        125000,
        150000,
        200000,
        250000,
        500000,
        750000,
        1000000,
        1250000,
        1500000,
        1750000,
        2000000,
        2500000,
        5000000,
        7500000,
        10000000,
        12500000,
        15000000,
        20000000,
        25000000,
        50000000,
        75000000,
        100000000 //100 million
        ];
        function getLabels(inMax,numLabels) {
            for (n=0;n<acceptableIntervals.length;n++) {
                if (acceptableIntervals[n]*numLabels>inMax) {
                    n--;
                    break;
                }
            }
            while (acceptableIntervals[n]*numLabels<inMax) {
                n++;
            }
            while (acceptableIntervals[n]*numLabels>inMax*1.5) {
                n--;
            }
            var outLabels={};
            for (m=0;m<numLabels*2;m++) {
                outLabels['label'+m]=(m*acceptableIntervals[n]);
            }
            return {labels:outLabels,interval:acceptableIntervals[n],count:numLabels};
        }

