﻿jQuery(function($) {
    var $parent = $("#ourVitrin");
    var aClass = "hotelAnchor";
    var root = "";

    var helper = {
        onReadyHandler : function() {
            $.ajaxSetup({
                'beforeSend': function(xhr) {
                    xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
                }
            });

            var host = window.location.host;
            var zone = "." + host.split(".").pop();
            root = "http://" + host.substring(0, host.indexOf(zone) + zone.length);

            renderMakeup();
            helper.createBlocks();
        },

        createBlocks : function() {
            this.createBlock(root + "/xml/xml_1_3.xml", null, 1, 1);
            this.createBlock(root + "/xml/xml_1_4.xml", null, 3, 1);
            this.createBlock(root + "/xml/xml_1_5.xml", null, 5, 1);

            this.createBlock(root + "/xml/xml_2_3.xml", null, 1, 2);
            this.createBlock(root + "/xml/xml_2_4.xml", null, 3, 2);
            this.createBlock(root + "/xml/xml_2_5.xml", null, 5, 2);

            this.createBlock(root + "/xml/xml_3_3.xml", null, 1, 3);
            this.createBlock(root + "/xml/xml_3_4.xml", null, 3, 3);
            this.createBlock(root + "/xml/xml_3_5.xml", null, 5, 3);
        },

        createBlock : function(xmlPath, errback, numberBlock, numberVitrin) {
            $.ajax({
                url : xmlPath,
                timeout : 30000,
                success : function(data) {
                    var json = $.xmlToJSON(data);
                    renderBlock(json["tour"], numberBlock, numberVitrin);
                    renderBlock(json["tour"], numberBlock + 1, numberVitrin);
                },
                error: function (response, status, error) {
                    if (errback) {
                        errback(response, status, error);
                    } else {
                        var errorTxt = "";
                        if ($.browser["msie"]) {
                            return;
                        }
                        if (response && response.status && response.statusText) {
                            errorTxt = "Error with code " + response.status + "\n" +
                                    "and desciption \"" + response.statusText + "\"" +
                                    "\noccured and request is failed!";
                        } else {
                            errorTxt = "Unknown error!";
                        }
                        //throwException(errorTxt);
                    }
                }
            });
        }
    };

    function renderBlock(json, numberBlock, numberVitrin) {
        if (json) {
            //            json = json[numberBlock - 1];
            var cls = "";
            if (numberBlock % 2 != 0) {
                json = json[0];
                cls = "vitrina-left";
            } else {
                json = json[1];
                cls = "vitrina-right";
            }
            var $vitrin = $parent.find(".vitrina").eq(numberVitrin - 1);
            var $block;
            if (numberBlock == 1 || numberBlock == 2) {
                $block = $vitrin.find("." + cls).eq(0);
            } else if (numberBlock == 3 || numberBlock == 4) {
                $block = $vitrin.find("." + cls).eq(1);
            } else if (numberBlock == 5 || numberBlock == 6) {
                $block = $vitrin.find("." + cls).eq(2);
            }
            var numImg = numberBlock + (numberVitrin - 1) * 6;
            if (numImg < 10) {
                numImg = "0" + numImg;
            }
            //            $block.find("img").attr("src", root + "/xml/" + "vitrina_city" + defaultCity + "/img/" + "img_" + numImg + ".jpg");
            //            $block.find("img").attr("src", root + "/xml/" + "vitrina_city" + defaultCity + "/img/" + "img_" + numImg + ".jpg");
            $block.find("img").attr("src", (json["hotel_preview"] && json["hotel_preview"][0]) ? getPropValue(json["hotel_preview"][0], "Text") : "http://new.legkotur.ru/search2/img/tur.jpg");

            var resortName = getPropValue(json["resort"][0], "Text");
            $block.find("H3").html(resortName);

            var countryName = getPropValue(json["country"][0], "Text").toLowerCase();
            countryName = countryName.charAt(0).toUpperCase() + countryName.substr(1);
            var cityfrom = getPropValue(json["cityfrom"][0], "Text").toLowerCase();
            cityfrom = cityfrom.charAt(0).toUpperCase() + cityfrom.substr(1);
            $vitrin.find("H2").html(countryName+" ("+cityfrom+")");

            var htmlHotel = renderHotel(json);
            $block.find("P").eq(0).html(htmlHotel);

            var departure = getPropValue(json["departure"][0], "Text");
            var nights = getPropValue(json["nights"][0], "Text") + "н.";
            var secondParHtml = "с " + departure + " на " + nights;
            $block.find("P").eq(1).html(secondParHtml);

            var price = "<span style='text-decoration:line-through; display:inline;'>" + renderPrice(json) + "</span>";
            var discount = renderDiscount(json) + " " + renderMeasure(json);
            $block.find("SPAN").eq(0).html(price + " " + discount);

            $block.find(".orderButton").click(function() {
                openTourForm(json, false);
            });

            $block.find(".creditButton").click(function() {
                openTourForm(json, true);
            });
        } else {
            throwException("in renderBlock json is null!");
        }
    }

    function openTourForm(json, credit) {
        var turObj = {
            credit : credit,
            adults : 2,
            children : 0
        };
        var tObj = {};
        for (var name in json) {
            if (json.hasOwnProperty(name) && json[name].length && json[name][0] && json[name][0].Text) {
                tObj[name] = json[name][0].Text;
            }
        }
        $.extend(turObj, tObj);
        turObj.economValues = turObj.econom;
        $.cookie("tour", JSON.stringify(turObj), {path: '/search2/', domain: '.legkotur.ru'});
        window.open("http://new.legkotur.ru/search2/tour.html");
        return false;
    }

    function renderHotel(data) {
        var a = "<a href='#' class='" + aClass + "' desc='" + getPropValue(data["hotel"][0], "ruspodesc") + "'>";
        return a + (toOneLine(getPropValue(data["hotel"][0], "Text")) + "</a>").toLowerCase();
    }

    function toOneLine(string) {
        if (string && string.length > 27) {
            if (string.indexOf("*") == string.length - 1) {
                string = string.substr(0, 22) + "..." + string.substr(string.length - 3, 3);
            } else {
                string = string.substr(0, 25) + "...";
            }
        }
        return string;
    }

    function renderMeasure(elem) {
        var res = "руб/";
        if (getPropValue(elem["pricetype"][0], "Text").toLowerCase() == "man") {
            res += "чел";
        } else {
            res += "комн";
        }
        res = "руб./тур на двоих";
        return res;
    }

    function renderPrice(elem) {
        return getPropValue(elem["price"][0], "Text");
    }

    function renderDiscount(elem) {
        var discount = 0;
        var price = renderPrice(elem);
        if (price < 30000) {
            discount = Math.ceil(price * (100 - 3) / 100);
        } else if (price >= 30000 && price < 60000) {
            discount = Math.ceil(price * (100 - 5) / 100);
        } else {
            discount = Math.ceil(price * (100 - 5) / 100);
        }
        return discount;
    }

    function getPropValue(obj, propName) {
        return obj["@" + propName] || obj[propName];
    }

    function throwException(errMsg) {
        alert(errMsg);
        throw errMsg;
    }

    function renderMakeup() {
        var clearDiv = '<div class="vitrina-clear"></div>';
        var vitrinHeader = '<h2><img src="" align="bottom" />Россия</h2>';
        var vitrinBlockContent =
                '<h3>&nbsp;</h3>' +
                        '<div class="vitrina-image">' +
                        '<img class="imageImitator">&nbsp;</img>' +
                        '</div>' +
                        '<div class="vitrina-text">' +
                        '<p>&nbsp;</p>' +
                        '<p>&nbsp;</p>' +
                        '<span>&nbsp;</span>' +
                        '<input class="orderButton" type="button" value="Заказать"/>' +
                        '<input class="creditButton" type="button" value="В кредит"/>' +
                        '</div>';
        var leftVitrinaDiv = '<div class="vitrina-left">' + vitrinBlockContent + '</div>';
        var rightVitrinaDiv = '<div class="vitrina-right">' + vitrinBlockContent + '</div>';
        var rowDiv = clearDiv + leftVitrinaDiv + rightVitrinaDiv;
        var vitrinaDiv = '<div class="vitrina">' + vitrinHeader + rowDiv + rowDiv + rowDiv + clearDiv + '</div>';
        var html = clearDiv + '<h2>Витрина низких цен:</h2>' + vitrinaDiv + clearDiv + vitrinaDiv + clearDiv + vitrinaDiv + clearDiv;
        $parent.html(html);

        $("A." + aClass).live("click", function() {
            var desc = $(this).attr("desc");
            window.open(desc);
            return false;
        });
    }

    helper.onReadyHandler();
});
