﻿document.observe("dom:loaded", OnDocumentLoad);

function ResolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

function OnDocumentLoad(evObj) {

    $$("body")[0].select("fieldset>div>.text").each(function (item) {
        new TextBoxExtender(item);
    }, this);

    $$("body")[0].select("fieldset>div>.drop").each(function (item) {
        new DropDownExtender(item);
    }, this);

    $$("body")[0].select("fieldset>div>.date").each(function (item) {
        new DateSelectorExtender(item);
    }, this);

    $$("body")[0].select("fieldset>div>.radio").each(function (item) {
        if (item.down("input").readAttribute("type") == "radio") {
            new RadioBoxExtender(item);
        }
        else {
            new CheckBoxExtender(item);
        }
    }, this);

    $$("body")[0].select("ul.tabNavigation").each(function (item) {
        new TabNavigation(item);
    }, this);

    $$("body")[0].select("img.tooltip").each(function (item) {
        new TooltipExtender(item.id, item, item.alt, "tooltip");
        item.alt = null;
    }, this);

    $$("body")[0].select("a.popup").each(function (item) {
        new PopupExtender(item);
    }, this);

    $$("a.scroll").each(function (item) {
        if ($(item.href.split("#")[1])) {
            item.TargetElement = $(item.href.split("#")[1]);
            item.href = "javascript:void(0);";
            Event.observe(item, "click", function (evObj) {
                var a = ($(Event.element(evObj)).up("a"))
		            ? $(Event.element(evObj)).up("a")
		            : $(Event.element(evObj));
                Effect.ScrollTo(a.TargetElement, { duration: '1', offset: 0 });
                a.blur();
            });
        }
    }, this);

    if ($("Banner")) {
        var pictures = new Array();
        pictures.push(ResolveUrl("~/images/banner/winter-1.jpg"));
        pictures.push(ResolveUrl("~/images/banner/winter-2.jpg"));
        pictures.push(ResolveUrl("~/images/banner/winter-3.jpg"));
        pictures.push(ResolveUrl("~/images/banner/winter-4.jpg"));
        pictures.push(ResolveUrl("~/images/banner/winter-5.jpg"));


        new BannerExtension(pictures);
    }

    if ($("AvCalendar")) {
        new CalendarConnector(new CalendarExtender($("AvCalendar")),
            FormElementExtender.Elements.get("txtArrivalDate"),
            FormElementExtender.Elements.get("txtWeeks"),
            FormElementExtender.Elements.get("txtPax"));

    }

    if ($("KeywordAutoComplete"))
        $("KeywordAutoComplete").hide();

    if ($("txtFullTextSearchContent"))
        new Ajax.Autocompleter($("txtFullTextSearchContent").down("input").id, "KeywordAutoComplete", baseUrl + languageCode + "/ul/Keyword.aspx", { paramName: "text" });

    if ($("LocationForm"))
        InitLocationSearch();

    if ($("DetailPictures"))
        new GalleryExtender($("DetailPictures"));

    if ( $("SearchInfo") )
    {
        Effect.BlindUp("SearchInfo", { duration: 0.5 });
        Event.observe($("TitleSearchInfo"), "click", function (evObj) {
            if ( $("SearchInfo").getStyle("display") == "block" )
                Effect.BlindUp("SearchInfo", {duration: 0.2});
            else
                Effect.BlindDown('SearchInfo', { duration: 0.2 });
        }, this);
    }

    if ( $("Navigation") && $("Content") )
        new StoredObjectsExtender();

    if ($("ObjectHistory"))
        new ObjectHistoryExtender($("ObjectHistory"));

    CorrectLayout();
    Event.observe(window, "resize", OnWindowResize);
}

function OnWindowResize(evObj) {
    CorrectLayout();
}

function CorrectLayout() {
    viewportProp = new ViewportProperties();

    if ($("Page")) {
        $("Page").setStyle({ height: ((viewportProp.DocHeight > viewportProp.WindowHeight) ? "auto" : viewportProp.WindowHeight + "px") });
    }
}

/********** FORM EXTENDER **********/
var FormElementExtender = Class.create(
{
    initialize: function (item) {
        this.Item = item;

        if (FormElementExtender.Elements == null)
            FormElementExtender.Elements = new Hash();

        FormElementExtender.Elements.set(item.id, this);

        var div = new Element("div");
        div.addClassName("inactivation");

        this.Item.insert(div);
    },

    RefreshElement: function (item) {
        this.Item = item;

        if (!this.Item.down(".inactivation")) {
            var div = new Element("div");
            div.addClassName("inactivation");

            this.Item.insert(div);
        }
    },

    Element: function () {
        return this.Item;
    },

    RemoveClassName: function (className) {
        if (this.Item.hasClassName(className))
            this.Item.removeClassName(className);
    },

    AddClassName: function (className) {
        if (!this.Item.hasClassName(className))
            this.Item.addClassName(className);
    },

    Enable: function () {
        this.RemoveClassName("disabled");
    },

    Disable: function () {
        this.AddClassName("disabled");
    },

    Confirm: function () {
        this.AddClassName("confirmed");
    },

    Unconfirm: function () {
        this.RemoveClassName("confirmed");
    },

    Select: function () {
        this.AddClassName("active");

        this.Unconfirm();
    },

    Deselect: function () {
        this.RemoveClassName("active");

        if (!this.IsEmpty())
            this.Confirm();
        else
            this.Unconfirm();
    },

    IsSelected: function () {
        return this.Item.hasClassName("active");
    },

    IsEmpty: function () {
        return true;
    }
});

var TextBoxExtender = Class.create(FormElementExtender, {
    initialize: function ($super, item) {
        $super(item);

        this.InputBox = (this.Item.down("textarea")) ? this.Item.down("textarea") : this.Item.down("input");

        this.ItemFocus = this.OnItemFocus.bindAsEventListener(this);
        this.ItemFocusLost = this.OnItemFocusLost.bindAsEventListener(this);
        this.InitialTextClick = this.OnInitialTextClick.bindAsEventListener(this);

        this.KeyPress = this.OnKeyPress.bindAsEventListener(this);

        Event.observe(this.InputBox, "focus", this.ItemFocus);
        Event.observe(this.InputBox, "blur", this.ItemFocusLost);

        this.InitialText = this.Item.down("span.initial");
        this.EnterTarget = this.Item.down("span.entertarget");

        if (this.InitialText)
            Event.observe(this.InitialText, "click", this.InitialTextClick);

        if (this.InitialText && this.InputBox.value != "")
            this.InitialText.setStyle({ display: "none" });

        this.EnterTarget = (this.EnterTarget && $(this.EnterTarget.innerHTML)) ? $(this.EnterTarget.innerHTML) : null;

        if (this.InputBox.className && this.InputBox.className != "")
            this.Item.className += " " + this.InputBox.className;

        this.Deselect();
    },

    SetText: function (text) {
        this.InputBox.value = text;
    },

    OnItemFocus: function (evObj) {
        var targetObj = $(Event.element(evObj));
        if (this.IsEmpty() && this.InitialText)
            this.InitialText.setStyle({ display: "none" });
        else
            targetObj.select();

        if (this.EnterTarget)
            Event.observe($$("body")[0], "keypress", this.KeyPress);

        this.Select();
    },

    OnItemFocusLost: function (evObj) {
        if (this.IsEmpty() && this.InitialText)
            this.InitialText.setStyle({ display: "block" });

        if (this.EnterTarget)
            Event.stopObserving($$("body")[0], "keypress", this.KeyPress);

        this.Deselect();
    },

    OnKeyPress: function (evObj) {
        if (evObj.keyCode == Event.KEY_RETURN) {
            Event.stop(evObj);
            Event.simulate(this.EnterTarget, "click");
        }
    },

    OnInitialTextClick: function (evObj) {
        this.InputBox.focus();
    },

    IsEmpty: function () {
        return (this.InputBox.value == "");
    }
});

var DateSelectorExtender = Class.create(FormElementExtender, {
    initialize: function ($super, item) {
        $super(item);

        this.InputBox = this.Item.down("input");
        this.InputBox.setAttribute("autocomplete", "off");

        this.ItemClick = this.OnItemClick.bindAsEventListener(this);
        this.CalendarChange = this.OnCalendarChange.bindAsEventListener(this);
        this.DocumentClick = this.OnDocumentClick.bindAsEventListener(this);

        Event.observe(this.Item, "click", this.ItemClick);

        this.InitialText = this.Item.down("span.initial");

        if (this.InitialText && this.InputBox.value != "")
            this.InitialText.setStyle({ display: "none" });

        if (this.InputBox.className && this.InputBox.className != "")
            this.Item.className += " " + this.InputBox.className;

        this.CalendarHolder = new Element("div");
        $$("body")[0].insert(this.CalendarHolder);
        this.CalendarHolder.addClassName("calendar");
        this.Calendar = new scal(this.CalendarHolder, this.InputBox,
        {
            oncalchange: this.CalendarChange,
            updateformat: 'dd.MM.yyyy',
            weekdaystart: 6,
            titleformat: 'MMMM yyyy'
        });
        this.CalendarHolder.setStyle({ left: this.Item.cumulativeOffset()[0] + "px", top: this.Item.cumulativeOffset()[1] + this.Item.getHeight() + 2 + "px" });
        this.CalendarHolder.hide();


        this.Deselect();
    },

    SetText: function (text) {
        this.InputBox.value = text;
    },

    OnCalendarChange: function (evObj) {
        var saturdayElement = this.Calendar.getSelectedElement().up(".weekbox").down(".dayboxsaturday");
        this.Calendar.setCurrentDate(this.Calendar.getDateByElement(saturdayElement));

        this.Calendar.getSelectedElement().up(".weekbox").addClassName("selectedweek");

    },

    OnItemClick: function (evObj) {
        if (this.IsSelected())
            this.Deselect();
        else
            this.Select();
    },

    OnDocumentClick: function (evObj) {
        var x = Event.pointerX(evObj), y = Event.pointerY(evObj);
        var itemPos = this.Item.cumulativeOffset();
        var drpPos = this.CalendarHolder.cumulativeOffset();

        if (x < itemPos[0] || y < itemPos[1] || x > (drpPos[0] + this.CalendarHolder.getWidth()) || y > (drpPos[1] + this.CalendarHolder.getHeight())) {
            this.Deselect();
        }
    },


    Select: function ($super) {
        $super();

        if (this.IsEmpty())
            this.InitialText.setStyle({ display: "none" });
        else
            this.InputBox.select();

        this.CalendarHolder.show();
        this.CalendarHolder.setStyle({ left: this.Item.cumulativeOffset()[0] + "px", top: this.Item.cumulativeOffset()[1] + this.Item.getHeight() + 2 + "px" });

        Event.observe(document, "click", this.DocumentClick);

    },

    Deselect: function ($super) {
        $super();

        if (this.IsEmpty() && this.InitialText)
            this.InitialText.setStyle({ display: "block" });

        this.CalendarHolder.hide();

        Event.stopObserving(document, "click", this.DocumentClick);

    },

    IsEmpty: function () {
        return (this.InputBox.value == "");
    }
});

var DropDownExtender = Class.create(FormElementExtender, {
    initialize: function ($super, item) {
        $super(item);

        this.Item = item;

        this.SelectChange = this.OnSelectChange.bindAsEventListener(this);
        this.SelectFocus = this.OnSelectFocus.bindAsEventListener(this);
        this.SelectBlur = this.OnSelectBlur.bindAsEventListener(this);

        this.InputBox = this.Item.down("input");
        this.SelectBox = this.Item.down("select");

        Event.observe(this.SelectBox, "change", this.SelectChange);
        Event.observe(this.SelectBox, "focus", this.SelectFocus);
        Event.observe(this.SelectBox, "blur", this.SelectBlur);

        this.InputBox.writeAttribute({ autocomplete: "off", readonly: true });

        this.SizeClass = null;

        var classNames = this.Item.classNames();
        classNames.each(function (item) { if (item == "full" || item == "half" || item == "quarter") this.SizeClass = item; }, this);

        if (this.SelectBox.className && this.SelectBox.className != "")
            this.Item.className += " " + this.SelectBox.className;


        this.InitialText = this.SelectBox[0].innerHTML;
        if (this.SelectBox[0].value == "")
            this.SelectBox[0].innerHTML = "----";

        this.ChangeSelection(this.InitialText);

    },


    RefreshElement: function ($super, item) {
        $super(item);

        this.InputBox = this.Item.down("input");
        this.SelectBox = this.Item.down("select");

        Event.observe(this.SelectBox, "change", this.SelectChange);

        this.Deselect();

        this.ChangeSelection(this.SelectBox.value);

    },

    Disable: function ($super) {
        $super();

        this.ChangeSelection(null);
    },

    IsEmpty: function ($super) {
        return (this.SelectBox.value == "");
    },

    SendChangeEvent: function () {
        this.Element().fire("selection:change", { Value: this.SelectedValue() });
    },

    SelectedValue: function () {
        return (this.IsEmpty()) ? null : this.SelectBox.value;
    },

    ChangeSelection: function (value) {
        this.SelectBox.setValue((value) ? value : "");
        this.InputBox.value = (this.SelectBox[this.SelectBox.selectedIndex].value == "") ? this.InitialText : this.SelectBox[this.SelectBox.selectedIndex].innerHTML;

        this.Deselect();
    },

    OnSelectChange: function (evObj) {
        this.InputBox.value = (this.SelectBox[this.SelectBox.selectedIndex].value == "") ? this.InitialText : this.SelectBox[this.SelectBox.selectedIndex].innerHTML;
        this.SendChangeEvent();

        this.Deselect();
    },

    OnSelectFocus: function (evObj) {
        this.Select();
    },

    OnSelectBlur: function (evObj) {
        this.Deselect();
    }


});


var CheckBoxExtender = Class.create(FormElementExtender,
{
    initialize: function ($super, item) {
        $super(item);
        this.Item = $(item);
        this.Label = this.Item.down("label");
        this.Input = this.Item.down("input");

        this.ItemClick = this.OnItemClick.bindAsEventListener(this);
        this.ItemOver = this.OnItemOver.bindAsEventListener(this);
        this.ItemOut = this.OnItemOut.bindAsEventListener(this);

        if (this.Input.checked)
            this.Item.addClassName("checked");

        Event.observe(this.Item, "click", this.ItemClick);
        Event.observe(this.Item, "mouseover", this.ItemOver);
        Event.observe(this.Item, "mouseout", this.ItemOut);

        if (this.Item.down("span.errMsg") && this.Item.down("span.errMsg").innerHTML != "")
            this.Item.className += " error";


        this.Deselect();
    },

    OnItemClick: function (evObj) {
        var targetObj = $(Event.element(evObj));

        if (targetObj.tagName.toLowerCase() != "a") {
            this.Input.checked = !this.Item.down("input").checked;

            this.Item.removeClassName("checked");

            if (this.Item.down("input").checked)
                this.Item.addClassName("checked");

            this.Deselect();
        }
    },

    OnItemOver: function (evObj) {
        this.Select();
    },

    OnItemOut: function (evObj) {
        this.Deselect();
    },

    IsEmpty: function ($super) {
        return !this.Item.down("input").checked;
    }
});


var RadioBoxExtender = Class.create(FormElementExtender,
{
    initialize: function ($super, item) {
        $super(item);
        this.Item = $(item);

        this.ItemClick = this.OnItemClick.bindAsEventListener(this);

        if (this.Item.down("input").checked)
            this.Item.addClassName("checked");

        Event.observe(this.Item, "click", this.ItemClick);

        this.Deselect();
    },

    OnItemClick: function (evObj) {
        var targetObj = $(Event.element(evObj));
        this.Item.down("input").checked = true;

        if (!this.Item.hasClassName("checked"))
            this.Item.addClassName("checked");

        this.Item.up("fieldset").select("input[name=\"" + this.Item.down("input").readAttribute("name") + "\"]").each(function (item) {
            if (!item.checked) {
                item.up(".radio").removeClassName("checked");
                FormElementExtender.Elements.get(item.up(".radio").id).Deselect();
            }
        }, this);

        this.Deselect();
    },

    IsEmpty: function ($super) {
        return !this.Item.down("input").checked;
    }
});
/********** FORM EXTENDER **********/



/********** CALENDAR **********/
var CalendarExtender = Class.create();
CalendarExtender.prototype =
{
    initialize: function (container) {
        this.Container = $(container);
        this.PreviousButton = this.Container.down(".previous");
        this.NextButton = this.Container.down(".next");
        this.FloatingContainer = this.Container.down(".floatingContainer");


        this.TemplateBase = new Template($("TemplateBase").innerHTML);
        this.TemplateItem = new Template($("TemplateItem").innerHTML);

        this.ItemClick = this.OnItemClick.bindAsEventListener(this);
        this.PreviousClick = this.OnPreviousClick.bindAsEventListener(this);
        this.NextClick = this.OnNextClick.bindAsEventListener(this);

        Event.observe(this.PreviousButton, "click", this.PreviousClick);
        Event.observe(this.NextButton, "click", this.NextClick);

        this.MonthItems = this.FloatingContainer.select("table");
        this.LeftItem = 0;

        this.MonthItems.each(function (item) {
            item.Offset = item.positionedOffset()[0];
            item.Month = $w(item.className)[0].replace("month", "");
            item.Year = $w(item.className)[1].replace("year", "");
        }, this);

        this.Container.select("td.av").each(function (item) {

            var obj = prices.AvPrices.detect(function (n) { return n.ID == $w(item.className)[0]; })

            if (obj) {
                item.PricingObj = obj;
                Event.observe(item, "click", this.ItemClick);


                var html = this.TemplateBase.evaluate(item.PricingObj);


                item.PricingObj.Items.each(function (item) {
                    html += this.TemplateItem.evaluate(item);
                }, this);

                new TooltipExtender(obj.ID, item, html.replace(" 00:00:00", ""), "tooltip");
            }

        }, this);
    },

    Element: function () {
        return this.Container;
    },

    OnItemClick: function (evObj) {
        var targetObj = $(Event.element(evObj));
        this.Element().fire("calendar:change", { ArrivalDate: targetObj.PricingObj.ArrivalDate });

    },

    OnNextClick: function (evObj) {
        if (this.LeftItem < this.MonthItems.length - 4) {
            this.LeftItem++;
            new Effect.Move(this.FloatingContainer, { x: -(this.MonthItems[this.LeftItem].Offset), duration: 0.2, mode: "absolute" });
        }
    },

    OnPreviousClick: function (evObj) {
        if (this.LeftItem > 0) {
            this.LeftItem--;
            new Effect.Move(this.FloatingContainer, { x: -(this.MonthItems[this.LeftItem].Offset), duration: 0.2, mode: "absolute" });
        }
    },

    Select: function (month, year) {
        var obj = this.MonthItems.detect(function (item) { return (item.Month == month && item.Year == year); })

        var index = this.MonthItems.indexOf(obj);


        if (index > 3) {

            if (index > this.MonthItems.length - 4)
                this.LeftItem = this.MonthItems.length - 4;
            else
                this.LeftItem = index - 1;

            this.FloatingContainer.setStyle({ left: -(this.MonthItems[this.LeftItem].Offset) + "px" });

            //new Effect.Move(this.FloatingContainer, { x: -(this.MonthItems[this.LeftItem].Offset), duration: 0, mode: "absolute" });
        }
    }
};
/********** CALENDAR **********/

/********** CALENDAR - INPUT CONNECTOR **********/
var CalendarConnector = Class.create(
{
    initialize: function (calendar, drpArrivalDate, drpWeeks, drpPax) {
        this.Calendar = calendar;
        this.DrpArrivalDate = drpArrivalDate;
        this.DrpWeeks = drpWeeks;
        this.DrpPax = drpPax;

        if (this.DrpArrivalDate.SelectedValue()) {
            var p = this.DrpArrivalDate.SelectedValue().split(" ")[0].split(".");

            this.Calendar.Select(parseInt(p[1]), parseInt(p[2]));
        }


        this.CalendarChange = this.OnCalendarChange.bindAsEventListener(this);
        this.InputChange = this.OnInputChange.bindAsEventListener(this);

        Event.observe(this.Calendar.Element(), "calendar:change", this.CalendarChange);
        Event.observe(this.DrpArrivalDate.Element(), "selection:change", this.InputChange);
        Event.observe(this.DrpWeeks.Element(), "selection:change", this.InputChange);
        Event.observe(this.DrpPax.Element(), "selection:change", this.InputChange);

        this.UpdateVisibility();
    },

    OnCalendarChange: function (evObj) {
        this.DrpArrivalDate.ChangeSelection(evObj.memo.ArrivalDate);

        __doPostBack("__Page", "ArrivalDateChanged");
    },

    OnInputChange: function (evObj) {
        var targetObj = $(Event.element(evObj));

        if (targetObj == this.DrpArrivalDate.Element())
            __doPostBack("__Page", "ArrivalDateChanged");

        if (targetObj == this.DrpWeeks.Element())
            __doPostBack("__Page", "WeeksChanged");

        if (targetObj == this.DrpPax.Element())
            __doPostBack("__Page", "PaxChanged");



        //this.UpdateVisibility();
    },

    UpdateVisibility: function () {
        if (this.DrpArrivalDate.SelectedValue())
            this.DrpWeeks.Enable();
        else
            this.DrpWeeks.Disable();

        if (this.DrpWeeks.SelectedValue())
            this.DrpPax.Enable();
        else
            this.DrpPax.Disable();
    }
});
/********** CALENDAR - INPUT CONNECTOR **********/




/********** TOOLTIP **********/
var TooltipExtender = Class.create();
TooltipExtender.prototype =
{
    initialize: function (id, overElement, content, tooltipCSSClass) {
        if (TooltipExtender.Tooltips == null)
            TooltipExtender.Tooltips = new Hash();

        if (!TooltipExtender.Tooltips.get(id))
            TooltipExtender.Tooltips.set(id, this);

        this.MouseMove = this.OnMouseMove.bindAsEventListener(this);
        this.ItemOver = this.OnItemOver.bindAsEventListener(this);
        this.ItemOut = this.OnItemOut.bindAsEventListener(this);

        this.overElement = $(overElement);

        if (!TooltipExtender.Tooltips.get(id).tooltip) {
            this.tooltip = new Element("div");
            this.tooltip.setStyle({ position: "absolute", display: "none" });
            this.tooltip.className = tooltipCSSClass;
            this.tooltip.innerHTML = content;

            $$("body")[0].insert(this.tooltip);
        }
        else {
            this.tooltip = TooltipExtender.Tooltips.get(id).tooltip;
        }

        this.mouseX = 0;
        this.mouseY = 0;

        Event.observe(this.overElement, "mouseover", this.ItemOver);

    },

    GetContent: function () {
        return this.tooltip.innerHTML;
    },

    OnItemOver: function (evObj) {
        var targetObj = $(Event.element(evObj));


        this.mouseX = Event.pointerX(evObj);
        this.mouseY = Event.pointerY(evObj);

        Event.observe(targetObj, "mouseout", this.ItemOut);
        Event.stopObserving(targetObj, "mouseover", this.ItemOver);

        Event.observe(targetObj, "mousemove", this.MouseMove);
        //Event.observe(document, "mousemove", this.MouseMove);

        this.tooltip.setStyle({ display: "block" });
        this.UpdatePosition();
    },

    OnItemOut: function (evObj) {
        var targetObj = $(Event.element(evObj));

        this.tooltip.setStyle({ display: "none" });

        Event.stopObserving(targetObj, "mouseout", this.ItemOut);
        Event.observe(targetObj, "mouseover", this.ItemOver);

        Event.stopObserving(targetObj, "mousemove", this.MouseMove);
        //Event.stopObserving(document, "mousemove", this.MouseMove);
    },

    OnMouseMove: function (evObj) {
        this.mouseX = Event.pointerX(evObj);
        this.mouseY = Event.pointerY(evObj);

        this.UpdatePosition();
    },

    UpdatePosition: function () {
        var viewport = new ViewportProperties();

        var y = ((viewport.WindowHeight) < (this.mouseY + 10 + $(this.tooltip).getHeight() - viewport.ScrollTop))
			? this.mouseY - 10 - $(this.tooltip).getHeight()
			: this.mouseY + 10;

        var x = ((viewport.WindowWidth) < (this.mouseX + 10 + $(this.tooltip).getWidth() - viewport.ScrollLeft))
			? this.mouseX - 10 - $(this.tooltip).getWidth()
			: this.mouseX + 10;

        this.tooltip.setStyle({ left: x + "px", top: y + "px" });
    }
};
/********** TOOLTIP **********/

/********** TAB NAVIGATION **********/
var TabNavigation = Class.create(
{
    initialize: function (tablist) {
        this.TabClick = this.OnTabClick.bindAsEventListener(this);
        this.TabList = tablist;
        this.CurrentElement = null;
        this.CookieStore = this.TabList.hasClassName("cookie");

        this.Cookie = new Cookies(document.href);

        this.TabList.select("li a").each(function (item) {
            item.TargetElement = $(item.href.split("#")[1]);
            item.href = "javascript:void(0);"
            Event.observe(item, "click", this.TabClick);

            if (this.CookieStore) {
                if (this.Cookie.get(this.TabList.id)) {
                    item.up("li").removeClassName("selected");

                    if (this.Cookie.get(this.TabList.id) == item.TargetElement.id)
                        item.up("li").addClassName("selected");
                }
            }

            if (item.up("li").hasClassName("selected"))
                item.TargetElement.show();
            else
                item.TargetElement.hide();


        }, this);
    },

    OnTabClick: function (evObj) {
        var targetObj = $(Event.element(evObj));
        targetObj.blur();

        this.Cookie.set(this.TabList.id, targetObj.TargetElement.id);

        this.TabList.select("li a").each(function (item) {
            if (item == targetObj)
                item.up("li").addClassName("selected");
            else
                item.up("li").removeClassName("selected");

            if (item.up("li").hasClassName("selected"))
                item.TargetElement.show();
            else
                item.TargetElement.hide();
        }, this);

    }
});

var PopupExtender = Class.create(
{
    initialize: function (item) {
        this.ItemClick = this.OnItemClick.bindAsEventListener(this);

        this.Item = item;

        this.Item.Url = this.Item.href;
        this.Item.href = "javascript:void(0);";

        this.Item.classNames().each(function (item) {
            if (item.startsWith("size")) {
                item = item.replace("size", "");
                this.Width = item.split("_")[0];
                this.Height = item.split("_")[1];
            }
        }, this);

        Event.observe(this.Item, "click", this.ItemClick);
    },

    OnItemClick: function (evObj) {
        window.open(this.Item.Url, 'PopUp', 'width=' + this.Width + ',height=' + this.Height + ',screenX=0,screenY=0');
    }
});

/********** BANNER **********/
var BannerExtension = Class.create(
{
    initialize: function (pictures) {
        this.SeccondAnimationStart = this.OnSeccondAnimationStart.bindAsEventListener(this);
        this.AnimationFinished = this.OnAnimationFinished.bindAsEventListener(this);
        this.PictureLoaded = this.OnPictureLoaded.bindAsEventListener(this);

        this.Pictures = pictures;
        this.Holder = $("Banner");
        this.NextPicture = null;
        this.CurrentPicture = null;

        this.IsAnimationFinished = true;
        this.IsPictureLoaded = false;

        this.LoadPicture();
    },

    LoadPicture: function () {
        var nextSrc = this.Pictures[parseInt(Math.random() * this.Pictures.length)];
        while (this.CurrentPicture && this.CurrentPicture.src.indexOf(nextSrc) != -1)
            nextSrc = this.Pictures[parseInt(Math.random() * this.Pictures.length)];



        if (this.Holder.down("img.pic" + this.Pictures.indexOf(nextSrc))) {
            this.NextPicture = this.Holder.down("img.pic" + this.Pictures.indexOf(nextSrc));

            this.IsPictureLoaded = true;

            if (this.IsAnimationFinished)
                this.ChangePicture();
        }
        else {
            this.NextPicture = $(new Element("img"));
            this.NextPicture.src = nextSrc;
            this.NextPicture.addClassName("pic" + this.Pictures.indexOf(nextSrc));
            new PeriodicalExecuter(this.PictureLoaded, 0.5);
        }

    },

    OnPictureLoaded: function (evObj) {
        if (this.NextPicture.complete) {
            evObj.stop();

            this.IsPictureLoaded = true;

            if (this.IsAnimationFinished)
                this.ChangePicture();
        }
    },

    ChangePicture: function (evObj) {
        this.IsPictureLoaded = false;
        this.IsAnimationFinished = false;

        if (!this.Holder.down("img.pic" + this.Pictures.indexOf(this.NextPicture.src))) {
            this.Holder.insert(this.NextPicture);
            this.NextPicture.hide();
        }

        if (this.CurrentPicture)
            new Effect.Appear(this.NextPicture, { duration: 6 });
        else
            this.NextPicture.show();

        new Effect.Move(this.NextPicture, { y: -(this.NextPicture.getHeight() - this.Holder.getHeight()),
            duration: 14, mode: "relative", afterFinish: this.SeccondAnimationStart
        });

        if (this.CurrentPicture) {
            new Effect.Fade(this.CurrentPicture, { duration: 6 });
            new Effect.Move(this.CurrentPicture, { y: 0,
                duration: 12, mode: "absolute", afterFinish: this.AnimationFinished
            });
        }

        this.CurrentPicture = this.NextPicture;
        this.NextPicture = null;

        this.LoadPicture();
    },

    OnSeccondAnimationStart: function (evObj) {
        this.IsAnimationFinished = true;

        if (this.IsPictureLoaded)
            this.ChangePicture();
    },

    OnAnimationFinished: function (evObj) {

        evObj.element.setStyle({ top: "0px" });
    }
});
/********** BANNER **********/

/********** IFRAME LOADER ***********/
var IFrameLoadingExtender = Class.create(
{
    initialize: function (holder, src, timeout) {
        this.Holder = $(holder);
        this.Src = src;

        this.PeriodicalExecute = this.OnPeriodicalExecute.bindAsEventListener(this);
        this.IframeLoaded = this.OnIframeLoaded.bindAsEventListener(this);

        var layout = new Element.Layout(this.Holder, false);

        this.Iframe = new Element("iframe",
        {
            frameborder: "0",
            style: "position:relative; width:" + layout.get("width") + "px;height:" + layout.get("height") + "px;background-color: transparent;",
            src: src,
            scrolling: "no"

        });

        this.Overlay = new Element("div");
        this.Overlay.addClassName("overlay");
        this.Holder.insert(this.Overlay);

        Event.observe(this.Iframe, "load", this.IframeLoaded);
        new PeriodicalExecuter(this.PeriodicalExecute, timeout);
    },

    OnPeriodicalExecute: function (evObj) {
        this.Holder.insert(this.Iframe);
        evObj.stop();
    },

    OnIframeLoaded: function (evObj) {
        this.Overlay.hide();

        var layout = new Element.Layout(this.Holder, false);
        this.Iframe.setStyle({ height: layout.get("height") + "px" });
        

        this.SendChangeEvent();
    },

    Refresh: function () {
        this.Overlay.show();

        this.Iframe.src = this.Iframe.src;
    },

    SendChangeEvent: function () {
        this.Iframe.fire("iframe:loaded");
    }
});
/********** IFRAME LOADER ***********/

/********** STORED OBJECTS ***********/
var StoredObjectsExtender = Class.create(
{
    initialize: function () {
        this.StoreObjectClick = this.OnStoreObjectClick.bindAsEventListener(this);
        this.ShowStoredClick = this.OnShowStoredClick.bindAsEventListener(this);
        this.DocumentClick = this.OnDocumentClick.bindAsEventListener(this);
        this.RemoveObjectClick = this.OnRemoveObjectClick.bindAsEventListener(this);

        this.NumberOfStoredObjects = 0;

        $$("a.fav").each(function (item) {
            item.ObjectID = item.href.split("#")[1];
            item.href = "javascript:void(0);";
            Event.observe(item, "click", this.StoreObjectClick);
        }, this);

        this.RowTemplate = new Template("<td><div class=\"thumbnail\"><img src=\"#{PictureUrl}\" /></div></td><td><a href=\"#{Url}\"><strong>#{Title}</strong><br />#{Summary}</td><td><div class=\"remove #{ObjectID}\"></div></td>");

        this.StoredObjectsPanelHolder = new Element("div");
        this.StoredObjectsPanelHolder.id = "StoredObjectsPanel";
        $("Content").insert(this.StoredObjectsPanelHolder);

        this.StoredObjectsTable = new Element("table");
        this.StoredObjectsTable.id = "StoredObjectsTable";
        this.StoredObjectsPanelHolder.insert(this.StoredObjectsTable);

        this.StoredObjectForm = new Element("div");
        this.StoredObjectForm.id = "StoredObjectForm";
        this.StoredObjectForm.addClassName("iframe");
        this.StoredObjectsPanelHolder.insert(this.StoredObjectForm);

        this.StoredObjectsPanelHolder.hide();

        this.ShowStoredObjects = new Element("div");
        this.ShowStoredObjects.id = "ShowStoredObjects";
        $("Navigation").insert(this.ShowStoredObjects);
        this.ShowStoredObjects.insert("<span>" + cShowStoredObjects.replace("#", this.NumberOfStoredObjects) + "</span>");
        this.ShowStoredObjects.hide();

        this.ShowStoreObjectsLoading = new Element("div");
        this.ShowStoreObjectsLoading.addClassName("overlay");
        this.ShowStoredObjects.insert(this.ShowStoreObjectsLoading);
        this.ShowStoreObjectsLoading.hide();


        this.MovingIcon = new Element("div");
        this.MovingIcon.id = "StoreObjectMovingIcon";
        $$("body")[0].insert(this.MovingIcon);
        this.MovingIcon.hide();

        new Ajax.Request(baseUrl + languageCode + "/" + "json/storeobject.aspx", {
            method: "GET",
            onSuccess: function (response) {
                this.NumberOfStoredObjects = response.responseText;
                this.ShowStoredObjects.down("span").innerHTML = cShowStoredObjects.replace("#", this.NumberOfStoredObjects);

                if (this.NumberOfStoredObjects > 0) {
                    Effect.Appear(this.ShowStoredObjects, { duration: 0.5 });
                    Event.observe(this.ShowStoredObjects, "click", this.ShowStoredClick);
                }
            } .bindAsEventListener(this)
        });
    },

    OnStoreObjectClick: function (evObj) {
        var targetObj = $(Event.element(evObj));
        var offset = targetObj.cumulativeOffset();
        var targetOffset = $("Content").cumulativeOffset();

        this.MovingIcon.show();
        this.MovingIcon.setStyle({ left: offset[0] + "px", top: offset[1] + "px", backgroundColor: "transparent" });
        new Effect.Move(this.MovingIcon, { y: targetOffset[1], x: targetOffset[0] + 860, mode: "absolute", duration: 1, afterFinish: function (evObj) {
            this.MovingIcon.setStyle({ backgroundColor: "#ffffff" });
            new Effect.Fade(this.MovingIcon, { duration: 0.2 });
        } .bindAsEventListener(this)
        });

        this.StoreObject(targetObj.ObjectID);
    },

    StoreObject: function (objectID) {
        new Ajax.Request(baseUrl + languageCode + "/" + "json/storeobject.aspx", {
            method: "POST",
            parameters: "objectid=" + objectID,
            onSuccess: function (response) {
                this.NumberOfStoredObjects = response.responseText;
                this.ShowStoredObjects.down("span").innerHTML = cShowStoredObjects.replace("#", this.NumberOfStoredObjects);

                if (this.NumberOfStoredObjects > 0 && !this.ShowStoredObjects.visible()) {
                    Effect.Appear(this.ShowStoredObjects, { duration: 0.5 });
                    Event.observe(this.ShowStoredObjects, "click", this.ShowStoredClick);
                }

            } .bindAsEventListener(this)
        });
    },

    OnShowStoredClick: function (evObj) {
        Event.stopObserving(this.ShowStoredObjects, "click", this.ShowStoredClick);

        this.ShowStoreObjectsLoading.show();

        new Ajax.Request(baseUrl + languageCode + "/" + "json/liststoredobjects.aspx", {
            method: "GET",
            onSuccess: function (response) {
                var result = response.responseJSON;

                this.NumberOfStoredObjects = result.length;
                this.ShowStoredObjects.down("span").innerHTML = cShowStoredObjects.replace("#", this.NumberOfStoredObjects);

                result.each(function (item) {
                    item.Title = (item.Value.Title && item.Value.Title.length > 80) ? item.Value.Title.substring(0, 80) : item.Value.Title;
                    item.Value.Summary = (item.Value.Summary && item.Value.Summary.length > 80) ? item.Value.Summary.substring(0, 80) : item.Value.Summary;
                    item.Value.PictureUrl = (item.Value.PictureUrl) ? item.Value.PictureUrl : baseUrl + "images/pixel.gif";

                    this.StoredObjectsTable.insert("<tr>" + this.RowTemplate.evaluate(item.Value) + "<tr>");
                }, this);

                this.StoredObjectsTable.select(".remove").each(function (item) {
                Event.observe(item, "click", this.RemoveObjectClick);
                }, this);

                this.ShowStoreObjectsLoading.hide();

                Effect.BlindDown(this.StoredObjectsPanelHolder, { duration: 0.5, afterFinish: function (evObj) {
                    Event.observe(document, "mousedown", this.DocumentClick);

                    if (!this.Iframe) {
                        this.Iframe = new IFrameLoadingExtender(this.StoredObjectForm, baseUrl + languageCode + "/storedobjectspanel.aspx", 0);
                    }
                } .bindAsEventListener(this)
                });
            } .bindAsEventListener(this)
        });
    },

    OnRemoveObjectClick: function (evObj) {
        var targetObj = $(Event.element(evObj));

        targetObj.up("tr").remove();

        new Ajax.Request(baseUrl + languageCode + "/" + "json/removeobject.aspx", {
            method: "POST",
            parameters: "objectid=" + targetObj.className.split(" ")[1],
            onSuccess: function (response) {
                this.NumberOfStoredObjects = response.responseText;
                this.ShowStoredObjects.down("span").innerHTML = cShowStoredObjects.replace("#", this.NumberOfStoredObjects);

                if (this.NumberOfStoredObjects == 0) {
                    Effect.Fade(this.StoredObjectsPanelHolder, { duration: 0.5 });
                    Effect.Fade(this.ShowStoredObjects, { duration: 0.5 });
                }
            } .bindAsEventListener(this)
        });
    },

    OnDocumentClick: function (evObj) {
        var x = Event.pointerX(evObj) - Element.cumulativeOffset(this.StoredObjectsPanelHolder)[0];
        var y = Event.pointerY(evObj) - Element.cumulativeOffset(this.StoredObjectsPanelHolder)[1];


        if (y <= -40 || y >= this.StoredObjectsPanelHolder.getHeight() + 40 || x <= -40 || x >= this.StoredObjectsPanelHolder.getWidth() + 40) {
            Event.stopObserving(document, "mousedown", this.DocumentClick);
            Effect.BlindUp(this.StoredObjectsPanelHolder, { duration: 0.5, afterFinish: function (evObj) {

                this.StoredObjectsTable.select("tr").each(function (item) {
                    item.remove();
                }, this);


                Event.observe(this.ShowStoredObjects, "click", this.ShowStoredClick);

            } .bindAsEventListener(this)
            });
        }
    }
});
/********** STORED OBJECTS ***********/

/********** OBJECT HISTORY ***********/
var ObjectHistoryExtender = Class.create(
{
    initialize: function (objectHistoryHolder) {
        this.RowTemplate = new Template("<td><div class=\"thumbnail\"><img src=\"#{PictureUrl}\" /></div></td><td><a href=\"#{Url}\"><strong>#{Title}</strong></td><td><div class=\"remove #{ObjectID}\"></div></td>");

        this.ObjectHistoryHolder = objectHistoryHolder;
        
        this.CurrentObject = (this.ObjectHistoryHolder.innerHTML == "") ? null : this.ObjectHistoryHolder.innerHTML;

        this.ObjectHistoryHolder.innerHTML = "";
        
        this.StoredObjectsTable = new Element("table");
        this.StoredObjectsTable.id = "StoredObjectsTable";
        this.ObjectHistoryHolder.insert(this.StoredObjectsTable);

        new Ajax.Request(baseUrl + languageCode + "/" + "json/objecthistory.aspx", {
            method: ((this.CurrentObject)?"POST":"GET"),
            parameters: ((this.CurrentObject)?"objectid="+this.CurrentObject:null),
            onSuccess: function (response) {

            var result = response.responseJSON;

            if ( result )
            {
                result.each(function (item) {
                    item.Title = (item.Title && item.Title.length > 80) ? item.Title.substring(0, 80) : item.Title;
                    item.Summary = (item.Summary && item.Summary.length > 80) ? item.Summary.substring(0, 80) : item.Summary;
                    item.PictureUrl = (item.PictureUrl) ? item.PictureUrl : baseUrl + "images/pixel.gif";

                    this.StoredObjectsTable.insert("<tr>" + this.RowTemplate.evaluate(item) + "</tr>");


                }, this);           
                 
            }

            } .bindAsEventListener(this)
        });
    },
});
/********** OBJECT HISTORY ***********/

/********** VIEWPORT PROPERTIES **********/
var ViewportProperties = Class.create();
ViewportProperties.prototype =
{
    initialize: function () {
        this.WindowWidth = 0;
        this.WindowHeight = 0;
        this.ScrollLeft = 0;
        this.ScrollTop = 0;
        this.DocWidth = 0;
        this.DocHeight = 0;

        this.Calculate();
    },

    Calculate: function () {
        if (window.innerWidth) {
            this.WindowWidth = window.innerWidth;
            this.WindowHeight = window.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientWidth) {
            this.WindowWidth = document.documentElement.clientWidth;
            this.WindowHeight = document.documentElement.clientHeight;
        }
        else if (document.body) {
            this.WindowWidth = document.body.clientWidth;
            this.WindowHeight = document.body.clientHeight;
        }

        if (window.pageYOffset) {
            this.ScrollLeft = window.pageXOffset;
            this.ScrollTop = window.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop) {
            this.ScrollLeft = document.documentElement.scrollLeft;
            this.ScrollTop = document.documentElement.scrollTop;
        }
        else if (document.body) {
            this.ScrollLeft = document.body.scrollLeft;
            this.ScrollTop = document.body.scrollTop;
        }

        if (document.body.scrollHeight > document.body.offsetHeight) {
            this.DocWidth = document.body.scrollWidth;
            this.DocHeight = document.body.scrollHeight;
        }
        else {
            this.DocWidth = document.body.offsetWidth;
            this.DocHeight = document.body.offsetHeight;
        }
    }

};
/********** VIEWPORT PROPERTIES **********/

/**
* Event.simulate(@element, eventName[, options]) -> Element
* 
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
*
*    $('foo').simulate('click'); // => fires "click" event on an element with id=foo
*
**/
(function () {

    var eventMatchers = {
        'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
        'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
    }
    var defaultOptions = {
        pointerX: 0,
        pointerY: 0,
        button: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false,
        bubbles: true,
        cancelable: true
    }

    Event.simulate = function (element, eventName) {
        var options = Object.extend(defaultOptions, arguments[2] || {});
        var oEvent, eventType = null;

        element = $(element);

        for (var name in eventMatchers) {
            if (eventMatchers[name].test(eventName)) { eventType = name; break; }
        }

        if (!eventType)
            throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

        if (document.createEvent) {
            oEvent = document.createEvent(eventType);
            if (eventType == 'HTMLEvents') {
                oEvent.initEvent(eventName, options.bubbles, options.cancelable);
            }
            else {
                oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
            }
            element.dispatchEvent(oEvent);
        }
        else {
            options.clientX = options.pointerX;
            options.clientY = options.pointerY;
            oEvent = Object.extend(document.createEventObject(), options);
            element.fireEvent('on' + eventName, oEvent);
        }
        return element;
    }

    Element.addMethods({ simulate: Event.simulate });
})();

var Cookies = Class.create({
    initialize: function (path, domain) {
        this.path = path || '/';
        this.domain = domain || null;
    },
    // Sets a cookie
    set: function (key, value, days) {
        if (typeof key != 'string') {
            throw "Invalid key";
        }
        if (typeof value != 'string' && typeof value != 'number') {
            throw "Invalid value";
        }
        if (days && typeof days != 'number') {
            throw "Invalid expiration time";
        }
        var setValue = key + '=' + escape(new String(value));
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var setExpiration = "; expires=" + date.toGMTString();
        } else var setExpiration = "";
        var setPath = '; path=' + escape(this.path);
        var setDomain = (this.domain) ? '; domain=' + escape(this.domain) : '';
        var cookieString = setValue + setExpiration + setPath + setDomain;
        document.cookie = cookieString;
    },
    // Returns a cookie value or false
    get: function (key) {
        var keyEquals = key + "=";
        var value = false;
        document.cookie.split(';').invoke('strip').each(function (s) {
            if (s.startsWith(keyEquals)) {
                value = unescape(s.substring(keyEquals.length, s.length));
                throw $break;
            }
        });
        return value;
    },
    // Clears a cookie
    clear: function (key) {
        this.set(key, '', -1);
    },
    // Clears all cookies
    clearAll: function () {
        document.cookie.split(';').collect(function (s) {
            return s.split('=').first().strip();
        }).each(function (key) {
            this.clear(key);
        } .bind(this));
    }
});