Dvintage.debugOn = false;
// extend Draggable.
// image can't be dragged past the canvas middle axes.
Dvintage.DraggableInCanvas = Class.create(Draggable, {
    draw: function(point) {
        var pos = Position.cumulativeOffset(this.element);
        var d = this.currentDelta();
        pos[0] -= d[0];
        pos[1] -= d[1];
        var p = [0, 1].map(function(i) {
            return (point[i] - pos[i] - this.offset[i])
        }.bind(this));
        if (p[0] >= Dvintage.canvas.mx)
            p[0] = Dvintage.canvas.mx
        if (p[0] + this.element.offsetWidth <= Dvintage.canvas.mx)
            p[0] = Dvintage.canvas.mx - this.element.offsetWidth
        if (p[1] >= Dvintage.canvas.my)
            p[1] = Dvintage.canvas.my
        if (p[1] + this.element.offsetHeight <= Dvintage.canvas.my)
            p[1] = Dvintage.canvas.my - this.element.offsetHeight
        var style = this.element.style;
        style.left = p[0] + "px";
        style.top = p[1] + "px";
        if (style.visibility == "hidden")
            style.visibility = ""; // fix gecko rendering
    }
})

Dvintage.wizardTab = null;

Dvintage.initializewizard = function () {

    var categories, colors, brands, currencies, vintageness, condition;
    var brandDOM = $('brand');
    var categoryDOM = $('category');
    var currencyDOM = $$('input[name="priceamount"]')[0];
    var proofofpurchaseDOM = $('proofofpurchase');
    var vintageDOM = $('vintageness');
    var conditionDOM = $('condition');

    new Ajax.Request(Subsite.baseHref + 'adwizard.html?initializewizard', {
        onSuccess: function(t) {

            var response = t.responseText.evalJSON();

            categories = Dvintage.sortCategories(response[0].categories);
            colors = response[1].colors;
            brands = response[2].brands;
            currencies = response[3].currencies;

            //todo: fill with ajax call for vintageness
            /*
             vintageness = [
             {name:"50's"},{name:"60's"},{name:"70's"},
             {name:"80's"},{name:"90's"},{name:"2000"},
             {name:"2001"},{name:"2002"},{name:"2003"},
             {name:"2004"},{name:"2005"},{name:"2006"},
             {name:"2007"},{name:"2008"}];
             */

            /* insert DOM tree like
             * <span class="dvintageradio" name="myradio">
             *	<span value="EUR">EUR</span> |
             *	<span value="USD">USD</span> |
             *	<span value="JPY">JPY</span>
             * </span>
             */
            // priceamount
            var currTopnode = new Element('span', {className:'dvintageradio',name:'pricecurrency'}).setStyle({
                marginLeft: '17px'
            });

            currencies.each(function (obj, index) {
                var currencycode = obj.currencycode;
                var currNode = new Element('span', {value:currencycode}).update(currencycode);
                currTopnode.appendChild(currNode);
                if (index < currencies.length - 1)
                    currTopnode.insert({bottom:' | '});
            })
            currencyDOM.insert({after:currTopnode})
            // now, transform this into Dvintage.Radioinput
            var currencyRadioInput = new Dvintage.Radioinput(currTopnode);
            currencyRadioInput.setValue('EUR');

            // initialize color's
            Dvintage.colorchooser = new Dvintage.Colorchooser();
            colors = colors.sort(function(a, b) {
                if (a.id < b.id) return -1;
                if (a.id > b.id) return 1;
            })		// sort by ID.
            colors.each(function(color) {
                Dvintage.colorchooser.addColor(color);
            })

            brands.each(function(obj) {
                var element = new Element('option', {value:obj.id, text:obj.name}).update(obj.name)
                brandDOM.appendChild(element)
            });
            // wire onchange behaviour
            brandDOM.observe('change', function() {
                $('hiddentitle').value = this[this.selectedIndex].readAttribute('text')
            });
            brandDOM.observe('custom:change', function() {
                $('hiddentitle').value = this[this.selectedIndex].readAttribute('text')
            });

            categories.each(function(obj) {
                var element = new Element('optgroup', {label:obj.displayName,value:obj.id}).setStyle({textTransform:'uppercase',fontWeight:'bold',    fontStyle:'normal'}).update(obj.displayName);
                categoryDOM.appendChild(element);
                obj.children.each(function(child) {
                    var element = new Element('option', {value:child.id, textvalue:child.displayName}).update('&nbsp;&nbsp;&nbsp;' + child.displayName);
                    categoryDOM.appendChild(element);
                })
            });

            // wire onchange behaviour
            categoryDOM.observe('change', Dvintage.configureSizes);
            categoryDOM.observe('custom:change', Dvintage.configureSizes);

            categoryDOM.observe('change', Dvintage.sizetable);
            categoryDOM.observe('custom:change', Dvintage.sizetable);


            /*
             vintageness.each(function(obj){
             var element = new Element('option', {value:obj.name}).update(obj.name);
             vintageDOM.appendChild(element);
             });
             */

            Dvintage.proofofpurchaseRadio = new Dvintage.Radioinput(proofofpurchaseDOM);
            Dvintage.proofofpurchaseRadio.setCallBack(Dvintage.createFeatureString);

            Dvintage.conditionRadio = new Dvintage.Radioinput(conditionDOM);

            // initialize image upload module.
            var numberofshelves = 3;
            var containingNode = $('step2');
            Dvintage.imageshelfs = new Dvintage.ImageShelfs(numberofshelves, containingNode);

            // edit an ad?
            var queryParams = location.search.toQueryParams();

            if (queryParams['adid']) {
                new Ajax.Request(Subsite.baseHref + 'editwizard.html?loadad&adid=' + queryParams['adid'], {
                    onSuccess: function(t) {

                        var response = t.responseText.evalJSON();

                        if (!response['id']) {
                            location.href = './404.html';
                            return;
                        }

                        // rename steps
                        $('allsteps').select('h1').each(function(h) {
                            h.innerHTML = h.innerHTML.replace('STEP', 'EDIT')
                        })

                        // prefill all steps
                        // step 1
                        categoryDOM.hide();
                        categoryDOM.value = response['categoryId'];
                        categoryDOM.up().insert(response['categoryName']);
                        categoryDOM.fire('custom:change');
                        brandDOM.next('a').hide();
                        brandDOM.value = response['brandId'];
                        brandDOM.hide();
                        brandDOM.up().insert({top: response['brandName']});
                        brandDOM.fire('custom:change');		// to set the title field.
                        
                        $('priceamount').value = response['priceAmount'];
                        currencyRadioInput.setValue(response['priceCurrency']);
                        $('vintageness').value = response['vintageness'];

                        // !! http://www.sixteensmallstones.org/ie-javascript-bugs-overriding-internet-explorers-documentgetelementbyid-to-be-w3c-compliant-exposes-an-additional-bug-in-getattributes
                        // IE returned the <meta name="description"> when using $('description').
                        $('step1').down('textarea').value = response['description'];
                        Dvintage.proofofpurchaseRadio.setValue(response['features']['proofofpurchase']);
                        // -- step 1


                        Dvintage.gotoStepOne();

                        // after dom updates:
                        Dvintage.wizardTab = new Dvintage.WizardTab({editmode:true, expired: response['expired']});


                        // step 2
                        // take it easy!
                        var doStepTwo = function() {
                            var adImages = ['/advertisement/' + response['encodedId'] + '/image/ZOOM/front.html?a','/advertisement/' + response['encodedId'] + '/image/ZOOM/label.html?a','/advertisement/' + response['encodedId'] + '/image/ZOOM/rear.html?a']
                            Dvintage.imageshelfs.initializeWithExcistingImages(adImages);
                            Dvintage.colorchooser.setSelectedColor(response['colorId']);
                        }.bind(this)
                        setTimeout(doStepTwo, 300);
                        // -- step 2

                        // step 3
                        var handlefeatures = function(feat) {
                            if (feat == 'unit') {
                                Dvintage.measurementUnitRadio.setValue(response['features'][feat]);
                                return;
                            }
                            var domnode;
                            if (domnode = $('step3').down('input[name=' + feat + ']')) {
                                domnode.value = response['features'][feat];
                            }
                        }
                        var featuresKeys = Object.keys(response['features']);
                        featuresKeys.each(handlefeatures)
                        Dvintage.conditionRadio.setValue(response['condition']);

                        if (response['originalSize'] != '' && response['originalSize'] != 0) { //patch for categories without size table
                            var originalSize = response['originalSize'].split(' ');
                            originalSize[1] = originalSize[1].replace('(', '').replace(')', '');
                            var handleSizeTable = function(div) {
                                if (!div.visible()) return;
                                div.select('.sizetable tr').each(function(row) {
                                    if ((row.down('td', 0).readAttribute('country') == originalSize[1]) && row.down('td[value=' + response['size'] + ']')) {
                                        row.down('td[value=' + response['size'] + ']').fire('custom:click');
                                    }
                                    ;
                                })
                            }
                            $$('.sizing').each(handleSizeTable)
                        }
                        // -- step 3

                        // step 4

                        // -- step 4
                        Dvintage.createFeatureString();

                        // add cancel edit links
                        $R(1, 4).each(function(i) {
                            var stepNode = $('step' + i);
                            var buttonNode = stepNode.down('.nextbutton');
                            var offsettop = buttonNode.offsetTop;
                            var cancelLink = new Element('a', {href:'./profile/myads.html'}).setStyle({display:'block',position:'absolute',right:'20px',textTransform:'uppercase',top:offsettop - 15 + 'px'}).update('cancel edit');
                            $('step' + i).insert(cancelLink);
                        })


                    }
                })
            } else {
                // after dom updates:
                Dvintage.wizardTab = new Dvintage.WizardTab;
            }

            //Dvintage.sizetable();
            Dvintage.togglespotlight();
            Dvintage.previewOverlay();


        }
    });
         
    brandDOM.observe('change', function(event){
        var el = event.findElement();
        
        var a_el = el.next();
        var hint_el = a_el.descendants()[0];
        
        var designer = el.options[ el.selectedIndex].text;
        
        var designerHint = new Array();
        
        designerHint['Armani'] = '<em>Giorgio</em> &amp; <em>Emporio&nbsp;Armani</em> only.<br />Thank you for placing <em>Armani&nbsp;Jeans</em> and <em>EA7</em> on our little sister <strong>Fashion-Vintage.com&nbsp;&gt;&gt</strong>';
        designerHint['Calvin Klein'] = '<em>Calvin Klein</em> first line only.<br />Thank you for placing <em>CK</em> and <em>CK&nbsp;Jeans</em> on our little sister <strong>Fashion-Vintage.com&nbsp;&gt;&gt</strong>';
        designerHint['Ralph Lauren'] = '<em>Ralph Lauren</em> only.<br />Thank you for placing <em>Polo&nbsp;Jeans</em> and <em>Polo&nbsp;Sport</em> on our little sister <strong>Fashion-Vintage.com&nbsp;&gt;&gt</strong>';
    	designerHint['Chloé'] = 'please note that <em>See by Chloé</em> is also listed!';
        designerHint['D&G'] = 'please note that <em>Dolce & Gabbana (first line)</em> is also listed!';
        designerHint['Dolce & Gabbana'] = 'please note that <em>D&G</em> is also listed!';
        designerHint['Donna Karan'] = 'please note that <em>DKNY</em> is also listed!';
        designerHint['DKNY'] = 'please note that <em>Donna Karan (first line)</em> is also listed!';
        designerHint['Just Cavalli'] = 'please note that <em>Roberto Cavalli (first line)</em> is also listed!';
        designerHint['KORS by MK'] = 'please note that <em>Micheal Kors (first line)</em> is also listed!';
        designerHint['MICHAEL by MK'] = 'please note that <em>Micheal Kors (first line)</em> is also listed!';
        designerHint['Marc Jacobs'] = 'please note that <em>Marc by Marc Jacobs</em> is also listed!';
        designerHint['Marc by Marc Jacobs'] = 'please note that <em>Marc Jacobs (first line)</em> is also listed!';
        designerHint['Michael Kors'] = 'please note that <em>KORS or MICHAEL by MK</em> is also listed!';
        designerHint['Prada'] = 'please note that <em>Prada Ligna Rossa</em> is also listed!';
        designerHint['Prada Ligna Rossa'] = 'please note that <em>PRADA (first line)</em> is also listed!';
        designerHint['RED Valentino'] = 'please note that <em>Valentino (first line) & Valentino Roma</em> are also listed!';
        designerHint['See by Chloé'] = 'please note that <em>Chloé (first line)</em> is also listed!';
        designerHint['Valentino'] = 'please note that <em>RED Valentino and Valentino Roma</em> are also listed!';
        designerHint['Valentino Roma'] = 'please note that <em>Valentino (first line) and RED Valentino</em> are also listed!';
        if (!designerHint[designer]){
            a_el.href = 'http://www.designer-vintage.com/brandsuggestionform.html';
            hint_el.innerHTML = 'Your designer not listed? &gt;&gt';
            hint_el.className = 'comment';
            
            el.className ='';
        } else {
            a_el.href = 'http://www.fashion-vintage.com/';
            hint_el.innerHTML = designerHint[designer];
            hint_el.className = 'comment fashion-hint-link';
        
            el.className ='fashion-hint';
        }
    });
}


Dvintage.colorchooser = Dvintage.Colorchooser = Class.create({
    initialize: function() {
        this.selectedColor = {id:null, name:null}
        this.allColors = [];
        this.trigger = $('colorchooser');
        this.trigger.observe('click', this._triggerClick.bind(this));
        this.colorBlock = $('colorBlock');
        this.container = $('colorBlockContainer');
        this.colorBlockSelectedColor = $('colorBlockSelectedColor');
        this.colorBlockHiddenField = $('colorBlockHiddenField');
        this.mouseoverelement = new Element('div').addClassName('colorBlockCellOver');
        this.editButton = new Element('div', {className:'uploadshelfeditbutton'}).update('edit');
        this._wireCloseButton();
    },
    _wireCloseButton: function () {
        this.closeButton = new Element('div').setStyle({position:'absolute',cursor:'pointer',right:'21px',top:'13px'}).update('CLOSE');
        this.colorBlock.insert(this.closeButton);
        this.closeButton.observe('click', function() {
            new Effect.BlindUp(this.colorBlock, {duration:.5})
        }.bind(this));
    },
    _triggerClick: function () {
        new Effect.BlindDown(this.colorBlock, {duration:.5});
    },
    _wireMouseActions: function (cell) {
        cell.observe('mouseover', this._cellMouseOver.bind(this));
        cell.observe('click', this._cellClick.bind(this));
    },
    _cellMouseOver: function (evt) {
        var element = evt.element();
        if (element == this.mouseoverelement)
            return;
        this.currentElement = element;
        this.mouseoverelement.update(element.readAttribute('name'));
        element.insert({
            top: this.mouseoverelement
        });
    },
    _cellClick: function (evt) {
        var element = evt.element();
        new Effect.BlindUp(this.colorBlock, {duration:.5});
        this.colorBlockSelectedColor.setStyle({
            border:'1px solid #ADA5A3',
            height:'34px',
            left:'44px',
            top:'18px',
            width:'34px',
            background:this.currentElement.style.background
        });
        this.selectedColor.name = this.currentElement.readAttribute('name');
        this.selectedColor.id = this.currentElement.readAttribute('colorid');
        this.trigger.down('.statusfooter').update(this.selectedColor.name);
        this.trigger.down('.statusfooter').insert(this.editButton);
        this.colorBlockHiddenField.value = this.selectedColor.id;
        this.colorBlockHiddenField.fire('custom:change');
    },
    addColor: function (color) {
        var hexvalue = '#' + color.name;
        this.allColors[color.id] = {name:color.displayName, hexvalue:hexvalue};
        var element = new Element('div').addClassName('colorBlockCell').writeAttribute({colorid:color.id,name:color.displayName,hexvalue:hexvalue});
        if (Dvintage.customColorThumbnails.include(color.name)) {
            element.setStyle({background:'url(/images/wizard/colorpicker_' + color.name + '.png) 1px 1px'});
        } else {
            element.setStyle({background:hexvalue});
        }
        this.container.appendChild(element);
        this._wireMouseActions(element);
    },
    getSelectedColor: function () {
        return this.selectedColor;
    },
    setSelectedColor: function (id) {
        var color = this.allColors[id];
        this.colorBlockSelectedColor.setStyle({background:color.hexvalue});
        this.selectedColor.name = color.name;
        this.selectedColor.id = id;
        this.colorBlockHiddenField.value = this.selectedColor.id
        this.colorBlockHiddenField.fire('custom:change');
    }
})


Dvintage.ImageShelfs = Class.create({
    initialize: function(nr, containingNode) {
        this.nrOfShelves = nr;
        this.containingNode = containingNode;
        this.shelves = [null];
        this.currentActive = null;
        this.nrOfFinishedUploads = 0;
        this._createShelves();
        this._setAliveFirst();
    },
    _createShelves: function () {
        for (var i = 1; i <= this.nrOfShelves; i++) {
            this.shelves.push(new Dvintage.ImageShelf(i, this));
        }
    },
    _setAliveFirst: function () {
        this.shelves[1].setAlive();
    },
    setCurrentActive: function (nr) {
        if (this.currentActive) {
            this.currentActive.setUnActive();
        }
        this.currentActive = this.shelves[nr];
    },
    setAliveNext: function (nr) {
        if (nr < this.nrOfShelves) {
            this.shelves[nr + 1].setAlive();
        }
    },
    updateShelveImage: function (nr, perms) {
        this.shelves[nr].updateShelveImage(perms);
    },
    initializeWithExcistingImages: function (srcs) {
        $$('#canvas .uploadedimage').invoke('addClassName', 'editmode');
        this.shelves.each(function(shelf, i) {
            if (shelf) {
                shelf.setTempImageUrl(srcs[i - 1]);
                shelf._afterUpload();
            }
        })
        // set the first active
        this.shelves[1].shelf.fire('custom:click');
    }
})


Dvintage.ImageShelf = Class.create({
    initialize: function(nr, imageshelfs) {
        this.DEAD = 0;
        this.ALIVE = 1;
        this.ACTIVE = 2;
        this.INACTIVE = 3;
        this.state = this.DEAD;
        this.nr = nr;
        this.imageNames = ['','full view','detail','label'];
        this.factor = 65 / 206;	// thumbnail vs canvas image
        this.defaultoffset = [88 * this.factor, 24 * this.factor]	// offset of the canvas
        this.imageshelfs = imageshelfs;
        this.hasTransformControls = false;
        this.form = $('wizardupload' + this.nr);
        this.input = this.form.down('input');
        this.label = this.form.down('label');
        this.setState(this.DEAD);
        this.imagesrc = 'adwizard.html?showimage&imagenr=' + this.nr;
        this._createShelf();
        this._insertValidateElement();
        this._wireUpload();
    },
    _insertValidateElement: function () {
        // element to be used by WizardTab, enable the next step button if all uploads are finished.
        this.validateElement = new Element('input', {type:'hidden',post:'true'});
        this.shelf.insert(this.validateElement);
    },
    unRegisterUploadFinished:  function () {
        // fire validate element.
        this.validateElement.value = '';
        this.validateElement.fire('custom:change');
    },
    _registerUploadFinished:  function () {
        // fire validate element.
        this.validateElement.value = 'Upload ' + this.nr + ' finished';
        this.validateElement.fire('custom:change');
    },
    _moveInputUnderMouse: function () {
        // trick to style the uploadbutton.

        this.form.observe('mousemove', function (evt) {
            var formOffsets = this.form.cumulativeOffset();
            var scrollOffset = this.form.getOffsetParent().scrollTop;
            this.input.setStyle({
                top:evt.pointerY() - formOffsets.top - 5 + scrollOffset + 'px',
                right: this.form.offsetWidth - (evt.pointerX() - formOffsets.left) - 40 + 'px'    // 90
            })

        }.bind(this))
    },
    _createShelf: function () {
        this.shelf = new Element('div', {id:'imageshelf' + this.nr,className:'imageshelf'});
        this.statusfooter = new Element('div', {className:'statusfooter'}).update(this.imageNames[this.nr]);
        this.shelf.insert(this.statusfooter);
        this.form.insert({before:this.shelf});
    },
    _wireUpload: function () {
        var iframe = new Element('iframe', {imagenr: this.nr, name: "uploadTarget" + this.nr});
        iframe.setStyle({position: 'absolute',left: '-5000px'});
        document.body.appendChild(iframe);

        this.form.setAttribute('target', 'uploadTarget' + this.nr);

        // todo: is this the best Safari fix, and, does it work for all versions?
        if (Prototype.Browser.WebKit) {
            iframe.observe('load', function() {
                Dvintage.images.images[this.nr].image.removeClassName('editmode');
                Dvintage.images.unsetTempImageUrl(this.nr);

                var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument :
                                iframe.contentWindow.document;
                var response = (iframeDoc.body.innerText) ? iframeDoc.body.innerText.evalJSON() :
                               iframeDoc.body.textContent.evalJSON();

                if ('FAILED' == response.status) {
                    this._afterUploadFailed(response.message);
                } else {
                    this._afterUpload();
                }

            }.bind(this));
        } else {
            iframe.observe('load', function () {
                if (this.isWired)
                    return;
                this.isWired = true;
                iframe.observe('load', function() {
                    Dvintage.images.images[this.nr].image.removeClassName('editmode');
                    Dvintage.images.unsetTempImageUrl(this.nr);

                    var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument :
                                    iframe.contentWindow.document;
                    var response = (iframeDoc.body.innerText) ? iframeDoc.body.innerText.evalJSON() :
                                   iframeDoc.body.textContent.evalJSON();

                    if ('FAILED' == response.status) {
                        this._afterUploadFailed(response.message);
                    } else {
                        this._afterUpload();
                    }
                }.bind(this));
            }.bind(this)
                    );
        }
    },
    _wireEditButton: function() {
        this.editButton = new Element('div', {className:'uploadshelfeditbutton'}).update('upload new');
        this.shelf.insert(this.editButton);
        this.editButton.observe('click', this._reset.bind(this))
    },

    _attachOnchangeHandler: function() {
        this.input.observe('change', function() {
            this.form.submit();
            this.label.setStyle({background:'url(images/wizard/ajaxloader.gif) no-repeat -10px 4px'});
        }.bind(this))
    },

    _reset:function() {
        if (!this.editButton.up()) return;
        this.label.setStyle({background:'#000'});
        this.form.show();
        this.editButton.remove();
        this.image.remove();
        this.imageContainer.remove();
        // replace input node with new one, so we can use onchange again, even if user selects an image with same name.
        this.input.remove();
        this.input = new Element('input', {type:'file', name:'file'});
        this.form.insert(this.input);
        this._attachOnchangeHandler();

    },

    _afterUploadFailed: function(errorMessage) {
        alert(errorMessage ? errorMessage : 'An unspecified error occurred.');

        this.setState(this.ACTIVE);

        this.label.setStyle({background:'#000'}); // remove loading bar
        this.form.show();

        // replace input node with new one, so we can use onchange again, even if user selects an image with same name.
        this.input.remove();
        this.input = new Element('input', {type:'file', name:'file'});
        this.form.insert(this.input);
        this._attachOnchangeHandler();
    },

    _afterUpload: function () {
        // image upload has finished (or, in editmode, after page load).
        if (this.tempimagesrc) {
            var src = this.tempimagesrc;
            Dvintage.images.setTempImageUrl(this.nr, src);
            this.tempimagesrc = null;
        }
        else {
            var date = new Date();
            var src = this.imagesrc + '&refresh=' + date.getTime();
            this.hasTransformControls = true;
        }

        this.setState(this.ACTIVE);
        this.form.hide();
        this.imageshelfs.setAliveNext(this.nr);
        this.shelf.observe('click', this._setActive.bind(this));
        this.shelf.observe('custom:click', this._setActive.bind(this));
        this.imageContainer = new Element('div', {className:'uploadshelfimage'});

        this.image = new Element('img', {src:src});
        this.image.setStyle({width:'120px', margin:'-5px 0 0 -28px'});
        this.imageContainer.insert(this.image);
        this.shelf.insert(this.imageContainer);
        // wire edit button
        this._wireEditButton();
        this._registerUploadFinished();
    },

    _setDead: function () {
        this.status = this.DEAD;
        this.label.setStyle({
            opacity: .5,
            cursor:'default'
        });
    },

    _setAlive: function () {
        this.status = this.ALIVE;
        this.label.setStyle({
            opacity: 1,
            cursor:'pointer'
        });
        // user can click for browse dialog
        this._moveInputUnderMouse();
        // submit form onchange;
        this._attachOnchangeHandler();
    },

    _setActive: function () {
        this.status = this.ACTIVE;
        this.imageshelfs.setCurrentActive(this.nr);
        this.shelf.setStyle({background:'#bbb', cursor:'default',borderColor:'#ada5a3'});
        $('finalimage').update(this.imageNames[this.nr]).show();
        Dvintage.images.setActiveImage(this.nr, true);
        if (this.hasTransformControls) {
            $('imagetransformcontrols').show();
            $('dragmousehelptext').show();
            $('usescrollwheeltext').show();
            $('disableimagecontrols').hide();

        }

    },
    _setUnActive: function () {
        this.status = this.UNACTIVE;

        Dvintage.images.setActiveImage(this.nr, true);
        this.shelf.setStyle({background:'#fff', cursor:'pointer'});
        if (this.hasTransformControls) {
            $('imagetransformcontrols').hide();
            $('dragmousehelptext').hide();
            $('usescrollwheeltext').hide();
            $('disableimagecontrols').show();
        }
    },
    setAlive: function () {
        this._setAlive()
    },
    setUnActive: function () {
        this._setUnActive();
    },
    updateShelveImage: function (perms) {
        var width = perms.dimensions[0] * this.factor + 'px';
        var offset = [-(this.defaultoffset[0] - (perms.move[0] * this.factor)) + 'px', -(this.defaultoffset[1] - (perms.move[1] * this.factor)) + 'px'];
        this.image.setStyle({width:width,marginTop:offset[1],marginLeft:offset[0]});
        var date = new Date();
        this.image.src = this.imagesrc + '&refresh=' + date.getTime();
    },
    setState: function (state) {
        if (state == this.DEAD)
            this._setDead();
        if (state == this.ALIVE)
            this._setAlive();
        if (state == this.ACTIVE)
            this._setActive();
    },
    setTempImageUrl: function (src) {
        this.tempimagesrc = src;
    }

})


Dvintage.WizardTab = Class.create({

    initialize: function() {
        this.options = Object.extend({
            editmode:false,
            expired:false
        }, arguments[0] || {});

        this.tabs = [];
        this.forms = [];

        // change texts if in edit mode
        if (this.options.editmode) {
            $$('.nextbutton').invoke('update', 'take a look');
            if (this.options.expired) {
                $$('.nextbutton')[$$('.nextbutton').length - 1].update('renew your ad');
            } else {
                $$('.nextbutton')[$$('.nextbutton').length - 1].update('save changes');
            }
        }

        // fill this.forms and this.tabs
        $$('.steps').each(function(stepNode, i) {
            var validElement = new Element('span', {className:'step_is_valid'}).hide();
            var tabNode = $('maincanvas').down('.tabsnavigatorcontainer div', i);
            tabNode.insert(validElement);

            this.fillTab(stepNode, i, tabNode, validElement);
            this.fillForm(stepNode, i, validElement);
        }.bind(this));

        this.activeTab = null;

        // open first tab
        this.tabs[0].open();
    },

    fillTab: function (stepNode, i, tabNode, validElement) {
        var tab = new Dvintage.Tab(stepNode, i, this, this.options.editmode, tabNode, validElement);
        tab.disableNext();
        this.tabs.push(tab);
    },

    fillForm: function (stepNode, i, validElement) {
        this.forms.push(new Dvintage.FormFields(stepNode, stepNode.select('input[post="true"], textarea[post="true"], select[post="true"]'), validElement, i, this))
    }

})

Dvintage.Tab = Class.create({

    initialize: function(stepNode, i, tab, editmode, tabNode, validElement) {
        this.stepNode = stepNode;
        this.tabNode = tabNode;

        this.validElement = validElement;

        this.nextbutton = stepNode.down('.nextbutton:not(#submitad)');

        this.hasBeenOpened = false;

        this.i = i;
        this.tab = tab;

        this.editmode = editmode;

        this.nextIsEnabled = false;
        this.scrollbar = null;

        Event.observe(window, 'resize', this._setScrollBar.bind(this));

        this.tabNode.observe('click', this.freeOpen.bind(this))

        this.validElement.observe('click', this.freeOpen.bind(this))

        if (this.nextbutton) {
            this.nextbutton.observe('click', this.next.bind(this));
            this.nextbutton.observe('custom:click', this.next.bind(this))
        }

    },

    freeOpen: function() {
        if (this.hasBeenOpened) {
            if (this.tab.activeTab.nextIsEnabled || this.tab.activeTab.i == 3) {            // current open tab must be valid && not be the last step...
                this.tab.activeTab.postStepElements();										// post changes current open tab
                this.open();
            } else {
                this.tab.forms[this.tab.activeTab.i].nextbutton.fire('custom:click');		// next is not enabled, so there's a error message to show.
            }
        }
    },

    _performAdditionalTasks: function() {

        // for all steps, close info popup's
        $('content').select('.commentpop').invoke('hide');

        if (this.i == 1) {

            var jar = new CookieJar({
                expires:60 * 60 * 24 * 750,   // seconds
                path: '/'
            });

            // user don't want to see this message again.
            if (jar.get('vimPhotoStylistDoNotShowAgain')) {
                return;
            }


            var VimPhotoStylistDoNotShowAgainToggle = Class.create({
                initialize:function() {
                    this.state = false;
                },
                toggle:function() {
                    this.state = !this.state;
                },
                getState:function() {
                    return this.state;
                }
            })
            var vimPhotoStylistDoNotShowAgainToggle = new VimPhotoStylistDoNotShowAgainToggle();

            var vimPhotoStylist = new Element('div', {id: 'vimPhotoStylist'});
            var vimPhotoStylistClose = new Element('div', {id: 'vimPhotoStylistClose'});
            var vimPhotoStylistDoNotShowAgain = new Element('div', {id: 'vimPhotoStylistDoNotShowAgain'});
            vimPhotoStylist.insert(vimPhotoStylistClose);
            vimPhotoStylist.insert(vimPhotoStylistDoNotShowAgain);

            this.stepNode.insert(vimPhotoStylist);
            vimPhotoStylistClose.observe('click', function() {

                vimPhotoStylist.remove()
                if (vimPhotoStylistDoNotShowAgainToggle.getState()) {
                    // set cookie
                    jar.put('vimPhotoStylistDoNotShowAgain', true);
                }

            })
            vimPhotoStylistDoNotShowAgain.observe('click', function() {

                vimPhotoStylistDoNotShowAgainToggle.toggle();

                if (vimPhotoStylistDoNotShowAgainToggle.getState()) {
                    vimPhotoStylistDoNotShowAgain.addClassName('donnotshowagainactive');
                } else {
                    vimPhotoStylistDoNotShowAgain.removeClassName('donnotshowagainactive');
                }

            })


        }
        if (this.i == 2) {
            var conditionsinfoDom = $('conditionsinfo');
            var conditionsinfoDomHeight = conditionsinfoDom.getHeight();
            var elementHeight = this.stepNode.getHeight();
            var availHeight = elementHeight - conditionsinfoDomHeight;
            availHeight = availHeight / 2;
            $('maincanvas').insert({after:conditionsinfoDom});
            conditionsinfoDom.setStyle({
                margin: availHeight + 74 + 'px 0 0 0'
            });
        }
        if (this.i == 3) {
            Dvintage.updateAdPreview()
        }
    },

    _setScrollBar: function() {
        if (this.tab.activeTab == this) {

            // new sizetable scrollbar step 3.
            if (this.i == 2 && typeof Dvintage.sizetableScrollBar != 'undefined') {
                Dvintage.sizetableScrollBar.update();
            }

            var viewPortHeight = document.viewport.getHeight();
            var stepNodeTop = this.stepNode.viewportOffset().top;
            var stepNodeHeight = this.stepNode.getHeight();
            var tabsnavigatorHeight = $('maincanvas').down('.tabsnavigator').getHeight();
            var footerHeight = $('footer').getHeight();

            var neededHeight = stepNodeTop + stepNodeHeight + tabsnavigatorHeight + footerHeight;
            if (viewPortHeight < neededHeight) {

                var newHeight = viewPortHeight - stepNodeTop - tabsnavigatorHeight - footerHeight;

                this.stepNode.setStyle({height:newHeight + 'px'})
            } else {
                this.stepNode.setStyle({height:'auto'})
            }

            if (!this.scrollbar) {
                this.scrollbar = new Dvintage.Scrollblock(this.stepNode);
            }

            this.scrollbar.reset();


        }
    },

    open: function() {
        if (this.tab.activeTab)
            this.tab.activeTab.close()
        this.tab.activeTab = this;
        this.hasBeenOpened = true;
        this.stepNode.show();

        this._setScrollBar();

        this._performAdditionalTasks();
        this.tabNode.addClassName('activetab');

    },
    close: function() {
        this.scrollbar.kill();
        this.scrollbar = null;
        this.tabNode.removeClassName('activetab');

        this.stepNode.hide();
    },
    next: function(evt) {
        if (!this.nextIsEnabled)
            return;
        evt.stop();
        this.postStepElements();
        if (this.editmode) {
            // open last step
            this.tab.tabs[this.tab.tabs.length - 1].open();
        }
        else {
            // open next step
            this.tab.tabs[this.i + 1].open();
        }
    },
    postStepElements: function () {
        // set session. use all relevant inputs of this tab.
        var serialize = Form.serializeElements(this.tab.forms[this.i].inputs);
        new Ajax.Request(Subsite.baseHref + 'adwizard.html?processstep', {
            parameters:serialize,
            onSuccess:function(t) {
                var result = t.responseText.evalJSON();
                Dvintage.rateTabel.setRates(result.advertisementPrice, result.premimumPrice, result.isedit);
            }
        });
    },
    enableNext: function() {
        if (this.nextbutton && !this.nextIsEnabled) {
            this.nextIsEnabled = true;
            this.nextbutton.setStyle({opacity:1}).removeClassName('inactive');
        }
    },
    disableNext: function() {
        if (this.nextbutton) {
            this.nextIsEnabled = false;
            this.nextbutton.setStyle({opacity:.3}).addClassName('inactive')
        }
    }

})


Dvintage.FormFields = Class.create({
    initialize: function(element, inputs, validElement, i, tab) {

        this.inputs = inputs;
        this.i = i;
        this.tab = tab;

        this.invalidInputs = this.inputs;
        this.validElement = validElement;

        if (this.nextbutton = element.down('.nextbutton')) {
            this.nextbutton.observe('click', this._markInvalidElements.bind(this));
            this.nextbutton.observe('custom:click', this._markInvalidElements.bind(this));
            this.nextbutton.observe('click', function() {
                this.blur()
            });
        }

        this.inputs.each(function(input) {
            if (input.getAttribute('validate'))
                input.observe('keydown', this._beforeInput.bind(this))
            input.observe('keyup', this._afterInput.bind(this))
            input.observe('change', this._afterInput.bind(this))
            input.observe('custom:change', this._afterInput.bind(this))
        }.bind(this))

        // editmode: all fields are pre-filled
        if (this.tab.options.editmode) {
            this.tab.tabs[i].hasBeenOpened = true;
            this.enableNext();
        }

    },
    enableNext: function() {
        this.tab.tabs[this.i].enableNext();
        this.validElement.show();
    },
    _beforeInput: function(evt) {
        if (String.fromCharCode(evt.keyCode).match(/\d/) || [Event.KEY_BACKSPACE,Event.KEY_TAB,Event.KEY_RETURN,Event.KEY_ESC,Event.KEY_LEFT,Event.KEY_UP,Event.KEY_RIGHT,Event.KEY_DOWN,Event.KEY_DELETE,Event.KEY_HOME,Event.KEY_END,Event.KEY_PAGEUP,Event.KEY_PAGEDOWN].include(evt.keyCode))
            return;
        evt.stop()
    },
    doCheck: function () {
        this._afterInput();
    },
    _afterInput: function (evt) {
        // reset invalid's
        var element = evt.element();
        element.setStyle({borderColor:'#ada5a3'});
        var test;
        if (test = element.next('.invalidMarker')) {
            test.parentNode.removeChild(test)
        }

        this.invalidInputs = [];
        this.inputs.each(function(ipt) {
            if (ipt.tagName == 'SELECT') {
                if (ipt[ipt.selectedIndex].disabled) {
                    this.invalidInputs.push(ipt);
                }
            }
            else {
                if (ipt.value == '') {
                    this.invalidInputs.push(ipt);
                }
            }
        }.bind(this))

        if (this.invalidInputs.length > 0) {
            this.tab.tabs[this.i].disableNext();
            this.validElement.hide();
        } else {
            this.enableNext();
        }
        if (Dvintage.debugOn)
            this.enableNext();
    },
    _markInvalidElements: function () {
        if (this.invalidInputs.length == 0)
            return;

        var message = new Element('div').setStyle({
            background:'#fff',
            border:'1px solid #ADA5A3',
            padding:'5px',
            position:'absolute',
            bottom:'53px',
            right:'22px',
            width:'315px',
            textTransform:'uppercase',
            zIndex:'10'}).update('Please fill out all the marked fields, thanks!').hide();

        this.nextbutton.parentNode.insert(message);

        new Effect.Appear(message, {
            afterFinish: function() {
                setTimeout(function() {
                    new Effect.Fade(message, {
                        afterFinish: function () {
                            message.parentNode.removeChild(message);
                        }
                    })
                }, 6000);
            }
        });

        this.invalidInputs.each(function(invalidInput) {
            var dvintageradio;
            if (dvintageradio = invalidInput.previous('.dvintageradio')) {
                dvintageradio.addClassName('invalid');
                dvintageradio.observe('click', function() {
                    dvintageradio.removeClassName('invalid');
                })
            } else if (invalidInput.up('.imageshelf')) {
                invalidInput.up('.imageshelf').setStyle({borderColor:'#B4005E'});
            } else if (invalidInput.tagName == 'SELECT') {
                invalidInput.setStyle({background:'#B4005E'});
                invalidInput.observe('click', function() {
                    invalidInput.setStyle({background:'#fff'});
                })
            } else {
                invalidInput.setStyle({borderColor:'#B4005E'});
                invalidInput.observe('click', function() {
                    invalidInput.setStyle({border:'1px solid #ADA5A3'});
                })
            }
        })
    }
})


Dvintage.sizetable = function() {
    // delete current sizetables

    $$('.sizing').invoke('remove');

    // create table
    var sizeFilter = new Dvintage.SizeFilter();
    var selectedOption = $('category').options[$('category').selectedIndex];
    var selectedValue = selectedOption.readAttribute('textvalue');

    // sets correct cat:
    var hasSizesByName = sizeFilter.hasSizesByName(selectedValue);

    // show or hide comment:
    if (hasSizesByName) {
        $('category_sizechart_info').show();
    } else {
        $('category_sizechart_info').hide();
    }

    if (hasSizesByName) {
        // insert new sizetable, create horizontal scrollbar.
        var sizeTableNodes = sizeFilter.createNodes();
        $('step3').insert({
            top: sizeTableNodes
        })

        setTimeout(function() {
            Dvintage.sizetableScrollBar = new Dvintage.ScrollblockH(sizeTableNodes.down('.sizetablescrollarea'));
        }, 500)


        var tableCells = $$('.sizetable td');
        var selectedcell = null;

        var attachevents = function(cell) {
            if (cell.hasClassName('p'))
                return;
            cell.observe('click', select.bind(cell))
            cell.observe('custom:click', select.bind(cell))
        }

        var select = function() {
            if (selectedcell) {
                selectedcell.removeClassName('sizetableCellSelected');
            }
            this.addClassName('sizetableCellSelected');
            selectedcell = this;
            var hiddeninput = $$('input[name=size]')[0];
            hiddeninput.value = this.getAttribute('value');
            var originalSize = $$('input[name=originalSize]')[0];
            originalSize.value = this.innerHTML + ' (' + this.readAttribute('country') + ')';
            hiddeninput.fire('custom:change');
            originalSize.fire('custom:change');

        }

        tableCells.each(attachevents);
    }
}

Dvintage.setCanvas = function() {
    var canvas = $('canvas');
    Dvintage.canvas = {
        element: canvas,
        ppt: [85,22],
        mx: 390 / 2,
        my: 265 / 2
    }

}

Dvintage.Image = Class.create({
    initialize: function(nr) {
        this.nr = nr;
        this.minWidth = 100;
        this.url = 'adwizard.html?showimage&imagenr=' + this.nr;
        this.loaded = false;
        this.swapWidthAndHeight = false;
        this._insertInDOM();
        this.updateSrc();
        this._initPerms();
        this._wireDrag();
        this._wirescaleByScrollWheel();
    },
    setTempImageUrl: function (url) {
        this.tempimageurl = url;
    },
    unsetTempImageUrl: function () {
        this.tempimageurl = null;
    },
    updateSrc: function () {
        if (this.swapWidthAndHeight) {
            this.image.setStyle({
                width: this.image.offsetHeight + 'px'
            })
            this.swapWidthAndHeight = false;
        }
        var date = new Date();
        if (this.tempimageurl) {
            this.image.src = this.tempimageurl;
        }
        else {
            this.image.src = this.url + '&refresh=' + date.getTime();
        }
    },
    _initPerms: function () {
        this.perms = {
            fliph: false,
            flipv: false,
            rotate: 0
        }
    },
    _insertInDOM: function() {
        this.image = new Element('img', {className:'uploadedimage'});
        Dvintage.canvas.element.insert({top:this.image});
    },
    _wireDrag: function() {
        new Dvintage.DraggableInCanvas(this.image, {
            zindex:0,
            onEnd: function() {
                Dvintage.imageshelfs.updateShelveImage(this.nr, this.getPerms())
            }.bind(this)
        });
    },
    _wirescaleByScrollWheel: function () {
        if (window.addEventListener)
            Event.observe(this.image, 'DOMMouseScroll', this._scaleByScrollWheel.bind(this));
        else
            Event.observe(this.image, 'mousewheel', this._scaleByScrollWheel.bind(this));
    },
    _scaleByScrollWheel: function(event) {
        /* http://adomas.org/javascript-mouse-wheel/ */
        var delta = 0;
        if (!event) /* For IE. */
            event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
            delta = event.wheelDelta / 10;
            /** In Opera 9, delta differs in sign as compared to IE.*/
            if (window.opera)
                delta = -delta;
        }
        else
        if (event.detail) { /** Mozilla case. */
            /** In Mozilla, sign of delta is different than in IE. **/
            delta = -event.detail * 5;

        }
        this.scale(delta);
    },
    getPerms: function () {
        var p = this.perms;
        var hideMe = false;

        // if not hidden, temporary set 'visible' to measure element inside.
        if (!$('step2').visible()) {
            hideMe = true;
            $('step2').show();
        }

        var returnValue = {
            fliph: p.fliph,
            flipv: p.flipv,
            rotate: p.rotate,
            move: [this.image.offsetLeft, this.image.offsetTop],
            dimensions: [this.image.offsetWidth, this.image.offsetHeight]
        }

        if (hideMe) {
            $('step2').setStyle({visibility:'visible'}).hide();
        }

        return returnValue;

    },
    hide: function() {
        this.image.setStyle({visibility:'hidden',zIndex:-1});
    },
    show: function() {
        this.image.setStyle({visibility:'visible',zIndex:0});
    },
    scale: function(Dw) {
        var w = this.image.offsetWidth;
        var newWidth = w + Dw;
        if (newWidth < this.minWidth)
            return;
        var x1 = this.image.offsetLeft;
        var y1 = this.image.offsetTop;
        var dx = x1 - Dvintage.canvas.mx;
        var dy = y1 - Dvintage.canvas.my;
        var x2 = x1 + ((dx / w) * Dw);
        var y2 = y1 + ((dy / w) * Dw);
        this.image.setStyle({
            width: w + Dw + 'px',
            top: y2 + 'px',
            left: x2 + 'px'
        });
        Dvintage.imageshelfs.updateShelveImage(this.nr, this.getPerms());
    },
    fliph: function() {
        if (this.perms.rotate == 90 || this.rotate == 270) {
            this.perms.flipv = !this.perms.flipv;
        }
        else {
            this.perms.fliph = !this.perms.fliph;
        }
        this.doTransformation('flipvertical');
    },
    flipv: function() {
        if (this.perms.rotate == 90 || this.perms.rotate == 270) {
            this.perms.fliph = !this.perms.fliph;
        }
        else {
            this.perms.flipv = !this.perms.flipv;
        }
        this.doTransformation('fliphorizontal');
    },
    rotcw: function() {
        this.perms.rotate = (this.perms.rotate == 270) ? 0 : this.perms.rotate + 90;
        this.swapWidthAndHeight = true;
        this.doTransformation('rotateright');
    },
    rotccw: function() {
        this.perms.rotate = (this.perms.rotate == 0) ? 270 : this.perms.rotate - 90;
        this.swapWidthAndHeight = true;
        this.doTransformation('rotateleft');
    },
    doTransformation: function(action) {
        new Ajax.Request(Subsite.baseHref + 'imagemanipulation.html?' + action, {
            parameters: {
                imagenr: this.nr
            },
            onSuccess: function() {
                this.updateSrc();
                Dvintage.imageshelfs.updateShelveImage(this.nr, this.getPerms())
            }.bind(this)
        })
    }
})

Dvintage.Images = Class.create({
    initialize: function() {
        //this.shelf = new Dvintage.Shelf();
        this.images = [null];
        this.image = null;
        this.zoomfactor = 400 / 210;	// the image that the server scales to.
        [1,2,3].each(this._createImages.bind(this));
        this._wireScaleSlider();
        this._wireTransformButtons();
        $$('.uploadshelf').each(this._wireShelf.bind(this))
    },
    _wireTransformButtons: function () {
        $('rotcw').observe('click', function() {
            this.image.rotcw()
        }.bind(this));
        $('rotccw').observe('click', function() {
            this.image.rotccw()
        }.bind(this));
        $('fliph').observe('click', function() {
            this.image.fliph()
        }.bind(this));
        $('flipv').observe('click', function() {
            this.image.flipv()
        }.bind(this));
    },
    _wireScaleSlider: function () {
        this.slider = {
            element: $('slider'),
            startoffsetTop: $('slider').offsetTop,
            currentOffsetTop: this.startoffsetTop,
            getDirection: function() {
                var delta = $('slider').offsetTop - this.currentOffsetTop;
                this.currentOffsetTop = $('slider').offsetTop;
                return -delta
            },
            reset: function() {
                this.currentOffsetTop = this.startoffsetTop;
            }
        }
        new Draggable(this.slider.element, {
            constraint: 'vertical',
            revert: true,
            change: this._scaleBySlider.bind(this),
            onEnd: function() {
                this.slider.reset();
            }.bind(this),
            snap: function(x, y, draggable) {
                function constrain(n, lower, upper) {
                    if (n > upper) return upper;
                    else if (n < lower) return lower;
                    else return n;
                }

                element_dimensions = Element.getDimensions(draggable.element);
                parent_dimensions = Element.getDimensions(draggable.element.parentNode);
                return[
                    constrain(x, 0, parent_dimensions.width - element_dimensions.width),
                    constrain(y, 0, parent_dimensions.height - element_dimensions.height)];
            }
        });
    },
    _scaleBySlider: function() {
        var delta = this.slider.getDirection();
        this.image.scale(delta * 15)
    },
    _wireShelf: function (element, i) {
        element.observe('click', this.setActiveImage.bind(this, i + 1));
    },
    _createImages: function(nr) {
        this.images.push(new Dvintage.Image(nr));
    },
    updateSrc: function () {
        this.image.updateSrc();
    },
    setTempImageUrl: function(nr, url) {
        this.images[nr].setTempImageUrl(url);
    },
    unsetTempImageUrl: function(nr) {
        this.images[nr].setTempImageUrl();
    },
    setActiveImage: function (nr, updateSrc) {
        if (this.image)
            this.image.hide();
        this.image = this.images[nr];
        if (updateSrc)
            this.updateSrc();
        this.image.show();
    },
    getPostParameters: function() {
        var query = new Hash();
        [1, 2, 3].each(function(i) {
            var image = this.images[i];
            var p = image.getPerms();
            query.set('fliph' + i, p.flipv);
            query.set('flipv' + i, p.fliph);
            query.set('rotateangle' + i, p.rotate);
            query.set('cropx' + i, Math.round((Dvintage.canvas.ppt[0] - p.move[0]) * this.zoomfactor));
            query.set('cropy' + i, Math.round((Dvintage.canvas.ppt[1] - p.move[1]) * this.zoomfactor));
            query.set('resizewidth' + i, Math.round(p.dimensions[0] * this.zoomfactor));
            query.set('resizeheight' + i, Math.round(p.dimensions[1] * this.zoomfactor));

        }.bind(this));
        return query;
    }
})

Dvintage.createFeatureString = function() {
    var featurestring = '';

    var measurementstableInput = $$('.measurementstable input');

    measurementstableInput.each(function(input) {
        if (!input.value.empty()) {
            featurestring += input.name + '__=__' + input.value + '__,__';
        }
    })

    if (typeof Dvintage.measurementUnitRadio != 'undefined') featurestring += 'unit__=__' + Dvintage.measurementUnitRadio.getValue() + '__,__';
    if (typeof unitlesssizeRadio != 'undefined') featurestring += 'unitlesssize__=__' + unitlesssizeRadio.getValue() + '__,__';
    if (typeof Dvintage.proofofpurchaseRadio != 'undefined') featurestring += 'proofofpurchase__=__' + Dvintage.proofofpurchaseRadio.getValue() + '__,__';

    if (featurestring.length != 0) {
        featurestring = featurestring.slice(0, -5);
    }
    $('featuresstep1').value = featurestring;
    $('featuresstep3').value = featurestring;
}


Dvintage.togglespotlight = function () {

    var isVIP = ($('getspotlight')) ? false : true;

    var posttoserver = function (premiumBool) {
        new Ajax.Request(Subsite.baseHref + 'adwizard.html?processstep',
        {parameters:{premium:premiumBool}})
    }

    var togglespotlight = function (value) {
        var adPreview = $('adPreview');
        if (value == 'off') {

            if (!isVIP) {
                $('getspotlight').show()
            }
            $('previewoverlayopen').setStyle({top:'150px',right:'580px'});

            adPreview.removeClassName('premiumAd').setStyle({margin:'0px 20px 30px 0pt',width:'119px', backgroundPosition:'left bottom'}).addClassName('normalAd');
            adPreview.down('.premiumAdDetails').removeClassName('premiumAdDetails').addClassName('normalAdDetails');
            adPreview.down('.premiumAdCreatedOn').removeClassName('premiumAdCreatedOn').addClassName('normalAdCreatedOn');

            adPreview.down('.premiumAdPrice').removeClassName('premiumAdPrice').addClassName('normalAdPrice').show();

            adPreview.down('.premiumAdImage').removeClassName('premiumAdImage').addClassName('normalAdImage').setStyle({left:'7px'});
            adPreview.down('.premiumAdDescription').hide();
            adPreview.down('.premiumAdTitle').removeClassName('premiumAdTitle').addClassName('normalAdTitle');

            adPreview.down('.premiumAdCountryCode').removeClassName('premiumAdCountryCode').addClassName('normalAdCountryCode');

            Dvintage.rateTabel.setSpotlightOff()

            var title = $('brand').options[$('brand').selectedIndex].readAttribute('text') + ' ' + Dvintage.cats2cat($('category').options[$('category').selectedIndex].readAttribute('textvalue'));
            adPreview.down('.normalAdTitle').update(title.truncate(20));
        }
        else {

            if (!isVIP) {
                $('getspotlight').hide()
            }
            $('previewoverlayopen').setStyle({top:'130px',right:'30px'});

            adPreview.removeClassName('normalAd').setStyle({margin:'0 0 51px 0px;',width:'721px', backgroundPosition:'center right', borderLeft:'1px solid #ada5a3'}).addClassName('premiumAd');
            adPreview.down('.normalAdDetails').removeClassName('normalAdDetails').addClassName('premiumAdDetails');
            adPreview.down('.normalAdCreatedOn').removeClassName('normalAdCreatedOn').addClassName('premiumAdCreatedOn');
            adPreview.down('.normalAdPrice').removeClassName('normalAdPrice').addClassName('premiumAdPrice').hide();

            adPreview.down('.normalAdImage').removeClassName('normalAdImage').addClassName('premiumAdImage').setStyle({left:'5px'});
            adPreview.down('.premiumAdDescription').show();
            adPreview.down('.normalAdTitle').removeClassName('normalAdTitle').addClassName('premiumAdTitle');

            /*
             * hack for dom not ready yet in IE
             */
            var title;
            setTimeout(function() {
                title = $('brand').options[$('brand').selectedIndex].readAttribute('text') + ' ' + Dvintage.cats2cat($('category').options[$('category').selectedIndex].readAttribute('textvalue'));
                adPreview.down('.premiumAdTitle').update(title);
            }, 1000)

            adPreview.down('.normalAdCountryCode').removeClassName('normalAdCountryCode').addClassName('premiumAdCountryCode');

            if (!isVIP) {
                Dvintage.rateTabel.setSpotlightOn()
            }
        }
        posttoserver(value == 'on');
    }

    if (!isVIP) {
        var spotlightonoff = new Dvintage.Radioinput($('spotlightonoff'));
        spotlightonoff.setValueByIndex(1);
        spotlightonoff.setCallBack(togglespotlight);
        $('getspotlight').onclick = function() {
            spotlightonoff.setValueByIndex(0);
        }
    } else {
        togglespotlight('on');
    }

}

Dvintage.updateAdPreview = function () {
    var topnode = $('adPreview');
    var isVIP = ($('getspotlight')) ? false : true;
    // the perms of image number 1
    var perms = Dvintage.images.images[1].getPerms();
    Dvintage.clipAndResizeImage(topnode.down('.premiumAdImage img, .normalAdImage img'), perms, 65 / 206);

    var date = new Date();
    topnode.down('.premiumAdImage img, .normalAdImage img').src = Dvintage.images.images[1].image.src + '&refresh=' + date.getTime();

    /*
     * This is great!
     * Internet explorer treats id's and names as interchangable. Therfore $('description) retrieves <meta name="description">
     * This solution works as long as the wanted textarea is first in the DOM.
     */
    var aTextareaNamedDescription = $$('textarea')[0];
    topnode.down('.premiumAdDescription').update(aTextareaNamedDescription.value.truncate(150));

    var title = $('brand').options[$('brand').selectedIndex].readAttribute('text') + ' ' + Dvintage.cats2cat($('category').options[$('category').selectedIndex].readAttribute('textvalue'));

    if (!isVIP)
        title = title.truncate(20);
    topnode.down('.premiumAdTitle, .normalAdTitle').update(title);
    topnode.down('.premiumAdPrice, .normalAdPrice').update(Dvintage.currencyToSymbol($$('input[name="pricecurrency"]')[0].value) + ' ' + $$('input[name="priceamount"]')[0].value + ',-');
}

Dvintage.clipAndResizeImage = function (image, perms, factor) {
    var defaultoffset = [88 * factor, 24 * factor]
    var width = perms.dimensions[0] * factor + 'px';
    var offset = [-(defaultoffset[0] - (perms.move[0] * factor)) + 'px', -(defaultoffset[1] - (perms.move[1] * factor)) + 'px'];
    image.setStyle({width:width,marginTop:offset[1],marginLeft:offset[0]});
}


Dvintage.gotoStepOne = function () {
    $('allsteps').setStyle({visibility:'visible'});
    $('introduction').setStyle({display:'none'});
    $('tabsnavigatorid').show();
}
Dvintage.introbutton = function () {
    $('introbutton').observe('click', Dvintage.gotoStepOne);
    // debug code:
    if (Dvintage.debugOn)
        Dvintage.gotoStepOne();
}

Dvintage.previewOverlay = function () {

    var overlayElement = $('previewoverlay');

    $('previewoverlayopen').observe('click', function () {

        overlayElement.down('h3').update($('brand').options[$('brand').selectedIndex].readAttribute('text') + ' ' + Dvintage.cats2cat($('category').options[$('category').selectedIndex].readAttribute('textvalue')));

        $('price').update($('priceamount').value + ' ' + $$('input[name="pricecurrency"]')[0].value);

        /*
         * This is great!
         * Internet explorer treats id's and names as interchangable. Therfore $('description) retrieves <meta name="description">
         * This solution works as long as the wanted textarea is first in the DOM.
         */
        var aTextareaNamedDescription = $$('textarea')[0];
        $('addetaildescription').update(aTextareaNamedDescription.value);

        var perms = Dvintage.images.images[1].getPerms();
        Dvintage.clipAndResizeImage($('img1').down('img'), perms, 210 / 206);
        var perms = Dvintage.images.images[2].getPerms();
        Dvintage.clipAndResizeImage($('img2').down('img'), perms, 65 / 206);
        var perms = Dvintage.images.images[3].getPerms();
        Dvintage.clipAndResizeImage($('img3').down('img'), perms, 65 / 206);

        var date = new Date();
        $('img1').down('img').src = Dvintage.images.images[1].image.src + '&refresh=' + date.getTime();
        $('img2').down('img').src = Dvintage.images.images[2].image.src + '&refresh=' + date.getTime();
        $('img3').down('img').src = Dvintage.images.images[3].image.src + '&refresh=' + date.getTime();

        overlayElement.down('td', 2).update(Dvintage.colorchooser.getSelectedColor().name);
        overlayElement.down('td', 5).update($$('input[name="originalSize"]')[0].value);
        overlayElement.down('td', 8).update($('vintageness')[$('vintageness').selectedIndex].innerHTML);
        overlayElement.down('td', 11).update($$('input[name="condition"]')[0].value);
        overlayElement.down('td', 14).update(Dvintage.proofofpurchaseRadio.getValue());

        // create the measurements table:
        var measurementsTable = $('measurementsTable');
        measurementsTable.select('tbody tr').invoke('remove');
        $$('input.measurements').each(function(inputNode, index) {
            var row = new Element('tr');
            var labelrowNode = inputNode.up('tr').previous('tr');
            var cell1 = new Element('td').update(labelrowNode.down('td', index).innerHTML);
            //			var cell1 = new Element('td').update(inputNode.readAttribute('name'));
            var cell2 = new Element('td').update(':');
            var cell3 = new Element('td').update(inputNode.value).setStyle({textAlign:'right',padding:'0 4px 0 4px'});
            var cell4 = new Element('td').update(Dvintage.measurementUnitRadio.getValue()).setStyle({padding:'0 4px 0 4px'});
            row.insert(cell1).insert(cell2).insert(cell3).insert(cell4);
            measurementsTable.down('tbody').insert(row);
        })

        new Effect.BlindDown(overlayElement, {duration:0.5})
    })

    $('previewoverlayclose').observe('click', function () {
        new Effect.BlindUp(overlayElement, {duration:0.5})
    })
}

Dvintage.wireSubmitButton = function() {
    var postAndStoreParamaters = function () {
        var imageParamaters = Dvintage.images.getPostParameters();
        var serializedImageParamaters = imageParamaters.toQueryString();
        // save last step in cookie. fix for use case where somebody creates an ad, but is not yet a user.
        var jar = new CookieJar({path: '/'});
        jar.put('my_advertisement', imageParamaters);
        location.href = Subsite.baseHref + "submitadvertisement.html?submitad&" + serializedImageParamaters;
    }
    $('submitad').observe('click', postAndStoreParamaters);
}

Dvintage.step0or1 = function() {
    // edit an ad?
    var queryParams = location.search.toQueryParams();
    if (queryParams['adid']) {
        Dvintage.gotoStepOne();
    }
    else {
        Dvintage.introbutton();
    }
}


Dvintage.RateTabel = Class.create({
	initialize:  function() {
		this.tabel = $('ratetabel');
		this.posting = this.tabel.down('td',1);
		this.spotlight = this.tabel.down('td',3);
		this.total = this.tabel.down('td',5);
		this.spolightStatus = false;
		this.postingR = 0;
		this.premiumR = 0;
        this.isEdit = false;
	},

	_formatPrice: function(price) {
		var displayPrice = roundNumber(price, 2);
        if (displayPrice == '0.00' && this.isEdit) {
            return 'PAID';
        }
		return '&euro; ' + displayPrice;
	},

	_setTotal: function(){
		var total = (this.spolightStatus)? parseFloat(this.postingR) + parseFloat(this.premiumR) : this.postingR;
		this.total.update(this._formatPrice(total))
	},

	setSpotlightOn: function() {
		this.spolightStatus = true;
		this.spotlight.setStyle({color:'#000'});
		this._setTotal();
	},

	setSpotlightOff: function() {
		this.spolightStatus = false;
		this.spotlight.setStyle({color:'#ADA5A3'});
		this._setTotal();
	},

	setRates: function (postRate, premiumRate, isEdit) {

        this.isEdit = isEdit;
		var postr = this._formatPrice(postRate);
		var premiumr = this._formatPrice(premiumRate);

        this.posting.update(postr);
		this.spotlight.update(premiumr);

		this.postingR = postRate;
		this.premiumR = premiumRate;
		this._setTotal();
	}
})


Dvintage.adPostingRates = function () {

    $('ad_posting_rates').observe('click', function() {
        $('maincanvas').insert($('ad_posting_rates_commentpop'));
        $('ad_posting_rates_commentpop').show();
    })


}
document.observe("dom:loaded", Dvintage.adPostingRates);

Dvintage.taskSchedular.setHaltExecution();
document.observe("dom:loaded", function() {
    Dvintage.taskSchedular.registerFunction(Dvintage.step0or1);
    Dvintage.taskSchedular.registerFunction(Dvintage.introbutton);
    Dvintage.taskSchedular.registerFunction(Dvintage.setCanvas);
    Dvintage.taskSchedular.registerFunction(function() {
        Dvintage.images = new Dvintage.Images()
    });
    Dvintage.taskSchedular.registerFunction(function() {
        if ($('ratetabel')) {
            Dvintage.rateTabel = new Dvintage.RateTabel()
        }
    });
    Dvintage.taskSchedular.registerFunction(Dvintage.initializewizard);
    Dvintage.taskSchedular.registerFunction(Dvintage.wireSubmitButton);

    Dvintage.taskSchedular.fireAll();
})
