﻿//var baseUrl = "http://www.delfin-tour.ru/TursSearchEngine/";
var colDateTo = "Выезд из Москвы";
var colPeriod = "Проживание";
var colPeriodFreeBout = "Проживание в любой день указанного периода";
var colDateFrom = "Прибытие в Москву";

var exp = 0;
var first = true;
function load() {
    if (!first)
        return;
    first = false;
    try {
        if (document.URL.indexOf("www.", 0) < 0)
            baseUrl = baseUrl.replace('www.', '');
    }
    catch (e) { }

    try {
        exp = eval(getQVar("export"));
        var agent = parseInt(getQVar("agent"), 10);
        var paramStr = "";
        if (agent != -1)
            paramStr += "&agent=" + agent;
        try {
            var tstr = "" + location.href;
            sindex = (tstr.length > 199) ? 199 : tstr.length;
            paramStr += "&curl=" + escape(tstr.substring(0, sindex));
            if (location.href != parent.location.href) {
                tstr = "" + parent.location.href;
                sindex = (tstr.length > 199) ? 199 : tstr.length;
                paramStr += "&parUrl=" + escape(tstr.substring(0, sindex));
            }
        } catch (e) { }
        var TurTbls = eval("[" + requireText(baseUrl + "TurDetails.ashx?key=" + document.getElementById("id_Tur").value + paramStr) + "]")[0];
        fillTbls(TurTbls);
        initVirtualTur(TurTbls.IdVirtTur);
    }
    catch (e) {
        //if (lastErr != "err")
        //alert(e);
    }

}


function initVirtualTur(id) {
    if (id == null || id == "")
        return;
    $("head").append('<style type="text/css"> .visualhotels-previews tr td a, .visualhotels a, .visualhotels-copyright a {color:#000099;} .visualhotels-copyright, .visualhotels-sections ul li, .visualhotels h1 {color:#666666;} .visualhotels, .visualhotels-previews tr td img, .visualhotels-panorama, .visualhotels-sections ul li.selected {border:#cccccc 1px solid; background-color:#ffffff;}.visualhotels2 {border:#666666 1px solid; background-color:#fafafa;} </style>' +
    '<link rel="stylesheet" type="text/css" href="http://visualhotels.com/vhtour/style/style.css">');
    //$("body").append('<div id="visualhotels_virtualtour" style="overflow-x: hidden; overflow-y: hidden; outline-width: 0px; outline-style: initial; outline-color: initial; height: auto; position: absolute; top: 0px; left: 0px; z-index: 1002; display:none;" ></div>'); //width:350px;position:relative;left:-175px; margin-left:50%;
    $("body").append('<div id="visualhotels_virtualtour" style="position:absolute;overflow:hidden;top:10px;left:20px;  display:none;" ></div>'); //width:350px;position:relative;left:-175px; margin-left:50%; 
var js_ = document.createElement('script');
js_.type = 'text/javascript';
js_.charset = "windows-1251";
js_.src = "http://visualhotels.com/vhtour/_vt.js.php?p=371&l=ru&h="+id;

document.getElementsByTagName('head')[0].appendChild(js_);
    //$.getScript("http://visualhotels.com/vhtour/_vt.js.php?p=371&l=ru&h=" + id);

    var a = $("#main-column").find("b:contains('Все фото')"); //img[src*=bull2.gif]");
    $(a[0].parentNode.parentNode).append('<br /><a href="#" onclick="showVirtualTur()" style=" line-height:20px;"><nobr><img src="http://visualhotels.com/img/eye/visualhotels_px.gif">' +
    '<b> Виртуальный тур</b></nobr></a>');

}
function showVirtualTur() {
    if (window.VH_ShowTour) {
        VH_ShowTour(1);
        $("#visualhotels_virtualtour").find("fieldset").remove();
        document.getElementById('visualhotels_virtualtour').style.display = 'block';
        window.VH_OnResize = function() {
            if (visualhotels_isfull) // full screen
            {
                var ml = document.getElementById('visualhotels_virtualtour');
                var ic = document.getElementById('visualhotels-inner-container');
                var pc = document.getElementById('panorama-container');
                ml.style.top = '0px';
                ml.style.left = '0px';
                var width = VH_GetW();
                var height = VH_GetH();
                visualhotels_panoramawidth = width - 222;
                visualhotels_panoramaheight = height - 75;
                ic.style.width = (width - 20) + 'px';
                ic.style.height = (height - 20) + 'px';
                pc.style.width = (width - 222) + 'px';
                pc.style.height = (height - 75) + 'px';
                pc.innerHTML = VH_GetFlash(visualhotels_currentsrc);
            }
            else // not full screen
            {
                var ml = document.getElementById('visualhotels_virtualtour');
                var width = VH_GetW();
                var height = VH_GetH();
                var left = parseInt((width - 698) / 2);
                var top = parseInt((height - 424) / 2);
                ml.style.top = top + 'px';
                ml.style.left = left + 'px';
            }
        }
        VH_OnResize();
        window.onresize = VH_OnResize;
    }
}

function requireText(url) {
    res = "";
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest;
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                document.getElementById("NoActiveX").style.cssText = "";
            }
        }
    } else {
        //alert("Your browser doesn't support AJAX");
        return;
    }

    if (req) {
        req.open("GET", url, false);
        req.send(null);
        res = req.responseText;
        lastErr = "ok";
    }
    if (req.status != 200) {
        //alert('Сервис поисковика недоступен!');
        lastErr = "err";
    }
    return res;
}

function getQVar(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "-1";
    else {
        //alert(name + " = " + results[1]);
        return results[1];
    }
}

var lastErr = "ok";

function newElement(type, text, attrName, attrVal) {
    var cell = document.createElement(type);
    if (text != null)
        cell.appendChild(document.createTextNode(text))
    if (attrName != null)
        cell.setAttribute(attrName, attrVal);
    return cell;
}
function newCubeCell(text, freePlaces, url, Fiery) {
    var el = newElement("td");
    var center = newElement("center");
    var miniTbl = newElement("table");
    var tblBody = document.createElement("tbody");
    var row = newElement("tr");
    var td1 = newElement("td");

    var priceSpan = newElement("span", text);
    priceSpan.setAttribute("price", text);
    var a;
    if (exp > 0)
        a = priceSpan; //document.createTextNode(text);
    else {
        a = newElement("a", null, "href", url);
        a.setAttribute("title", "Забронировать");
        a.setAttribute("target", "_blank");

        a.appendChild(priceSpan);
    }
    td1.appendChild(a);
    if (Fiery == "1")
        td1.className = "Fiery";
    var td2 = newElement("td");

    if ((freePlaces == "-") || (text == "-") || (text == ""))
        ;
    else if (freePlaces == "")
        td2.className = "place_byRequest";
    else if (eval(freePlaces) <= 0)
        td2.className = "place_no";
    else if (eval(freePlaces) == 1)
        td2.className = "place_one";
    else
        td2.className = "place_available";

    row.appendChild(td1);
    row.appendChild(td2);
    tblBody.appendChild(row);
    miniTbl.appendChild(tblBody);
    center.appendChild(miniTbl)
    el.appendChild(center);
    return el;
}

function calcPrices(priceType) {
    try {
        var imgs = document.getElementById("currencies").getElementsByTagName("img");
        for (var i = 0; i < imgs.length; i++) { imgs[i].height = 11; imgs[i].width = 16; }
        imgs[priceType + 1].height = 20; imgs[priceType + 1].width = 29;
        var priceSpans = document.getElementById("tblsDiv").getElementsByTagName("span");
        if (priceType == -1)
            document.getElementById("currencyVal").innerHTML = " (конвертирование по курсу: <b>1</b> RUR/RUR)";
        else
            document.getElementById("currencyVal").innerHTML = " (конвертирование на " + currencies[priceType].Date + " по курсу ЦБ РФ-1%: <b>" + currencies[priceType].Value + " </b> " + currencies[priceType].Code + "/RUR)";

        var cur = (priceType == -1) ? 1.0 : eval(currencies[priceType].Value);
        for (var i = 0; i < priceSpans.length; i++) {
            var price = eval(priceSpans[i].getAttribute("price"));
            if (price)
                priceSpans[i].innerHTML = "" + parseInt(price / cur);
        }
    }
    catch (e) {
        alert(e);
    }
}
var currencies;
function initCurrencies() {
    try {
        var currenciesDiv = document.getElementById("currencies");
        for (var i = 0; i < currencies.length; i++) {
            var el = newElement("img", null, "src", baseUrl + currencies[i].ImgUrl);
            el.setAttribute("title", currencies[i].Name);
            el.style.cursor = "pointer";
            eval("el.onclick = function() { calcPrices(" + i + "); };");
            currenciesDiv.appendChild(document.createTextNode("  "));
            currenciesDiv.appendChild(el);
        }
        var el = newElement("span", null, "id", "currencyVal");
        el.innerHTML = " (конвертирование по курсу: <b>1</b> RUR/RUR)";
        currenciesDiv.appendChild(el);
    }
    catch (e) {
        alert(e);
    }
}

function checkHref(div, txt) {
    try {
        var a = div.getElementsByTagName("a")[0];
        if (a&&(a.href.indexOf("/.html", 0) > 0) /*|| (exp > 0)*/)
            a.parentNode.innerHTML = a.innerHTML + ". ";
        if (txt == null || txt == '')
            txt = 'Стоимость на человека <b>за заезд</b>, руб';
        if (txt.length > 1)
            div.innerHTML = div.innerHTML + " " + txt;
    } catch (e) { }
}


var maxCol = 5;
var turType = "1";
function fillTbls(TurTbls) {
    turType = TurTbls.Type;
    currencies = TurTbls.currencies;
    initCurrencies();
    maxCol = (turType == "1") ? 5 : 7;
    var tbls = document.getElementById("tblsDiv");
    //document.title = TurTbls.Name;

    var divs = tbls.getElementsByTagName("div");
    for (var i = 0; i < TurTbls.turDetails.length; i++) {
        var curDiv = tbls;
        for (var k = 0; k < divs.length; k++) {
            if (divs[k].getAttribute("HDID") == TurTbls.turDetails[i].Id) {
                curDiv = divs[k];
                checkHref(curDiv, TurTbls.turDetails[i].CaptionText);
                break;
            }
        }
        var rooms = TurTbls.turDetails[i].Rooms;
        var c = 0, st = 0, predC = 0;
        for (var j = 0; j < rooms.length; j++) {
            c += rooms[j].CostsByCategory.length;
            if (((c >= maxCol) || (predC >= maxCol)) && (rooms.length >= 2) && (j > 0)) {
                predC = c;
                c = 0;
                fillTbl(curDiv, TurTbls.turDetails[i], st, j);
                st = j;
            }
        }
        fillTbl(curDiv, TurTbls.turDetails[i], st, rooms.length);
    }
}

function fillTbl(tbls, TurDetails, st, len, st2, len2) {
    if (st == null) {
        st = 0;
        len = TurDetails.Rooms.length;
    }

    if (((len - st) == 1) && (st2 == null)) {
        var categLen = TurDetails.Rooms[st].CostsByCategory.length
        if (categLen >= maxCol) {
            fillTbl(tbls, TurDetails, st, len, 0, (categLen / 2) | 0);
            fillTbl(tbls, TurDetails, st, len, (categLen / 2) | 0, categLen);
            return;
        }
    }

    var tbl = newElement("table", null, "width", "100%");
    tbl.appendChild(newElement("thead"));
    tbl.appendChild(newElement("tbody"));

    if (len <= 0) {
        tbl.appendChild(newElement("caption", "Нет данных"));
        return;
    }

    //tbl.appendChild(newElement("caption", TurDetails.Name));
    var tblBody = tbl.getElementsByTagName("tbody")[0]; //document.createElement("tbody");
    var row = newElement("tr");
    var row2 = newElement("tr");

    //формируем заголовок для дат

    if (turType == "1") {//если тур является экскурсионным
        var cell = newElement("th", colDateTo, "rowSpan", "2");
        cell.setAttribute("width", "10%");
        row.appendChild(cell);
    }

    if (turType == "3") {
        cell = newElement("th", colPeriodFreeBout, "rowSpan", "2");
        cell.setAttribute("width", "10%");
        cell.setAttribute("style", "font-size:10px");
        row.appendChild(cell);
    }
    else {
        cell = newElement("th", colPeriod, "rowSpan", "2");
        cell.setAttribute("width", "10%");
        row.appendChild(cell);
    }

    if (turType == "1") {//если тур является экскурсионным
        cell = newElement("th", colDateFrom, "rowSpan", "2");
        cell.setAttribute("width", "10%");
        row.appendChild(cell);
    }

    for (var i = st; i < len; i++) {
        var room = TurDetails.Rooms[i];
        row.appendChild(newElement("th", room.Name, "colSpan", room.CostsByCategory.length));
        for (var j = (len2 ? st2 : 0); j < (len2 ? len2 : room.CostsByCategory.length); j++) {
            //row2.appendChild(newElement("th", room.CostsByCategory[j].Name));
            var el = newElement("th", room.CostsByCategory[j].Name);
            el.className = "tblHeader2";
            row2.appendChild(el);
        }
    }
    row.className = "tblHeader1";
    //row2.className = "tblHeader2";

    var thead = tbl.getElementsByTagName("thead")[0];
    thead.appendChild(row);
    thead.appendChild(row2);

    var rowCol = false;
    for (var k = 0; k < TurDetails.turDates.length; k++) {

        row = newElement("tr");

        if (turType == "1") //если тур является экскурсионным
            row.appendChild(newElement("td", TurDetails.turDates[k].DateTo));
        var el = newElement("td");
        el.className = "turDates";
        el.innerHTML = '<nobr>&nbsp;' + TurDetails.turDates[k].Date + '&nbsp;</nobr>';
        row.appendChild(el);
        if (turType == "1") //если тур является экскурсионным
            row.appendChild(newElement("td", TurDetails.turDates[k].DateFrom));
        var isNotEmpty = false;
        for (var i = st; i < len; i++) {
            var room = TurDetails.Rooms[i];
            for (var j = (len2 ? st2 : 0); j < (len2 ? len2 : room.CostsByCategory.length); j++) {
                row.appendChild(newCubeCell(room.CostsByCategory[j].Costs[k],
				room.CostsByCategory[j].FreePlaces[k], room.CostsByCategory[j].URLs[k], room.CostsByCategory[j].Fiery[k]));
                if (room.CostsByCategory[j].Costs[k] != "")
                    isNotEmpty = true;
            }
        }

        if (isNotEmpty) {
            row.className = (/*(k % 2) == 0*/rowCol ? "tblEvenRow" : "tblOddRow");
            rowCol = !rowCol;
            tblBody.appendChild(row);
        }
    }
    tbl.appendChild(tblBody);
    tbls.appendChild(tbl);
    tbls.appendChild(newElement("br"));
}

///////////////////////////////////load///////////////////////////////////////////////
/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", load, false);
}

/* for Internet Explorer */
/*@cc_on@*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        load(); // call the onload handler
    }
};
/*@end@*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            load(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = load;
