// cp@ltur.de, 09.05.2011

var CarListManager = {};
CarListManager.Mnx = function() {};
CarListManager.Mnx.prototype = {
    carHireStation:'',
    pickupDateTime:null,
    dropoffDatetime:null,
    ageDriver:-1,
    numPax:2,
    pageManager:null,
    showWaitingFunc:null,
    hideWaitingFunc:null,
    onNoResultFunc:null,
    setPageManager:function (pm) {
        this.pageManager = pm;
    },
    setHireStation:function (st) {
        this.carHireStation = st;
    },
    setPickupDateTime:function (dt) {
        this.pickupDateTime = dt;
    },
    getPickupDateTime:function () {
        return this.toTime(this.pickupDateTime);
    },
    setDropoffDateTime:function (dt) {
        this.dropoffDatetime = dt;
    },
    getDropoffDateTime:function () {
        return this.toTime(this.dropoffDatetime);
    },
    setAgeDriver:function (age) {
        this.ageDriver = age;
    },
    setNumPax:function (num) {
        this.numPax = num;
    },
    setShowWaitingFunc:function (func) {
        this.showWaitingFunc = func;
    },
    setHideWaitingFunc:function (func) {
        this.hideWaitingFunc = func;
    },
    setOnNoResultFunc:function (func) {
        this.onNoResultFunc = func;
    },
    fireUpdate:function () {
        this.showWaitingFunc();
        jQuery.ajax({
            type: "GET",
            dataType: "json",
            cache: false,
            url: "/lturfly/cu.ltml",
            data: this.buildCommand(),
            context:this,
            success:this.onResponse
        });
    },
    buildCommand:function () {
        var cmd = {
            cmd: "searchForCars",
            st:  this.carHireStation,
            pd:  this.pickupDateTime,
            dd:  this.dropoffDatetime
        };
        if (this.ageDriver >= 18) {
            cmd.ad = this.ageDriver;
        }
        if (this.numPax >= 2) {
            cmd.ns = this.numPax;
        }
        return cmd;
    },
    onResponse:function (data, status, jqXHR) {
        if (data.success && data.success == 'OK') {
            this.hideWaitingFunc();
            this.pageManager.onUpdate(data, status, jqXHR);
        } else {
            this.onNoResultFunc();
        }
    },
    toTime:function (dt) { //Y-m-d\TH:i 
        var rgx = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d?\d):(\d\d)/;
        rgx.exec(dt);
        return ((new Date(parseInt(RegExp.$1, 10), parseInt(RegExp.$2, 10) - 1, parseInt(RegExp.$3, 10), parseInt(RegExp.$4, 10), parseInt(RegExp.$5, 10), 0)).getTime() / 1000);
    }
};

var CarPageManager = {};
CarPageManager.Mnx = function (oCarDetailsView, categories, tabBuilderFunc) {
    this.oCarDetailsView = oCarDetailsView;
    this.tabBuilderFunc  = tabBuilderFunc;
    this.categories      = categories;
};
CarPageManager.Mnx.prototype = {
    searchId:null,
    actCarId:null,
    actTab:'small',
    categories:[],
    tabViews:{},
    oCarDetailsView:null,
    carListCat:{},
    onInit:null,
    setOnInitFunc: function (f) {
        this.onInit = f;
    },
    register:function (subject) {
        subject.addObserver(this);
    },
    
    onUpdate:function (data, status, jqXHR) {
        if (data.carList) {
            this.init(data);
        }
    },
    getCarId:function (cat, id) {
        return this.carListCat[cat][id]._id;
    },
    showCarDataByCarId:function (id) {
        var self = this;
        jQuery.each(self.carListCat, function (cat, arrCOL) {
            jQuery.each(arrCOL, function (key, arrCO) {
                if (id == arrCO._id) {
                    jQuery('#ltMietListTab_' + cat).click();
                    return self.showCarDetails(cat, key);
                }
            });
        });
    },
    showCarDetails:function (cat, id) {
        this.actCarId = id;
        this.oCarDetailsView.display(this.carListCat[cat][id]); 
        
        return true;
    },
    init:function (data) {       
        var self = this;
        var co  = data.carList[0];
        var cat = co.Vehicle_.vehicleCategory_;
        this.searchId = data.carSearchId;
        
        jQuery.each(this.categories, function (k, c) {
            self.carListCat[c] = [];
        });
        
        var buffer = '';
        jQuery.each(data.carList, function (k, c) {
            buffer += "(" + k + ") (" + c._id + ")\n";
        });

        jQuery.each(data.carList, function (v, c) {
            var vcat = c.Vehicle_.vehicleCategory_;
            self.carListCat[vcat].push(c);
        });
        this.initTabViews(cat);
        this.showCarDetails(cat, 0);
        if (jQuery.isFunction(this.onInit)) {
            this.onInit(this.searchId, this.getCarId(cat, 0));
        }
    },
    initTabViews:function (catDetailsOffer) {
        var self = this;
        var sorryHTML = '<p>Es liegen keine Angebote f&uuml;r diese Kategorie vor.</p>';
        jQuery.each(this.categories, function (k, c) {
            var elemId = '#ltMietListTab_' + c + '_con';
            if (self.carListCat[c].length > 0) {
                jQuery('#ltMietListAmount_' + c).html(self.carListCat[c].length);
                self.tabBuilderFunc(elemId, self.carListCat[c], 'ltMiet_' + c);
            } else {
                jQuery(elemId).html(sorryHTML);   
            }
        });
        jQuery('#ltMietListTab_' + catDetailsOffer).click();
    }
};

var CarDetailView = {};
CarDetailView.Mnx = function (cp,cn,fl,sn,il,p, d) {
    this.jPic           = cp;
    this.jCarName       = cn;
    this.jFeatureList   = fl;
    this.jSupplier      = sn;
    this.jInsuranceList = il;
    this.jPrice         = p;
    this.jDays          = d;
}
CarDetailView.Mnx.prototype = {
    jPic:null,
    jCarName:null,
    jFeatureList:null,
    jSupplier:null,
    jInsuranceList:null,
    jPrice:null,
    jDays:null,
    picCache:{},
    display:function (oCarOffer) {
        if (oCarOffer.Vehicle_.pictureSmall_) {
            this.jPic.css('background', 'url(' + oCarOffer.Vehicle_.pictureSmall_.replace(/http:/, 'https:') + ') center center');
        }
        if (oCarOffer.Vehicle_.vehicleName_) {
            this.jCarName.html(oCarOffer.Vehicle_.vehicleName_);
        }
        if (oCarOffer.supplierLogo_) {
            this.jSupplier.attr('src', oCarOffer.supplierLogo_.replace(/http:/, 'https:'));
            if (oCarOffer.supplierName_) {
                this.jSupplier.attr('title', oCarOffer.supplierName_);
                this.jSupplier.attr('alt', oCarOffer.supplierName_);
            }
        }
        var insurances = [];
        if (oCarOffer.coverageRules) {
            var i=0;
            jQuery.each(oCarOffer.coverageRules, function(key, val) {
                if (++i < 5) {
                    insurances.push("<li>" + val + "</li>");
                }
            });
            this.jInsuranceList.html(insurances.join(""));
        }
        this.jFeatureList.html('');
        if (oCarOffer.Vehicle_.maxPassengers_ > 0) {
            var srcP = "/images/ic/mnx/psB" + oCarOffer.Vehicle_.maxPassengers_ + ".gif";
            var txtP = "Personen";
            this.jFeatureList.append(this.createImage(srcP, txtP));
        }
        if (oCarOffer.Vehicle_.baggageQuantity_ > 0) {
            var srcG = "/images/ic/mnx/lgB" + oCarOffer.Vehicle_.baggageQuantity_ + ".gif";
            var txtG = "Gepäckstücke";
            this.jFeatureList.append(this.createImage(srcG, txtG));
        }
        if (oCarOffer.Vehicle_.doorCount_ > 0) {
            var srcD = "/images/ic/mnx/drs" + oCarOffer.Vehicle_.doorCount_ + ".gif";
            var txtD = "Türen";
            this.jFeatureList.append(this.createImage(srcD, txtD));
        }
        if (oCarOffer.Vehicle_.airCondition_) {
            var srcK = "/images/ic/mnx/klima.gif";
            var txtK = "Klimaanlage";
            this.jFeatureList.append(this.createImage(srcK, txtK));
        }
        if (!oCarOffer.Vehicle_.automatic_) {
            var srcS = "/images/ic/mnx/manuell.gif";
            var txtS = "Schaltgetriebe";
            this.jFeatureList.append(this.createImage(srcS, txtS));
        } else {
            var srcS = "/images/ic/mnx/automatic.gif";
            var txtS = "Automatikgetriebe";
            this.jFeatureList.append(this.createImage(srcS, txtS));
        }
        this.jPrice.html(oCarOffer.totalAmount_ + " " + oCarOffer.CurrencyCode_);
        var days = this.calcDays(oCarOffer.returnTimestamp_, oCarOffer.pickUpTimestamp_);
        this.jDays.html(((days == 1)? "1 Tag" : days + " Tage"));
    },
    createImage:function (s, t) {
        if (!this.picCache[s]) {
            var img = jQuery('<img />').attr({
                src: s,
                title: t,
                alt: t
            });    
            this.picCache[s] = img;
        }
        return this.picCache[s];
    },
    calcDays:function (l, f) {
        return Math.round((l - f) / (60 * 60 * 24));
    }
};

