var map;
var marker;

calendarSelector = {
    currentDate: null,
    minDate: null,
    maxDate: null,
    target: null,

    DayNames: ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
    Monthes: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],

    create: function() {
        var txt = "<div class='calendarBlock'>";
            txt+= "<h1>Month</h1><h2>2011</h2>";
            txt+= "<a class='prevMonth'>&nbsp;</a>";
            txt+= "<a class='nextMonth'>&nbsp;</a>";
            txt+= "<table><tr>";
            for (var i=0; i<7; i++) txt+="<th"+(i>=5 ? ' class="weekend"' : '')+">"+this.DayNames[i]+'</th>';
            txt+= "</tr>";
            for (var j=0; j<6; j++) {
                txt+="<tr>";
                for (i=0; i<7; i++) txt+="<td><span><a>N</a></span></td>";
                txt+="</tr>";
            }
            txt+= "</table>";
        this.obj = $(txt);
        this.obj.appendTo(document.body);
    },

    setTarget: function(obj) {
        this.target = obj;
        this.obj.css({left: ($(obj).offset().left + obj.clientWidth+9)+"px", top: $(obj).offset().top+"px"});
        var t = obj.value;
        if (t=="") {
            this.currentDate = new Date();
        } else {
            var tmp = new Date();
            this.currentDate = new Date(tmp.getFullYear(), t.replace(/^\d+\.(\d+)$/, '$1') - 1, t.replace(/^(\d+)\.\d+$/, '$1'));
            if (this.currentDate<tmp) this.currentDate.setFullYear(tmp.getFullYear()+1);
        }
        var tmp2 = new Date();
            tmp2.setTime(tmp2.getTime() + 86400000);
        if (tmp2>=this.currentDate) {
            this.currentDate = new Date();
            this.currentDate.setTime(tmp2.getTime());
        }
        this.minDate = new Date();
        this.minDate.setTime(Math.floor(tmp2.getTime()/86400000)*86400000);
        this.maxDate = tmp2;
        this.maxDate.setTime(Math.floor(this.maxDate.getTime()/86400000)*86400000 + 86400000*364);
        this.currentDate.setHours(0);
        this.currentDate.setMinutes(0);
        this.currentDate.setSeconds(0);
        this.minDate.setHours(0);
        this.minDate.setMinutes(0);
        this.minDate.setSeconds(0);
        this.maxDate.setHours(0);
        this.maxDate.setMinutes(0);
        this.maxDate.setSeconds(0);
        if (obj.name=="dateTo") {
            var x0 = document.getElementsByName("dateFrom")[0];
            if (x0.value!="") {
                var d0 = x0.value.replace(/^(\d+)\.(\d+)$/, '$1');
                var m0 = x0.value.replace(/^(\d+)\.(\d+)$/, '$2') - 1;
                var y0 = this.minDate.getFullYear();
                var t0 = new Date(y0, m0, d0, 0, 0, 0);
                if (t0<this.minDate) t0.setFullYear(y0+1);
                this.minDate = new Date();
                this.minDate.setTime(t0.getTime()+86400000);
            }

            if (this.currentDate.getTime()<this.minDate.getTime()) {
                this.currentDate.setTime(this.minDate.getTime());
                this.target.value = this.to2dig(this.currentDate.getDate())+"."+ this.to2dig(this.currentDate.getMonth()+1);
            }
        }


        this.setCalendar();

        this.obj.fadeIn("fast");
    },

    setCalendar: function() {
        $(".calendarBlock table td").removeClass("selected");
        $(".calendarBlock h1").html(this.Monthes[this.currentDate.getMonth()]);
        $(".calendarBlock h2").html(this.currentDate.getFullYear());
        var tmp = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), 1);
        var day = tmp.getDay();
        if (tmp.getMonth==11) {
            tmp.setFullYear(tmp.getFullYear()+1);
            tmp.setMonth(0);
        } else {
            tmp.setMonth(tmp.getMonth()+1);
        }
        tmp.setTime(tmp.getTime()-86400000);
        var daysCount = tmp.getDate();
        if (day==0) day=7;
        var x = $(".calendarBlock table a");
        for (var i=0; i<x.length; i++) {
            var xx = i-day+2;
            if (xx<1 || xx>daysCount) xx="";
            $(x[i]).html(xx);
            if (xx!="") {
                x[i].parentNode.style.cursor = "pointer";
                var data = this.to2dig(xx)+"."+this.to2dig(this.currentDate.getMonth()+1);
                $(x[i]).data("val", data);
                var d2 = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), xx,0,0,0);
                if (Math.floor(d2/86400000)<Math.floor(this.minDate/86400000) || d2>this.maxDate) {
                     $(x[i]).addClass("unselectable"); 
                     x[i].parentNode.style.cursor = "default";
                } else
                     $(x[i]).removeClass("unselectable"); 
                $(x[i]).data("date", d2);
                if (data==this.target.value) $(x[i].parentNode.parentNode).addClass("selected"); else $(x[i].parentNode.parentNode).removeClass("selected");
            }
            else {
                x[i].parentNode.style.cursor = "default";
                $(x[i]).data("");
            }
            $(x[i]).click(function() {
                if (this.innerHTML=="" || $(this).hasClass('unselectable')) return false;
                calendarSelector.target.value = $(this).data("val");
                $(".calendarBlock table td").removeClass("selected");
                $(this.parentNode.parentNode).addClass('selected');
                calendarSelector.currentDate = $(this).data("date");

                calendarSelector.hide();
            });

        }
    },

    nextMonth: function() {
        var z = this.currentDate.getTime();
        var t = this.currentDate.getMonth();
        if (t==11) {
            t = 0; this.currentDate.setFullYear(this.currentDate.getFullYear()+1);
        } else t++;
        this.currentDate.setMonth(t);
        if (this.currentDate.getTime()>this.maxDate.getTime()) this.currentDate.setTime(z);
        this.setCalendar();
        return false;
    },

    prevMonth: function() {
        var z = this.currentDate.getTime();
        var t = this.currentDate.getMonth();
        if (t==0) {
            t = 11; this.currentDate.setFullYear(this.currentDate.getFullYear()-1);
        } else t--;
        this.currentDate.setMonth(t);
        if (this.currentDate.getTime()<this.minDate.getTime()) this.currentDate.setTime(z);
        this.setCalendar();
        return false;
    },

    hide: function() {
        this.obj.fadeOut("fast");
    },

    to2dig: function(N) {
        if ((N+"").length ==2) return N;
        return "0"+N+"";
    }
};

$(document).ready(function() {
    calendarSelector.create();
    $(".prevMonth").add(".nextMonth").each(function() { this.src="javascript: void(0);" });
    $(".prevMonth").click(function() { calendarSelector.prevMonth(); });
    $(".nextMonth").click(function() { calendarSelector.nextMonth(); });

    $("input.date").click(function() {
        calendarSelector.setTarget(this);
    });

    $(".photo-container .button").click(function() {
        var cs = parseInt($(".photo-placeholder .photo-scroller").css("left"));
        if ($(this).hasClass('second')) cs = parseInt($(".popupPic .photo-scroller").css("left"));
        var wd = parseInt($(".photo-scroller").css("width"));
        var w = parseInt($(".photo-container")[0].clientWidth);
        if ($(this).hasClass("left")) var step=123; else var step=-123;
        if (!$(this).hasClass("second") && ((step>0 && cs>=0) || (step<0 && cs<=w-wd))) return false;
        if ($(this).hasClass("second") && ((step>0 && cs>=0) || (step<0 && cs<=615-wd))) return false;

        if (!$(this).hasClass('second')) $(".photo-placeholder .photo-scroller").animate({left: (cs+step)+"px"}, "fast");
        else $(".popupPic .photo-scroller").animate({left: (cs+step)+"px"}, "fast");
    });

    photoResizer();

    $(".popupPic .close").click(function() { $(".popupPic").fadeOut("slow"); });
    $(".popupMap .close").click(function() { $(".popupMap").fadeOut("slow"); });

    $(".photo-placeholder .photo-scroller div.image").click(function() {
        $(".popupPic").fadeIn("slow");
        setPicture(this.getElementsByTagName("img")[0].src);
    });
    $(".popupPic .photo-scroller div.image").click(function() {
        setPicture(this.getElementsByTagName("img")[0].src);
    });

    $(".googleMap").each(function() {
        if (GBrowserIsCompatible()) {
                map = new GMap2(this);

                map.addControl(new GMapTypeControl());
                map.addControl(new GLargeMapControl());
                map.enableScrollWheelZoom();

                marker = new GMarker(new GLatLng(0,0));
                map.addOverlay(marker);

                $(".popupMap").hide();
        }
    });

    $("#commentsBlock").each(function() {
        getComments(1);
    });


    $(".sendSberbank").click(function() {
        sendSberbank();
        return false;
    });

    $(".bookmark").click(function() {
        return add2Fav(this);
    });

    if (window.opera) {
        $("select.time").css({'top': '2px'});
    }
    if (navigator.appVersion.match(/MSIE/)) {
//        if (!navigator.appVersion.match(/MSIE\s6/)) $("select.time").css({'top': '4px'});
    }

    if ($(".full-map").length>0) {
        setAllFlatsOnMap();
    }

    if (windowHeight()<=600) {
        $(".popupPic").add(".popupMap").css({top: '0px', 'margin-top': '0px'});
    };

    $(".checkrequired").click(function(e) {
        var x = this;

        while (x.tagName.toLowerCase()!="form" && x.tagName.toLowerCase()!="body") x = x.parentNode;
        if (x.tagName.toLowerCase()!="form") return false;

        var req =$(x).find(".required");

        for (var i=0; i<req.length; i++) {
            if (req[i].value.replace(/\s/, '')=="") {
                alert("Заполнены не все обязательные поля!");
                $(req[i]).css({borderColor: "red"});
                req[i].onkeydown = function() { $(this).css({borderColor: ''}); }
                req[i].onmouseover = function() { $(this).css({borderColor: ''}); }
                req[i].focus();
                return false;
            }
        }

        x.submit();

        return false;
    });
});

var photoResizer = function() {
    var p = $(".photo-container");
    if (p.length==0) return false;
    var w = p[0].clientWidth;
    $(".photo-placeholder .photo-container .window").css({width: (w-60)+"px"});
}

window.onresize = photoResizer;

var setPicture=function(src) {
    var src2 = src.replace(/w\=(\d+)/, 'w0=600');
        src2 = src2.replace(/h\=(\d+)/, 'h=410');
    $(".full-photo-view").css({backgroundImage: "url("+src2+")"});
}

var showMap = function(lat, lng) {
    var center = new GLatLng(lat, lng);
    map.setCenter(center, 15);
    marker.setLatLng(center);

    if (!navigator.appVersion.match(/MSIE\s6/)) $(".popupMap").css({opacity: 1, left: "50%"});
    $(".popupMap").fadeIn("slow");
}

var sendComment = function() {
    if ($("#commentUserName")[0].value.replace(/\s/g, '') == "") {
        $(".errors").html("Представьтесь, пожалуйста");
        $("#commentUserName")[0].focus();
        return false;
    }

    if ($("#commentMessage")[0].value.replace(/\s/g, '') == "") {
        $(".errors").html("Пожалуйста, напишите что-нибудь.");
        $("#commentMessage")[0].focus();
        return false;
    }

    if ($("#commentCapcha")[0].value.replace(/\s/g, '') == "") {
        $(".errors").html("Введите код, указанный на картинке");
        $("#commentCapcha")[0].focus();
        return false;
    }

    $.ajax({
        url: "/sendComment.php",
        data: { username: $("#commentUserName")[0].value, 
                message: $("#commentMessage")[0].value, 
                capcha: $("#commentCapcha")[0].value,
                flatID: $("#flatId")[0].value
        },
        success: function(msg) {
            switch (msg) {
                case "Bad capcha": 
                        $(".errors").html("Вы ввели неправильный код. Повторите, пожалуйста.");
                        $("#commentCapcha")[0].value = "";
                        $("#capchaimg")[0].src = "/capcha.php?"+Math.random();
                    break;
                case "Ok":
                        $(".sendMessage").css({visibility: "hidden"});
//                        $(".errors").css({marginBottom: "50px"});
                        $(".errors").html("Ваше сообщение успешно отправлено!<br/>Оно появится на сайте после проверки модератором.");
                    break;
                default: alert(msg);
            }
        }
    });
}

var getComments = function(pageN, xl) {
    var b = $("#commentsBlock");
    if (b.length==0) return false;
    if (!xl) xl = 0;

    currentCommentsPage = pageN;

    $.ajax({
        url: "/getComments.php",
        data: {
            flat: $("#flatId")[0].value,
            page: pageN,
            x: xl
        },
        success: function(msg) {
            $("#commentsBlock").html(msg);
            $(".pagenumber").add(".pageservice").add(".board a").each(function() {
                this.href="javascript: void(0);";
            });
            $(".pagenumber").click(function() {
                var p = this.id.replace(/\D/g, '');
                    getComments(p);
            });

            $(".messages li").hover(function() {
                var i = this.id.replace(/\D/g, '');
                    $("#a_"+i).animate({opacity: 1});
            }, function() {
                var i = this.id.replace(/\D/g, '');
                    $("#a_"+i).animate({opacity: 0});
            });

            $(".messageDelete").click(function() {
                var i = this.id.replace(/\D/g, '');
                if (confirm("Вы действительно хотите удалить сообщение?")) {
                    $.ajax({
                        url: "/sendComment.php",
                        data: { m: "delete", flat: $("#flatId")[0].value, id: i },
                        success: function(msg) {
                            getComments(currentCommentsPage);
                        }
                    });
                };
            });

            $(".messageShow").click(function() {
                var i = this.id.replace(/\D/g, '');
                $.ajax({
                    url: "/sendComment.php",
                    data: { m: "show", flat: $("#flatId")[0].value, id: i },
                    success: function(msg) {
                        getComments(currentCommentsPage);
                    }
                });
            });

            $(".messageHide").click(function() {
                var i = this.id.replace(/\D/g, '');
                $.ajax({
                    url: "/sendComment.php",
                    data: { m: "hide", flat: $("#flatId")[0].value, id: i },
                    success: function(msg) {
                        getComments(currentCommentsPage);
                    }
                });
            });

        }
    });
}

var switchAdmMode = function() {
    getComments(currentCommentsPage, 1);
}

var sendSberbank = function() {
    if ($("#userName")[0].value.replace(/\s/, '')=='') {
        alert ("Укажите ФИО");
        $("#userName").focus();
        return false;
    }
    if ($("#userAddress")[0].value.replace(/\s/, '')=='') {
        alert ("Укажите адрес");
        $("#userAddress").focus();
        return false;
    }
    if ($("#userFlat")[0].value.replace(/\s/, '')=='') {
        alert ("Укажите назначение платежа");
        $("#userFlat").focus();
        return false;
    }
    if ($("#userAmount")[0].value.replace(/\D/, '')=="") {
        alert ("Укажите сумму платежа");
        $("#userAmount").focus();
        return false;
    }

    $(".usual2").fadeOut("slow");
    var kvt = open("/sb.php?userName=" + $("#userName")[0].value + "&" +
                           "userAddress=" + $("#userAddress")[0].value + "&" +
                           "userFlat=" + $("#userFlat")[0].value + "&" +
                           "amount=" + $("#userAmount")[0].value + "&" + 
                           "msie=" + (navigator.appVersion.match(/MSIE/)),
                    "kvtf",
                    "width=800,height=600,scrollbars=no,status=no,toolbar=no,location=no,directories=no,menubar=no,resizable=no");
        kvt.focus();
}

var add2Fav = function (x){
    if (document.all  && !window.opera) {
         if (typeof window.external == "object") {
            window.external.AddFavorite (document.location, document.title);
            return true;
          }
          else return false;

    }
    else{
        x.href=document.location;
        x.title=document.title;
        x.rel = "sidebar";
        return true;
    }
}

var setAllFlatsOnMap = function() {
    $.ajax({
        url: "/getFlats.php",
        success: function(msg) {
            eval(msg);

            lat = 59.95; long=30.316666676667;

            map = new GMap2($(".full-map")[0]);
            var center = new GLatLng(lat, long);
            map.setCenter(center, 12);

            map.enableScrollWheelZoom();
            map.addControl(new GMapTypeControl());
            map.addControl(new GLargeMapControl());


            for (var i=0; i<allFlats.length; i++) {
                allFlats[i].marker = new GMarker(new GLatLng(allFlats[i].position.latitude,allFlats[i].position.longitude));

                var price = 0;
                if (allFlats[i].pricesp>0) {
                    price = "<s>"+allFlats[i].price + " руб.</s><br><span style='color: red;'>"+allFlats[i].pricesp+" руб.</span>";
                } else {
                    price = allFlats[i].price + " руб.";
                }
                var content = "<div class='infoWindow'><h1>"+allFlats[i].address+"</h1>";
                    content+= "<table><tr><td align='right'><strong>Комнат: </strong></td><td>"+allFlats[i].rooms+"</td></tr>";
                    content+= "<tr><td align='right'><strong>Этаж: </strong></td><td>"+allFlats[i].floor+"</td></tr>";
                    content+= "<tr><td align='right'><strong>Спальных мест: </strong></td><td>"+allFlats[i].beds+"</td></tr>";
                    content+= "<tr><td valign='top' align='right'><strong>Цена: </strong></td><td>"+price+"</td></tr>";
                    content+= "</table></div>";
                allFlats[i].marker._defaultContent = content;
                allFlats[i].marker._link = allFlats[i].link;
                map.addOverlay(allFlats[i].marker);
                GEvent.addListener(allFlats[i].marker, "mouseover", function() {
                    this.openInfoWindowHtml(this._defaultContent);
                });

                GEvent.addListener(allFlats[i].marker, "mouseout", function() {
                    this.closeInfoWindow();
                });

                GEvent.addListener(allFlats[i].marker, "click", function() {
                    location.href = this._link;
                });
            }            
        }
    });
}

var windowHeight = function() {
var de = document.documentElement;

return self.innerHeight || ( de && de.clientHeight ) || document.body.clientHeight;
}
