﻿    function search(){
        var bRet = doesTreeHaveCheckedChildren(treeCountry, 'txtCountryCodes', true, true);
        if (!bRet){
            alert("You must select at least one country in order to produce a report.");
        }
        else{
            bRet = doesTreeHaveCheckedChildren(treeSection, 'txtSectionCodes', true, false);
            if (!bRet){
                alert("You must select at least one profile section in order to produce a report.");
            }
        }
        return bRet;
    }
    
function doesTreeHaveCheckedChildren(tree, fld, twolevels, isCountry){
    var bRet = false;
    var sCodes = "";
    var nodes = tree.getRoot().children;
    for (var x=0;x<nodes.length;x++){
        if (twolevels)
        {
            for (var y=0;y<nodes[x].children.length;y++){
                var n = nodes[x].children[y];
                if (n.checkState == 2) {
                    bRet = true;
                    if (isCountry == true)
                    {
                        sCodes += n.id.substring(3) + ",";
                    }
                    else
                    {
                        sCodes += n.id + ",";
                    }
                }
            }
        }
        else{
            var n = nodes[x];
            if (n.checkState == 2) {
                bRet = true;
                sCodes += n.label + ",";
            }
        }
    }
    document.getElementById(fld).value = sCodes;
    return bRet;
}

	var treeSection;
	var treeCountry;
	var results;
	var nodeIndex;
	var searchoptions;
	var bChanges = false;
	var bFirstLoad = true;

	function treeInit() {
        bChanges = false;
		buildTrees();
        bFirstLoad = false;
	}
    function buildTrees() {
        treeSection = new YAHOO.widget.TreeView("treeSection");
        for (var i = 0; i < sections.SectionCategories.length;i++) {
            var cat = sections.SectionCategories[i];
            
            var bExpanded = false;
            var tmpNode = new YAHOO.widget.TaskNode(cat.CategoryName, treeSection.getRoot(), bExpanded);
            for (var x=0;x<cat.Charts.length;x++){
                var o = { 
                    id: cat.Charts[x].ID, 
	                // Tooltip will use the title attribute 
	                label: cat.Charts[x].Name + "<img src=\"../../CPGraphsLARGE/Thumbs/" + cat.Charts[x].Thumbnail + "\" />",
	                thumbnail: cat.Charts[x].Thumbnail
                };            
                var tmpChild = new YAHOO.widget.TaskNode(o, tmpNode, true);
//                var tmpChild = new YAHOO.widget.TaskNode(cat.Charts[x].Name, tmpNode, true);
                tmpChild.id = cat.Charts[x].ID;
                //tmpChild.thumbnail = cat.Charts[x].Thumbnail;
            }
        }
        var nodes = treeSection.getRoot().children;
        for (var x=0;x<nodes.length;x++){
            if (nodes[x].children.length == 0)
            {
                treeSection.removeNode(nodes[x]);
            }
        }
        
        treeSection.subscribe("checkClick", function(node) {
              bChanges = true;
           });
        treeSection.draw();

        createCountryTreeView();
        
    }
    function createCountryTreeView(){   
        treeCountry = new YAHOO.widget.TreeView("treeCountries");
    
//        var allCountries = new YAHOO.widget.TaskNode("All Countries", treeCountry.getRoot(), false);
//        
        for (var x=0;x<regions.length;x++)
        {
            var toplevel;
            if (regions[x].CountryRegionType == "All Countries")
            {
                toplevel = new YAHOO.widget.TaskNode(regions[x].CountryRegionType, treeCountry.getRoot(), false);
            }
            else
            {
                toplevel = new YAHOO.widget.TextNode(regions[x].CountryRegionType, treeCountry.getRoot(), false);
            }
            toplevel.id = "l1" + x;

            for (var y=0;y<regions[x].Regions.length;y++)
            {
                var parent = toplevel;
                if (regions[x].Regions[y].RegionName != "All Countries")
                {
                    parent = new YAHOO.widget.TaskNode(regions[x].Regions[y].RegionName, toplevel, false);
                    parent.id = "l2" + x;
                }

//                for (var z=0;z<regions[x].Regions[y].Countries.length;z++)
//                {
//                    for (var i=0;i<cpcountries.Countries.length;i++)
//                    {
//                        if (cpcountries.Countries[i].ID == regions[x].Regions[y].Countries[z])
//                        {
//                            var country = new YAHOO.widget.TaskNode(cpcountries.Countries[i].Name, midlevel, true);
//                            country.id = "l3" + x + regions[x].Regions[y].Countries[z];
//                            break
//                        }
//                    }
//                }
//                //
                for (var z=0;z<regions[x].Regions[y].Countries.length;z++)
                {
                    for (var i=0;i<cpcountries.Countries.length;i++)
                    {
                        if (cpcountries.Countries[i].ID == regions[x].Regions[y].Countries[z])
                        {
                            country = new YAHOO.widget.TaskNode(cpcountries.Countries[i].Name, parent, true);
                            country.id = "l3" + x + regions[x].Regions[y].Countries[z];
                            break
                        }
                    }
                }
                //
                
            }
        }


        treeCountry.subscribe("checkClick", function(node) {
            // build up list of all checked countries within the particular high level section of the country treeview
            var x = node.id.charAt(2, 1);
            var sCountries = "";
            var nodes = treeCountry.getRoot().children;
            for (var y=0;y<nodes[x].children.length;y++){
                if (nodes[x].children[y].checked && nodes[x].children[y].id.length > 3)
                {
                    sCountries += "|" + nodes[x].children[y].id.substring(3) + "|";
                }
                for (var z=0;z<nodes[x].children[y].children.length;z++)
                {
                    var n = nodes[x].children[y].children[z];
                    if (n.checked) sCountries += "|" + n.id.substring(3) + "|";
                }
            }
            //check off all versions of a country
            var nodes = treeCountry.getRoot().children;
            for (var x=0;x<nodes.length;x++)
            {
                for (var y=0;y<nodes[x].children.length;y++){
                    if (nodes[x].children[y].id.length > 3)     // handle all countries section
                    {
                        var n = nodes[x].children[y];
                        if (!n.checked)
                        {
                            if (sCountries.indexOf("|" + n.id.substring(3) + "|") > -1) n.check();
                        }
                        else
                        {
                            if (sCountries.indexOf("|" + n.id.substring(3) + "|") == -1) n.uncheck();
                        }
                    }
                    for (var z=0;z<nodes[x].children[y].children.length;z++)
                    {
                        var n = nodes[x].children[y].children[z];
                        if (!n.checked)
                        {
                            if (sCountries.indexOf("|" + n.id.substring(3) + "|") > -1) n.check();
                        }
                        else
                        {
                            if (sCountries.indexOf("|" + n.id.substring(3) + "|") == -1) n.uncheck();
                        }
                    }
                }
            }                                

            bChanges = true;
           });
        treeCountry.draw();
    }       

	YAHOO.util.Event.onDOMReady(treeInit);




YAHOO.namespace('AL.util');
YAHOO.AL.util.JSON = new function(){
    var useHasOwn = {}.hasOwnProperty ? true : false;
    var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
    
    var pad = function(n) {
        return n < 10 ? '0' + n : n;
    };
    
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return '\\u00' +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };
    
    var encodeArray = function(o){
        var a = ['['], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case 'undefined':
                    case 'function':
                    case 'unknown':
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : YAHOO.AL.util.JSON.encode(v));
                        b = true;
                }
            }
            a.push(']');
            return a.join('');
    };
    
    var encodeDate = function(o){
        return '"' + o.getFullYear() + '-' +
                pad(o.getMonth() + 1) + '-' +
                pad(o.getDate()) + 'T' +
                pad(o.getHours()) + ':' +
                pad(o.getMinutes()) + ':' +
                pad(o.getSeconds()) + '"';
    };
    
    this.encode = function(o){
        if(typeof o == 'undefined' || o === null){
            return 'null';
        }else if(o instanceof Array){
            return encodeArray(o);
        }else if(o instanceof Date){
            return encodeDate(o);
        }else if(typeof o == 'string'){
            return encodeString(o);
        }else if(typeof o == 'number'){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == 'boolean'){
            return String(o);
        }else {
            var a = ['{'], b, i, v;
            for (var i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case 'undefined':
                    case 'function':
                    case 'unknown':
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ':',
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push('}');
            return a.join('');
        }
    };
    
    this.decode = function(json){
        try{
            if(validRE.test(json)) {
                return eval('(' + json + ')');
            }
        }catch(e){
        }
        throw new SyntaxError("parseJSON");
    };
}();


var rpc = {
    "successevent":"",
    "failuremsg":"", 
    
    handleSuccess:function(o){
        YAHOO.example.container.wait.hide();
	    successevent(o.responseText);
    },
    handleFailure:function(o){
        alert(o.responseText);
        YAHOO.example.container.wait.hide();
        alert(failuremsg);
    },
    startRequest:function(sucevnt, failmsg, url, params) {
        successevent = sucevnt;
        failuremsg = failmsg;
        showProgress();   
        YAHOO.util.Connect.asyncRequest('POST', url, callback, params);
    }
};
var callback =
{
	success:rpc.handleSuccess,
	failure:rpc.handleFailure,
	scope: rpc
};

YAHOO.namespace("example.container");
function showProgress(){
    if (!YAHOO.example.container.wait) {
        // Initialize the temporary Panel to display while waiting for external content to load
        YAHOO.example.container.wait = 
                new YAHOO.widget.Panel("wait",  
                                                { width: "260px", 
                                                  fixedcenter: true, 
                                                  close: false, 
                                                  draggable: false, 
                                                  modal: true,
                                                  visible: false
                                                } 
                                            );
        YAHOO.example.container.wait.setHeader("Narrowing search criteria, please wait...");
        YAHOO.example.container.wait.setBody("<img src=\"Reserved.ReportViewerWebControl.axd?opType=Resource&Version=8.0.50727.42&Name=Icons.SpinningWheel.gif\"/> <span style='font-size:32px;'>Searching...</span>");
        YAHOO.example.container.wait.render(document.body);
    }
    YAHOO.example.container.wait.show();
}






/**
 * The check box marks a task complete.  It is a simulated form field 
 * with three states ...
 * 0=unchecked, 1=some children checked, 2=all children checked
 * When a task is clicked, the state of the nodes and parent and children
 * are updated, and this behavior cascades.
 *
 * @extends YAHOO.widget.TextNode
 * @constructor
 * @param oData    {object}  A string or object containing the data that will
 *                           be used to render this node.
 * @param oParent  {Node}    This node's parent node
 * @param expanded {boolean} The initial expanded/collapsed state
 * @param checked  {boolean} The initial checked/unchecked state
 */
YAHOO.widget.TaskNode = function(oData, oParent, expanded, checked) {

    if (YAHOO.widget.LogWriter) {
        this.logger = new YAHOO.widget.LogWriter(this.toString());
    } else {
        this.logger = YAHOO;
    }

    if (oData) { 
        this.init(oData, oParent, expanded);
        this.setUpLabel(oData);
        this.setUpCheck(checked);
    }

};

YAHOO.extend(YAHOO.widget.TaskNode, YAHOO.widget.TextNode, {

    /**
     * True if checkstate is 1 (some children checked) or 2 (all children checked),
     * false if 0.
     * @type boolean
     */
    checked: false,

    /**
     * checkState
     * 0=unchecked, 1=some children checked, 2=all children checked
     * @type int
     */
    checkState: 0,

    taskNodeParentChange: function() {
        //this.updateParent();
    },

    setUpCheck: function(checked) {
        // if this node is checked by default, run the check code to update
        // the parent's display state
        if (checked && checked === true) {
            this.check();
        // otherwise the parent needs to be updated only if its checkstate 
        // needs to change from fully selected to partially selected
        } else if (this.parent && 2 == this.parent.checkState) {
             this.updateParent();
        }

        // set up the custom event on the tree for checkClick
        /**
         * Custom event that is fired when the check box is clicked.  The
         * custom event is defined on the tree instance, so there is a single
         * event that handles all nodes in the tree.  The node clicked is 
         * provided as an argument.  Note, your custom node implentation can
         * implement its own node specific events this way.
         *
         * @event checkClick
         * @for YAHOO.widget.TreeView
         * @param {YAHOO.widget.Node} node the node clicked
         */
        if (this.tree && !this.tree.hasEvent("checkClick")) {
            this.tree.createEvent("checkClick", this.tree);
        }

        this.subscribe("parentChange", this.taskNodeParentChange);

    },

    /**
     * The id of the check element
     * @for YAHOO.widget.TaskNode
     * @type string
     */
    getCheckElId: function() { 
        return "ygtvcheck" + this.index; 
    },

    /**
     * Returns the check box element
     * @return the check html element (img)
     */
    getCheckEl: function() { 
            return document.getElementById(this.getCheckElId()); 
    },

    /**
     * The style of the check element, derived from its current state
     * @return {string} the css style for the current check state
     */
    getCheckStyle: function() { 
        return "ygtvcheck" + this.checkState;
    },

    /**
     * Returns the link that will invoke this node's check toggle
     * @return {string} returns the link required to adjust the checkbox state
     */
    getCheckLink: function() { 
        return "YAHOO.widget.TreeView.getNode(\'" + this.tree.id + "\'," + 
            this.index + ").checkClick()";
    },

    /**
     * Invoked when the user clicks the check box
     */
    checkClick: function() { 
        this.logger.log("previous checkstate: " + this.checkState);
        if (this.checkState === 0) {
            this.check();
        } else {
            this.uncheck();
        }
        this.onCheckClick(this);
        this.tree.fireEvent("checkClick", this);
    },

    /**
     * Override to get the check click event
     */
    onCheckClick: function() { 
        this.logger.log("onCheckClick: " + this);
    },

    /**
     * Refresh the state of this node's parent, and cascade up.
     */
    updateParent: function() { 
        var p = this.parent;

        if (!p || !p.updateParent) {
            this.logger.log("Abort udpate parent: " + this.index);
            return;
        }

        var somethingChecked = false;
        var somethingNotChecked = false;

        for (var i=0;i< p.children.length;++i) {
            if (p.children[i].checked) {
                somethingChecked = true;
                // checkState will be 1 if the child node has unchecked children
                if (p.children[i].checkState == 1) {
                    somethingNotChecked = true;
                }
            } else {
                somethingNotChecked = true;
            }
        }

        if (somethingChecked) {
            p.setCheckState( (somethingNotChecked) ? 1 : 2 );
        } else {
            p.setCheckState(0);
        }

        p.updateCheckHtml();
        p.updateParent();
    },

    /**
     * If the node has been rendered, update the html to reflect the current
     * state of the node.
     */
    updateCheckHtml: function() { 
        if (this.parent && this.parent.childrenRendered) {
            this.getCheckEl().className = this.getCheckStyle();
        }
    },

    /**
     * Updates the state.  The checked property is true if the state is 1 or 2
     * 
     * @param the new check state
     */
    setCheckState: function(state) { 
        this.checkState = state;
        this.checked = (state > 0);
    },

    /**
     * Check this node
     */
    check: function() { 
        this.logger.log("check");
        this.setCheckState(2);
        for (var i=0; i<this.children.length; ++i) {
            this.children[i].check();
        }
        this.updateCheckHtml();
        this.updateParent();
    },

    /**
     * Uncheck this node
     */
    uncheck: function() { 
        this.setCheckState(0);
        for (var i=0; i<this.children.length; ++i) {
            this.children[i].uncheck();
        }
        this.updateCheckHtml();
        this.updateParent();
    },

    // Overrides YAHOO.widget.TextNode
    getNodeHtml: function() { 
        this.logger.log("Generating html");
        var sb = [];

        var getNode = 'YAHOO.widget.TreeView.getNode(\'' +
                        this.tree.id + '\',' + this.index + ')';


        sb[sb.length] = '<table border="0" cellpadding="0" cellspacing="0">';
        sb[sb.length] = '<tr>';
        
        for (var i=0;i<this.depth;++i) {
            //sb[sb.length] = '<td class="' + this.getDepthStyle(i) + '"> </td>';
            sb[sb.length] = '<td class="' + this.getDepthStyle(i) + '"><div class="ygtvspacer"></div></td>';
        }

        sb[sb.length] = '<td';
        sb[sb.length] = ' id="' + this.getToggleElId() + '"';
        sb[sb.length] = ' class="' + this.getStyle() + '"';
        if (this.hasChildren(true)) {
            sb[sb.length] = ' onmouseover="this.className=';
            sb[sb.length] = 'YAHOO.widget.TreeView.getNode(\'';
            sb[sb.length] = this.tree.id + '\',' + this.index +  ').getHoverStyle()"';
            sb[sb.length] = ' onmouseout="this.className=';
            sb[sb.length] = 'YAHOO.widget.TreeView.getNode(\'';
            sb[sb.length] = this.tree.id + '\',' + this.index +  ').getStyle()"';
        }
        sb[sb.length] = ' onclick="javascript:' + this.getToggleLink() + '"> ';
        //sb[sb.length] = '</td>';
        sb[sb.length] = '<div class="ygtvspacer"></div></td>';

        // check box
        sb[sb.length] = '<td';
        sb[sb.length] = ' id="' + this.getCheckElId() + '"';
        sb[sb.length] = ' class="' + this.getCheckStyle() + '"';
        sb[sb.length] = ' onclick="javascript:' + this.getCheckLink() + '">';
        //sb[sb.length] = ' </td>';
        sb[sb.length] = '<div class="ygtvspacer"></div></td>';
        

        sb[sb.length] = '<td>';
        sb[sb.length] = '<a';
        sb[sb.length] = ' id="' + this.labelElId + '"';
        sb[sb.length] = ' class="' + this.labelStyle + '"';
        sb[sb.length] = ' href="' + this.href + '"';
        sb[sb.length] = ' target="' + this.target + '"';
        sb[sb.length] = ' onclick="return ' + getNode + '.onLabelClick(' + getNode +')"';
        if (this.hasChildren(true)) {
            sb[sb.length] = ' onmouseover="document.getElementById(\'';
            sb[sb.length] = this.getToggleElId() + '\').className=';
            sb[sb.length] = 'YAHOO.widget.TreeView.getNode(\'';
            sb[sb.length] = this.tree.id + '\',' + this.index +  ').getHoverStyle()"';
            sb[sb.length] = ' onmouseout="document.getElementById(\'';
            sb[sb.length] = this.getToggleElId() + '\').className=';
            sb[sb.length] = 'YAHOO.widget.TreeView.getNode(\'';
            sb[sb.length] = this.tree.id + '\',' + this.index +  ').getStyle()"';
        }
        sb[sb.length] = (this.nowrap) ? ' nowrap="nowrap" ' : '';
        sb[sb.length] = ' >';
        sb[sb.length] = this.label;
        sb[sb.length] = '</a>';
        sb[sb.length] = '</td>';
        sb[sb.length] = '</tr>';
        sb[sb.length] = '</table>';

        return sb.join("");

    },

    toString: function() {
        return "TaskNode (" + this.index + ") " + this.label;
    }

});