(function(window, document){
    "use strict";
    /**
     * @brief 默认主程入口，在这里将重新加载所必要的lib
     */
    var $ = function(id){
        var board;
        if(undefined === id || "string" !== typeof(id)){
            throw "ID(" + id + ") is invalid, plz choose one correctly.";
            return false;
        }

        function setup(div){
            var splash = document.createElement("div");
            splash.innerHTML = "努力载入中";
            splash.style.lineHeight = div.clientHeight + "px";
            splash.style.textAlign = "center";

            div.appendChild(splash);
        }
        board = document.getElementById(id);
        setup(board);

        var libs = {
            jquery: "http://code.jquery.com/jquery-1.11.0.min.js"
        };
        var themes = {
            "default": "default.css",
            "green": "green.css"
        };

        /** 公共方法 */
        var Dom = function(){};

        Dom.prototype.create = function (ele, cls){
            var div =  document.createElement(ele);
            if(cls){
                div.className = cls;
            }
            return div;
        };

        Dom.prototype.createButton = function(text, className, eventName, event){
            className = className || "";
            var button = this.create("button");
            button.innerHTML = text;
            button.className = "happybutton " + className;
            if(eventName){
                button.addEventListener(eventName, event);
            }
            return button;
        };

        Dom.prototype.createRadiusBall = function(color, min, max){
            var MIN = min || 1;
            var MAX = max || 33;
            var CLS = "happyball";
            if(undefined !== color){
                CLS += " " + color;
            }

            var self = this;
            var ball = self.create("input");
            ball.type = "text";
            ball.className = CLS;
            ball.value = self.rangeFixed(MIN, MAX);
            ball.setAttribute("request", "true");

            ball.addEventListener("mouseup", function(e){
                ball.select();
                e.preventDefault();
            });

            ball.addEventListener("keydown", function(e){
                var keyCode = e.keyCode;

                if((57 < keyCode || 48 > keyCode) && 8 !== keyCode){
                    e.preventDefault();
                }
            });
            ball.addEventListener("change", function(e){
                var input = e.target;
                var value = input.value;
                value = value ? parseInt(value) : 1;
                if(MIN > value || NaN === value){
                    value = MIN;
                }
                else if(MAX < value){
                    value = MAX;
                }
                input.value = self.setFixed(value);
            });

            return ball;
        };

        Dom.prototype.createNumberSel = function(defaultText, min, max){
            min = min || 0;
            var sel = this.create("div");
            sel.className = "number-sel";
            sel.value = defaultText || 0;

            var lController = this.create("span");
            lController.innerHTML = "-";
            lController.className = "pre-control";

            var input = this.create("input");
            input.type = "text";
            input.className = "sel-input";
            input.placeholder = sel.value;
            input.value = sel.value;

            var rController = this.create("span");
            rController.innerHTML = "+";
            rController.className = "next-control";

            sel.appendChild(lController);
            sel.appendChild(input);
            sel.appendChild(rController);

            lController.addEventListener("click", function(){
                --sel.value;
                if(undefined !== min && sel.value <= min){
                    sel.value = min;
                }

                input.value = sel.value;
            });

            rController.addEventListener("click", function(){
                ++sel.value;
                if(undefined !== max && max <= sel.value){
                    sel.value = max;
                }
                input.value = sel.value;
            });

            return sel;
        };

        Dom.prototype.createBonus = function(){
            var TOTAL = "2亿123万";
            var AMOUNT = 63;
            var MAX_MONEY = "50000000万"

            var bonus = this.create("div");
            bonus.innerHTML = TOTAL +
                "万滚存，预计可以开出" +
                "<span class='striking'>"+
                AMOUNT + "注" + MAX_MONEY +
                "</span>大奖";
            return bonus;
        };

        Dom.prototype.get = function(id){
            return document.getElementById(id);
        };

        Dom.prototype.rangeFixed = function(min, max, fixed){
            fixed = fixed || 2;
            var result = String(Math.floor(Math.random() * (max - min)) + min);

            return this.setFixed(result, fixed);
        };

        Dom.prototype.setFixed = function(number, fixed){
            fixed = fixed || 2;
            var string = String(number);
            var length = fixed - string.length;
            while(0 < length){
                --length;
                string = "0" + string;
            }

            return string;
        }

        var dom = new Dom();
        /** 公共方法定义结束 */

        var BKC = {
            init: function(){
                var head = document.getElementsByTagName("head")[0];
                var style = dom.create("link");
                style.media = "all";
                style.rel = "stylesheet";
                style.href = "http://127.0.0.1:8080/jczg/numberLottery/themes/" + themes[this.theme];
                head.appendChild(style);

                board.innerHTML = "";
                board.style.fontSize = "14px";
                if(1 < this.collections.length){
                    board.appendChild(this.tabbar);
                    this.setTab(this.tab);
                }
                board.appendChild(this.body);
            },
            
            /** 入口 */
            create: function(options){
                var options = options || {};
                this.theme = options.theme || "default";
                this.tab = options.tab || 0;
                if(0 > this.tab){
                    this.tab = 1;
                }

                this.collections = [];
                var index = 0;
                while(arguments[++index]){
                    var options = arguments[index];
                    // options = options || {};
                    options.text = options.text || "确认提交";
                    options.afterSubmit = options.afterSubmit || function(){};
                    options.bkc = this;
                    this.collections.push(options);
                }

                this.tabar = {};
                if(1 < this.collections.length){
                    this.tabbar = this.createTabbar(this.collections);
                }
                if(this.tab >= this.collections.length){
                    this.tab = this.collections.length - 1;
                }

                var dispatch = {};
                dispatch["ssq"] = this.createSSQ;
                dispatch["dlt"] = this.createDLT;
                this.pages = [];
                this.body = dom.create("div");
                this.body.className = "bkc-body";
                for(var index in this.collections){
                    var ele = this.collections[index];
                    ele.bkc = {};
                    ele.bkc.submit = this.submit;
                    ele.bkc.tab = this.tab;
                    ele.bkc.options = ele;
                    ele.bkc.reallySubmit = this.reallySubmit;
                    var page = dispatch[ele.type](ele);
                    this.pages.push(page);
                    this.body.appendChild(page);
                }
                this.init();
            },

            createTabbar: function(collections){
                var self = this;
                var dict = {};
                dict["ssq"] = "双色球";
                dict["dlt"] = "大乐透";
                var tabbar = dom.create("nav");

                for(var index in collections){
                    var tab = dom.create("span");
                    tab.className = "item";
                    tab.innerHTML = collections[index].title || dict[collections[index].type];
                    tab.addEventListener("click", function(){
                        var index = Array.prototype.indexOf.call(this.parentNode.children, this);
                        self.setTab(index);
                    });
                    tabbar.appendChild(tab);
                }
                tabbar.className = "bkc-nav";
                return tabbar;
            },

            setTab: function(index){
                var length = this.collections.length;
                for(var i = 0; i < length; ++i){
                    this.pages[i].style.display = "none";
                    this.tabbar.children[i].className = "item";
                }

                this.pages[index].style.display = "block";
                this.tabbar.children[index].className = "item cur";
            },

            createSSQ: function(options){
                var self = options.bkc;
                var ssq = dom.create("div");
                ssq.innerHTML = "创建了一个双色球" +
                    "<br>";

                var row1 = dom.create("div", "row");
                // 前区球
                var foreBalls = [];
                for(var i = 0; i < 6; ++i){
                    var ball = dom.createRadiusBall();
                    foreBalls.push(ball);
                    row1.appendChild(ball);
                }

                // 后区球
                var backBalls = [];
                for(var i = 0; i < 1; ++i){
                    var ball = dom.createRadiusBall("blue", 1, 16);
                    backBalls.push(ball);
                    row1.appendChild(ball);
                }
                row1.appendChild(ball);

                // 机选
                var randomButton = dom.createButton("机选", "", "click", function(){
                    for(var i in foreBalls){
                        var ball = foreBalls[i];
                        var r = dom.rangeFixed(1, 33);
                        ball.value = r;
                    }

                    for(var i in backBalls){
                        var ball = backBalls[i];
                        var r = dom.rangeFixed(1, 16);
                        ball.value = r;
                    }
                });
                row1.appendChild(randomButton);

                // 提交
                var submitButton = dom.createButton("选择投注", "submit", "click", function(){
                    var data = {};
                    data.fore = [];
                    for(var i in foreBalls){
                        var v = foreBalls[i].value;
                        data.fore.push(v);
                    }
                    data.back = [];
                    for(var i in backBalls){
                        var v = backBalls[i].value;
                        data.back.push(v);
                    }
                    data.ratio = numberSel.value;

                    if(options.beforeSubmit){
                        self.data = data;
                        options.beforeSubmit(self);
                    }
                    else{
                        self.reallySubmit(options.url, options.method, data, options.afterSubmit);
                    }
                });
                row1.appendChild(submitButton);

                var row2 = dom.create("div", "row");
                var numberSel = dom.createNumberSel(1, 0);
                row2.appendChild(numberSel);

                var banner = dom.createBonus();
                row2.appendChild(banner);

                ssq.appendChild(row1);
                ssq.appendChild(row2);
                return ssq;
            },

            createDLT: function(options){
                var self = options.bkc;
                var dlt = dom.create("div");

                dlt.style.display = "none";
                dlt.innerHTML = "" +
                    "创建了一个大乐透" +
                    "<input type='text' name='dlt' request='true'>";

                var submit = dom.createButton(options.text, "click", function(){
                    if(options.beforeSubmit){
                        options.beforeSubmit(self);
                    }
                    else{
                        var data = self.queryData(dlt);
                        self.reallySubmit(options.url, options.method, data, options.afterSubmit);
                    }
                });
                dlt.appendChild(submit);
                return dlt;
            },

            queryData: function(div){
                var data = {};
                var list = div.querySelectorAll("*[request='true']");
                var length = list.length;
                for(var i = 0; i < length; ++i){
                    var item = list[i];
                    data[item.getAttribute("name")] = item.value;
                }
                return data;
            },

            submit: function(data){
                var self = this;
                var options = self.options;
                if(undefined === data){
                    data = self.data;
                }
                self.reallySubmit(options.url, options.method, data, options.afterSubmit);
            },

            reallySubmit: function(url, type, data, callback){
                var self = this;
                type = type || "get";
                data = data || {};
                self.httpRequest = new XMLHttpRequest;
                self.httpRequest.onreadystatechange = function(){
                    if(4 === self.httpRequest.readyState){
                        if(200 === self.httpRequest.status){
                            callback(self.httpRequest.responseText);
                        }
                    }
                };
                type = type.toUpperCase();
                var params = "";
                for(var a in data){
                    params +=  "&" + a + "=" + encodeURIComponent(data[a]);
                }
                if("GET" === type){
                    if(0 === params.length){
                        params = "";
                    }
                    else{
                        params = "&" + params.substr(1);
                    }
                    self.httpRequest.open("GET", url + params, true);
                    self.httpRequest.send();
                }
                else if("POST" === type){
                    if(0 === params.length){
                        params = "";
                    }
                    else{
                        params = params.substr(1);
                    }
                    self.httpRequest.open("POST", url);
                    self.httpRequest.setRequestHeader("content-Type", "application/x-www-form-urlencoded");
                    self.httpRequest.send(params);
                }
                else{
                    throw "Unknown Requst Type(" + type + ")";
                }
            }
        };

        return BKC;
    };

    window._ = $;
})(window, document);
