//element
var iconTrue = null;
var pNameTips = null;
var succTemplateStr = "";
//config
var badCharList = "★☆※♀♂‖︱︴﹏﹋﹌↑↓→←↘↙┇┅﹉﹍⊙●Ψ№㊣∑⌒≠ゃ▂∩△▽ˋˊψ﹢﹣±∫∮∝∞∧∨∏∥∠≌∽≦≧≒﹤﹥ˇ∵∴≈卐々∪∈℡§ミ灬ξζωㄨ≮≯〖〗﹃﹄┌┐└┘∟「」┗┛◆◇◣◢◥▲▼⊿◤▆▇█■▓□〓≡╝╚╔╗╬═╓╩┠┨┯┷┏┓┳";
var MAIN_GAME_TYPE_VALUE = "0";
var MAIN_GAME_TYPE_TEXT = "";
var mainTypeText = "";
var mainTypeValue = "";

/****************************** function ******************************/

function disabledForm(disable)
{
    disable = disable === true ? true : undefined;
    $(".bigBtnGroup").attributes["disabled"] = disable;
}

var StepBox = 
{
    currentStep: 1,
    prev: function(callback = function(){})
    {
		if (StepBox.currentStep == 3 && mainTypeValue != MAIN_GAME_TYPE_VALUE) 
		    StepBox.currentStep--;
		StepBox.currentStep--;
		StepBox.show(StepBox.currentStep, callback);
    },
    next: function(callback = function(){})
    {
		if (StepBox.currentStep == 1 && mainTypeValue != MAIN_GAME_TYPE_VALUE) 
		    StepBox.currentStep++;
		StepBox.currentStep++;
		StepBox.show(StepBox.currentStep, callback);
    },
    show: function(stepNum, callback = function(){})
    {
        if (stepNum < 1)
            stepNum = 1;
		else if (stepNum > 4)
            stepNum = 4;
		StepBox.currentStep = stepNum;
		
		$$(".step").filter(function(obj)
        {
            obj.style["display"] = "none";
        });
        
        var elem = self.select("#step" + stepNum);
        if (elem) 
            elem.style["display"] = "block";
        
        if (typeof(callback) == "function") 
            callback();
    }
};

var MainType = 
{
    init: function(listData)
    {
        var html = "";
        for (var i = 0; i < listData.length; i++) 
        {
            html += "<li><input class='btn' onclick='MainType.setData(\"" + listData[i]["type"] + "\", " + listData[i]["id"] + ")' type='button' value='" + listData[i]["type"] + "' /></li>";
            if (listData[i]["id"] == MAIN_GAME_TYPE_VALUE) 
                MAIN_GAME_TYPE_TEXT = listData[i]["type"];
        }
        
        $(".bigBtnGroup ul").html = html;
    },
    setData: function(text, value)
    {
        mainTypeValue = value;
        mainTypeText = text;
		StepBox.next(mainGameObj.showText);
    }
};

var GameTab = 
{
    init: function(listData)
    {
        var tempArr = [];
        for (var i = 0; i < listData.length; i++) 
        {
            if (listData[i]["element"].length) 
                tempArr = tempArr.concat(listData[i]["element"]);
        }
        listData = tempArr;
        
        var html = "";
        var htmlHot = "";
        var htmlOther = "";
        for (var i = 0; i < listData.length; i++) 
        {
            var obj = listData[i];
            
            if (obj["create"] != 0) 
            {
                var style = obj["style"] ? " style='" + obj["style"] + "' " : "";
				var imgTag = obj["logo"] ? "<img src='" + obj["logo"] + "' />" : "";
                if (obj["hot"] == 1) 
					htmlHot += "<a onclick='mainGameObj.add(\"" + obj["id"] + "\", \"" + obj["name"] + "\")' href='#' value='" + obj["id"] + "' title='" + obj["name"] + "'" + style + ">" + imgTag + obj["name"] + "</a>";
				else 
					htmlOther += "<a onclick='mainGameObj.add(\"" + obj["id"] + "\", \"" + obj["name"] + "\")' href='#' value='" + obj["id"] + "' title='" + obj["name"] + "'" + style + ">" + imgTag + obj["name"] + "</a>";
            }
        }
        html += "<div class='gameListItem'>" + htmlHot + "</div>";
        html += "<div class='gameListItem'>" + htmlOther + "</div>";
        $("div.tabContent").html = html;
        
        GameTab.change(0);
    },
    change: function(index)
    {
        var tabList = $$(".tab a");
        var contentList = $$(".tabContent > div");
        
        for (var i = 0; i < tabList.length; i++) 
        {
            if (i == index) 
            {
                tabList[i].attributes.addClass("current");
                contentList[i].style["display"] = "block";
            }
            else 
            {
                tabList[i].attributes.removeClass("current");
                contentList[i].style["display"] = "none";
            }
        }
    }
};

class MainGame
{
	var _data = [];
    var maxSize = 4;
    
    function this()
    {
        this._data = [];
		this.onUpdate([]);
    }
    
    function init(data)
    {
        $("#btnStep2Prev").style["display"] = "none";
		$("#btnStep2Next").style["display"] = "none";
		$("#btnEditSave").style["visibility"] = "visible";
		StepBox.show(2);
		
		this._data = data;
        this.onUpdate(this._data);
    }
    
    function add(gameId, gameName)
    {
        var obj = 
        {
            "id": gameId,
            "name": gameName
        };
        if (this._data.length < this.maxSize && this._indexOf(obj["id"]) == -1) 
        {
            this._data.push(obj);
            this.onUpdate(this._data);
        }
    }
    
    function remove(gameId)
    {
        if (this._indexOf(gameId) != -1) 
        {
            this._removeData(gameId);
            this.onUpdate(this._data);
        }
    }
    
    function getData()
    {
        return this._data;
    }
    
    function onUpdate(dataList)
    {
		var html = "";
        for (var i = 0; i < this.maxSize; i++) 
        {
            if (i < dataList.length) 
                html += "<li><span>" + dataList[i]["name"] + "</span><a href='#' onclick='mainGameObj.remove(\"" + dataList[i]["id"] + "\")'></a></li>";
            else 
                html += "<li class='empty'></li>";
        }
        $("ul.selectedMainGame").html = html;
		
		var nextBtnDisableState = this._data.length <= 0 ? true : undefined;
		$("#btnStep2Next").state.disabled = nextBtnDisableState;
		$("#btnEditSave").state.disabled = nextBtnDisableState;
    }
    
	function showText()
    {
        $("ul.form li:first-child span").text = mainTypeText;
		var gameListBox = $("ul.form li:nth-child(2) p");
		if (mainTypeValue == MAIN_GAME_TYPE_VALUE)
		{
			var html = "";
			for (var i = 0; i < mainGameObj._data.length; i++)
				html += "<span>" + mainGameObj._data[i]["name"] + "</span>";
			gameListBox.html = html;
		}
		else
		{
			gameListBox.clear();
		}
    }
	
	function getParam(inEdit = false)
    {
        var arr = [];
		!inEdit && arr.push(mainTypeValue);
		for (var i = 0; i < this._data.length; i++)
		    arr.push(this._data[i]["id"]);
		return arr.join(",");
    }
	
	function save()
	{
		setEditBtnState(0);
		view.saveEdit(this.getParam(true));
	}
	
    function _indexOf(gameId)
    {
        for (var i = 0; i < this._data.length; i++) 
        {
            if (this._data[i]["id"] == gameId) 
                return i;
        }
        return -1;
    }
    
    function _removeData(gameId)
    {
        var index = this._indexOf(gameId);
        if (index != -1) 
        {
            var part1 = this._data.slice(0, index);
            var part2 = this._data.slice(index);
            part2.shift();
            this._data = part1.concat(part2);
        }
    }
}

function setEditBtnState(stateCode)
{
	var disable = stateCode == 1 ? undefined : true;
	$("#btnEditSave").state.disabled = disable;
}

/****************************** form checker ******************************/

var error_tips = 
{
    blank: lang["cTipBlank"],
    space: lang["cTipSpace"],
    less_char: lang["cTipLessChar"],
    more_char: lang["cTipMoreChar"],
    not_exist: lang["cTipNotExist"],
    error_char: lang["cTipErrorChar"],
    slogan_more_char: lang["cTipSloganMoreChar"]
};

var nameAjaxChecker = new AjaxChecker("inpName");
nameAjaxChecker.checkStart = function(elem)
{
    pNameTips.style["color"] = "#666";
    pNameTips.text = lang["cCheckingName"];
    view.checkName(elem.value);
};
nameAjaxChecker.checkEnd = function(data)
{
    this.checkEndSuper(data);
    
    if (data == "1") 
    {
        iconTrue.style["visibility"] = "visible";
        pNameTips.html = "&nbsp;";
    }
    else 
    {
        iconTrue.style["visibility"] = "hidden";
        pNameTips.style["color"] = "red";
        if (data == "0") 
            pNameTips.html = error_tips.not_exist;
        else 
            pNameTips.html = data;
    }
};

var nameChecker = new FormChecker("inpName", "pNameTips", ["keyup"]);
nameChecker.addCheckerFun(function(obj)
{
    var strName = obj.input.value;
    
    iconTrue.style["visibility"] = "hidden";
    obj.span.style["color"] = "red";
    
    if (strName == "") 
    {
        obj.span.text = error_tips.blank;
        return false;
    }
    if (/^\s+|\s+$/.test(strName)) 
    {
        obj.span.text = error_tips.space;
        return false;
    }
    if (getByteLen(strName) < 6) 
    {
        obj.span.text = error_tips.less_char;
        return false;
    }
    if (getByteLen(strName) > 30) 
    {
        obj.span.text = error_tips.more_char;
        return false;
    }
    for (var i = 0; i < strName.length; i++) 
    {
        if (badCharList.indexOf(strName.fromCharCode(strName[i])) != -1) 
        {
            obj.span.text = error_tips.error_char;
            return false;
        }
    }
    
    nameAjaxChecker.check();
    
    return true;
});

var descChecker = new FormChecker("inpSlogan", "pSloganTips", ["keyup"]);
descChecker.addCheckerFun(function(obj)
{
    if (getByteLen(obj.input.value) > 30) 
    {
        obj.span.style["color"] = "red";
        obj.span.text = error_tips.slogan_more_char;
        return false;
    }
    obj.span.html = "&nbsp;";
    return true;
});

/****************************** for c++ callback ******************************/

//for c++
function initTypeList(listData)
{
    MainType.init(listData);
    GameTab.init(listData);
}

//for c++
function getServerCountCallback(data)
{
    var createTotal = data["createTotal"];
    var createdCount = data["createdCount"];
    
    if (createdCount >= createTotal) 
    {
        $("#divCountTips").html = strFormat(lang["cNotCanCreate"], createTotal);
        disabledForm(true);
    }
    else 
    {
        $("#divCountTips").html = strFormat(lang["cCanCreate"], createTotal - createdCount);
        disabledForm(false);
    }
}

//for c++
function checkNameCallback(data)
{
    nameAjaxChecker.checkEnd(data);
}

//for c++
function startCreateCallback(sid)
{
    var templateData = 
    {
        sname: $("#inpName").value,
        smaintype: mainTypeText,
        sid: sid
    };
    $("#step4").html = templateReplace(succTemplateStr, templateData);
	StepBox.show(4);
}

//for c++
function createErrorCallback()
{
    $("#btnCreate").state.disabled = undefined;
}

/****************************** element event handle ******************************/

function startCreate()
{
	if (descChecker.check() && nameChecker.check() && nameAjaxChecker.result() == "1") 
    {
        var typeValue = mainGameObj.getParam(); //the first item is main type value
        view.startCreate($("#inpName").value, typeValue, $("#inpSlogan").value);print(typeValue);
        $("#btnCreate").state.disabled = true;
        $("#creating").style["visibility"] = "visible";
    }
}

//view.onCloseWindow()

/****************************** init ******************************/

var mainGameObj = null;
self.ready = function()
{
	iconTrue = $("#iconTrue");
    pNameTips = $("#pNameTips");
	succTemplateStr = $("#step4").html;
    disabledForm(true);
	StepBox.show(1);
	mainGameObj = new MainGame();
    
    view.onLoadhtmlComplete();
    view.getServerCount();

    //mainGameObj.init([{"id":"10015","name":"fdfdf"}]);
};

function mainGameObjinit(d)
{
    mainGameObj.init(d);
};
