/*
 * Main Entry
 */
(function(){
    google.setOnLoadCallback(function(){
        app = new map2fun.control.AppManager();
        app.preload(function(){
            app.map = new google.maps.Map2($("#mapCanvas")[0]);
            app.map.setCenter(app.accountManager.clientGeo.clientLatLng, 11);
            app.map.addControl(new google.maps.SmallMapControl());
            app.dataControl = new map2fun.data.DataControl();
			app.addComponent(new map2fun.control.ui.LocationSelect("location"));
            app.addComponent(new map2fun.control.ui.Lightbox("lightbox"));
            app.addComponent(new map2fun.control.ui.MainView("mainView")).setActivity("roam");
            
            app.accountManager.autoLogin();
        });
        
        app.ui.mainView.swap = function(e){
            var act;
            if (!e) {
                act = "roam";
            }
            else 
                if (typeof e == "string") {
                    act = e;
                }
                else {
                    act = e.target.name;
                }
			
			if ((act == "shareNode" || act == "sharePath") && app.accountManager.status == map2fun.USER_OFF) {
                var con = $("<div class='notLogin lightbox' />");
                var title = $("<h3>您还没登陆</h3>");
                var msg = $("<p>登陆之后才能继续操作，请</a>").append($("<a />", {
                    className: "action",
                    click: function(){
                        $("a.userRegister").click();
                    },
                    text: "注册"
                })).append(" 或 ").append($("<a />", {
                    className: "action",
                    click: function(){
                        $("a.userLogin").click();
                    },
                    text: "登陆"
                }));
                con.append(title).append(msg);
                app.show(con[0]);
				return;
            }
			
            app.ui.mainView.setActivity(act);
            
            var links = $("#mapAction a");
            links.removeClass("current");
            
            $(".dynamic").hide();
            $(".recyclable").empty();
            $(".once").remove();
            
            $(".mapWrapper").css("height", "270px").show();
            $("#mapInfo .indicator").text("当前没有可用地图信息！");
            
            $(window).unbind("scroll");
            
            switch (act) {
                case "roam":
                    $("a.roam").addClass("current");
                    $("#recommendation").show();
                    $(".mapWrapper").css("height", "560px");
                    break;
                case "findNode":
                    $("a.findNode").addClass("current");
                    $("#searchOptions, #selectType, #unitResults").show();
                    break;
                case "findPath":
                    $("a.findPath").addClass("current");
                    $("#searchOptions, #pathResults").show();
                    $(window).scroll(function(){
                        var act = app.ui.mainView.activity;
                        if (act == "findPath") {
                            if ($(this).scrollTop() > 540) {
                                $(".mapWrapper").css({
                                    top: $(this).scrollTop() - 252 + "px",
                                    left: "0px"
                                });
                            }
                            else {
                                $(".mapWrapper").css({
                                    top: "0px",
                                    left: "0px"
                                });
                            }
                        }
                    });
                    break;
                case "shareNode":
                    links.removeClass("current");
                    $("a.shareNode").addClass("current");
                    $("#steps").empty().html("<ol id='share-node-steps' class='stepList'><li class='current'>定位这个场所的地址</li><li>描述场所详情</li><li>完成</li></ol>");
                    $("#searchOptions, #steps, #mapInfo").show();
                    $(".mapWrapper").css("height", "560px");
                    break;
                case "sharePath":
                    $("#steps").empty().html("<ol id='share-path-steps' class='stepList'><li class='current'>选定路线上的场所</li><li>描述这条路线</li><li>完成</li></ol>");
                    $("#unitBusket, #searchOptions, #selectType, #unitResults, #steps").show();
                    $("a.sharePath").addClass("current");
                    break;
                    
            };
            $("input#desc").val("地点关键词");
            app.map.clearOverlays();
            app.map.checkResize();
            app.map.setCenter(app.accountManager.clientLatLng, 11);
        };
        
        app.ui.mainView.init(function(){
            var lightbox = app.ui.lightbox, dataControl = app.dataControl, mainView = app.ui.mainView;
            
            $(document).bind("reveal.facebox", function(e){
                $("#facebox .content [title]").bubble();
            });
            
            $("#mapAction a").click(mainView.swap);
            mainView.buttons.register = $("a.userRegister").click(function(e){
                lightbox.open(mainView.views.register);
                
            });
            
            mainView.buttons.login = $("a.userLogin").click(function(){
                lightbox.open(mainView.views.login);
            });
            
            mainView.buttons.logout = $("a.userLogout").click(function(){
                app.accountManager.logout();
            });
            
            mainView.buttons.submitBusket = $("a#submitBusket").click(function(){
                dataControl.submitUnits();
                
            });
            
            mainView.buttons.resetBusket = $("a#resetBusket").click(function(){
                dataControl.resetUnits();
            });
            
            
            $("body").click(function(event){//buttons inside lightbox
                var field = $(event.target).parents(".lightbox").find("form");
                switch (event.target.name) {
                    case "register":
                        if (dataControl.validate(field)) {
                            app.accountManager.register({
                                "email": field.find("input[name='email']").val(),
                                "userName": field.find("input[name='userName']").val(),
                                "password": map2fun.utils.hex_md5(field.find("input[name='password']").val()),
                                "verifyCode": field.find("input[name='verifyCode']").val()
                            });
                        }
                        break;
                    case "login":
                        if (dataControl.validate(field)) {
                            app.accountManager.login({
                                "userName": field.find("input[name='userName']").val(),
                                "password": map2fun.utils.hex_md5(field.find("input[name='password']").val()),
                                "rememberMe": field.find("input[name='rememberMe']")[0].checked
                            });
                        }
                        break;
                    case "verifyCode":
                        event.target.src = map2fun.VERIFY_CODE_PATH + "?rd=" + Math.random();
                        break;
                    case "submitUnit":
                        if (dataControl.validate(field)) {
                            dataControl.addUnit({
                                nodeId: field.find("span.nodeId")[0].innerHTML,
                                title: field.find("input[name='unitName']").val(),
                                desc: field.find("textarea[name='unitDesc']").val(),
                                type: field.find("select[name='type']")[0].options[field.find("select[name='type']")[0].selectedIndex].value,
                                cost: field.find("input[name='cost']").val(),
                                score: field.find("select[name='score']")[0].options[field.find("select[name='score']")[0].selectedIndex].value
                            });
                            
                        }
                        break;
                    case "submitPath":
                        if (dataControl.validate(field)) {
                            dataControl.addPath({
                                name: field.find("input[name='pathName']").val(),
                                desc: field.find("textarea[name='pathDesc']").val(),
                                score: field.find("select[name='score']")[0].options[field.find("select[name='score']")[0].selectedIndex].value
                            });
                        }
                        break;
                };
            });
            
            //creating views
            mainView.views.login = new map2fun.control.ui.View("User Login", "html", 340, 300, ".loginWin");
            mainView.views.register = new map2fun.control.ui.View("User Registeration", "html", 600, 450, ".registerWin");
            mainView.views.addUnit = new map2fun.control.ui.View("AddUnit", "html", 620, 600, ".unitDetail");
            mainView.views.addPath = new map2fun.control.ui.View("AddPath", "html", 620, 600, ".pathDetail");
            mainView.views.addUnitResp = new map2fun.control.ui.View("AddUnitResponse", "html", 600, 600, ".addUnitResp");
            mainView.views.addPathResp = new map2fun.control.ui.View("AddPathResponse", "html", 600, 600, ".addPathResp");
        });
        
    });
}());
