window.AtToursSearchFormUpdater = function(options) {
    if (options) Object.extend(this, options);
    //if ($(this.tourTypeIds)) $(this.tourTypeIds).observe('change', this.update.bindAsEventListener(this));
    var elem = false;
    this.cNames = ['tourTypeIds', 'countryIds', 'resortIds', 'hotelIds', 'starIds', 'cityIds'];
    this.bind();
}

window.AtToursSearchFormUpdater.prototype = {
    
    tourTypeIds: false,
    countryIds: false,
    resortIds: false,
    hotelIds: false,
    starIds: false,
    cityIds: false,
    instanceId: false,

    isUpdating: false,

    axUrl: 'index2.php?option=com_avantravel&no_html=1&task=axList&Itemid=3',

    bind: function() {
        for(var i = 0; i < this.cNames.length; i++) 
        if (elem = $(this[this.cNames[i]])) {
            elem.observe('change', this.update.bindAsEventListener(this, this.cNames[i]));
            if (window.console) console.log(this.cNames[i] + ' observed');
        }
    },

    update: function(event, cName) {
        //return false;
        if (window.console) console.log(cName + ' changed');
        if (!this.isUpdating) {
            var data = {};
            var axControls = [];
            var elem;
            for(var i = 0; i < this.cNames.length; i++) {
                if (elem = $(this[this.cNames[i]])) {
                    data[this.cNames[i] + '[]'] = $F(elem);
                    if (this.cNames[i] != 'tourTypeIds') axControls[axControls.length] = this.cNames[i];
                }
            }
            if (this.instanceId) data.instanceId = this.instanceId;
            data['axControls[]'] = axControls;
            var query = $H(data).toQueryString();
            if (window.console) console.log(query);
            this.isUpdating = true;
            new Ajax.Request(this.axUrl + '&' + query, {
                onSuccess: function(transport, json) {
                    this.isUpdating = false;
                    var updatedData = eval("[" + transport.responseText + "]");
                    updatedData = updatedData[0];
                    for(var i = 0; i < this.cNames.length; i++) {
                        if ((elem = $(this[this.cNames[i]])) && updatedData[this.cNames[i]]) {
                            elem.replace(updatedData[this.cNames[i]]);
                        }
                    }
                    this.bind();
                }.bind(this),

                onFailure: function() {
                    this.isUpdating = false;
                }.bind(this)
            });
        } else {
            if (window.console) console.log("updating");
        }
    }
}

function otlt (oId, oDesc, box) {
    //window.alert(oId+" "+oDesc);
    if (!window.offerIds) window.offerIds = new Array();
    if (!window.offerDescrs) window.offerDescrs = new Array();
    if (!window.offersMap) window.offersMap = new Array();
        
    if (box.checked) {
        // кнопка была нажата - "отбираем" новый тур
        //window.alert('Box is checked');
        if (!window.offersMap[oId]) {
            var n = window.offerIds.length;
            window.offersMap[oId] = n;
            window.offerIds[n] = oId;
            window.offerDescrs[n] = oDesc;
            storeSelectedOffers();
        }

    } else {
        // кнопка отжата - "вычеркиваем" данный тур из отобранных
        //window.alert('Box is unchecked');
        if (window.offersMap[oId] != null) {
            n = window.offersMap[oId];
            //var oldS = window.offerIds.join(", ");
            window.offerIds[n] = null;
            window.offerDescrs[n] = null;
            window.offersMap[oId] = null;
            //var newS = window.offerIds.join(", ");
            //window.alert("was: " + oldS + "\nis: " + newS);
            eraseCookie(cookieName = "selectedOffer["+oId+"][desc]");
        }
    }
    updateOffersModule();
}

function updateOffersModule() {
    var offersModule = document.getElementById("selectedOffers");
    var offersModuleContainer = document.getElementById("selectedOffersModule");
    var sHTML = "";
    var suffix = (window.offerLinkItemId? "&Itemid=" + window.offerLinkItemId : "");
    var id;
    
    if (!offersModule) {
        //window.alert("offers module not found!");
        return;
    }
    
    if (window.offerIds && window.offerDescrs) {
        var n = 0, divClass;
        for (var i = 0; i < window.offerIds.length; i++ ) if ((id = window.offerIds[i]) != null) {
            n++;
            var descr = window.offerDescrs[i];
            var ref = "<a href='"+window.liveSite+"/index.php?option=com_avantravel&task=offer&offerId=" + id + suffix + "'>" + descr + "</a>";
            
            divClass = n % 2? "selo_odd" : "selo_even";
            sHTML += "<div class=\'"+divClass+"\'>"+ref+"</div>";
            
            var checkbox = document.getElementById('otlt_' + id);
            if (checkbox) {
                //window.alert('Checkbox found for offer #' + id);
                checkbox.checked = true;
            }
        }
        if (n) sHTML += "<p class='viewAllSelected'><a href='"+window.liveSite+"/index.php?option=com_avantravel&task=tours&offerIds[]="
            +window.offerIds.join("&offerIds[]=")+(window.offerLinkItemId? "&Itemid=" + window.offerLinkItemId : "")+"'>Просмотреть отобранные туры</a></p>";
        if (n) sHTML += "<p class='clearAllSelected'><a href='#' onclick='clearSelectedOffers(true);'>Очистить список</a></p>";
        createCookie("selectedOfferIds", window.offerIds.join(","), 2);
    }
    //window.alert("sHTML is " + sHTML);
    offersModule.innerHTML = sHTML;
    if (offersModuleContainer) offersModuleContainer.style.display = n? "" : "none";
    
}

function clearSelectedOffers(confirm) {
    if (confirm && !window.confirm('Очистить список отобранных туров?')) return false;
    if (window.offerIds && window.offerDescrs) {
        var id;
        for (var i = 0; i < window.offerIds.length; i++ ) if ((id = window.offerIds[i]) != null) {
            var descr = window.offerDescrs[i];
            eraseCookie("selectedOffer["+id+"][desc]");
    
            var checkbox = document.getElementById('otlt_' + id);
            if (checkbox) {
                checkbox.checked = false;
            }
        }
    }
    
    eraseCookie("selectedOfferIds");
    window.offerIds = new Array();
    window.offerDescrs = new Array();
    window.offersMap = new Array();
    
    updateOffersModule();
    
}

function loadSelectedOffers() {
    var ids;
    window.offerIds = new Array();
    window.offerDescrs = new Array();
    window.offersMap = new Array();
    if (ids = readCookie("selectedOfferIds")) {
        var arrIds = ids.split(",");
        var offerDsc;
        var n = 0;
        for (var i = 0; i < arrIds.length; i++) {
            if (offerDesc = readCookie("selectedOffer["+arrIds[i]+"][desc]")) {
                window.offerIds[n] = arrIds[i];
                window.offerDescrs[n] = offerDesc;
                window.offersMap[arrIds[i]] = n;
                n++;
            }
        }                                    
        //window.alert(n+ ' selected offers loaded');
    } else {
        //window.alert('offerIds cookie empty or not found');
    }
}

function storeSelectedOffers() {
    //eraseCookie("selectedOfferIds");
    if (window.offerIds && window.offerDescrs) {
        var cookieName;
        var id;
        for (var i = 0; i < window.offerIds.length; i++ ) if ((id = window.offerIds[i]) != null) {
            var descr = window.offerDescrs[i];
            if (descr) {
                eraseCookie(cookieName = "selectedOffer["+window.offerIds[i]+"][desc]");
                createCookie(cookieName, descr, 2);
            }
        }
        createCookie("selectedOfferIds", window.offerIds.join(","), 2);
        //window.alert(window.offerIds.join(","));
    }
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Event.observe(window, 'load', function() {
  loadSelectedOffers();
  updateOffersModule();
});


