﻿// JScript 文件
(function(){
if (typeof window.$5 == 'undefined') window.$5 = {};

var fpBookHotel = floatPanel({
    target:$('#bookHotelsDiv'),
    onShow:function(s){
        $('#hidBookHotelId').val(s.id.substring(12));
    },
    //autoFollow:false,
    enableEsc:true,
    modal:true
});

var hotel = window.$5.hotel = function(hotelId, type) {
    if(isNaN(hotelId) || hotelId < 1) throw new Error("ID必须为大于0的数字");
    $5.ajax('Hotel.' + type, {hotelId:hotelId}, function(ret){
        if (ret.Status == '0') {
            var html = ret.Data;
            $('#hotel' + type + 'Div').html(html);
            
            switch(type) {
                case 'Comments':
                    hotel.initComments(hotelId);
                    break; 
                case 'Pictures':
                    hotel.initPictures(hotelId);
                    break; 
                case 'Rooms':
                    hotel.initRooms();
                    break;
            }
        } else {
            alert(ret.Error);
        }
    });
};
hotel.initRooms = function() {
    this.initHotelImage2($('#hotelRoomsDiv'),6);
};
hotel.initComments = function(hotelId){
    var faces = $('#submitCommentDiv').find('img');
    faces.each(function(i){
        $(this).click(function(){
            var name = $5.getFileName(this.src);
            $('#commentContent').val($('#commentContent').val() + '{' + name + '}');
            $('#commentContent').focus();
        });
    });
    $('#formAddComment').submit(function(){
        var content;
        if (!(content = jQuery.trim(this.content.value))) {
            alert("评论内容不能为空");
            this.content.focus();
        } else {
            $5.hotel.addComment(hotelId,content);
            this.content.value = ""; 
            $('#submitCommentDiv').parent()[0].scrollTop = 282;
        }
        
        return false;
    });
    $5.smartInput($('#formAddComment').find('textarea'));
    $('.commentQuote').click(function(){
        hotel.quoteComment($(this).parent().prev().html());
    });
    if (parseInt($('#hotelCommentNum').val(), 10) == 0) $('#commentList').prev().hide();
};
// 引用留言
hotel.quoteComment = function(html) {
    var reg = /<img src="\/images\/face\/(\d+).gif" height="40" width="40">/ig;
    if ($.browser.msie) reg = /<IMG height=40 src="[^"]+\/images\/face\/(\d+).gif" width=40>/g;
    var ubb = html.replace(reg, '{$1}').replace(/<br\/?>/ig,'\n    ').replace(/&nbsp;/ig, ' ');;
    ubb = '------------------------引用------------------------\n    ' + ubb + '\n----------------------------------------------------\n';
    var c = $($('#formAddComment')[0].content);
    c.val((c.val() ? c.val() + '\n' : '') + ubb).focus();
    $('#submitCommentDiv').parent()[0].scrollTop = 0;
};
// 发表评论
hotel.addComment = function(hotelId,content){
    content = content.replace(/\n/ig, '<br/>').replace(/ /g, '&nbsp;');
    $5.ajax("Hotel.AddComment", {hotelId:hotelId,content:content}, function(ret){
        if (ret.Status == 0) {
            var num = parseInt($('#hotelCommentNum').val(), 10)+1;
            if (num == 1) $('#commentList').prev().show();
            var li = $(ret.Data);
            li.find('.commentFloor').html(num);
            $('#hotelCommentNum').val(num);
            $('#menu').find('a')[4].innerHTML = '评论(' + num + ')';
            li.insertBefore('#commentList > *:first');
            
            li.find('.commentQuote').click(function(){
                hotel.quoteComment($(this).parent().prev().html());
            });
        } else {
            alert(ret.Error);
        }
    },function(){});
};
// 初始化图片
var initedPictures = false;
hotel.initPictures = function(hotelId){
    // 防止多次初始化
    if (initedPictures) return;
    else initedPictures = true;
    var pics = $('#hotelPictureList').val().split('|');
    $5.hotel.loadPicture(hotelId, pics, 0);
    $('#prevImageLink').click(function(){
        $5.hotel.loadPicture(hotelId, pics, hotel.currentPicIndex-1);
    });
    var sn = function(){
        $5.hotel.loadPicture(hotelId, pics, hotel.currentPicIndex+1);
    };
    $('#hotelPicturesImage').click(sn);
    $('#nextImageLink').click(sn);
};
hotel.loadPicture = function(hotelId, pics, i) {
    if (pics == '') return;
    if (i < 0 || i >= pics.length) return;
    var img = $('#hotelPicturesImage');
    img.width(32);
    img.height(32);
    img.attr('src', '/images/loading.gif');
    img.attr('alt', 'loading...');
    var pic = pics[i];
    var w = $5.config('hotel.maxPicWidth'),h = $5.config('hotel.maxPicHeight');
    $5.loadImage('/picture/hotel/' + hotelId + '/' + pic, function(){
        if (this.width <= w && this.height <= h) {
            img.width(this.width);
            img.height(this.height);
        } else {
            if (this.width/w > this.height/h) {
                img.width(w);
                img.height(h * (w/this.width));
            } else {
                img.height(h);
                img.width(w * (h/this.height));
            }
        }
        $('#imageTitleDiv').html(pic.substring(0, pic.lastIndexOf('.')));        
        img.attr('src', this.src);
        img.attr('alt', pic);
        
        hotel.currentPicIndex = i;
        $('#prevImageLink').attr('class',(i > 0) ? 'arrowLeft' : 'arrowLeft2');
        $('#nextImageLink').attr('class', (i < pics.length - 1) ? 'arrowRight' : 'arrowRight2');
        if (i < pics.length - 1) {
            $('#hotelPicturesImage').attr('class','hand');
        } else {
            $('#hotelPicturesImage').attr('class', '');
        }
        
    });
};
hotel.currentPicIndex = 0;
// 初始化预定酒店面板
hotel.initBookPanel = function(){
    var form = $5('formBookHotels') || $5('formBookHotels2');
    if (!form) return;
    $(form.bookImage).each(function(){
        $(this).click(function(){
            this.previousSibling.click();
        });
    });

    var checks = $(form.bookTarget);
    checks.each(function(){
        $(this).click(function(){
            var num = 0;
            checks.each(function(){
                if (this.checked) num++;
            });
            $('#bookCenterNum').html(num + '');
        });
    });
    form.onsubmit = function(){
        $(form.bookTarget).each(function(){
            if(this.checked) {
                var wnd = window.open('/Link.aspx?hotelId=' + form.hotelId.value + '&bookTarget=' + this.value
                     + '&checkInDate=' + form.checkInDate.value + '&checkOutDate=' + form.checkOutDate.value);
                if (wnd == null) {
                    alert("使用该功能需要您的浏览器支持本站的弹出窗口。");
                }
            }
        });
        return false;
    };
};
// 初始化日期控件
hotel.initDatePicker = function(today,nextDay, type){
    type = (typeof type == 'undefined') ? '' : type;
    var inId = '#checkInDate' + type, outId = '#checkOutDate' + type;
    $(inId).datepicker({
        changeYear:false,
        changeMonth:false,
        closeAtTop:false,
        minDate:today,
        speed:'',
        onSelect:function(date){
            if (date > $(outId).val()) {
                $(outId).val(date);
            }
            var tmp=date.split('-');
            setTimeout(function(){
            $(outId).datepicker('change', {minDate:new Date(tmp[0],parseInt(tmp[1], 10)-1,tmp[2])});
            $(outId).datepicker('show');
            },100);
        }
    });
    $('#checkInImg' + type).click(function(){
        $(inId).datepicker('show')
    });
    $(outId).datepicker({
        changeYear:false,
        changeMonth:false,
        closeAtTop:false,
        speed:'',
        minDate:today
    });
    $('#checkOutImg' + type).click(function(){
        $(outId).datepicker('show')
    });
};
//初始化分享代码窗口
hotel.initShareCode=function(){
    var fp = floatPanel({
        target:$('#shareCodeDiv'),
        width:360,
        modal:true
    });
    $('#shareCodeLink').click(function(){
        fp.show();
    });
};

hotel.initSearch=function(){
    $('#formSearch')[0].onsubmit = function(){
        if (!$.trim(this.keyword.value)) {
            this.keyword.focus();
            return false;
        }
        return true;
    };
};

var fpRoom = floatPanel({
    target:$('#hotelRoomVideoContainer'),
    modal:true,
    width:640,
    //enableEsc:true,
    onHide:function(){
        $.browser.msie && $('#roomVideoFla')[0].stop();
        $('#hotelRoomVideoDiv').empty();
    }
});
hotel.showRoom=function(videoId){
    if (isNaN(videoId) || videoId < 1) return;
    var html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"\
        width="640" height="400" id="roomVideoFla">\
        <param name="movie" value="/player.swf?vid=' + videoId + '&amp;pach=../" />\
        <param name="quality" value="high" />\
        <param name="allowFullScreen" value="true" />\
        <param name="BGCOLOR" value="#000000" />\
        <param name="type" value="application/x-shockwave-flash" />\
        <param name="allowfullscreen" value="true" />\
        <param name="wmode" value="opaque"/>\
        <embed src="/player.swf?vid=' + videoId + '&amp;pach=../" width="640" quality="high" height="400" wmode="opaque" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" allowfullscreen="true" bgcolor="#000000"></embed>\
    </object>';
    $('#hotelRoomVideoDiv').html(html);
    fpRoom.show();
};
// 初始化比较方面的ui控件
hotel.initCompare=function(){
    // 使浏览器地址栏不出现#
    $5('compareLink').onclick =function(){
        var ids = $('#formCompare input');
        var checkedIds = [];
        ids.each(function(){
            if (this.checked) checkedIds.push(this.value);
        });
        if (checkedIds.length < 2) {
            alert("至少需要选择两个酒店进行比较");
            return false;
        }
        $('#formCompare').submit();
        return false;
    };
};
// 初始化用来进行比较的checkbox的点击事件
hotel.initCompareCheck=function(){
    $('#formCompare input').each(function(){
        // 必须是一开始就已经选择上，现在没有选上，并且没有被删除过的才会引起向服务器端发送删除该hotel的请求
        if (this.defaultChecked) {
            this.setAttribute('deleted', 0);
            $(this).click(function(){
                if (!this.checked && this.getAttribute('deleted') == '0') {
                    var s = this;
                    $5.ajax('Hotel.RemoveCompare', {hotelId:this.value}, function(ret){
                        if (ret.Status == 0) s.setAttribute('deleted', 1);
                        else alert(ret.Error);
                    });
                }
            });
        }
    });
};
// 初始化移除比较链接的点击事件
hotel.initCompareRemove=function() {
    $('.removeCompare').click(function(){
        var hotelId = this.getAttribute('hotelId');
        var link = $(this);
        $5.ajax('Hotel.RemoveCompare', {hotelId:hotelId},function(ret){
            if (ret.Status == 0) {
                var url = $('#hidFrom').val();
                var td = link.parent().parent().parent();
                link.parent().parent().replaceWith('<table cellpadding="0" cellspacing="0" border="0" width="100%">\
                    <tr><td align="center">\
                        <a href="' + url + '">添加更多酒店...</a>\
                    </td></tr>\
                </table>\
                ');  
                
                // 和后面的td进行交换
                if (td.next().length > 0) {
                    var tr = td.parent();
                    td.remove();
                    tr.append(td);
                }              
            }
        });
    });
};
hotel.initBookLinks=function(){
    $('.bookHotelImage').click(function(){
        fpBookHotel.show(this);
    });
};
hotel.initTabs = function(hotelId, lo, la){
    var _initMap = function(lo, la) {
        $5.gmap.initHotel($5('hotelMapDiv'),lo, la, 12);
    };
    var initHotelMap = _initMap;
    if (window.location.hash == '#Map') {
        initHotelMap = function(lo, la){$(window).bind('load', function(){_initMap(lo, la);})};
    }

    var ans = ['Video','Pictures','Rooms','Hits','Comments','Map'];
    
    var current = 0;
    var $video = $('#hotelVideoDiv');
    var _pos = $video.offset();
    var lis = $('#menu li');
    lis.each(function(i){
        var li = $(this);
        li.find('a').click(function(){
            if (i == current) return;
            var _old = ans[current], _new = ans[i];        
            li.toggleClass('selected');
            $(lis[current]).toggleClass('selected');
            var elem = $('#hotel' + _new + 'Div');
            if (_old == 'Video') {
                $video.css({position:'absolute',top:-1000,left:0});
            } else $('#hotel' + _old + 'Div').hide();
            if (_new == 'Video') {
                $video.css({position:'',top:_pos.top,left:_pos.left});
            } else elem.show();
            current = i;
            
            if (_new == "Pictures"){
                $5.hotel.initPictures(hotelId);
                return;
            }
            if (elem.html()) return;
            
            if (_new == "Map") {
                $('#hotelMainDiv').hide();
                $('#hotelMapDiv').show();
                if (!$('#hotelMapDiv').html()) initHotelMap(lo,la);
                return;
            } else {
                $('#hotelMainDiv').show();
                $('#hotelMapDiv').hide();
            }
            $5.hotel(hotelId, ans[i]);
        });
    });

    var hash = window.location.hash;
    if (hash && hash != "#Video") {
        hash = hash.substring(1);
        $.each(ans,function(i,s){
            if (s == hash) {
                $(lis[i]).find('a').trigger('click');
            }
        });
    }
};
hotel.initHotelImage = function(){
    $('.hotelList').pngFix();
    var curMask = null;
    $('.hotelList').bind('scroll',function(){
        if(curMask) {
            curMask.css('visibility','hidden');
            curMask=null;
        }
    });
    $('.hotelImage').each(function(){
        var img = $(this);
        if ($.browser.msie && $.browser.version < 7) {
            var onMask = false;
            img.prev().mouseover(function(){onMask = true;});
            img.prev().mouseout(function(){onMask = false;});
            img.mouseover(function(){
                (curMask =img.addClass('hotelImage2').prev()).css('visibility','visible');
            });
            img.mouseout(function(){
                setTimeout(function(){
                if (!onMask) {img.removeClass('hotelImage2').prev().css('visibility','hidden');}
                },1);
            });
        } else {
            img.mouseover(function(){
                (curMask = img.addClass('hotelImage2').prev()).css('visibility','visible');
            });
            var img1 = img.prev();
            img1.mouseout(function(){
                img.removeClass('hotelImage2').prev().css('visibility','hidden');
            });
         }
    });
};
//初始化酒店图片
hotel.initHotelImage2 = function(div,i){
    div = div || $('#hotelListDiv');
    i = i || 5;
    div.pngFix();
    $('.hotelImage' + i).each(function(){
        var img = $(this);
        if ($.browser.msie && $.browser.version < 7) {
            var onMask = false;
            img.prev().mouseover(function(){onMask = true;});
            img.prev().mouseout(function(){onMask = false;});
            img.mouseover(function(){
                img.prev().css('visibility','visible');
            });
            img.mouseout(function(){
                setTimeout(function(){
                if (!onMask) {img.prev().css('visibility','hidden');}
                },1);
            });
            var f = function(){$5.hotel.showRoom($(this).parent().attr('videoId'));};
            img.prev().click(f);
            img.click(f);
        } else {
            img.mouseover(function(){
                img.prev().css('visibility','visible');
            });
            var img1 = img.prev();
            img1.mouseout(function(){
                img.prev().css('visibility','hidden');
            });
            img1.click(function(){
                $5.hotel.showRoom($(this).parent().attr('videoId'));
            });
         }
    });
};
})()
