﻿    var $jq = jQuery.noConflict();

    $jq(document).ready(function() {
        // setup accordions
        $jq("#allocPicker").accordion({
            active: true,
            alwaysOpen: false,
            autoheight: false
        }).bind("change.ui-accordion", function(event, ui) {
            if (ui != undefined) {
                var imgElement = $jq("#" + $jq(ui.newHeader).get(0).id + " .l1Expander").get(0);
                var imgElementSrc = $jq(imgElement).attr("src");
                if (imgElementSrc.match(/plus.gif$/))
                    $jq(imgElement).attr("src", "/allocation-tool/images/minus.gif");
                else
                    $jq(imgElement).attr("src", "/allocation-tool/images/plus.gif");

                if (!($jq(ui.oldHeader).length == 0))
                    $jq("#" + $jq(ui.oldHeader).get(0).id + " .l1Expander").attr("src", "/allocation-tool/images/plus.gif");
            }
        });

        $jq(".accordBlockNest").accordion({
            active: true,
            alwaysOpen: false,
            autoheight: false
        }).bind("change.ui-accordion", function(event, ui) {
            if (ui != undefined) {
                var imgElement = $jq("#" + $jq(ui.newHeader).get(0).id + " .l2Expander").get(0);
                var imgElementSrc = $jq(imgElement).attr("src");
                if (imgElementSrc.match(/plus.gif$/))
                    $jq(imgElement).attr("src", "/allocation-tool/images/minus.gif");
                else
                    $jq(imgElement).attr("src", "/allocation-tool/images/plus.gif");
            }
        });

        $jq(".accordBlockShowAll").accordion({
            active: true,
            alwaysOpen: false,
            autoheight: false
        });

        // setup tooltips            
        $jq("#indexByGroup img[@src$='cia.info.jpg'],#indexByAlpha img[@src$='cia.info.jpg']").tooltip({
            showURL: false,
            extraClass: "accordToolTip"
        });

        // prev/next
        $jq("#nextAlloc").bind("click", function() {
            showTab("dhtmlgoodies_tabView1", 1);
        });
        $jq("#nextBench").bind("click", function() {
            showTab("dhtmlgoodies_tabView1", 2);
        });
        $jq("#prevBench").bind("click", function() {
            showTab("dhtmlgoodies_tabView1", 0);
        });
        $jq("#prevProp").bind("click", function() {
            showTab("dhtmlgoodies_tabView1", 1);
        });

        // l1 counts
        $jq("#allocPicker .level1Head").each(function(i) {
            var lev1 = this;
            $jq("#" + this.id + " + div").each(function(p) {
                var count = $jq("#" + $jq(this).get(0).id + " .level").length;
                var term;
                if (count == 1) term = "index"; else term = "indices";
                $jq("#" + lev1.id + " small").text("(" + count + " " + term + ")");
            });
        });

        // l2 counts
        $jq("#allocPicker .level2Head").each(function(i) {
            var lev2 = this;
            $jq("#" + this.id + " + div").each(function(p) {
                var count = $jq("#" + $jq(this).get(0).id + " .level").length;
                var term;
                if (count == 1) term = "index"; else term = "indices";
                $jq("#" + lev2.id + " small").text("(" + count + " " + term + ")");
            });
        });

        // l3 counts
        $jq("#allocPicker .level3Head").each(function(i) {
            var lev3 = this;
            $jq("#" + this.id + " + div").each(function(p) {
                var count = $jq("#" + $jq(this).get(0).id + " .level").length;
                var term;
                if (count == 1) term = "index"; else term = "indices";
                $jq("#" + lev3.id + " small").text("(" + count + " " + term + ")");
            });
        });

        // expand/collapse
        $jq("#expander, #expanderImg").bind("click", function() {
            if (!($jq("#expander").html().search("Expand") == -1)) {
                $jq("#allocPicker").accordion("disable");
                $jq(".accordBlockNest").accordion("disable");
                $jq("#allocPicker div[@id$='--i']").show();
                $jq("#expander").text("Collapse all");
                $jq("#expanderImg").attr("src", "/allocation-tool/images/minus.gif");
                $jq(".l1Expander, .l2Expander").css("display", "none");
            }
            else {
                $jq("#allocPicker").accordion("enable");
                $jq(".accordBlockNest").accordion("enable");
                $jq("#allocPicker div[@id$='--i']").hide();
                $jq(".accordBlockShowAll div[@id$='--i']").show();
                $jq("#expander").text("Expand all");
                $jq("#expanderImg").attr("src", "/allocation-tool/images/plus.gif");
                $jq(".l1Expander, .l2Expander").css("display", "inline");
                $jq(".l1Expander, .l2Expander").attr("src", "/allocation-tool/images/plus.gif");
            }
        });

        // show all at level3
        $jq(".accordBlockShowAll").accordion("disable");
        $jq(".accordBlockShowAll div[@id$='--i']").show();

        // masking
        $jq("#allocPicker input[@type=text],#pnlAllocAlpha input[@type=text], #txtAmount").focus(function() {
            this.value = stripToNumbers(this.value);
            this.select();
        });

        $jq("#allocPicker input[@type=text],#pnlAllocAlpha input[@type=text]").blur(function() {
            var moneyAmtType = 0
            moneyAmtType = this.id.split("--")[1]; // for $ (1 or 11) or % (2 or 12) textbox
            var part1 = this.id.split("--")[0];
            var tempId = part1.split("_");
            var indexId = tempId[tempId.length - 1]; // last one has the indexid

            var enteredNum = 0;
            enteredNum = stripToNumbers(this.value);

            if (isNaN(enteredNum)) {
                alert("Enter numbers only.");
                this.value = "0%";

                switch (moneyAmtType) {
                    case "2":
                        $jq("#" + part1 + "--1").html("$0");
                        calcSubTotals($jq(this).parent().parent(), true);
                        break;
                    case "12":
                        $jq("#" + indexId + "--11").html("$0");
                        break;
                }
                calcTotal();
                return;
            }

            enteredNum = Math.round(enteredNum);

            // calc values
            var investAmount = 0;
            investAmount = stripToNumbers($jq("#txtAmount").val());

            switch (moneyAmtType) {
                case "2":
                case "12":
                    var calc = Math.round((parseInt(enteredNum) * investAmount) / 100);
                    $jq("#allocPicker span[@id$='" + part1 + "--1']").html(formatCurrency(calc));
                    $jq("#allocPicker input[@type=text][@id$='" + part1 + "--2']").val(formatPercent(enteredNum));
                    $jq("#" + indexId + "--11").html(formatCurrency(calc));
                    $jq("#" + indexId + "--12").val(formatPercent(enteredNum));
                    break;
            }

            $jq("#allocPicker div[@id$='--i']").each(function(i) {
                calcSubTotals(this, true);
            });

            calcTotal();

            //            if(parseInt(stripToNumbers($jq("#totalPct").text())) > 100)
            //                alert("Total allocations will need to be less 100%.");
        });

        $jq("#txtAmount").blur(function() {
            if (isNaN($jq(this).val())) {
                alert("The investment amount is not valid.");
                $jq(this).val("$10,000");
                return;
            }

            var investAmt = $jq(this).val();

            // recalc
            $jq("#allocPicker input[@type=text][@id$='--2']").each(function() {
                var pct = stripToNumbers(this.value);
                var id = $jq(this).get(0).id.split("--")[0];

                if (!(pct == 0)) {
                    var calc = Math.round((parseInt(pct) * investAmt) / 100);
                    $jq("#" + id + "--1").html(formatCurrency(calc));
                }
            });
            $jq("#pnlAllocAlpha input[@type=text][@id$='--12']").each(function() {
                var pct = stripToNumbers(this.value);
                var id = $jq(this).get(0).id.split("--")[0];

                if (!(pct == 0)) {
                    var calc = Math.round((parseInt(pct) * investAmt) / 100);
                    $jq("#" + id + "--11").html(formatCurrency(calc));
                }
            });

            // calculate the allocations
            $jq("#allocPicker div[@id$='--i']").each(function(i) {
                calcSubTotals(this, true);
                calcTotal();
            });

            this.value = formatCurrency(this.value);
        });

        // resets allocations
        $jq("#btnReset").bind("click", function() {
            $jq("#txtAmount").val("$10,000");

            $jq("#allocPicker input[@type=text], #pnlAllocAlpha input[@type=text]").each(function(i) {
                $jq(this).val("0%");
            });

            $jq("#allocPicker span[@id$='--1'], #pnlAllocAlpha span[@id$='--11']").each(function(i) {
                $jq(this).html("$0");
            });

            $jq("#ddStartYear").val(0);
            $jq("#ddRebalance").val(0);

            $jq("#allocPicker div[@id$='--i']").each(function(i) {                
                calcSubTotals(this, true);
                calcTotal();
            });
        });

        $jq("#imgGoCIAHome").bind("click", function() {
            window.history.go(-2);
        });

        // ----- stuff for blended benchmarks is below this            
        $jq("#spanCustomBenchmark").css("font-weight", "bold");
        $jq("#divBlendedBlurb").css("font-size", "10px");
        $jq("#divBlendedBlurb").css("margin-left", "20px");
        $jq("#divBlendedBlurb").css("width", "200px");
        $jq("#divEditBlended").css("margin-left", "20px");
        $jq("#divEditBlended").css("color", "blue");
        $jq("#divEditBlended").css("width", "130px");

        $jq("#chkBench tr:first td").each(function(i) {
            $jq(this).css("background", "url(images/CIA.CustomBenchmarkBG.gif) no-repeat");
            $jq(this).css("height", "63px");
            $jq(this).css("vertical-align", "top");
        });

        if ($jq("#chkBench input[@type=checkbox]:first").attr("checked") == true) { // show change
            $jq("#divEditBlended").css("display", "");
            $jq("#divBlendedBlurb").css("display", "none");
        }

        $jq("#gvBlended input[@type=text]").focus(function() {
            if (this.value.length > 0)
                this.value = stripToNumbers(this.value);
        });

        $jq("#gvBlended input[@type=text]").change(function() {
            var enteredNum = 0;
            enteredNum = stripToNumbers(this.value);

            if (isNaN(enteredNum)) {
                alert("Enter numbers only");
                this.value = "0%";
                calcBlendedTotal();
                return;
            }

            this.value = formatPercent(this.value);

            calcBlendedTotal();
        });

        $jq("#chkBench input[@type=checkbox]:first").bind("click", function() {
            if ($jq(this).attr("checked"))
                showBlended();
            else
                clearBlended();
        });

        // resets benchmarks
        $jq("#btnBenchReset").bind("click", function() {
            $jq("#chkBench input[@type=checkbox]").each(function(i) {
                $jq(this).removeAttr("checked");
            });

            clearBlended();
        });

        // ----- stuff for blended benchmarks is above this

        // change view
        $jq("#ddGroupBy").bind("change", function() {
            if ($jq("#ddGroupBy").val() == "group") {
                $jq("#indexByGroup").css("display", "block");
                $jq("#indexByAlpha").css("display", "none");
            }
            else {
                $jq("#indexByGroup").css("display", "none");
                $jq("#indexByAlpha").css("display", "block");
            }
        });

        $jq(".related").bind("click", function() {
            window.open("http://claymoreinvestments.ca/etf/fund/" + $jq(this).html().toLowerCase());
        });

        // open all on load
        $jq("#allocPicker div[@id$='--i']").show();
        $jq("#expander").text("Collapse all");
        $jq("#expanderImg").attr("src", "images/minus.gif");
        $jq(".l1Expander, .l2Expander").css("display", "none");

        // calculate the allocations
        $jq("#allocPicker div[@id$='--i']").each(function(i) {
            calcLineItems();
            calcSubTotals(this, true);
            calcTotal();
        });
    });
    
    // calc total. parent will contain textboxes and the total div will be right above this element
    // parent id looks like this 'xxx--i'. "
    function calcSubTotals(parent, showZeros) {                   
        var parentId = $jq(parent).get(0).id.split("--")[0];                
        var runningPct = 0;
        var runningAmt = 0;

        $jq("#" + $jq(parent).get(0).id + " input[@type=text]").each(function(i) {
            runningPct += parseInt(stripToNumbers(this.value));
        });

        $jq("#" + $jq(parent).get(0).id + " .amount").each(function(i) {
            runningAmt += parseInt(stripToNumbers($jq(this).html()));
        });
        
        if(showZeros) {
            $jq("#" + parentId + "--t").text(formatCurrency(runningAmt));
            $jq("#" + parentId + "--p").text(formatPercent(runningPct));
        }                    
        else {
            $jq("#" + parentId + "--t").text(runningAmt == 0 ? "" : formatCurrency(runningAmt));
            $jq("#" + parentId + "--p").text(runningPct == 0 ? "" : formatPercent(runningPct));
        }
                        
        // we now need to total all the way up
        // logic: 
        // at level1 the parent name is "style--i". 
        // at level2 the parent name is "style_substyle--i". 
        // at level3 the parent name is "style_substyle_class--i". 
        var levels = parentId.split("_");
        if(levels.length == 2) { // at level 2        
            calcSubTotals($jq("#" + levels[0] + "--i"), showZeros);
        }
        else if (levels.length == 3) { // at level 3                    
            calcSubTotals($jq("#" + levels[0] + "_" + levels[1] + "--i"), showZeros);
        }                
    }
    
    function calcTotal() {            
        var runningAmt = 0;
        var runningPct = 0;
        $jq("#allocPicker > #pnlAllocPicker > a > span[@id$='--t']").each(function(i) {
            if(!($jq(this).html().length == 0))
              runningAmt += parseInt(stripToNumbers($jq(this).text()));
        });
        $jq("#allocPicker > #pnlAllocPicker > a > span[@id$='--p']").each(function(i) {                    
            if(!($jq(this).html().length == 0))                    
              runningPct += parseInt(stripToNumbers($jq(this).text()));
        });
        $jq("#totalAmt").text(formatCurrency(runningAmt));
        $jq("#totalPct").text(formatPercent(runningPct));
        $jq("#totalAmtAlpha").text(formatCurrency(runningAmt));
        $jq("#totalPctAlpha").text(formatPercent(runningPct));
    }

    function calcLineItems() {
        $jq("#allocPicker input[@type=text], #pnlAllocAlpha input[@type=text]").each(function(i){
            var part1 = this.id.split("--")[0];            
            var tempId = part1.split("_");
            var indexId = tempId[tempId.length - 1]; // last one has the indexid
            var investAmount = 0;
            investAmount = stripToNumbers($jq("#txtAmount").val());         

            var enteredNum = 0;
            enteredNum = stripToNumbers(this.value);

            var calc = Math.round((parseInt(enteredNum) * investAmount) / 100);
            $jq("#allocPicker span[@id$='" + part1 + "--1']").html(formatCurrency(calc));            
            $jq("#" + indexId + "--11").html(formatCurrency(calc));            
        });
    }
    
    function showBlended()
    {
        // populate with values (if previously saved) before opening...
        var data = $jq("#txtBlendedInfo").val();        
        var indexArray = [];
        var indexIds = [];
        var val = "";
        var id = "";
        
        if (data.length > 0)
        {
            indexArray = data.split(";");
            indexIds = $jq("#gvBlended span");
            
            for (j = 0; j < indexArray.length; j++)
            {
                if (indexArray[j].length > 0)
                {
                    var temp = indexArray[j].split(":");
                    id = temp[0];
                    val = temp[1];
                    
                    $jq("#gvBlended input[@type=text]").each(function(i) {
                        if (id == $jq(indexIds[i]).html())
                        {
                            $jq(this).val(val);
                        }
                    });
                }
            }
            calcBlendedTotal();
        }
        
        $jq('#pnlBlended').modal({persist:false, onClose:closeBlended});
        
    }
    
    function clearBlended()
    {
        $jq("#lblBlendedInfo").html("");
        $jq("#divEditBlended").css("display","none");
        $jq("#divBlendedBlurb").css("display","");
        $jq("#txtBlendedInfo").val("0");
        $jq("#blendedTotal").html("0");
        $jq("#gvBlended input[@type=text]").each(function(i) {
            $jq(this).val("");
        });
    }
    
    function calcBlendedTotal()
    {
        var total = 0;
        $jq("#gvBlended input[@type=text]").each( function() {
            if (!isNaN(stripToNumbers(this.value)))
            {
                total += parseInt(stripToNumbers(this.value));
            }
        });
        
        $jq("#blendedTotal").html(formatPercent(total));
    }
    
    function closeBlended()
    {        
        if ($jq("#blendedTotal").html().length > 0)
        {
            if ($jq("#txtBlendedInfo").val().length == 0 || $jq("#txtBlendedInfo").val() == "0")
            {
                $jq("#chkBench input[@type=checkbox]:first").removeAttr("checked");
                $jq("#divBlendedBlurb").css("display","");
            }
        }
        else
        {
            $jq("#chkBench input[@type=checkbox]:first").removeAttr("checked");
            $jq("#divBlendedBlurb").css("display","");
        }
        
        $jq.modal.close();
    }
    
    function saveBlended()
    {
        var textBoxes = [];
        var indexIds = [];
        var txt = "";
        
        if (!isNaN($jq("#blendedTotal").html())) {
            if (parseInt($jq("#blendedTotal").html()) != 100) {
                alert("Total Custom Benchmark Allocation must equal 100%");
                return;
            }
        }
        
        textBoxes = $jq("#gvBlended input[@type=text]");
        indexIds = $jq("#gvBlended span");        
                    
        for (i = 0; i < textBoxes.length; i++) {
            if (textBoxes[i].value.length > 0)                
                txt += $jq(indexIds[i]).html() + ":" + stripToNumbers(textBoxes[i].value) + ";"                
        }
        
        $jq("#txtBlendedInfo").val(txt);
        
        if (txt.length > 0)
        {
            $jq("#divEditBlended").css("display","");
            $jq("#divBlendedBlurb").css("display","none");
        }
        else
        {
            $jq("#divEditBlended").css("display","none");
            $jq("#divBlendedBlurb").css("display","");
        }
        
        $jq.modal.close();
    }
    
    function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);            
        num = Math.floor(num/100).toString();            
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
            num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + '$' + num);
    }
    
    function formatPercent(num) {
        return num + '%';
    }
    
    function stripToNumbers(stringy) {
        if(stringy.length == 0) 
            return 0;
        else {                
            var regex = /\$| |,|%/g; // all $ and ,
            var stripped = stringy.replace(regex, "");
            var num = 0;
            num = Math.round(stripped);
            return num;
        }                
    }
