//google map api
//document.write("<script src='http://ditu.google.cn/maps?file=api&amp;v=2&amp;key=" + mapKey + "' type='text/javascript'></script>");

var targets = new Array();
var geocoder = null;
var bounds = null;
var hotelInfos = {};
var lastCityName = "";
var rightViewCount = 0;
var rightViewMaxCount = 13;
var mapType = null;
var hasMarker = false;
var marks = new Array();
var mgr = null;
var cityName = "";
var cityEnuName = "";
var countryCode = "";
var cityCode = "";
var btnViewSmall = null;
var btnViewBig = null;
var intervalFunHandlerId = null;

function selectMapItem(li) {
    var cs_city = new csCity(li.innerHTML);
    $("#mapCityName").val(cs_city.chsName);
    $("#mapCityEnuName").val(cs_city.enuName);
    $("#mapCountryCode").val(cs_city.countryCode);
    $("#mapCityCode").val(cs_city.cityCode);
}

function clearDefaultTxt() {
    if ($("#mapCountryCode").val() == "") {
        $("#mapCityName").val("");
    }
}

$(document).ready(function() {
    //设置地图城市autoComplete
    autocompleteCityName($("#mapCityName"), selectMapItem);
});

function getMap() {
    cityName = $("#mapCityName").val();
    cityEnuName = $("#mapCityEnuName").val();
    countryCode = $("#mapCountryCode").val();
    cityCode = $("#mapCityCode").val();
    setTimeout("initPageMap()", 200);
}

function getCityName(chsName, enuName, p_cityCode, p_countryCode) {
    cityName = chsName;
    cityEnuName = enuName;
    cityCode = p_cityCode;
    if(p_countryCode){
        countryCode = p_countryCode;
    }else {
        countryCode = "CN";
    }
    $("#mapCityName").val(cityName);
    $("#mapCityEnuName").val(enuName);
    $("#mapCountryCode").val(countryCode);
    $("#mapCityCode").val(cityCode);

    setTimeout("initPageMap()", 200);
}

function initPageMap() {
    if ($("#mapCountryCode").val() == "") {
        $("#mapCityName").val("");
        daAlert($("#mapCityName"), errorCityNameMsg);

        return false;
    }
    geocoder = new GClientGeocoder();
    bounds = new GLatLngBounds();
    
    initPage();
}

function initPage() {
    load();
    showHotelsInCityMap();
}

function showHotelsInCityMap() {
    showCity(cityName);
    initMap();
    $("input.gsc-input").val(gMapLocalSearchTip);
}

var nowShowBigMap = false;
function viewBigMap()
{
    nowShowBigMap = true;
    //$("#map_search").css("left", $("#map_search").position().left+"px");
    $("#map_search").css("top", $("#map_search").position().top);
    $("#map_search").css("position", "absolute");
    $("#map_search").animate({width:'652px'}, "fast");
    $("#map_search").animate({top:$("#query").position().top + 43 + "px"}, "fast");
    $("#map_search").animate({height:$("#map_title").position().top - $("#query").position().top + 317 + "px"}, "fast");
    if ($.browser.version.indexOf("6.0") > -1)
    {
        iframeDecorateDiv("map_search", "mapIframe");
    }

    //添加缩小按钮
    if (!btnViewSmall)
    {
        btnViewSmall = new TextControl(textViewSmall, 590, 28, textViewSmall, viewSmallMap);
    }
    map.removeControl(btnViewBig);
    map.addControl(btnViewSmall);
}

function viewSmallMap()
{
    nowShowBigMap = false;
    $("#map_search").animate({width:'460px'}, "fast");
    $("#map_search").animate({height:"322px"}, "fast");
    $("#map_search").animate({top:$("#map_title").position().top + 37 + "px"}, "fast");
    addViewBigBtn();
}


function addViewBigBtn() {
    if (nowShowBigMap == false)
    {
        if (btnViewSmall) {
            map.removeControl(btnViewSmall);
        }
        map.addControl(btnViewBig);
    } else {
        if (btnViewBig) {
            map.removeControl(btnViewBig);
        }
        map.addControl(btnViewSmall);
    }


}

function initMap() {
    hotelInfos = {};
    $("#hotel_list ul").html("");
    rightViewCount = 0;
    map.clearOverlays();
    bounds = new GLatLngBounds();
    marks = new Array();
    showHotels();
}

function showHotels() {
    hasMarker = false;
    var mapLeft = $("#map_search").position().left;
    var mapTop =  $("#map_search").position().top;
    $("#map_hotel_data_loading").css({"left":mapLeft+150+"px","top":mapTop+100+"px"});
    $("#map_hotel_data_loading").show();
    $(".progressBar").progressBar({increment:1, speed:150});
    $.ajax({
        dataType: "json",
        url: _contextpath + "/hotel/queryHotelByMap.action",
        data: $("#queryHotelForMap").serialize(),
        type: 'POST',
        success: function(data) {
            if (data && data.hotels) {
                createHotelMarker(data.hotels[0]);
            }
        },
        async: true
    });
}

function createHotelMarker(hotels) {
    setTimeout(function() {
        for (var j = 0; j < hotels.length; j++) {
            addHotelMarker(hotels[j]);
        }
        var boundsLevel = 10;

        setupWeatherMarkers(boundsLevel);
        $("#map_hotel_data_loading").hide();
    }, 200);
}

function setupWeatherMarkers(boundsLevel) {
    mgr = new GMarkerManager(map);
    for (var i = parseInt(boundsLevel)-1; i >=0; i--) {
        mgr.addMarkers(getMarks(5), i);
    }
    mgr.addMarkers(getMarks(15), boundsLevel);
    var j = 1;
    for (var i = parseInt(boundsLevel); i < 15; i++) {
        mgr.addMarkers(getMarks(15 + j * 10), i);
        j++;
    }
    mgr.addMarkers(getMarks(marks.length), 14);
    mgr.addMarkers(getMarks(marks.length), 15);
    mgr.refresh();
}

function getMarks(n) {
    var displayMarks = new Array();
    for (var i = 0, marksLength = marks.length; i < marksLength && i < n; i++) {
        displayMarks.push(marks[i]);
    }
    return displayMarks;
}

function load() {
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new google.maps.LocalSearch());
//    addViewBigBtn();
}


function showCity(city) {
    lastCityName = city;

    map.addControl(new GMapTypeControl());

    if (geocoder) {
        geocoder.getLatLng(
                city,
                function(point) {
                    if (point) {
                        map.setCenter(point, 10);
                    }
                });
    }
}

function conditionChanged(info) {
    return info && info.checkinDate == $("#checkinDate").val()
            && info.checkoutDate == $("#checkoutDate").val()
            && info.roomQuantity == $("#roomQuantity").val()
            && info.adultCount == $("#adultCount").val()
            && info.childrenCount == $("#childrenCount").val();
}

function addHotelMarker(hotel) {
    if (hotel.hotelBasicInfo && hotel.hotelBasicInfo.position) {
        var hotelLatitude = hotel.hotelBasicInfo.position.latitude;
        var hotelLongitude = hotel.hotelBasicInfo.position.longitude;

        if (hotelLatitude && hotelLongitude && $.trim(hotelLatitude).length > 0 && $.trim(hotelLongitude).length > 0) {

            var point = new GLatLng(Number(hotelLatitude), Number(hotelLongitude));

            bounds.extend(point);
            var icon = new GIcon(G_DEFAULT_ICON);

            if (hotel.favorite) {
                icon.image = imgPath + "/MarkerDot.gif";
            } else {
                icon.image = imgPath + "/BlueMarkerDot.gif";
            }
            icon.shadow = "";
            icon.iconSize = new GSize(16, 23);
            icon.iconAnchor = new GPoint(0, 23);
            icon.maxHeight = 30;
            var marker = new GMarker(point, icon);
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml("<h3>" + hotel.hotelBasicInfo.hotelName +
                                          "</h3> <br><br> <font color='red'> " + inQuery + "</font>");

                var info = hotelInfos[hotel.hotelBasicInfo.passport];

                if (conditionChanged(info)) {
                    marker.openInfoWindowHtml(info.popContent);
                } else {

                    $("#hotelPassport").val(hotel.hotelBasicInfo.passport);
                    $("#hotelCategoryName").val(hotel.hotelCategory);

                    queryRoomRate(marker, hotel);
                }
            });
            hasMarker = true;
            marks.push(marker);
        }
    }
}

function queryRoomRate(marker, hotel) {
    $.ajax({
        url: _contextpath + "/hotel/queryRoomRateByMap.action",
        data: getCondition(),
        type: 'POST',
        success: function(data) {
            try {
                var json = eval('(' + data + ')');

                if (json.hotel) {
                    var popContent = $("#hotelTemplate").html();

                    if ((json.hotel.minPrice == null || $.trim(json.hotel.minPrice).length == 0
                            || parseInt(json.hotel.minPrice) <= 0)) {
                        popContent = $("#noRatehotelTemplate").html();
                    }
                    popContent = popContent.replace(/_hotel_passport_/g, "" + json.hotel.passportCode);
                    if (json.hotel.hotelCategory.toUpperCase() == 'AGENT') {
                        popContent = popContent.replace(/src="about:blank"/g, "src='" + agent_hotel_dfs + "/breviaryPicture.do?hotelPassportCode=" + hotel.passportCode + "'");
                    } else {
                        popContent = popContent.replace(/src="about:blank"/g, "src='" + dfs + "/picture/" + json.hotel.passportCode + "/thumbnail'");
                    }
                    popContent = popContent.replace(/_hotel_category_name_/g, "" + json.hotel.hotelCategory);
                    popContent = popContent.replace(/_hotel_name_/g, "" + json.hotel.hotelName);
                    popContent =
                    popContent.replace(/_hotel_star/g, "" + generateHotelRatingDesc(json.hotel.hotelRating,json.hotel.equilantRating));
                    popContent = popContent.replace(/_hotel_address_/g, "" + json.hotel.addressLine);
                    if (json.hotel.aboutMinPrice != null && json.hotel.aboutMinPrice != "unsupport") {
                        popContent = popContent.replace(/_hotel_currency_/g, "" + json.hotel.aboutCurrency);
                        popContent = popContent.replace(/_hotel_price_/g, "" + json.hotel.aboutMinPrice);
                    } else {
                        popContent = popContent.replace(/_hotel_currency_/g, "" + json.hotel.currency);
                        popContent = popContent.replace(/_hotel_price_/g, "" + json.hotel.minPrice);
                    }

                    hotelInfos[hotel.hotelBasicInfo.passport] = {};
                    hotelInfos[hotel.hotelBasicInfo.passport].roomQuantity = $("#roomQuantity").val();
                    hotelInfos[hotel.hotelBasicInfo.passport].adultCount = $("#adultCount").val();
                    hotelInfos[hotel.hotelBasicInfo.passport].childrenCount = $("#childrenCount").val();
                    hotelInfos[hotel.hotelBasicInfo.passport].checkinDate = $("#checkinDate").val();
                    hotelInfos[hotel.hotelBasicInfo.passport].checkoutDate = $("#checkoutDate").val();
                    hotelInfos[hotel.hotelBasicInfo.passport].popContent = popContent;

                    marker.openInfoWindowHtml(popContent);
                }
            } catch(e) {
                showTimeoutInfo(hotel, marker)
            }

        },
        complete: function (request, textStatus) {
            if (textStatus == "timeout" || textStatus == "error" || textStatus == "parsererror") {
                showTimeoutInfo(hotel, marker);
            }
        },
        async: true,
        timeout: 40000

    });
}

function showTimeoutInfo(hotel, marker) {
    var popContent = $("#timeoutTemplate").html();
    popContent = popContent.replace(/_hotel_passport_/g, "" + hotel.passportCode);
    if (hotel.hotelCategory.toUpperCase() == 'AGENT') {
        popContent = popContent.replace(/src="about:blank"/g, "src='" + agent_hotel_dfs + "/breviaryPicture.do?hotelPassportCode=" + hotel.passportCode + "'");
    } else {
        popContent = popContent.replace(/src="about:blank"/g, "src='" + dfs + "/picture/" + hotel.passportCode + "/thumbnail'");
    }
    popContent = popContent.replace(/_hotel_category_name_/g, "" + hotel.hotelCategory);
    popContent = popContent.replace(/_hotel_name_/g, "" + hotel.hotelName);
    popContent =
    popContent.replace(/_hotel_star/g, "" + generateHotelRatingDesc(hotel.hotelRating,hotel.equilantRating));
    popContent = popContent.replace(/_hotel_address_/g, "" + hotel.addressLine);

    marker.openInfoWindowHtml(popContent);
}

function getCondition() {
    var condition = {"condition.cityName":cityName,"condition.cityEnuName":cityEnuName,
        "condition.cityCode":cityCode, "condition.countryCode":countryCode,
        "condition.checkinDate":$("#checkinDate").val(), "condition.checkoutDate":$("#checkoutDate").val(),
        "condition.roomQuantity":$("#roomQuantity").val(),
        "condition.adultCount":$("#adultCount").val(),"condition.childrenCount":$("#childrenCount").val(),
        "hotelPassport":$("#hotelPassport").val(),"hotelCategoryName":$("#hotelCategoryName").val(),
        "booker.id":$("#bookerId").val()
    }
    return condition;
}

/*TextControl类 ============================================================================
*author Karry
*添加按钮扩展,
*继承自GControl()
*value--按钮的value 值
*left--按钮与左边框的距离（像素）
*top--按钮与上边框的距离（像素）
*/
function TextControl(value, left, top, toolTip, clickFunction) {
    this.value_ = value || "按钮";
    this.left_ = left || 77;
    this.top_ = top || 7;
    this.toolTip_ = toolTip || "";
    this.clickFunction_ = clickFunction;
}
TextControl.prototype = new GControl();
TextControl.prototype.initialize = function(map)
{
    var container = document.createElement("div");
    var containerDiv = document.createElement("div");
    container.title = this.toolTip_;
    this.setButtonStyle_(containerDiv);
    container.appendChild(containerDiv);
    containerDiv.appendChild(document.createTextNode(this.value_));
    GEvent.addDomListener(containerDiv, "click", this.clickFunction_);
    this.map_ = map;
    this.map_.getContainer().appendChild(container);
    return container;
}
TextControl.prototype.getDefaultPosition = function()
{
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(this.left_, this.top_));
}
TextControl.prototype.setButtonStyle_ = function(button)
{
    button.style.color = "#000000";
    button.style.backgroundColor = "white";
    button.style.font = "12px '宋体'";
    button.style.border = "1px solid black";
    button.style.padding = "2px";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "4em";
    button.style.cursor = "pointer";
}
/*TextControl类 end============================================================================*/
btnViewBig = new TextControl(textViewBig, 400, 28, textViewBig, viewBigMap);
btnViewSmall = new TextControl(textViewSmall, 590, 28, textViewSmall, viewSmallMap);