var _wizard = null, _wizardPage = null, _wizardPageDiv = null, _selectContentDlg = null, _titleClicked,
_contentNum = null, _layout, _layoutNum, _editMode, _titleCleared, _contentSelectDiv = null;

function Content(width, heigth) {
    this.width = width;
    this.heigth = heigth;
    this.url = "";
    this.type = "";
    this.cat = "";
    this.param = "";
    this.formFactor = "M"; // M = narrow, H = wide
}

function createWizard() {

    if (_wizard == null) {
        var innerHtml = "<div id='wizardBox' class='wizardBox clearfix'><h3>Add new panel wizard</h3>" +
                    "<div id='wizardLayout' class='clearfix'>" +
                    "<div id='wizardSteps'><ul><li class='active'>Choose layout</li><li>Define content</li><li>Define panel title</li></ul></div>" +
                    "<div id='wizardContentBox'><div id='wizardHeader'></div>" +
                    "<div id='wizardContent' class='clearfix'></div>" +
                    "<div id='wizardButtonsBox' class='clearfix'>" +
                    "<a href='javascript:wizardClose();' class='wizardCancel'></a>" +
                    "<a href='javascript:wizardNext();' class='wizardNext' id='wizardNext'></a>" +
                    "<a href='javascript:wizardPrev();' class='wizardPrev' id='wizardPrev'></a>" +
                    "</div></div></div></div>";

        _wizard = new dijit.Dialog({ title: "", content: innerHtml });
        _wizard.titleBar.style.display = "none";
        _wizard.refocus = false;


        // set fixed dialog size. This doesn't work via css!
        var wizardBox = dojo.byId('wizardBox');
        wizardBox.style.width = 540 + "px";
        wizardBox.style.height = 400 + "px";

        _wizardPageDiv = new Array();
        _wizardPageDiv[0] = document.createElement("div");
        _wizardPageDiv[1] = document.createElement("div");
        _wizardPageDiv[2] = document.createElement("div");


        _wizardPageDiv[0].innerHTML = "<div class='layoutListBox'>" +
            "<a href='javascript:selectLayout(0);' ondblclick='javascript:selectLayout(0);wizardNext();' class='selected'>" +
            "<img src='images/wizard_layout1.gif' alt='Layout 1' /></a>.1</div>" +
	        "<div class='layoutListBox'>" +
	        "<a href='javascript:selectLayout(1);' ondblclick='javascript:selectLayout(1);wizardNext();'>" +
	        "<img src='images/wizard_layout2.gif' alt='Layout 2' /></a>.2</div>" +
	        "<div class='layoutListBox'>" +
	        "<a href='javascript:selectLayout(2);' ondblclick='javascript:selectLayout(2);wizardNext();'>" +
	        "<img src='images/wizard_layout3.gif' alt='Layout 3' /></a>.3</div>" +
		    "<div class='layoutListBox'>" +
		    "<a href='javascript:selectLayout(3);' ondblclick='javascript:selectLayout(3);wizardNext();'>" +
		    "<img src='images/wizard_layout4.gif' alt='Layout 4' /></a>.4</div>";

        // to be set when layout is selected
        _wizardPageDiv[1].innerHTML = "";

        _wizardPageDiv[2].innerHTML = "<input type='text' name='wizardTitle' id='wizardTitle' value='' maxlength='22' " +
            "onClick='wizardTitleClick();' onkeypress='wizardKeyPress(event);'/>";

        var wizardContent = dojo.byId('wizardContent');
        wizardContent.appendChild(_wizardPageDiv[0]);
        wizardContent.appendChild(_wizardPageDiv[1]);
        wizardContent.appendChild(_wizardPageDiv[2]);

        var innerHtml2 = "<div id='selectContentBox'><h2>Select Content</h2>" +
            "<div id='selectContentLayout' class='clearfix'>" +
            "<div id='selectContent'><div id='selectType'>" +
            "<input type='radio' name='r1' id='radio_Q' value='Q' onclick='contentTypeChanged(\"Q\", \"\", \"\");' />" +
            "<span onclick='contentTypeChanged(\"Q\", \"\", \"\");'>Market Quotes & Charts </span>" +
            "<input type='radio' name='r1' id='radio_N' value='N' onclick='contentTypeChanged(\"N\", \"\", \"\");' />" +
            "<span onclick='contentTypeChanged(\"N\", \"\", \"\");'>News </span>" +
            "<input type='radio' name='r1' id='radio_S' value='S' onclick='contentTypeChanged(\"S\", \"\", \"\");' />" +
            "<span onclick='contentTypeChanged(\"S\", \"\", \"\");'>Stock Quotes </span>" +
            "</div><div id='contentSelectDiv'></div>" +
            "<div id='selectContentButtonsBox' class='clearfix'>" +
            "<a href='javascript:selectContentCancel();' class='selectContentCancel'></a>" +
            "<a href='javascript:selectContentOK();' class='selectContentOK'></a>" +
            "</div></div></div>";

        _contentSelectDiv = new Array();
        _contentSelectDiv['Q'] = document.createElement("div");
        _contentSelectDiv['N'] = document.createElement("div");
        _contentSelectDiv['S'] = document.createElement("div");

        _contentSelectDiv['Q'].style.display = 'none';
        _contentSelectDiv['N'].style.display = 'none';
        _contentSelectDiv['S'].style.display = 'none';

        _contentSelectDiv['Q'].innerHTML = "<div><select name='selMarket' id='selMarket' onchange='javascript:selMarketChanged(\"\");' onkeypress='selContentKeyPress(event);'>" +
            "<option value='0' selected >Loading...</option>" +
            "</select>Market </div><br /><div>" +
            "<select name='selContent' id='selContent' onkeypress='selContentKeyPress(event);'>" +
            "<option value='0' selected >Loading...</option>" +
            "</select>Available Content </div>";

        _contentSelectDiv['N'].innerHTML = "<div><select name='selNewsCat' id='selNewsCat' onchange='javascript:selNewsCatChanged(\"\");' onkeypress='selContentKeyPress(event);'>" +
            "<option value='0' selected >Loading...</option>" +
            "</select>News Category </div><br /><div>" +
            "<select name='selNewsSubCat' id='selNewsSubCat' onkeypress='selContentKeyPress(event);'>" +
            "<option value='0' selected >Loading...</option>" +
            "</select>News Subcategory </div>";

        _contentSelectDiv['S'].innerHTML = "<div><input name='txtStock' id='txtStock' maxlength='24' value='' " +
            "onkeypress='selContentKeyPress(event);' />" +
            "Stock<b><sup>*</sup></b> Symbol: </div>" +
            "<br /><br /><div><b><sup>*</sup></b>US/Canadian exchanges only</div>";

        //wizardBox.appendChild(_selectContentDlg);
        _selectContentDlg = new dijit.Dialog({ title: "", content: innerHtml2 });
        _selectContentDlg.titleBar.style.display = "none";
        _selectContentDlg.refocus = false;


        var contentSelectDiv = dojo.byId('contentSelectDiv');
        contentSelectDiv.appendChild(_contentSelectDiv['Q']);
        contentSelectDiv.appendChild(_contentSelectDiv['N']);
        contentSelectDiv.appendChild(_contentSelectDiv['S']);

        // set fixed dialog size. This doesn't work via css!
        var selectContent = dojo.byId('selectContentBox');
        selectContent.style.width = 390 + "px";
        selectContent.style.height = 210 + "px";

        GetHTMLMarketList();
        GetHTMLNewsCategories();
    }
}

function contentTypeChanged(t, cat, param) {

    //if (t != 'S' && _contentSelectDiv[t].style.display == 'block') return;

    _contentSelectDiv['Q'].style.display = (t == 'Q') ? 'block' : 'none';
    _contentSelectDiv['N'].style.display = (t == 'N') ? 'block' : 'none';
    _contentSelectDiv['S'].style.display = (t == 'S') ? 'block' : 'none';

    dojo.byId('radio_' + t).checked = true;

    try {
        switch (t) {
            case 'Q':
                var selMarket = dojo.byId('selMarket');
                if (cat == "") {
                    selMarket.selectedIndex = 0;
                    selMarketChanged("");
                }
                else {
                    selMarket.value = cat;
                    selMarketChanged(param);
                }
                selMarket.focus();
                break;
            case 'N':
                var selNewsCat = dojo.byId('selNewsCat');
                if (cat == "") {
                    selNewsCat.selectedIndex = 0;
                    selNewsCatChanged("");
                } else {
                    selNewsCat.value = cat;
                    selNewsCatChanged(param);
                }
                selNewsCat.focus();
                break;
            case 'S':
                var txtStock = dojo.byId('txtStock');
                txtStock.value = param;
                txtStock.focus();
                break;
        }
    }
    catch (ex) {
    }
}

function resetSelectContent() {

    var type = _layout[_contentNum].type;
    var cat = _layout[_contentNum].cat;
    var param = _layout[_contentNum].param;

    if (type == "") type = 'Q';
    contentTypeChanged(type, cat, param);
}

function selMarketChanged(val) {

    var marketId = dojo.byId('selMarket').value;
    var formFactor = _layout[_contentNum].formFactor;

    GetHTMLContentList(marketId, formFactor, val);
}

function selNewsCatChanged(val) {
    var selNewsCat = dojo.byId('selNewsCat');

    GetHTMLNewsSubCategories(selNewsCat.value, val);

}

function selectContentOK() {

    var radio_Q = dojo.byId('radio_Q');
    var radio_N = dojo.byId('radio_N');
    var radio_S = dojo.byId('radio_S');

    if (radio_Q.checked) {
        _layout[_contentNum].type = 'Q';
        _layout[_contentNum].cat = dojo.byId('selMarket').value;
        _layout[_contentNum].param = dojo.byId('selContent').value;
    }
    else if (radio_N.checked) {
        _layout[_contentNum].type = 'N';
        _layout[_contentNum].cat = dojo.byId('selNewsCat').value;
        _layout[_contentNum].param = dojo.byId('selNewsSubCat').value;
    }
    else if (radio_S.checked) {
        var stock = safeString(dojo.byId('txtStock').value);
        if (stock == "") {
            //alert('Please enter Symbol or Part of Name');
            //return;
            stock = "0";
        }
        _layout[_contentNum].type = 'S';
        _layout[_contentNum].param = stock;
    }
    else {
        // error
        return;
    }

    // apply selected
    var t = dojo.byId('defined' + _contentNum);
    dojo.addClass(t, "set");
    t.innerHTML = "<a href='javascript:defineContent(" +
        _contentNum + ");'>Change</a>";

    if (_layoutNum != 0) {
        t.innerHTML += "<br /><a href='javascript:removeContent(" +
            _contentNum + ");' class='remove'>Remove</a>";
    }

    _selectContentDlg.hide();

    if (_layoutNum == 0) {
        wizardNext();
    }

    _wizard.show();
}

function removeContent(i) {
    _contentNum = i;
    _layout[_contentNum].type = "";
    _layout[_contentNum].param = "";

    var t = dojo.byId('defined' + _contentNum);
    dojo.removeClass(t, "set");
    t.innerHTML = "<a href='javascript:defineContent(" +
    _contentNum + ");'>Click to set content</a>";
}

function selectContentCancel() {
    _selectContentDlg.hide();

    _wizard.show();
}

function defineContent(i) {

    _contentNum = i;
    _selectContentDlg.autofocus = false;
    _selectContentDlg.startup();

    _wizard.hide();

    _selectContentDlg.show();

    resetSelectContent();
}

function resetWizard(tfid) {

    _editMode = (tfid == null) ? false : true;
    current_tfid = tfid;

    var nodes = dojo.byId('wizardSteps').childNodes[0].childNodes;
    _titleClicked = false;
    
    if (tfid == null) {
        _titleCleared = false;

        _wizardPage = 0;
        _layoutNum = 0;

        dojo.byId('wizardPrev').style.display = 'none';
        dojo.byId('wizardNext').className = 'wizardNext';

        var wizardTitle = dojo.byId('wizardTitle');
        wizardTitle.style.fontStyle = "italic";

        _wizardPageDiv[0].style.display = 'inline';
        _wizardPageDiv[1].style.display = 'none';
        _wizardPageDiv[2].style.display = 'none';

        nodes[0].className = "active";
        nodes[1].className = "";
        nodes[2].className = "";

        dojo.byId('wizardHeader').className = "wizardHeader0";

        selectLayout(0);
    }
    else {
        _titleCleared = true;
        var t = getPanel(tfid);
        var res = t.contentId.split('&');
        var z, i;
        for (i = 0; i < res.length; ++i) {
            z = res[i].split('=');

            if (z[0] == 'layout') {
                _layoutNum = parseInt(z[1]);
                prepareLayout();
            }
        }

        for (i = 0; i < res.length; ++i) {
            z = res[i].split('=');

            switch (z[0]) {
                case 'type0': _layout[0].type = z[1];
                    break;

                case 'type1': _layout[1].type = z[1];
                    break;

                case 'type2': _layout[2].type = z[1];
                    break;

                case 'cat0': _layout[0].cat = z[1];
                    break;

                case 'cat1': _layout[1].cat = z[1];
                    break;

                case 'cat2': _layout[2].cat = z[1];
                    break;

                case 'param0': _layout[0].param = z[1];
                    break;

                case 'param1': _layout[1].param = z[1];
                    break;

                case 'param2': _layout[2].param = z[1];
                    break;
            }
        }
        _wizardPage = 1;

        dojo.byId('wizardPrev').style.display = 'none';
        dojo.byId('wizardNext').className = 'wizardNext';
        var wizardTitle = dojo.byId('wizardTitle');
        wizardTitle.value = t.title;
        wizardTitle.style.fontStyle = "normal";

        _wizardPageDiv[0].style.display = 'none';
        _wizardPageDiv[1].style.display = 'inline';
        _wizardPageDiv[2].style.display = 'none';

        nodes[0].className = "";
        nodes[1].className = "active";
        nodes[2].className = "";

        //selectLayout(_layoutNum);
        for (i = 0; i < _layout.length; ++i) {
            if (_layout[i].type != "") {
                var t = dojo.byId('defined' + i);
                dojo.addClass(t, "set");
                t.innerHTML = "<a href='javascript:defineContent(" +
                    i + ");'>Change</a>";

                if (_layoutNum != 0) {
                    t.innerHTML += "<br /><a href='javascript:removeContent(" +
                        i + ");' class='remove'>Remove</a>";
                }
            }
        }

        dojo.byId('wizardHeader').className = "wizardHeader1";
    }
}

function selectLayout(index) {

    var t = dojo.query("div.layoutListBox a");

    for (var i = 0; i < t.length; ++i) {

        if (i == 3 - index) {
            t[i].className = "selected";
            _layoutNum = 3 - i;
        }
        else {
            t[i].className = "";
        }
    }
}

function wizardNext() {
    if (_selectContentDlg.open) return;

    switch (_wizardPage) {
        case 0:
            _wizardPage = 1;
            dojo.byId('wizardPrev').style.display = _editMode ? 'none' : 'inline';

            var nodes = dojo.byId('wizardSteps').childNodes[0].childNodes;
            nodes[0].className = "set";
            nodes[1].className = "active";
            _wizardPageDiv[0].style.display = 'none';
            _wizardPageDiv[1].style.display = 'inline';

            prepareLayout();

            break;
        case 1:
            var isEmpty = true;
            for (var i = 0; i < _layout.length; ++i) {
                if (_layout[i].type != "") isEmpty = false;
            }

            if (isEmpty) {
                alert('Please select content');
                return;
            }

            _wizardPage = 2;
            dojo.byId('wizardNext').className = 'wizardFinish';
            var nodes = dojo.byId('wizardSteps').childNodes[0].childNodes;
            nodes[1].className = "set";
            nodes[2].className = "active";
            _wizardPageDiv[1].style.display = 'none';
            _wizardPageDiv[2].style.display = 'inline';

            if (!_titleCleared && !_editMode) {
                var radio_Q = dojo.byId('radio_Q');
                var radio_N = dojo.byId('radio_N');
                var radio_S = dojo.byId('radio_S');
                var wizardTitle = dojo.byId('wizardTitle');
                var title;
                if (radio_Q.checked) {
                    var selMarket = dojo.byId('selMarket');
                    title = selMarket.options[selMarket.selectedIndex].innerHTML;
                }
                else if (radio_N.checked) {
                    title = "Headlines";
                }
                else if (radio_S.checked) {
                    title = "Stock";
                }

                wizardTitle.value = safeString(title);
            }
            dojo.byId('wizardPrev').style.display = 'inline';
            break;

        case 2:
            if (!_editMode) {
                wizardCreatePanel();
            }
            else {
                wizardApplyPanel();
            }
            wizardClose();
            return;
    }
    dojo.byId('wizardHeader').className = "wizardHeader" + _wizardPage;
}

function prepareLayout() {

    var val, col;
    col = _wizardPageDiv[0].getElementsByTagName('input');

    _layout = new Array();

    switch (_layoutNum) {
        case 0:
            _layout[0] = new Content(285, 293);
            _wizardPageDiv[1].innerHTML = "<div class='layoutChangeBox'><div class='layoutSmallPanel clearfix'>" +
                "<div id='defined0' class='layoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
                "<a href='javascript:defineContent(0);'>Click to set content</a>" +
                "</div></div></div>";
            break;

        case 1:
            _layout[0] = new Content(285, 293);
            _layout[1] = new Content(285, 293);
            _layout[2] = new Content(285, 293);
            _wizardPageDiv[1].innerHTML = "<div class='layoutChangeBox'><div class='layoutBigPanel clearfix'>" +
                "<div id='defined0' class='tallLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
	                "<a href='javascript:defineContent(0);'>Click to set content</a></div>" +
                "<div id='defined1' class='smallLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
	                "<a href='javascript:defineContent(1);'>Click to set content</a></div>" +
                "<div id='defined2' class='smallLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
	                "<a href='javascript:defineContent(2);'>Click to set content</a></div></div></div>";
            break;

        case 2:
            _layout[0] = new Content(285, 293);
            _layout[1] = new Content(285, 293);

            _wizardPageDiv[1].innerHTML = "<div class='layoutChangeBox'><div class='layoutBigPanel clearfix'>" +
                "<div id='defined0' class='tallLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
            	    "<a href='javascript:defineContent(0);'>Click to set content</a>" +
                "</div><div id='defined1' class='tallLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
            	    "<a href='javascript:defineContent(1);'>Click to set content</a>" +
                "</div></div></div>";
            break;

        case 3:
            _layout[0] = new Content(285 * 2, 293);
            _layout[0].formFactor = "H";

            _layout[1] = new Content(285 * 2, 293);
            _layout[1].formFactor = "H";

            _wizardPageDiv[1].innerHTML = "<div class='layoutChangeBox'><div class='layoutBigPanel clearfix'>" +
                "<div id='defined0' class='wideLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
                	"<a href='javascript:defineContent(0);'>Click to set content</a>" +
                "</div><div id='defined1' class='wideLayoutBox' onmouseover='javascript:overLayoutBox(this);'>" +
                	"<a href='javascript:defineContent(1);'>Click to set content</a>" +
                "</div></div></div>";
            break;
    }
}

function wizardPrev() {
    if (_selectContentDlg.open) return;

    switch (_wizardPage) {
        case 1:
            _wizardPage = 0;
            dojo.byId('wizardPrev').style.display = 'none';
            var nodes = dojo.byId('wizardSteps').childNodes[0].childNodes;
            nodes[0].className = "active";
            nodes[1].className = "";
            _wizardPageDiv[0].style.display = 'inline';
            _wizardPageDiv[1].style.display = 'none';
            break;

        case 2:
            _wizardPage = 1;
            dojo.byId('wizardPrev').style.display = _editMode ? 'none' : 'inline';

            dojo.byId('wizardNext').className = 'wizardNext';
            var nodes = dojo.byId('wizardSteps').childNodes[0].childNodes;
            nodes[1].className = "active";
            nodes[2].className = "";
            _wizardPageDiv[1].style.display = 'inline';
            _wizardPageDiv[2].style.display = 'none';
            break;
    }
    dojo.byId('wizardHeader').className = "wizardHeader" + _wizardPage;
}

function wizardClose() {
    if (_selectContentDlg.open) return;

    _wizard.hide();
}

function wizardCreatePanel() {

    var title, contentId, type, newpanel, layoutType;

    title = getWizardTitle(false);

    contentId = makeQueryString();

    getContentAndCreatePanel(contentId, title);
}


function wizardApplyPanel() {

    var title, contentId, type, newpanel, layoutType;

    title = getWizardTitle(false);

    contentId = makeQueryString();

    getContentAndResizePanel(contentId, current_tfid, title);
}

function overLayoutBox(obj) {
    dojo.addClass(obj, "active");
    obj.onmouseout = function() { dojo.removeClass(this, "active") }
}

function getLayoutTypeByHeight(h) {
    var cells_cnt, layoutType, browserFactor = 1.0;
    if (dojo.isIE) {
        browserFactor = 0.977;
    }
    else if (dojo.isSafari) {
        browserFactor = 0.945;
    }
    else if (dojo.isOpera) {
        browserFactor = 0.758;
    }
    else {
        // Firefox2, Google Chrome
        browserFactor = 0.99;
    }

    cells_cnt = Math.ceil((45 + parseInt(browserFactor * h)) / CH);

    if (_layoutNum == 0) {
        layoutType = cells_cnt * 2 - 1;
    }
    else {
        layoutType = cells_cnt * 2;
    }

    return layoutType;
}

function wizardTitleClick() {
    if (_titleClicked) return;
    //    if (!_titleCleared) {
    var wizardTitle = dojo.byId('wizardTitle');
    wizardTitle.select();
    _titleClicked = true;
    //        wizardTitle.style.fontStyle = "normal";
    //        _titleCleared = true;
    //    }
}

function safeString(str) {
    str = dojo.trim(str);
    str = str.replace(/</g, "&lt;"); //strip html tags
    str = str.replace(/>/g, "&gt;");
    str = str.replace(/&amp;/g, "&");
    return str;
}

// true - replace empty title with default panel title
// false - allow empty title
function getWizardTitle(replaceEmpty) {
    var title = safeString(dojo.byId('wizardTitle').value);

    if (title == "" && replaceEmpty) {
        var radio_Q = dojo.byId('radio_Q');
        var radio_N = dojo.byId('radio_N');
        var radio_S = dojo.byId('radio_S');

        if (radio_Q.checked) {
            var selMarket = dojo.byId('selMarket');
            title = selMarket.options[selMarket.selectedIndex].innerHTML;
        }
        else if (radio_N.checked) {
            title = "Headlines";
        }
        else if (radio_S.checked) {
            title = "Stock";
        }
        title = safeString(title);
    }

    return title;
}

function makeQueryString() {
    var contentId = "layout=" + _layoutNum;
    try {
        contentId += "&type0=" + _layout[0].type;
    }
    catch (err) {
    }
    try {
        contentId += "&type1=" + _layout[1].type;
    }
    catch (err) {
    }
    try {
        contentId += "&type2=" + _layout[2].type;
    }
    catch (err) {
    }
    try {
        contentId += "&cat0=" + _layout[0].cat;
    }
    catch (err) {
    }
    try {
        contentId += "&cat1=" + _layout[1].cat;
    }
    catch (err) {
    }
    try {
        contentId += "&cat2=" + _layout[2].cat;
    }
    catch (err) {
    }
    try {
        contentId += "&param0=" + _layout[0].param;
    }
    catch (err) {
    }
    try {
        contentId += "&param1=" + _layout[1].param;
    }
    catch (err) {
    }
    try {
        contentId += "&param2=" + _layout[2].param;
    }
    catch (err) {
    }

    return contentId;
}

function selContentKeyPress(e) {

    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if (code == 13) selectContentOK();
}

function wizardKeyPress(e) {

    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if (code == 13) wizardNext();
}