/**
 * Main script for Omanbay
 *
 * @author Steven Bakhtiari <steven@ctisn.com>
 * @copyright Copyright (c) 2009, CTI Support Network
 */
var Obay = {
    // Omanbay javascript.
    init: function () {
        Obay.listing.init();
        Obay.form.init();
        Obay.advancedsearch.init();
        Obay.helptopics.init();
    },

    // General jazz
    general: {
        hourglass: {
            element: null,
            started: false,
            offsetX: -15,
            offsetY: 10,

            // return the hourglass element
            get: function () {
                if (Obay.general.hourglass.element === null) {
                    // create the element
                    Obay.general.hourglass.element = new Element('div', {
                        'id': 'hourglass',
                        'styles': {
                            'display': 'none',
                            'position': 'absolute',
                            'z-index': 1000
                        }
                    });
                }

                return Obay.general.hourglass.element;
            },

            // enable loading notification (requires click event to see where mouse is)
            start: function (event) {
                if (Obay.general.hourglass.started === false) {
                    Obay.general.hourglass.get().setStyles({
                        'display': 'block',
                        'top': event.page.y + Obay.general.hourglass.offsetY,
                        'left': event.page.x + Obay.general.hourglass.offsetX
                    }).inject(document.body);

                    window.addEvent('mousemove', Obay.general.hourglass.move);

                    Obay.general.hourglass.started = true;
                }
            },

            // disable loading notification
            stop: function () {
                if (Obay.general.hourglass.started === true) {
                    window.removeEvent('mousemove', Obay.general.hourglass.move);
                    Obay.general.hourglass.element.setStyle('display', 'none').dispose();

                    Obay.general.hourglass.started = false;
                }
            },

            // make the hourglass trail the mouse
            move: function (event) {
                Obay.general.hourglass.get().setStyles({
                    'top': event.page.y + Obay.general.hourglass.offsetY,
                    'left': event.page.x + Obay.general.hourglass.offsetX
                });
            }
        }
    },

    // Listing namespace... related code goes here
    listing: {
        init: function () {
            Obay.listing.image.init();
			// if it's a listing and has not finished
			if ($('listing-information') && ( $('listing-state').value == '0' ) ) {
				Obay.listing.update.init();
			}
            if ($('category-selector') && (!Browser.Engine.trident4)) {
                // If javascript is enabled show the normal selection
                $('category-selector').setStyle('display','block');
                $('listing-selector').setStyle('display','block');
                $('listing-input').setStyle('display','none');
                Obay.listing.getListingByCat.init();
            }
			
        },
        
        image: {
            imagePreviewContainer: null,
                        
            init: function () {
                if (Obay.listing.image.imagePreviewContainer = $('images-container')) {
                    // add click event to switch between previews when selecting a thumbnail
                    $$('#listing-thumbnails li a').addEvent('click', Obay.listing.image.displayPreview);
                    var previewImage = Obay.listing.image.imagePreviewContainer.getElement('img.image-preview');
                }
            },

            // show preview image on thumbnail selection
            displayPreview: function (event) {
                event.stop();

                // grab the existing preview image
                var existingImage = Obay.listing.image.imagePreviewContainer.getElement('img.image-preview');

                /**
                 * Return early if the selected thumbnail is
                 * the already loaded and visible preview image.
                 */
                if (existingImage.src == this.href) return;

                // start the "hourglass"
                //Obay.general.hourglass.start(event);

                /**
                 * Load the image and then inject it
                 * into the document.
                 */
                var image = new Asset.image(this.href, {
                    'class': 'image-preview',
                    'onload': function (newImage) {
                        newImage.inject(existingImage, 'before');

                        // fade out and destroy the old image
                        existingImage.get('tween', {
                            'property': 'opacity',
                            'onComplete': function (img) {
                                img.destroy();
                                //Obay.general.hourglass.stop();
                            }
                        }).start(0);
                    }
                })
            }
        },
        
        /**
         * @author Sergi <sergi@ctisn.com>
         */
		update: {
			// Every 1 min			
			interval: 60000,
            // Every 10 seconds
			short_interval: 10000,
			timer: null,
	        init: function() {												
				//Init the update listing function				
				var updateCall = Obay.listing.update.updateBid();
			},            
			updateBid: function() {
				var listingId = $('listing-id').value;
				
				var url = location.protocol + "//" + location.host + '/listing/update';
                new Request.JSON({
                	'url': url,
                    'onSuccess': function (response) {
						if (response) {
                            Obay.listing.update.setValues(response);	
						}                    							
						Obay.listing.update.checkResetInterval(response);
                	}
            	}).get({ 'format': 'json', 'listing_id': listingId });
			},
			
            setValues: function(response) {
				// If the response is valid
				//if (!((response.is_finished == true))) {
                if (!response.is_finished) {
					if ($('finishes-in'))	$('finishes-in').setText(response.active_until);
					if ($('active-until')&&(response.active_until != false))	$('active-until').setProperty('html', response.active_until);
					if ($('bid-count')) 	$('bid-count').setProperty('html', response.bid_count);
					if ($('bid-amount'))	$('bid-amount').setProperty('value', response.bid_amount);
					if ($('current-price'))	$('current-price').setProperty('html', response.current_price);
					if ($('end-time'))      $('end-time').setProperty('html', response.end_time);
					if ($('bids-table'))	$('bids-table').set('html', response.bids_table);
				}
			},
            checkResetInterval: function(response) {
				if (response) {
					if ((response.ending_now == true)&&(response.is_finished == false)) {
						// The bid is ending soon, switch to short interval	
						Obay.listing.update.interval = Obay.listing.update.short_interval;
						Obay.listing.update.timer = Obay.listing.update.updateBid.delay(Obay.listing.update.interval);
					}
					else if ((response.is_finished == true)&&(response.already_checked==false)) {
						// The bid has ended, reload the page
						$clear(Obay.listing.update.timer);
						window.location.reload();
					} 
					else if ((response.ending_now == false)&&(response.is_finished == false)){
						// The bid is not ending within a short interval
						Obay.listing.update.updateBid.delay(Obay.listing.update.interval);
					}
				}				
			}			
		}, // end of update 
		/*
		 * author Sergi < sergi@ctisn.com >
		 */
		getListingByCat: {
            init: function() {
                //Init the update listing function
                Obay.listing.getListingByCat.getListing();
            },
            getListing: function() {
                    var cat_selector = $('category');
                    // Hide the without javascript message
                    ($('without-js')).setStyle('display','none');
                    ($('with-js')).setStyle('display','block');
                    
                    // When changing category react
                    cat_selector.addEvent('change', function (event) {
                        var url = location.protocol + "//" + location.host + '/listing/getlistingsbycat';
                        new Request.JSON({
                            'url': url,
                            'onSuccess': function (response) {
                                if (response) {
                                    
                                    var listings = $('listing');
                                    // Delete other options
                                    listings.getElements('option[value!=0]').dispose();
                                    // Add all elements to the listing selection box                                    
                                    for (var i = 0; i < response.listings.length ; i++) {
                                        new Element('option', {
                                            'text': response.listings[i],
                                            'value': response.listing_ids[i]
                                        }).inject(listings);
                                    }
                                        
                                }                                               
                            }
                        }).get({ 'format': 'json', 'category_id': cat_selector.value });
                     });
            }
        }
		
    },

    // Generic form namespace... related code goes here
    form: {
        // Form initialisation
        init: function () {
            if ($('login') || $('main-login')) Obay.form.login.init();
            if ($('registration')) Obay.form.registration.init();
			if (($('new-listing-categories'))&&(!Browser.Engine.trident4)) {
                 Obay.form.initNewListingCategorySliders();
            }           
            if ($('new-listing-details')) Obay.form.newListingDetails.init();
            if ($('new-listing-images')) Obay.form.newListingPhotos.init();
            
            if ($('email-list')) Obay.form.emails.init();
        },

        // Login form
        login: {
            init: function () {
                $$('#login_email', '#login_password').addEvent('focus', Obay.form.login.clearInputField);
            },

            clearInputField: function (event) {
                if (this.value == 'email@example.com' || this.value == 'password') {
                    this.value = '';
                }
            }
        },
        
        // Registration form
        registration: {
            // Registration form initialisation
            init: function () {
                Obay.form.registration.languageSelectInit();
            },

            languageSelectInit: function () {
                var otherField = $('other_language_field');

                // disable the 'other language' input whilst it's hidden
                otherField.getElement('input').set('disabled', 'disabled');

                var otherFieldSlider = new Fx.Slide(otherField, {
                    /**
                     * The slider is about to be opened,
                     * re-enable the input for users.
                     */
                    'onStart': function (el) {
                        if (!this.open) {
                            el.getElement('input').erase('disabled');
                        }
                    },
                    /**
                     * The slider has just been closed,
                     * we can disable the input again.
                     */
                    'onComplete': function (el) {
                        if (!this.open) {
                            el.getElement('input').set('disabled', 'disabled');
                        }
                    }
                }).hide();

                $('reg_language').addEvent('change', function (event) {
                    if (this.value == 0) {
                        otherFieldSlider.slideIn();
                    } else {
                        if (otherFieldSlider.open) {
                            otherFieldSlider.slideOut();
                        }
                    }
                });
            }
        },

        // Form used to create a new listing
        newListingDetails: {
            /**
             * Store fetched data to make subsequent
             * access of the same data much faster,
             * instead of repeatedly contacting the server.
             */
            regions: new Hash(),
            towns:   new Hash(),

            init: function () {
                var regionSelect = $('region-select');

                if (regionSelect) {
                    regionSelect.addEvent('change', Obay.form.newListingDetails.populateTownSelect);
                }
            },

            /**
             * Generate option elements
             * and inject into the select.
             *
             * @param data Array
             * @param html dom element select
             * @return void
             */
            buildSelectMarkup: function (data, select) {
                if (data.length > 0) {
                    var select = $(select);

                    for (var i = 0; i < data.length; i++) {
                        new Element('option', {
                            'text': data[i].title,
                            'value': data[i].id
                        }).inject(select);
                    }
                }
            },

            /**
             * The region select box should be populated
             * with regions of the selected country only.
             * Fetch the associated regions from the server
             * where they're stored in the database.
             */
            populateRegionSelect: function (event) {
                var countryId = parseInt(this.get('value'), 10);
                var regionSelect = $('region-select');
                var townSelect = $('town-select');

                // Delete all but the first option
                regionSelect.getElements('option[value!=0]').dispose();
                townSelect.getElements('option[value!=0]').dispose();

                /**
                 * The countryId should never
                 * be NaN, but be prepared, "just in-case" (tm).
                 */
                if (!isNaN(countryId) && countryId > 0) {
                    /**
                     * Check to see if we already have the region
                     * data before attempting to grab it from the server.
                     */
                    if (Obay.form.newListingDetails.regions.has(countryId)) {
                        Obay.form.newListingDetails.buildSelectMarkup(Obay.form.newListingDetails.regions.get(countryId), regionSelect);
                    } else {
                        var url = location.protocol + "//" + location.host + '/data/get-regions';
                        new Request.JSON({
                            'url': url,
                            'onSuccess': function (response) {
                                Obay.form.newListingDetails.regions.set(countryId, response.regions);
                                Obay.form.newListingDetails.buildSelectMarkup(response.regions, regionSelect);
                            }
                        }).get({ 'format': 'json', 'country_id': countryId });
                    }
                }
            },

            /**
             * The town select box should be populated
             * with towns of the selected region only.
             * Fetch the associated towns from the server
             * where they're stored in the database.
             */
            populateTownSelect: function () {
                var regionId = parseInt(this.get('value'), 10);
                var townSelect = $('town-select');

                // Delete all but the first option
                townSelect.getElements('option[value!=0]').dispose();

                /**
                 * The regionId should never
                 * be NaN, but be prepared, "just in-case" (tm).
                 */
                if (!isNaN(regionId) && regionId > 0) {
                    /**
                     * Check to see if we already have the region
                     * data before attempting to grab it from the server.
                     */
                    if (Obay.form.newListingDetails.towns.has(regionId)) {
                        Obay.form.newListingDetails.buildSelectMarkup(Obay.form.newListingDetails.towns.get(regionId), townSelect);
                    } else {
                        var url = location.protocol + "//" + location.host + '/data/get-towns';
                        new Request.JSON({
                            'url': url,
                            'onSuccess': function (response) {
                                Obay.form.newListingDetails.towns.set(regionId, response.towns);
                                Obay.form.newListingDetails.buildSelectMarkup(response.towns, townSelect);
                            }
                        }).get({ 'format': 'json', 'region_id': regionId });
                    }
                }
            }
        },

        // Category selection when creating a new listing
        initNewListingCategorySliders: function () {
            $$('ol#new-listing-categories li span.parent-category').each(function (trigger) {
                /**
                 * The following is based on the assumption
                 * that the content to slide is a sibling
                 * of the trigger. For example, a dt dd pairing
                 * or a header tag and div tag.
                 */
                var content = trigger.getNext('ol');

                if (content !== null) {
                    var path = location.protocol + "//" + location.host + '/skins/www/default/media/';

                    trigger.setStyles({
                        'cursor': 'pointer',
                        'padding-left': 23,
                        'background-image': 'url(' + path + 'images/twisty-plus.png)',
                        'background-repeat': 'no-repeat',
                        'background-position': '8px 50%'
                    });

                    /**
                     * Store the slider instance in
                     * the trigger that causes the slide.
                     *
                     * Also toggle a flag to show if the trigger
                     * has been activated.
                     *
                     * Hide by default.
                     */
                    trigger.store('slider', new Fx.Slide(content, {
                        'transition': 'linear:in:out',
                        'duration': 0,
                        'onComplete': function (el) {
                            el.getParent('div').setStyle('height', 'auto');

                            if (this.open) {
                                trigger.setStyle('background-image', 'url(' + path + 'images/twisty-minus.png)');
                            } else {
                                trigger.setStyle('background-image', 'url(' + path + 'images/twisty-plus.png)');
                            }
                        }
                    }).hide());

                    /**
                     * Create an event handler that will
                     * retrieve the slider and toggle
                     * between open and closed states on
                     * each fire of the event.
                     */
                    trigger.addEvent('click', function () {
                        this.retrieve('slider').toggle();
                    });
                }
            });
        },

        newListingPhotos: {
            imageList: null,

            init: function () {
                Obay.form.newListingPhotos.upload.init();
                Obay.form.newListingPhotos.selection.init();
            },
            
            upload: {
                iframe: null,
                form: null,
                input: null,
                progressBar: null,

                /**
                 * Asynchronous uploads work, but there are a couple of small
                 * issues to work around. Testing on a production server would
                 * be idea, as it's difficult to test locally and I'm not sure
                 * the bandwidth throttling tool I'm using is very good. If the
                 * issues still exist, comment out the asynchronous init stuff,
                 * at least until we have the time to iron out the little bugs.
                 * 
                 * issues:
                 * 1) Even though the initial fetch for data is done after 2 seconds,
                 *    this is still checking the progress before the actual file transfer
                 *    has begun, and thus, it fails as the "progress" contains no data, but
                 *    returns as "done". Annoying. This need thorough testing on a production
                 *    server to know for sure...
                 */
                init: function () {
                    // automagically submit the form when selecting a file
                    var form = $('image-upload');
                    var input = form.getElement('#image-input-field');

                    Obay.form.newListingPhotos.upload.form = form;
                    Obay.form.newListingPhotos.upload.input = input;

                    if (form && input) {
                        // remove the "upload" button
                        form.getElement('fieldset.actions').destroy();

                        // inject dwProgressBar into document
                        /*var li = Obay.form.newListingPhotos.upload.input.getParent();
                        Obay.form.newListingPhotos.upload.progressBar = new dwProgressBar({
                            'container': li,
                            'boxID': 'progress-bar',
                            'percentageID': 'progress-bar-percentage',
                            'displayID': 'progress-bar-text',
                            'displayText': true
                        });*/

                        // submit the form after selecting a file
                        input.addEvent('change', function (event) {
                            // if form errors, remove them now
                            if ($('form-errors')) $('form-errors').destroy();
                            
                            // Disable the Continue button
                            var action_form = $('new-listing-images');
                            var continue_button = action_form.getElement('#continue-button');
                            continue_button.set('disabled', 'disabled');
                                                        
                            // submit the form
                            form.submit();
                            
                            // start checking the file upload progress
                            //Obay.form.newListingPhotos.upload.getProgress.delay(1000);
                        });

                        // init iFrame upload
                        /*Obay.form.newListingPhotos.upload.iframe = new IFrame({
                            'id': 'upload-target',
                            'name': 'upload-target',
                            'styles': {
                                'width': 10,
                                'height': 10,
                                'border': 0,
                                'overflow': 'hidden',
                                'position': 'absolute',
                                'left': -10000
                            }
                        }).inject(document.body);

                        // let the server know this is an iframe upload
                        new Element('input', {
                            'type': 'hidden',
                            'name': 'iframe',
                            'value': 1
                        }).inject(form);

                        // tell the form to submit to the iframe
                        form.setProperty('target', 'upload-target');*/
                    }
                },

                // pull upload progress from the server
                getProgress: function () {
                    var url = location.protocol + "//" + location.host + '/sell/upload-image-progress';
                    new Request.JSON({
                        'url': url,
                        'onSuccess': Obay.form.newListingPhotos.upload.processProgress
                    }).get({ 'format': 'json' });
                },

                // process data and update the progress bar
                processProgress: function (data) {
                    if (!data.done) {
                        // upload in progress
                        Obay.form.newListingPhotos.upload.getProgress.delay(1000);

                        // we don't want to divide by 0 in-case the file transfer hasn't actually begun yet ;)
                        if (data.total > 0) {
                            // calculate % done
                            var percent = data.current / data.total * 100;
                            Obay.form.newListingPhotos.upload.progressBar.set(percent);
                        }
                    } else {
                        // upload finished
                        Obay.form.newListingPhotos.upload.input.value = null;
                        var apcKeyInput = $('apc-key');

                        // set the new apc key for the next (potential) upload
                        if (apcKeyInput && data.apcKey) {
                            apcKeyInput.value = data.apcKey;
                        }

                        if (data.errors.length == 0) {
                            Obay.form.newListingPhotos.upload.finished(data);
                        } else {
                            Obay.form.newListingPhotos.upload.displayErrors(data.errors);
                        }
                        
                        // reset the progress bar
                        Obay.form.newListingPhotos.upload.progressBar.set(0);
                    }
                },

                // add the newly uploaded image to the thumbnail list
                finished: function (data) {
                    // set the src to the newly uploaded temp image
                    var src = location.protocol + "//" + location.host + '/media/tmp/' + data.filename;

                    var imageList = Obay.form.newListingPhotos.getImageList();
                    var li    = new Element('li').inject(imageList);
                    var label = new Element('label', { 'for': data.imageId }).inject(li);
                    var image = new Element('img', { 'src': src }).inject(label);
                    var input = new Element('input', {
                        'type': 'checkbox',
                        'checked': true,
                        'id': data.imageId,
                        'name': 'images[]',
                        'value': data.imageId
                    }).inject(li);

                    // make sure the li's are processed!
                    Obay.form.newListingPhotos.selection.init();
                },
                
                displayErrors: function (errors) {
                    var ul = new Element('ul', {
                        'id': 'form-errors'
                    }).inject(Obay.form.newListingPhotos.upload.form, 'before');
                    
                    errors.each(function (error) {
                        new Element('li', { 'text': error }).inject(ul);
                    });
                    
                    var tween = new Fx.Tween(ul, {
                        'property': 'opacity',
                        'onComplete': function (el) {
                            el.destroy();
                        }
                    });
                    
                    tween.start.delay(5000, tween, 0);
                }
            },

            getImageList: function () {
                if (Obay.form.newListingPhotos.imageList === null) {
                    var imageList = $('uploaded-images');

                    if (!imageList) {
                        // build and inject imageList
                        imageList = new Element('ol', {
                            'id': 'uploaded-images'
                        }).replaces('no-images-message');
                    }

                    Obay.form.newListingPhotos.imageList = imageList;
                }

                return Obay.form.newListingPhotos.imageList;
            },

            selection: {
                init: function () {
                    $$('ol#uploaded-images > li').each(function (li) {
                        if (!li.retrieve('processed')) {
                            li.store('processed', true);
                            var input = li.getElement('input');
                            var img =  li.getElement('img');

                            // hide the input
                            input.setStyle('display', 'none');

                            // create and inject "status" image
                            var path = location.protocol + "//" + location.host + '/skins/www/default/media/icons/';
                            var statusImg = new Element('img', {
                                'src': path + (input.checked ?  'add' : 'delete') + '.png',
                                'styles': {
                                    'position': 'absolute',
                                    'top': 5,
                                    'right': 5
                                }
                            }).inject(li);

                            var boundSelect = Obay.form.newListingPhotos.selection.select.bindWithEvent({
                                'input': input,
                                'statusImg': statusImg
                            });

                            li.addEvent('click', boundSelect);
                            li.setStyle('position', 'relative');
                        }
                    });
                    // Set the continue button to enabled
                    var action_form = $('new-listing-images');
                    var continue_button = action_form.getElement('#continue-button');
                    continue_button.setProperty('disabled', '');
                },

                select: function (event) {
                    event.stop();

                    if (this.input.checked) {
                        this.input.checked = false;
                        this.statusImg.src = this.statusImg.src.replace('add', 'delete');
                    } else {
                        this.input.checked = true;
                        this.statusImg.src = this.statusImg.src.replace('delete', 'add');
                    }
                }
            }
        },
        emails: {
            init: function(){
                ($('add-address')).addEvent( 'click', Obay.form.emails.addEmail );
            },
            /**
             * Add an email element to the list
             */
            addEmail: function() {
                var mails = $('email-list');
                var mailitem = new Element('li');
                var path = location.protocol + "//" + location.host + '/skins/www/default/media/icons/';
                 
                var mailtextbox = new Element('input', {
                    'type':'text',
                    'name': 'emails[]'
                }).inject(mailitem);
                
                var removemailbtn = new Element('img', {
                    'src':path + 'delete.png'                                
                }).inject(mailitem);
                
                removemailbtn.addEvent('click', Obay.form.emails.removeEmail);
                
                
                mailitem.inject(mails);
            },
            /**
             * This function removes the parent
             * object of the given one.
             * 
             * @param {Object} event
             */
            removeEmail: function(event) {
                this.parentNode.dispose();
            }
        }
        
    
    },

    /**
     * @author Sergi <sergi@ctisn.com>
     */
    advancedsearch: {
    	init: function () {
    		if ($('on_listitem')) Obay.advancedsearch.tabInit();    		
    	},
    	tabInit: function () {
    		var tab1 = $('tabpage-1');
    		// Checkboxes
			var type = $('search-type');
    		var listitem  = $('on_listitem');
    		var helptopic = $('on_helptopic');
			// Hide checkboxes (unobtrosive js)
    		$('search-types').setStyle('display','none');			
    		// Tab buttons
    		var itembutton = $('item-search');
    		var topicbutton = $('topic-search');
			
			var fieldset = $('advanced-search-fieldset');
			var fieldsetdiv = $('all-search');
    		fieldsetdiv.setStyle('height','auto');
			fieldset.setStyle('height','auto');
				
    		// Hide item selection details if searching through topics			
    		if (!listitem.get('checked')) {
				tab1.setStyle('display', 'none');
				topicbutton.className='selected';
			} else {
				itembutton.className='selected';
			}
    		/**
    		 * Add tab events: 
    		 * When clicking a tab change the appearance
    		 * of the other tab (switching classes), also
    		 * of the last element border bottom (using li.last
    		 * class). Finally, set the "search on" checkboxes 
    		 * values as needed.    		 
    		 */ 
    		itembutton.addEvent('click',
				function(event) {
					tab1.setStyle('display','block');
					topicbutton.className='';
					this.className='selected';
					helptopic.set('checked','');
					listitem.set('checked','checked');
				}
    		);
    		topicbutton.addEvent('click',
				function(event) {
					tab1.setStyle('display','none');
					itembutton.className='';
					this.className='selected';
					helptopic.set('checked','checked');
					listitem.set('checked','');
				}
    		);    		
    	}
    },

    /**
     * @author Sergi <sergi@ctisn.com>
     */
    helptopics: {
    	init: function () {    		
			if (!Browser.Engine.trident4){
				if ($('help-topics')) Obay.helptopics.initSliders();
			}
    	},
    	initSliders: function() {
    		var path = location.protocol + "//" + location.host + '/skins/www/default/media/icons/';
    		var up_path = path + 'arrow_up.png';
			var down_path = path + 'arrow_down.png';
			
    		//for each expandable list element add a new slider, which on sliding completition will set to auto all heights inside it
    		$('help-topics').getElements('.expandable').each(
    			function(elem) {
					var list_element = new Fx.Slide(elem.getElement('ul'), {
                        'transition': 'linear:in:out',
                        'duration': 0,
						'onComplete': function (el) {
							var parent = el.getParent().getParent();
	                        // When completed set the height of the parent div's to auto so the content is correctly shown.
							parent.getElements('div').each(function (elem) {
								elem.setStyle('height', 'auto');
			                });
	                    }	
					});					
					//hide the lists
					list_element.hide();
					
					// Set the image source
					var expand = elem.getElement('.more-sign').set('src',down_path);
					var expand = elem.getElement('.more-sign').setStyle('visibility','visible');
					
					//Add events:
					//When clicking the divider the content will expand
					elem.getElement('.expandable-header').addEvent('click',
						function(event) {
							var expand = this.getElement('.more-sign');							
							//if it's the divider or the arrow clicked, then toggle 
							if (!this.get('link-clicked')) {
								list_element.toggle();							
								//switch images
								if (list_element.open) {
                                    expand.set('src',down_path);
								} else {
                                    expand.set('src',up_path);
                                }
							}
						}
					);    					
					//when clicking the link we don't want the content to expand
		    		elem.getElement('.no-expand').addEvent('click',
						function(elem) {
	    					//we don't want to expand the element if it's clicked
	    					this.getParent().set('link-clicked','true');
						}
					);
    			}//end of function elemnt
    		); // end of foreach expandable    		
    	}
    }
};

window.addEvent('domready', Obay.init);