/**
 *
 * @package map2fun.control.ui
 * @class Node
 */
map2fun.control.ui.Node = function(node, name, type){
    // province and city data may not exsit, so just use data of the address selectors
    
    //this.province = node.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
    //this.city = node.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
    
    this.province = app.ui.location.get().province;
    this.city = app.ui.location.get().city;
    
    var _a1, _a2, _a3, _a4, _a;
    try {
        _a1 = node.AddressDetails.Country.AdministrativeArea.Locality.AddressLine[0];
    } 
    catch (e) {
        _a1 = "";
    }
    try {
        _a2 = node.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.AddressLine[0]
    } 
    catch (e) {
        _a2 = "";
    }
    try {
        _a3 = node.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName;
    } 
    catch (e) {
        _a3 = "";
    }
    try {
        _a4 = node.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
    } 
    catch (e) {
        _a4 = "";
    }
    
    this.title = _a1 + _a2 + _a3 || name;
    
    this.address = node.address;
    
    this.minZoom = node.minZoom;
    this.maxZoom = node.maxZoom;
    
    this.lat = node.Point.coordinates[1];
    this.lng = node.Point.coordinates[0];
    
    this.id = map2fun.utils.encode([{
        Latitude: this.lat,
        Longitude: this.lng
    }]);
    
    this._marker = null;
};

map2fun.control.ui.Node.prototype.getMarker = function(){
    if (this._marker) {
        return this._marker;
    }
    
    var icon = map2fun.control.ui.Node.yellowicon;
    var latlng = new GLatLng(this.lat, this.lng);
    var marker = new GMarker(latlng);
    
    GEvent.bind(marker, "click", this, function(){
        marker.openInfoWindow(this.getContent());
    });
    
    this._marker = marker;
    
    return marker;
};

map2fun.control.ui.Node.prototype.getBrief = function(){//content for sidebar
    var _class = this;
    
    var address = $("<span class='desc'></span>").text(this.address);
    var title = $("<a href='#' class='action title'>" + this.title + "</a>").click(function(){
        app.map.panTo(new google.maps.LatLng(_class.lat, _class.lng));
        GEvent.trigger(_class.getMarker(), "click");
    });
    var item = $("<li></li>").append(title).append(title).append(address);
    
    return item;
};

map2fun.control.ui.Node.prototype.getContent = function(){//content for popup
    var _class = this;
    var title = $("<span class='nodeTitle'>" + this.title + "</span>");
    var address = $("<span class='nodeAddress'>" + this.address + "</span>");
    
    var content = $("<div class='resultContent'></div>");
    var confirm = $("<a class='action resultConfirm' href='#'>选择此地址</a>").click(function(){
        $.getJSON(map2fun.ADD_NODE_PATH, {
            id: _class.id,
            lat: _class.lat,
            lng: _class.lng,
            province: _class.province,
            city: _class.city,
            address: _class.address
        }, function(data){
            if (data.result.status == 1) {
                app.ui.lightbox.open(app.ui.mainView.views.addUnit);
                $("span.nodeId").text(_class.id);
            }
        });
        
    });
    content.append(title).append(address).append(confirm);
    return content[0];
};

/**
 * @classDescription Results from local server
 * @constructor
 * @param {Object} result
 */
map2fun.control.ui.LocalResult = function(units){
    this.units = this.getUnits(units);
    this.code = units[0].code;
    this.address = units[0].address || "";
    
    this.title = this.getLiteAddress();
    this.lat = map2fun.utils.decode(units[0].code)[0][0];
    this.lng = map2fun.utils.decode(units[0].code)[0][1];
    
    this._marker = null;
    
    
};

map2fun.control.ui.LocalResult.prototype.getUnits = function(units){
    var u = units;
    if (!units[0].getLink) {
        u = new Array();
        $.each(units, function(i, item){
            u.push(new map2fun.control.ui.Unit(item));
        });
    }
    return u;
};

map2fun.control.ui.LocalResult.prototype.getUnitById = function(id){
    $.each(this.units, function(i, item){
        if (item.id == id) 
            return item;
    });
    return null;
};

map2fun.control.ui.LocalResult.prototype.getBreif = function(){//for list content
    var _class = this;
    
    var node = $("<li class='local-result'></li>");
    var nodeLink = $("<a href='#' class='action'></a>").text(this.title).click(function(){
        GEvent.trigger(_class.getMarker(), "click");
    });
    var title = $("<h4 class='title'></h4>").append(nodeLink);
    var address = this.address ? $("<span class='desc'>" + this.address + " | <a href='" + this.getLink() + "'>查看附近的全部场所</a></span>") : "";
    var unitList = $("<ul class='unitList clearfix'></ul>");
    $.each(this.units, function(i, item){
        unitList.append(item.getBrief(i));
    });
    return node.append(title).append(address).append(unitList);
};


map2fun.control.ui.LocalResult.prototype.getMarker = function(markerInfo){
    if (this._marker) {
        return this._marker;
    }
    
    var icon = map2fun.control.ui.Node.yellowicon;
    var latlng = new GLatLng(this.lat, this.lng);
    var marker = new GMarker(latlng);
    
    GEvent.bind(marker, "click", this, function(){
        marker.openInfoWindow(markerInfo);
    });
    
    this._marker = marker;
    
    return marker;
};

map2fun.control.ui.LocalResult.prototype.getLink = function(){
    return map2fun.NODE_DETAIL_PATH + "?id=" + this.code;
};

map2fun.control.ui.LocalResult.prototype.getLatLng = function(){
    var p = map2fun.utils.decode(this.code)[0];
    return new google.maps.LatLng(p[0], p[1]);
};

map2fun.control.ui.LocalResult.prototype.getPoint = function(){
    return map2fun.utils.decode(this.code)[0];
};

map2fun.control.ui.LocalResult.prototype.toString = function(){
    return this.lat + ", " + this.lng;
};

map2fun.control.ui.LocalResult.prototype.destroyUnit = function(id){
    var id = this.units.indexOf(this.getUnitById(id));
    if (id) 
        this.units.splice(id, 1);
};

map2fun.control.ui.LocalResult.prototype.getLiteAddress = function(){
    var province = app.ui.location.get().province;
    var city = app.ui.location.get().city;
    
    return this.address.replace(map2fun.utils.trim(province + city), "");
};

map2fun.control.ui.LocalResult.prototype.getContent = function(){//for popup window
    var title = $("<span class='nodeTitle'></span>").text(this.title);
    var detail = $("<span class='desc'>共有" + this.units.length + "场所，<a href='" + this.getLink() + "'>查看详细内容</a></span>");
    var guideTxt = this.address ? $("<span class='desc'>出行参考: <a href='http://ditu.google.cn/maps?daddr=" + encodeURIComponent(this.address) + "&dirflg=r'>公交查询</a> | <a href='http://ditu.google.cn/maps?daddr=" + encodeURIComponent(this.address) + "&dirflg=d'>驾车查询</a></span>") : "";
    var con = $("<div class='nodeResult'></div>").append(title).append(detail).append(guideTxt);
    return con[0];
};

map2fun.control.ui.LocalResult.prototype.getUnitInfo = function(){
    var title = $("<span class='nodeTitle'></span>").text(this.title);
    var list = $("<ul></ul>");
    $.each(this.units, function(i, item){
        list.append("<a class='external' href='" + item.getLink() + "'>" + item.name + "</a>");
    });
    var detail = $("<a class='external' href='" + this.getLink() + "'>察看该地址详情</a>");
    var guideTxt = this.address ? $("<span class='desc'>出行参考: <a href='http://ditu.google.cn/maps?daddr=" + encodeURIComponent(this.address) + "&dirflg=r'>公交查询</a> | <a href='http://ditu.google.cn/maps?daddr=" + encodeURIComponent(this.address) + "&dirflg=d'>驾车查询</a></span>") : "";
    var con = $("<div class='nodeResult'></div>").append(title).append(list).append(detail).append(guideTxt);
    return con[0];
};

map2fun.control.ui.LocalResult.sortUnitByNode = function(units){
    if (!units || units.length == 0) 
        return;
    var nodes = new Object(), results = new Array();
    $.each(units, function(i, item){
        if (!nodes[item.code]) {
            nodes[item.code] = new Array();
        }
        nodes[item.code].push(item);
    });
    for (var code in nodes) {
        results.push(new map2fun.control.ui.LocalResult(nodes[code]));
    }
    return results;
};

/**
 * @classDescription type for unit in a node
 * @param {Object} unit
 */
map2fun.control.ui.Unit = function(unit){
    this.id = unit.id;
    this.name = unit.name;
    this.cost = unit.cost;
    this.type = unit.type;
    this.score = unit.score;
    this.desc = unit.desc || "";
    this.code = unit.code;
    this.address = unit.address;
};

map2fun.control.ui.Unit.prototype.getLink = function(){
    return map2fun.UNIT_DETAIL_PATH + "?id=" + this.id;
};

/**
 * @param {int} i index of unit
 */
map2fun.control.ui.Unit.prototype.getBrief = function(i){
    var unitLink = $("<a href='" + this.getLink() + "'></a>");
    var _ex = (i + 1) % 3 == 0 ? "ex" : "";
    var unit = $("<li class='radius " + _ex + "' rel='" + this.id + "'></li>").hover(function(){
        $(this).addClass("hover")
    }, function(){
        $(this).removeClass("hover")
    });
    var meta = $("<p class='meta'></p>");
    var title = $("<h5 class='title'></h5>").text(this.name).attr("rel", this.code);
    var cost = $("<span class='unit-cost'></span>").text(this.cost + "元");
    var type = $("<span class='unit-type'></span>").text(map2fun.UNIT_TYPE[this.type]);
    var score = $("<span class='unit-score'></span>").text(this.score);
    meta.append("类型 ").append(type).append(" 人均消费 ").append(cost).append(" 评分 ").append(score);
    var desc = this.desc ? $("<p class='desc'></p>").text(this.desc).append(unitLink.addClass("more").text("查看详情")) : "";
    if (app.ui.mainView && app.ui.mainView.activity == "sharePath") {
        title.click($.proxy(this.addToBusket, this));
    }
    
    return unit.append(title).append(meta).append(desc);
};

map2fun.control.ui.Unit.prototype.addToBusket = function(e){//build heading for sidebar 
    if ($("#unitBusket .indicator")[0]) {
        $("#unitBusket .indicator").hide();
        $("#unitBusket .busketAction").show();
    }
    var item = $(e.target).closest("li").fadeOut(function(){
        var isEmpty = false;
        var node = $(e.target).closest("li.local-result");
        $.each(node.find("li"), function(i, item){
            if ($(item).css("display") != "none") {
                isEmpty = false;
                return false;
            }
            else {
                isEmpty = true;
            }
        });
        
        if (isEmpty) {
            node.hide();
        }
    });
    var id = item.attr("rel");
    var code = item.find("h5").attr("rel");
    
    var title = $("<a />", {
        text: this.name,
        href: this.getLink(),
        title: this.address,
        rel: code,
        "className": "unit-title"
    });
    
    var cancelButton = $("<a href='#' class='action fir cancel'>取消</a>").click(this.removeFromBusket);
    var heading = $("<li class='heading'></li>").attr("rel", id).append(title).append(cancelButton).fadeIn();
    
    $("#unitBusket .list").append(heading);
};

map2fun.control.ui.Unit.prototype.removeFromBusket = function(e){
    var heading = $(e.target).closest("li.heading");
    var id = heading.attr("rel");
    var unit = $("#addressList").find("li[rel='" + id + "']").fadeIn();
    var node = unit.closest("li.local-result");
    var isEmpty = false;
    
    $.each(node.find("li"), function(i, item){
        if ($(item).css("display") != "none") {
            isEmpty = false;
            return false;
        }
        else {
            isEmpty = true;
        }
    });
    
    if (!isEmpty) {
        node.show();
    }
    
    heading.fadeOut(function(){
        $(this).remove();
        if (!$("#unitBusket .list li")[0]) {
            $("#unitBusket .indicator").show();
            $("#unitBusket .busketAction").hide();
        }
        
    });
};

map2fun.control.ui.Path = function(path){
    this.id = path.id;
    this.name = path.name;
    this.units = this.getUnits(path.units);
    this.localResults = this.getLocalResults();
    this.points = this.getPoints();
    this.code = this.getCode();
    this.polyline = new Object();
    this.steps;
    this._always = false;
    this._marked = false;
    this._show = true;
    
};

map2fun.control.ui.Path.prototype.getLocalResults = function(){
    return map2fun.control.ui.LocalResult.sortUnitByNode(this.units);
};

map2fun.control.ui.Path.prototype.getCode = function(){
    var points = new Array();
    $.each(this.points, function(i, item){
        points.push({
            Latitude: item[0],
            Longitude: item[1]
        });
    });
    
    return map2fun.utils.encode(points);
    
};

map2fun.control.ui.Path.prototype.getPoints = function(){
    var p = new Array();
    $.each(this.localResults, function(i, item){
        p.push(item.getPoint());
    });
    return p;
};

map2fun.control.ui.Path.prototype.getPointStr = function(){
    var a = new Array();
    $.each(this.points, function(i, item){
        a.push(item + "");
    });
    return a;
};

map2fun.control.ui.Path.prototype.getUnits = function(units){
    var u = new Array();
    $.each(units, function(i, item){
        u.push(new map2fun.control.ui.Unit(item));
    });
    return u;
};

map2fun.control.ui.Path.prototype.getLink = function(){
    return map2fun.PATH_DETAIL_PATH + "?id=" + this.id;
};

map2fun.control.ui.Path.prototype.getContent = function(){
    var _class = this;
    var path = $("<li class='path-result radius'></li>");
    var title = $("<h4 class='title'></h4>").append($("<a />", {
        href: this.getLink(),
        text: this.name
    }));
    var showPath = $("<a />", {
        className: "action showPath",
        href: "#",
        text: "显示这条路线",
        click: function(){
            _class.show();
            $(this).hide().siblings("a.hidePath").css("display", "inline");
        }
    }).hide();
    var hidePath = $("<a />", {
        className: "action hidePath",
        href: "#",
        text: "隐藏这条路线",
        click: function(){
            _class.hide();
            $(this).hide().siblings("a.showPath").css("display", "inline");
        }
    });
    
    var more = $("<span />").addClass("more").append(showPath).append(hidePath);
    var unitList = $("<ol class='unitList clearfix'></ol>");
    
    $.each(this.units, function(i, item){
        var unit = item.getBrief(i);
        unit.append("<span class='number'>" + (i + 1) + "</span>").removeClass("radius").unbind();
        unitList.append(unit);
    });
    
    var _len = this.units.length;
    var _li = unitList.find("li");
    if (_len % 3 == 0) {
        _li.eq(_len - 1).addClass("last");
        _li.eq(_len - 2).addClass("last");
        _li.eq(_len - 3).addClass("last");
    }
    _li.eq(_len - 1).addClass("last");
    if (_len % 3 == 1) {
        _li.eq(_len - 1).addClass("last");
    }
    if (_len % 3 == 2) {
        _li.eq(_len - 1).addClass("last");
        _li.eq(_len - 2).addClass("last");
    }
    
    path.hover(function(){
        if (_class._show) {
            _class.highlight();
        }
        $(this).addClass("hover");
        
    }, function(){
        if (_class._show) {
            _class.deHighlight();
            
        }
        $(this).removeClass("hover");
    });
    
    return path.append(title).append(more).append(unitList);
};

map2fun.control.ui.Path.prototype.highlight = function(e){
    app.map.panTo(this.localResults[this.localResults.length - 1].getLatLng());
    this.polyline.setStrokeStyle({
        color: "#930606",
        weight: 8
    });
    
};

map2fun.control.ui.Path.prototype.deHighlight = function(e){
    this.polyline.setStrokeStyle({
        color: "#3752FD",
        weight: 6
    });
};

map2fun.control.ui.Path.prototype.mark = function(){
    if (this._marked) {
        this.polyline.show();
        $.each(this.localResults, function(i, item){
            item.getMarker().show();
        });
    }
    else {
        app.map.addOverlay(this.polyline);
        $.each(this.localResults, function(i, item){
            app.map.addOverlay(item.getMarker(item.getUnitInfo()));
        });
        this._marked = true;
    }
    this._show = true;
};

map2fun.control.ui.Path.prototype.show = function(){

    this.polyline.show();
    $.each(this.localResults, function(i, item){
        item.getMarker().show();
    });
    
    this._show = true;
};

map2fun.control.ui.Path.prototype.hide = function(){
    this.polyline.hide();
    $.each(this.localResults, function(i, item){
        item.getMarker().hide();
    });
    
    this._show = false;
};

map2fun.control.ui.Path.prototype.setPath = function(polyline){
    this.polyline = polyline;
    this.polyline.setStrokeStyle({
        color: "#3752FD",
        weight: 6
    });
};
