/**
 * Capital - Immobilienkompass
 *
 * Contains additional JavaScript code for reloaded version of immokompass
 *
 * @link       http://www.capital-immobilien.de/
 * @package    immokompass
 * @version    0.1
 *
 * @todo: should be merged with immokompass.js
 *
 * Encodingtest: äöüß
 */


if (typeof cec == "undefined" || !cec) {
    /**
     * Set cec global namespace object, if not exists.
     * @class cec
     * @static
     */
    var cec = {};
}


// #############################################################################


/**
 * @class  Estate gallery handler class, provides loading an displaying of images.
 * @static
 */
cec.EstateGalleryV2 = {
    galleryId:    "",
    iStep:        5,
    iCurrentPos:  3,
    aImages:      null,
    aAnchors:     null,

    /**
     * Main initialization function
     *
     * @param  {String}   id    Estate gallery id
     * @param  {Integer}  step  Nnumber of displayed images and pager step size
     * @param  {Integer}  autoloadPos  Position of zoom image to load
     */
    init: function (id, step, autoloadPos) {
        this.galleryId  = id;
        this.iStep      = step;
        this.aImages    = new Array();
        this.aAnchors   = new Array();

        // register previous page function at left anchor
        if (obj = $("estate_gallery_list").down('.prevImage').down()) {
            obj.onclick = function () {
                cec.EstateGalleryV2.previousPage();
            }
        }

        // register next page function at left anchor
        if (obj = $("estate_gallery_list").down('.nextImage').down()) {
            obj.onclick = function () {
                cec.EstateGalleryV2.nextPage();
            }
        }

        // loop thru availabe gallery pics counter and store elements
        for (var pos=0; pos<this.iStep; pos++) {
//##++##            console.log('pos', pos);
            if (obj = $("estate_gallery_list").down('img', pos)) {
                this.aImages.push(obj);

                var elem = obj.up(0);
                elem.onclick = function () {
                    cec.EstateGalleryV2.show(this);
                }
                elem.id = "galleryimage-" + String(pos + 1);
                this.aAnchors.push(elem);
//##++##                console.log('img obj', this.aImages[this.aImages.length-1]);
//##++##                console.log('a obj', this.aAnchors[this.aAnchors.length-1]);
            }
        }

        if (typeof(autoloadPos) !== "undefined") {
            // load image at desired pos
            this._loadDetails(autoloadPos);
        }
    },


    /**
     * Pager to load next x images
     */
    nextPage: function(){
        var pos = this.iCurrentPos + this.iStep;
        this._loadDetails(pos);
    },


    /**
     * Pager to load previous x images
     */
    previousPage: function() {
        var pos = this.iCurrentPos - this.iStep;
        this._loadDetails(pos);
    },


    /**
     * Displays image, is called by click on an anchor
     *
     * @param  {Object}  obj  Anchor object
     */
    show: function(obj){
        var pos = obj.id.replace("galleryimage-", "");
        if (this.iCurrentPos == pos) {
            return;
        }
        this._loadDetails(pos);
    },


    /**
     * Processes details response.
     *
     * @param  {Ajax.Response}  transport  Response object
     */
    processDetailsResult: function(transport) {
//##++##        console.log('transport.headerJSON', transport.headerJSON);
        if (!transport.headerJSON) {
            return;
        }
        var json = transport.headerJSON;
        if (!json.images) {
            return;
        }
//##++##        console.log('json.images', json.images);

        json.images.each(function(item, pos) {
//##++##            console.log('json.images item', item);

            if (cec.EstateGalleryV2.aImages[pos]) {
                cec.EstateGalleryV2.aImages[pos].src   = item.src;
                cec.EstateGalleryV2.aImages[pos].title = item.title;
            }
            if (cec.EstateGalleryV2.aAnchors[pos]) {
                cec.EstateGalleryV2.aAnchors[pos].id = "galleryimage-" + item.pos;
            }
            if (pos == 2) {
                cec.EstateGalleryV2.iCurrentPos = item.pos;
            }

        });

        $("estate_gallery_desc").update(json.description);
    },


    /**
     * Sends request to load image at desired position.
     *
     * @param  {Integer}  position  Image to load at position
     */
    _loadDetails: function(position) {
        new Ajax.Request('../servlet/gallery', {
            method: 'post',
            parameters: {action: "estategallery_load_details", galleryid: this.galleryId, pos: position, step: this.iStep},
            onSuccess: function(transport) {
                cec.EstateGalleryV2.processDetailsResult(transport);
            }
        });
    }
}


// #############################################################################


/**
 * @class  Class to manage estate search autocompleter results
 * @static
 */
cec.EstateSearch = {

    /**
     * To store last city
     */
    lastCity: "",
    
    /**
     * Flag to enable pulsate effect after distincts were loaded
     */
    enablePulsateEffect: true,
    
    /**
     * Number of pulses (default is 5)
     */
    pulsatePulses: 2,
    
    /**
     * Pulse effect duration (default is 2.0)
     */
    pulsateDuration: 0.8,

    /**
     * Callback function to set selected city id
     *
     * @param {Object}  text  Input element or list item
     * @param {Object}  elem  List item object (li)
     */
    setCityId: function(text, elem) {
//##++##        console.log('setCityId: elem', elem.innerHTML.toLowerCase);
//##++##        console.log('setCityId: elem.id', elem.id);
        cec.EstateSearch.lastCity = elem.innerHTML.toLowerCase;
        cec.EstateSearch.loadDistrictsByCityId(elem.id);
    },

    /**
     * Callback function to set city id by selected zip code
     *
     * @param {Object}  elem  List item object (li)
     */
    setCityIdByZipResult: function(item) {
//##++##        console.log('item', item);
//##++##        console.log('itemval', item);
        $("id_addressform_stadt").value = item.innerHTML;
        cec.EstateSearch.setCityId(item.innerHTML, item);
    },

    /**
     * Performs a request to load districts by passed city id
     *
     * @param {String}  cityId   Identifier of city (e. g. "cityid-1234")
     */
    loadDistrictsByCityId: function(cityId) {
        cec.EstateSearch._loadDistricts(cityId);
    },

    /**
     * Performs a request to load districts by passed city name
     *
     * @param {String}  cityName  Name of city or city name
     */
    loadDistrictsByCityName: function(cityName) {
        if (cityName.toLowerCase != cec.EstateSearch.lastCity) {
            cec.EstateSearch.lastCity = cityName.toLowerCase;
        }
        cec.EstateSearch._loadDistricts(cityName);
    },

    /**
     * Performs a request to load districts by passed city id
     *
     * @param {String}  cityIdOrName  Identifier of city (e. g. "cityid-1234")
     *                                or city name
     */
    _loadDistricts: function(cityIdOrName) {
        var that = this;
        new Ajax.Updater("id_addressform_stadtteil_outer", '../servlet/autocompleteCity', {
            parameters: { action: "getdistricts", cityid: cityIdOrName },
            onComplete: function (){
                if (that.enablePulsateEffect == true) {
                    new Effect.Pulsate("id_addressform_stadtteil_outer", {
                        pulses:   that.pulsatePulses,
                        duration: that.pulsateDuration
                    });
                }
            }
        });
    }
}


// #############################################################################


/**
 * Extend Element Class.
 *
 * Use the prefix "cec_" for new methods to prevent conflicts with new versions in future.
 */
Element.addMethods({
    /**
     * Replaces desired classname against another one.
     *
     * @param  {Object}  element      Element where the classname is to replace
     * @param  {String}  searchName   Classname to search
     * @param  {String}  replaceName  Classname to replace
     * @param  {Boolean} force        Force replacement either if searchName doesn't exists.
     */
    cec_replaceClassName: function(element, searchName, replaceName, force) {
        if ($(element).hasClassName(searchName)) {
            $(element).removeClassName(searchName);
            $(element).addClassName(replaceName);
        } else if (force == true) {
            $(element).addClassName(replaceName);
        }
    }

});


// #############################################################################


// Firebug emulation, to prevent errors if firebug is not available
if (!("console" in window) || !("firebug" in console)) {
    (function(){
        window.console = {
            log:   function(){},
            debug: function(){},
            info:  function(){},
            warn:  function(){},
            error: function(){}
        }
    })();
}

