var imageBase = "/static/images/";
var freakingMagicNumber = 5;
var loadComplete = false;

Event.observe(window, 'load', function() {
    initDrops();
    initSplits();
    initSuggestions();
    initExpandablebuttons();
	if(typeof initElements == 'function') {
		initElements();
	}
	initCars();
	if($('selflink')) {
		$('selflink').observe('click', linkPop.bindAsEventListener($('selflink')));
	}
	loadComplete = true;
} );

function initSuggestions() {
    var inp = $$( "input.suggest" );
    for( i = 0; i < inp.length; i++ ) {
        inp[i].orgVal = inp[i].value;
        inp[i].onfocus = function( e ) {
            if( e.target.value == e.target.orgVal ) {
                e.target.value = "";
                e.target.style.color = "#000";
            }
        }
        inp[i].onblur = function( e ) {
            if( e.target.value == "" ) {
                e.target.value = e.target.orgVal;
                e.target.style.color = "#666";
            }
        }
    }
}

function initDrops() {
    var drops = document.getElementsByClassName( "dropmenu" );
    for( i = 0; i < drops.length; i++ ) {
        drops[i].opened = false;                                        // Set status
        drops[i].content = drops[i].next( ".dropcontent" );          // Define content
        drops[i].content.style.left = drops[i].offsetLeft + 2 + "px";   // Set position
        drops[i].content.style.top = drops[i].offsetTop + drops[i].offsetHeight + "px";
        if( drops[i].content.offsetWidth < drops[i].offsetWidth ) drops[i].content.style.width = drops[i].offsetWidth - 6 + "px";
        
        drops[i].onclick = function() {
            this.blur();
            if( this.opened == false ) {
                this.content.style.display = "block";
                this.opened = true;

                var drop = this;    // Dirty tricks with these events. Could be better by using Observe
                document.onmousedown = function( e ) {
                    if( e == undefined ) var target = Event.element( event );
                    else var target = e.target;
                    if( target != drop.firstChild ) {
                        drop.content.style.display = "none";
                        drop.opened = false;
                        document.onmousedown = null;
                    }
                }
            } else {
                this.content.style.display = "none";
                this.opened = false;
            }
        }
    }
}

function initSplits() {
    var drops = document.getElementsByClassName( "splitbutton" );
    for( i = 0; i < drops.length; i++ ) {
        var menu = drops[i].menu = drops[i].getElementsBySelector(".menu")[0];                    // Find and save menu object to split button
        menu.opened = false;                                                                        // Set status
        drops[i].content = menu.content = drops[i].getElementsByClassName( "dropcontent" )[0];    // Define content
        
        // Set position
        drops[i].content.style.left = 2 + "px"; 
        drops[i].content.style.top = 25 + "px";
        if( drops[i].content.offsetWidth < drops[i].offsetWidth + 25 ) drops[i].content.style.width = drops[i].offsetWidth - 6 + 25 + "px";
        
        // Set selected value automaticly
        drops[i].value = drops[i].firstDescendant().innerHTML;
        drops[i].items = drops[i].getElementsBySelector( "li a" ); 
        for( j = 0; j < drops[i].items.length; j++ ) {
            if( drops[i].value.endsWith( drops[i].items[j].innerHTML ) ) {
                drops[i].orgVal = drops[i].value.split( drops[i].items[j].innerHTML )[0];
                drops[i].items[j].up().addClassName("selected");
            }
        }

        menu.onclick = function() {
            this.blur();
            if( this.opened == false ) {
                this.content.style.display = "block";
                this.opened = true;

                var drop = this;    // Dirty tricks with these events. Could be better by using Observe
                document.onmousedown = function( e ) {
                    if( e == undefined ) var target = Event.element( event );
                    else var target = e.target;
                    if( target != drop && $( drop ).descendantOf( target ) == true ) {
                        drop.content.style.display = "none";
                        drop.opened = false;
                        document.onmousedown = null;
                    }
                }
            } else {
                this.content.style.display = "none";
                this.opened = false;
            }
        }
    }
}
function initSearchResults() {
	var results = $$("#searchresults .result" );
	for( i = 0; i < results.length; i++ ) {
		Event.observe( results[i], "mouseover", function() {
			this.addClassName( "selected" );
		});
		Event.observe( results[i], "mouseout", function() {
			this.removeClassName( "selected" );
		});
	}
}

function initExpandablebuttons() {
	var buttons = $$(".expandablebutton" );
	for( i = 0; i < buttons.length; i++ ) {
		if( !buttons[i].initialized ) {
		
			buttons[i].link = buttons[i].select( "H4" )[0];
			buttons[i].content = buttons[i].select( ".content" )[0].wrap( "div", { "class": "contentWrapper" } );
			buttons[i].down().insert( new Element( "div", { "class": "clear" } ), "bottom" );
			
			// Set content position
			buttons[i].content.setStyle( { left: -buttons[i].offsetLeft - buttons[i].up().offsetLeft + parseFloat( buttons[i].up().up().getStyle('padding-left') ) + "px", width: ( buttons[i].up().up().getDimensions().width - parseFloat( buttons[i].up().up().getStyle('padding-left') ) - parseFloat( buttons[i].up().up().getStyle('padding-right') ) ) + "px" } );
			buttons[i].content.down().setStyle( { display: "block"} );

			if( buttons[i].hasClassName( "open" ) ) {
				buttons[i].up().open = buttons[i];
				//buttons[i].content.setStyle( { display: "block", width: buttons[i].up().up().offsetWidth - parseFloat( buttons[i].up().up().getStyle( "padding-left" ) ) * 2 - parseFloat( buttons[i].content.getStyle( "padding-left" ) ) * 2 + "px" } );
				buttons[i].content.setStyle( { display: "block" } );
				buttons[i].setStyle( { marginBottom: buttons[i].content.down().getDimensions().height + 0 + "px" } );
			}
			else {
				buttons[i].content.setStyle( { display: "none" } );
			}
			
			// Create round corners
			if( buttons[i].up(".sbox") ) {
				buttons[i].content.addClassName( "noindent" );
				var left;
				if( Prototype.Browser.IE  ) left = buttons[i].offsetLeft + buttons[i].up().offsetLeft - parseFloat( buttons[i].up(".sbox_container").getStyle("padding-left") ) + 3;
				else left = buttons[i].positionedOffset()[0] + buttons[i].up().positionedOffset()[0];
				buttons[i].content.setStyle( { left: -left + "px", width: ( buttons[i].up(".sbox").getDimensions().width - 6 ) + "px" } );
			}
			else {
				buttons[i].content.down().setStyle( { width: parseFloat( buttons[i].content.getStyle( "width" ) ) - parseFloat( buttons[i].content.down().getStyle( "padding-left" ) ) * 2 - 2 + "px" } );
				buttons[i].content.down().insert( new Element( "div", { "class": "lt" } ) );
				buttons[i].content.down().insert( new Element( "div", { "class": "lb" } ) );
				buttons[i].content.down().insert( new Element( "div", { "class": "rt" } ) );
				buttons[i].content.down().insert( new Element( "div", { "class": "rb" } ) );
			}
			
			// Set openingfuntions			
			Event.observe( buttons[i].link, "click", function() {
				var current = this.up();
				
				// Open
				if( !this.up().hasClassName( "open" ) )  {
					current.fire('expandablebutton:opening');
					current.content.setStyle( { position: "absolute" } );
					if( current.up().open) {
						
						new Effect.Morph( current.up().open.content, { style: { height: "0px" }, duration: 0.5 } );
						new Effect.Morph( current.up().open, { style: { marginBottom: "0px" }, duration: 0.5, beforeFinish: function(i) {
							current.addClassName( "open" );
							current.content.setStyle( { height: "0", display: "block" } );
							new Effect.Morph( current.content, { style: { height: current.content.down().offsetHeight + "px" }, duration: 0.5, beforeStart: function(i) {
								current.up().open.removeClassName( "open" );
								current.up().open.content.setStyle( { display: "none" } );
								current.up().open = current;
							} } );
							new Effect.Morph( current, { style: { marginBottom: current.content.down().offsetHeight + "px" }, duration: 0.5 } );
							current.setStyle( { display: "block", visibility: "visible" } );
						;} } );
					}
					else {
						current.up().open = current;
						current.addClassName( "open" );
						current.content.setStyle( { height: "0", display: "block" } );
						new Effect.Morph( current.content, { style: { height: current.content.down().offsetHeight + "px" }, duration: 0.5 } );
						new Effect.Morph( current, { style: { marginBottom: current.content.down().offsetHeight + "px" }, duration: 0.5 } );
						current.setStyle( { display: "block", visibility: "visible" } );
					}
				}
				// Close
				else {
					
					current.up().open = false;
					
					new Effect.Morph( current.content, { style: { height: "0px" }, duration: 0.5 } );
					new Effect.Morph( current, { style: { marginBottom: "0px" }, duration: 0.5, afterFinish: function() { current.removeClassName( "open" ); current.content.setStyle( { display: "none" } ); } } );
				}
			});
			
			
			buttons[i].initialized = true;
		}
	}	
}

function setSplitVal( sel ) {
    var sbtn        = sel.up().up().up();                                       // Define splitbutton
    var newValue    = sel.firstChild.nodeValue;                                 // Define new value
    sbtn.firstDescendant().update( sbtn.orgVal + newValue );                    // Set value to button
    sbtn.getElementsBySelector( ".selected" )[0].removeClassName("selected");   // Unset selected
    sel.up().className = "selected";                                            // Set selected
    sbtn.menu.onclick();                                                        // Close menu
    return newValue;
}


/* ===================== SLIDER ===================== */

function Slider( base, l, t ) {
    $(base).immediateDescendants().each( function( i ) { $(i).setStyle({display: "none"}); } );

    new Insertion.Bottom( base, "<div id='" + base + "slider'><div id='" + base + "label'>" + l + "</div><div id='" + base + "leftSlider'></div><div id='" + base + "rightSlider'></div><div id='" + base + "sliderRange'></div><div id='" + base + "leftLabel'></div><div id='" + base + "rightLabel'></div></div>" );

    var l      = $( base + "label" ).addClassName( 'label' );
    var s      = $( base + "slider" ).addClassName( 'slider' );
    s.r        = $( base + "rightSlider" ).addClassName( 'rightSlider' );
    s.l        = $( base + "leftSlider" ).addClassName( 'leftSlider' );
    if(Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
        s.l.setStyle({cursor: 'ew-resize'});
        s.r.setStyle({cursor: 'ew-resize'});
    }
    s.range     = $( base + "sliderRange" ).addClassName( 'sliderRange' );
    s.ll        = $( base + "leftLabel" ).addClassName( "sliderLabelLeft" );
    s.lr        = $( base + "rightLabel" ).addClassName( "sliderLabelRight" );
    s.t         = t;
    s.ticOffset = s.l.offsetWidth;
    Event.observe( s, "click", sliderJump );
    
    s.v         = $$( "#" + base + " select" );
    s.ticSize   = ( $( base + "slider" ).offsetWidth - s.l.offsetWidth )  / ( s.v[0].length );
    s.l.onTic   = s.v[0].selectedIndex;
    s.l.type    = 1;
    s.l.pair    = s.r;
    s.l.observe( "mousedown", sliderMove );
    s.l.onclick = function() {}

    if( s.v[1].selectedIndex == 0 && s.v[1].options[0].defaultSelected == false ) s.v[1].selectedIndex  = s.v[1].length - 1;
    s.r.onTic = s.v[1].selectedIndex;
    s.r.type = 2;
    s.r.pair = s.l;
    s.r.observe( "mousedown", sliderMove );

    syncHandlePositions( s );    // Set handlers to selected positions
    
    s.range.type = 3;
    s.range.l = s.l;
    s.range.r = s.r;
    Event.observe( s.range, "mousedown", sliderMove );
    
    if( s.v[0].selectedIndex == 0 ) {
      s.ll.update( s.v[0][s.v[0].selectedIndex].text );
    } else {
      s.ll.update( s.v[0][s.v[0].selectedIndex].text + " " + s.t);
    }
    
    if( s.v[1].selectedIndex == s.v[0].length -1 ) {
      s.lr.update( s.v[1][s.v[1].selectedIndex].text );
    } else {
      s.lr.update( s.v[1][s.v[1].selectedIndex].text + " " + s.t );
    }

    new Insertion.Bottom( s, "<div id=\""+base+"tics\" class=\"tics\" width=\"220\" height=\"50\"></div>" );
    
    // draw tics
    var tics = $(base+'tics');
    for( i = 0; i <= s.v[0].length; i ++ ) {
        var x = Math.round( s.ticSize * i ) + 7;
        new Insertion.Bottom( tics, "<img src=\"" + imageBase  + "slider_tic.gif\" style=\"left: " + x + "px\" />" );
    }
    return s;
}

function syncHandlePositions( slider ) {
    slider.l.onTic  = slider.v[0].selectedIndex;
    slider.r.onTic  = slider.v[1].selectedIndex;

    moveHandle( slider.l );
    moveHandle( slider.r );
}

function sliderMove( e ) {
    s = Event.element( e );
    
    if( s.type == 3 ) {
        s.onTic = Math.round( ( Event.pointerX(e) - Position.cumulativeOffset(s.up())[0] - s.up().ticOffset ) /  s.up().ticSize );
    }
    
    if(Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
        $$( "BODY" )[0].setStyle({"cursor": "ew-resize"});
    } else {
        $$( "BODY" )[0].setStyle({"cursor": "e-resize"});
    }
    $$( "BODY" )[0].observe( "mousemove", calculateMovement );
    $$( "BODY" )[0].observe( "mouseup", endSliderMovement );
    
    if((Prototype.Browser.Opera || Prototype.Browser.IE) && null == document.falsef) {
		document.falsef = true;
		$$( "BODY" )[0].observe('mousemove', removeSelection);
    }
    if(Prototype.Browser.WebKit) $$('body')[0].setStyle({'-khtml-user-select': 'none'});
	if((Prototype.Browser.Gecko) && null == document.falsef) {
		document.falsef = true;
		$(document).observe('mousemove', retFalse);
	}

    Event.stopObserving( s, "mousedown", sliderMove );
}

function calculateMovement( e ) {
    var mX = Event.pointerX(e);
    if( s.type != 3 && mX < Position.cumulativeOffset(s.up())[0] + s.offsetWidth / 2 ) {
        mX = Position.cumulativeOffset(s.up())[0] + Math.round(s.offsetWidth / 2);
    }
    if( s.type != 3 && mX > Position.cumulativeOffset(s.up())[0] + s.up().offsetWidth - s.offsetWidth / 2 ) {
        mX = Position.cumulativeOffset(s.up())[0] + s.up().offsetWidth - Math.round(s.offsetWidth / 2);
    }

    if( s.type == 1 ) { // move left slider
        if( mX == Position.cumulativeOffset(s.up())[0] + s.up().offsetWidth - s.offsetWidth / 2 ) 
            mX -= s.offsetWidth;
        newTic = Math.round( ( mX - s.offsetWidth / 2 - Position.cumulativeOffset(s.up())[0] ) /  s.up().ticSize );
        if( s.pair.onTic >= newTic && newTic >= 0 ) { 
            s.onTic = newTic; 
            moveHandle( s ); 
        }
        else if( s.pair.onTic < newTic && newTic <= s.up().v[0].length -1 ) {
            s.pair.onTic    = s.pair.onTic + ( newTic - s.onTic );
            if( s.pair.onTic > s.up().v[0].length -1 ) s.pair.onTic = s.up().v[0].length -1; moveHandle( s.pair );
            
            s.onTic = newTic;   
            moveHandle( s );
        }          
    }
    if( s.type == 2 ) { // move right slider
        mX += 5;
        newTic = Math.round( ( mX - Math.round(s.offsetWidth / 2) - Position.cumulativeOffset(s.up())[0] - freakingMagicNumber ) /  s.up().ticSize );

        if( s.pair.onTic <= newTic && newTic < s.up().v[0].length ) { 
            s.onTic = newTic;
            moveHandle( s );
        } else if( s.pair.onTic > newTic && newTic >= 0 ) {
            s.pair.onTic    = s.pair.onTic + ( newTic - s.onTic );
            if( s.pair.onTic < 0 ) s.pair.onTic = 0; moveHandle( s.pair );
            s.onTic      = newTic;   
            moveHandle( s );
        }
    }
    if( s.type == 3 ) { // move range handler
    	if( !s.offset ) s.offset = mX - Position.cumulativeOffset(s.l)[0];

        newTicL = Math.round( ( mX - Position.cumulativeOffset(s.up())[0] - s.offset  ) /  s.up().ticSize );
	      if( newTicL < 0 ) newTicL = 0;
				newTicR = s.r.onTic + ( newTicL - s.l.onTic );
				if( newTicR >= s.up().v[0].length ) {
					newTicL -= newTicR - ( s.up().v[0].length -1 );
					newTicR = ( s.up().v[0].length - 1 );
				}

        s.l.onTic = newTicL;    
        moveHandle( s.l );
                
        s.r.onTic = newTicR;    
        moveHandle( s.r );
    }
}

function retFalse() {
    return false;
}

function moveHandle( s ) {
    if( s.type == 1 ) { 
        s.setStyle({ left: Math.round( s.onTic * s.up().ticSize ) + "px" });
    }
    if( s.type == 2 ) { 
        s.setStyle({ left: Math.round( s.up().ticSize + s.onTic * s.up().ticSize ) + "px" }); 
    }
    
    var rangeWidth = ( parseFloat( s.up().r.style.left ) - parseFloat( s.up().l.style.left ) - freakingMagicNumber );
    var leftWidth = ( parseFloat( s.up().l.style.left ) + freakingMagicNumber )

    if( !isNaN( rangeWidth ) ) 
        s.up().range.setStyle({ left: leftWidth + "px", width: rangeWidth + "px" });
    
    s.up().v[0].selectedIndex   = s.up().l.onTic;   // Update range handler, values and labels
    s.up().v[1].selectedIndex   = s.up().r.onTic;
    
    if( s.up().v[0].selectedIndex == 0 ) {
      s.up().ll.update( s.up().v[0][s.up().v[0].selectedIndex].text );  
    } else {
      s.up().ll.update( s.up().v[0][s.up().v[0].selectedIndex].text + " " + s.up().t );
    }
    
    if( s.up().v[1].selectedIndex == s.up().v[0].length -1 ) {
      s.up().lr.update( s.up().v[1][s.up().v[1].selectedIndex].text);   
    } else {
      s.up().lr.update( s.up().v[1][s.up().v[1].selectedIndex].text + " " + s.up().t ); 
    }  
}

function sliderJump( e ) {
    s = Event.element( e );
    if( s.className == "slider" ) {
        newTic = Math.round( ( Event.pointerX( e ) - Position.cumulativeOffset( s )[0] - freakingMagicNumber ) / s.ticSize );
        
        if( newTic >= s.v[0].length ) 
            newTic = s.v[0].length - 1;
            
        if( newTic < s.l.onTic ) { 
            s.l.onTic = newTic; 
            moveHandle( s.l ); 
        }
        if( newTic > s.r.onTic ) { 
            s.r.onTic = newTic; 
            moveHandle( s.r ); 
        }
    }
}

function removeSelection() {
	if(document.selection && document.selection.empty){
		document.selection.empty() ;
	} else if(window.getSelection) {
		sel=window.getSelection();
	if(sel && sel.removeAllRanges)
		sel.removeAllRanges() ;
	} 
}

function endSliderMovement( e ) {
	$$( "BODY" )[0].setStyle({"cursor": "auto"});
	$$( "BODY" )[0].stopObserving( "mousemove", calculateMovement );
	$$( "BODY" )[0].stopObserving( "mouseup", endSliderMovement );
    if((Prototype.Browser.Opera || Prototype.Browser.IE) && null != document.falsef) {
		document.falsef = null;
		$$( "BODY" )[0].stopObserving('mousemove', removeSelection);
    }
	if(Prototype.Browser.WebKit) $$('body')[0].setStyle({'-khtml-user-select': 'auto'});
	if(Prototype.Browser.Gecko && null != document.falsef) {
		document.falsef = null;
		$(document).stopObserving('mousemove', retFalse);
	}
	
	if( s.type == 3 ) s.offset = false;

	Event.observe( s, "mousedown", sliderMove );
}

/* ===================== Buticon ===================== */

function Buticon( base, l, imgbase ) {
    var times = 1;
    $(base).immediateDescendants().each( function( i ) { $(i).setStyle({display: "none"}); } );

    new Insertion.Bottom( base, "<div id='" + base + "buticon'><div id='" + base + "label'>" + l + "</div><div id='" + base + "value'><img src='" + imageBase + imgbase + ".gif'></div></div>" );
    new Insertion.Top( $$( "BODY" )[0],"<div id='" + base + "content'></div>" );
    
    var l      = $( base + "label" ).addClassName( 'label' );
    var b      = $( base + "buticon" ).addClassName( 'buticon' );
    b.c      = $( base + "content" ).addClassName( 'buticonContent' );
    b.val      = $( base + "value" ).addClassName( 'value' );
    b.ol        = l;
    b.c.position = Position.cumulativeOffset( b );
    b.c.setStyle({ position: "absolute", left: b.c.position[0] + "px", top: b.c.position[1] + "px" } );
    b.v      = $$( "#" + base + " select" )[0];
    b.selected = b.v.selectedIndex;
    b.i      = new Array( b.v.length );
    
    var maxHeight = 0;

    if( b.v.length > 8 ) {
        b.c.setStyle( { width: b.offsetWidth * 5 + "px" } );
        times = 5;
    }
    else if( b.v.length > 6 ) {
        b.c.setStyle( { width: b.offsetWidth * 2 + "px" } );
        times = 2;
    }

    for( i = 0; i < b.v.length; i++ ) {
        var newText = b.v[i].text;
        var newImg;
        if( newText.blank() == true ) newText = l.innerHTML;
        var newId = newText.gsub( " ", "_" ).toLowerCase();

        if( i == 0 ) newImg = imgbase + ".gif";
        else newImg = imgbase + "_" + newId + ".gif";
        new Insertion.Bottom( b.c, "<div id='" + base + "_" + newId + "'><img src=\"" + imageBase + newImg + "\"/>" + newText + "</div>" );
        b.i[ i ] = $( base + "_" + newId ).addClassName( 'item' );
        if( i == 0 && b.v.length > 6 ) {
            b.i[ i ].setStyle( { 'float': "none" } );
            b.i[ i ].addClassName( 'selected' );
        }

        b.i[ i ].i = i;
        b.i[ i ].image  = newImg;
        b.i[ i ].text   = newText;
        b.i[ i ].b    = b;

        b.i[ i ].observe( "click", selectButicon);
        if( b.v.selectedIndex == i ) selectButicon( null, b.i[i] );
    }

    for( i = 0; i < ((b.v.length ) % times - 1); i++ ) {
        new Insertion.Bottom( b.c, "<div id='" + base + "_e" + i + "'></div>" );
        var newEmpty = $( base + "_e" + i ).addClassName( 'emptyitem' );
    }

    b.observe( "click", function( e ) {
        if( b.c.getStyle( "display" ) == "none" ) {
            b.c.setStyle( { display: "block", left: Position.cumulativeOffset( b )[0] + "px", top: Position.cumulativeOffset( b )[1] + "px" } );
            if( !b.c.itemHeight ) {
                b.c.itemHeight = 0;
                b.c.childElements().each( function( i ) { if( i.offsetHeight > b.c.itemHeight ) b.c.itemHeight = i.offsetHeight; else i.setStyle({ height: b.c.itemHeight + "px" }) } );
            }
        }
        else if( b.c.getStyle( "display" ) == "block" ) b.c.setStyle( { display: "none" } );
        Event.stop( e );
        $$( "BODY" )[0].observe( "mousedown", b.hideMenu );
    } );

    b.hideMenu = function( e ) {
        if( !Event.element( e ).up( "#" + b.c.id ) ) {
            b.c.setStyle( { display: "none" } );
            $$( "BODY" )[0].stopObserving( "mousedown", b.hideMenu );
        }
    }

    return b;
}

function selectButicon( e, obj ) {
        if( e != null ) var me = Event.element( e );
        else var me = obj;
        
        if( me.nodeName != "DIV" ) me = me.up( "div" );
        setButiconValue( me );
}

function setButiconValue( me ) {
        me.siblings().each( function( i ) { i.removeClassName("selected") ;} );
        me.addClassName( "selected" );
        me.b.ol.update( me.text );
        me.b.val.firstDescendant().src = imageBase + me.image;
        me.b.v.selectedIndex = me.i;
        me.b.c.setStyle( { display: "none" } );
}

function syncButicon( b ) {
    setButiconValue( b.i[ b.v.options.selectedIndex ] );    
}

/* ===================== SERIES SELECTOR ===================== */

function Series( base, guide, useManualLastView, manualScript ) {
    $(base).immediateDescendants().each( function( i ) { $(i).setStyle({display: "none"}); } );
    
    new Insertion.Before( base, "<div id='" + base + "_selection'><div id='" + base + "_selection_back'>Back</div></div><div id='" + base + "series'><div id='" + base + "_container'></div></div>" );
    
    var s          = $( base + "series" ).addClassName( 'series' );
    var l          = s.l = $( base + "_selection" ).addClassName( 'seriesselection' );
    var b          = $( base + "_selection_back" ).addClassName( 'back' );
    var scont      = $( base + "_container" ).addClassName( 'seriescontainer' );
    s.v      = $$( "#" + base + " select" );
    
    s.c          = new Array();
    s.guide  = guide;
    s.open    = 0;

    l.firstDescendant().hide();
    l.firstDescendant().observe( "click", function( e ) {
        if( scont.offsetLeft < 0 ) {
            seriesBack( s.c[ s.open ].prevC );
            s.open--;
        }
    } );

    // Create last view
    if( useManualLastView ) {
        i = s.v.length;
        new Insertion.Bottom( scont, "<div id='" + base + "_" + i + "'></div>" );
        var manualView = $( base + "_" + i ).addClassName( 'seriescolumn' );
        manualView.manual = true;
        manualView.setStyle({ left: parseFloat( s.getStyle( "width" ).sub( "px", "" ) ) * i + "px" });
        manualView.update( $( useManualLastView ).innerHTML );
        $( useManualLastView ).remove();
        manualView.l = l;
        manualView.init = function() {
            eval( manualScript );
        }
    }
    
    s.v.each( function( n, i ) { 
        new Insertion.Bottom( l, "<span id='" + base + "_" + i + "_selection'></span>" );
        
        new Insertion.Bottom( scont, "<div id='" + base + "_" + i + "'></div>" );
        s.c[ i ] = $( base + "_" + i ).addClassName( 'seriescolumn' );

        s.c[ i ].setStyle({ left: parseFloat( s.getStyle( "width" ).sub( "px", "" ) ) * i + "px" });
        s.c[ i ].selection =  $( base + "_" + i + "_selection" ).addClassName( 'seriesselectionvalue' );
        s.c[ i ].selection.hide();
        
        scont.setStyle({ width: scont.offsetWidth + s.c[ i ].offsetWidth + "px" } );
        if( $( s.v[i] ) ) s.v[i] = $( s.v[i] ); 
        else s.v[i] = $( document.getElementsByName( s.v[i] )[0] );
        s.c[ i ].v    = s.v[i];
        s.c[ i ].sid    = base + "series";

        if( i > 0 ) {
            s.c[ i ].prevC = s.c[ i - 1 ];
            s.c[ i - 1 ].nextC = s.c[ i ];
            s.v[ i ].observe('change', function(event){ addSeriesValues( s.c[ i ] ); } );
            
            //if( scont.offsetLeft != ( s.c[ i ].offsetLeft * -1 - 1) ) s.c[ i ].hide();
            if( parseFloat(  scont.getStyle( "left" ).sub( "px", "" ) ) != parseFloat(  s.c[ i ].getStyle( "left" ).sub( "px", "" ) ) * -1 ) s.c[ i ].hide();
        }
        else {
            s.c[ i ].prevC = false;
            if( i < s.c.length ) s.c[ i ].nextC = s.v[ i + 1 ];
        }
        if( s.v[i].length > 1 ) {
            addSeriesValues( s.c[ i ], s.v[ i ] );
        }
    } );

    if( useManualLastView ) {
        s.c[ s.v.length - 1 ].nextC = manualView;
        s.c[ s.v.length ] = s.c[ s.v.length - 1 ];
        manualView.prevC = s.c[ s.v.length - 1 ];
    }
    
    s.c[ 0 ].selection.show();
    if( s.c[ 0 ].selection.innerHTML == "" ) s.c[ 0 ].selection.update( guide );
    
    return s;
}

function addSeriesValues( c ) {
    clearSeriesValues( c );
    for( i = 0; i < c.v.length; i++ ) {
        new Insertion.Bottom( c, "<div id=\"" + c.id + i + "\">" + c.v[i].text + "</div>" );
        nv = $( c.id + i );
        nv.i = i;
        if( c.nextC && $(c.v).select('option')[i].innerHTML != "" ) {
            nv.folder = true;
            nv.addClassName( "folder" );
            
            if( i == c.v.selectedIndex ) {
                nv.addClassName( "folderselected" );
                var selected = nv;
                selected.i = i;
            }
        }
        else if( i == c.v.selectedIndex ) {
            nv.addClassName( "selected" );
            var selected = nv;
            selected.i = i;
        }
        
        nv.observe("click", function( e ) { Event.element( e ).selectItem( this );  } );

        nv.selectItem = function( o ) {
            o.up().selection.show();
            
            if($('makeandmodel_0_selection') || $('newmakeandmodel_0_selection')) {
	            //Truncating duplicate string parts
	            var tempSelection = o.innerHTML;
	            var oldSelectionObject = $('makeandmodel_0_selection');
	            if(oldSelectionObject == null){
	                oldSelectionObject = $('newmakeandmodel_0_selection');
	            }
	            if(tempSelection.indexOf(oldSelectionObject.innerHTML) !=-1){
	                tempSelection = tempSelection.substring(oldSelectionObject.innerHTML.length);
	            }
	            o.up().selection.update( tempSelection );
	            //Truncate ends
	        } else {
	        	o.up().selection.update( o.innerHTML );
	        }

            if( o.up().getElementsByClassName( "folderselected" )[0] ) o.up().getElementsByClassName( "folderselected" )[0].removeClassName( "folderselected" );
            else if( o.up().getElementsByClassName( "selected" )[0] ) o.up().getElementsByClassName( "selected" )[0].removeClassName( "selected" );
                
            if( o.folder == true ) {
                o.addClassName( "folderselected" );
            } else {
                o.addClassName( "selected" );
            }
            
            o.up().v.selectedIndex = o.i;
            if( o.up().v.onchange != undefined ) o.up().v.onchange();

            if( c.nextC && $(o.up().v).select('option')[o.i].innerHTML != "" ) {
                c.nextC.show();
                var s = $( o.up().sid );
                s.open++
                c.up().up().l.firstDescendant().show()

                if( c.nextC.manual ) c.nextC.init();
                else addSeriesValues( c.nextC );

                new Effect.Move( s.firstDescendant(),{ x: -( s.offsetWidth - 2 ), mode: 'relative', duration: 0.5, afterFinish: function( e ) { o.up().scrollStore = o.up().scrollTop; o.up().hide(); } });
            }
        }
    }
    
    if( selected ) {
        setTimeout(function() { // Lets give some time for IE to init this object
            c.scrollTop = ( selected.offsetTop ) - ( selected.offsetHeight * 1.5 );
            c.scrollStore = c.scrollTop;
        },0001);
        
        if( c.nextC && c.nextC.selectedIndex != false && c.nextC.length > 0 ) {
            selected.up().selection.show();
            selected.up().selection.previousSiblings()[0].show();
            selected.up().selection.update( selected.innerHTML );
            //c.up().setStyle({ left: ( c.up().offsetLeft - c.offsetWidth + 1 ) + "px" } );
            c.up().setStyle({ left: ( parseFloat( c.up().getStyle( "left" ).sub( "px", "" ) ) - parseFloat( c.getStyle( "width" ).sub( "px", "" ) ) ) + "px" } );
            c.up().up().open++;
        }
    }
}

function seriesBack( cPrev, syncToSelect) {
    cont = cPrev.up();
    cont.up().startX = parseFloat( cont.getStyle( "margin-left" ).sub( "px", "" ) ); 
    
    cPrev.nextC.selection.update( "" );
    cPrev.nextC.v.options.length = 0;

    if( cPrev.prevC == false ) {
        cont.up().l.firstDescendant().hide();
        cPrev.selection.update( cont.up().guide );
        cPrev.nextC.v.options.length = 0;
    }

    cPrev.show();
    cPrev.scrollTop = cPrev.scrollStore;

    new Effect.Move( cont,{ x: ( cont.up().offsetWidth - 2 ), mode: 'relative', duration: 0.5, afterFinish: function( e ) { 
        cPrev.scrollStore = cPrev.scrollTop; cPrev.nextC.hide();
        if( syncToSelect ) syncSeries( cont.up(), syncToSelect );
    } } );
}

function syncSeries( series, changedSelect ) {
    if ( changedSelect != series.c[ series.open ].v ) {
        seriesBack( series.c[ series.open ].prevC, changedSelect );
        series.open--;
    }
    else series.c[ series.open ].childNodes[changedSelect.options.selectedIndex].selectItem( series.c[ series.open ].childNodes[changedSelect.options.selectedIndex] );
}

function clearSeriesValues( c ) {
    c.innerHTML = "";
}

/* ===================== SEARCH OPTIONS ===================== */
function initSearchOptions( c, hideMinimizeButtons ) {
    // defaults to false:
    hideMinimizeButtons = (hideMinimizeButtons == null ? false : hideMinimizeButtons);
    
    var oo = new Array();
    for( i = 0; i <= c; i++ ) {
        if( $( "show_search_options" + i ) ) {
            if( $( "search_options" + i ).hasClassName( "hidden" ) ) {
                Effect.SlideUp( "search_options" + i, { duration: 0, afterFinish: function( e ) { e.element.removeClassName( "hidden" ); } } );
            }
            else oo[oo.length] = "search_options" + i;
            $( "show_search_options" + i ).orginalWidth  = $( "show_search_options" + i ).offsetWidth;
            $( "show_search_options" + i ).orginalMargin    = 12;
            $( "show_search_options" + i ).orginalPadding   = 12;
            $( "search_options" + i ).orginalMargin          = 10;
        }
    }

    if( hideMinimizeButtons && oo.length == 1 ) $$( "#" + oo[0] + " .minimizebutton" )[0].hide();
}

function showSearchOptions( c, myLink ) {
    o = $( "search_options" + c );
    o.c = o.firstDescendant();
    var myLink = $( "show_" + o.id );
    $$( ".minimizebutton" ).each( function( i ) { i.show(); } );

    // animate movements
    Effect.SlideDown( o.id, { duration: 0.5 } );
    new Effect.Morph( myLink.id ,{
      style:{
        width:'0px',
        marginLeft: '0px',
        paddingLeft: '0px',
        opacity: '0'
      }, duration: 0.5
    });
}

function hideSearchOptions( o ) {
    o              = $( o );
    o.c          = o.firstDescendant();
    var myLink    = $( "show_" + o.id );
    myLink.removeClassName( "hidden" );
    
    // See if only one option-panel will be open
    var c = $$(".search_options");
    var oo = new Array();
    for( i = 0; i < c.length; i++ ) 
        if( c[i] != o && c[i].offsetHeight > 0 ) 
            oo[oo.length] = c[i].id;
    if( oo.length == 1 && $$( "#" + oo[0] + " .minimizebutton" )[0] ) 
        Effect.Fade( $$( "#" + oo[0] + " .minimizebutton" )[0], { duration: 0.8 } );

    // animate movements
    Effect.SlideUp( o.id, { duration: 0.5 } );
    new Effect.Morph( myLink.id ,{
      style:{
        width: myLink.firstDescendant().offsetWidth + 'px',
        marginLeft: myLink.orginalMargin + 'px',
        paddingLeft: myLink.orginalPadding + 'px',
        opacity: '1'
      }, duration: 0.5
    });
}

/* ===================== STARS ===================== */
function safety_highlight(stars_id){
    var stars = stars_id.substr(0, 1);
    var favouriteId = stars_id.substr(1);
    for (var curStar = 1; curStar < 6; curStar++) {
        if (curStar <= stars) {
            $(curStar + favouriteId).addClassName( "staron" );
        }
        else {
            $(curStar + favouriteId).removeClassName( "staron" );
        }
    }
}

function safety_losehighlight(stars_id){
    var favouriteId = stars_id.substr(1);
    for (var curStar = 1; curStar < 6; curStar++) {
        var curItem = $(curStar + favouriteId);
        if (curItem.className.indexOf('selected_star') == -1) {
            if( curItem.selected != true ) curItem.removeClassName( "staron" );
            else curItem.addClassName( "staron" );
        }
        else {
            curItem.addClassName( "staron" );
        }
    }
}

function safety_setStarVal(stars_id){
    var varName = stars_id.substr(2);
    var stars      = stars_id.substr(0, 1);

    for (curStar = 1; curStar < 6; curStar++) {
        curItem = $(curStar + "_" + varName);
        if( curItem.hasClassName( "staron" ) ) {
            curItem.selected = true;
        }
        else {
            curItem.selected = false;
        }
    }
      $( varName ).value = stars;
    //favouriteId = favouriteId.substr(1);
    //new Ajax.Request("/s/favourite/favouriteform?id=" + favouriteId + "&stars=" + stars);
}

/* ===================== CONTENT SLIDE ===================== */

function initContentSlide() {
    $$( ".slidecontent" ).each( function( s ) {
        if( !s.initialized ) {
            s.initialized = true;
            // s.up().setStyle({ position: "relative", clear: "both" } );
            if( !s.up().getStyle( "position" ) ) s.up().setStyle({ position: "relative", clear: "both" } );
            s.setStyle({ position: "relative", overflow: "hidden", top: "1px", clear: "both" });
            s.open = 0;
            s.pages = s.immediateDescendants();
            if(s.pages.length < 2) {
            	return;
            } 
            new Insertion.After( s, '<div class="slidefooter"><div class="controls"><div class="back" onclick="contentSlide( this, \'right\' );"></div><div class="contentslideitems"><div class="selected"></div></div><div class="forward" onclick="contentSlide( this, \'left\' );"></div></div></div>' );

            for( i = 0; i < s.pages.length; i++  ) {
                s.pages[i].setStyle( {
                    position: 'absolute',
                    width: s.offsetWidth + "px"
                } );
                if( i > 0 ) {
                    s.pages[i].setStyle( { left: s.offsetWidth + "px" } );
                    s.pages[i].hide();
                    new Insertion.Bottom( s.next().descendants()[2], '<div></div>' );
                }
            }
            s.indicators = s.next().descendants()[2];
            s.next().down().immediateDescendants()[0].s = s;
            s.next().down().immediateDescendants()[2].s = s;
            s.next().down().setStyle( { left: ( s.offsetWidth - s.next().down().offsetWidth ) / 2 + "px", 'float': "none" } );
        }
    } );
}

function contentSlide( o, dir ) {
    if( dir == "left" ) {
        var d = -1;
        var next = o.s.open < o.s.pages.length -1 ? o.s.open + 1 : 0;
    } else {
        var d = 1;
        var next = o.s.open > 0 ? o.s.open - 1 : o.s.pages.length -1;
    }
    var oldP = o.s.pages[ o.s.open ];
    var newP = o.s.pages[ next ].show();
    
    o.s.indicators.descendants()[ o.s.open ].removeClassName( "selected" );
    o.s.indicators.descendants()[ next ].addClassName( "selected" );
    
    newP.show();

    new Effect.Move( oldP,{ x: o.s.offsetWidth * d, mode: 'relative', duration: 0.5, beforeFinish: function( i ) { oldP.hide(); oldP.setStyle( { left: o.s.offsetWidth + "px" } ); } });
    if( dir == "right" ) newP.setStyle( { left: -o.s.offsetWidth + "px" } );
    new Effect.Move( newP,{ x: o.s.offsetWidth * d, mode: 'relative', duration: 0.5 });

    o.s.open = next;
}

var slideActive = false;

function carThumbHover(event) {
	if(!loadComplete) return;
	var car = this.getOffsetParent();
	var info = car.getElementsByClassName('info')[0];
	if(info && !info.hasClassName('contenpopup')) {
		car.info = info;
		info.addClassName('contentpopup');
		var pos = car.cumulativeOffset();
		var h = car.getHeight();
		var cw = car.getWidth();
		$$('body')[0].insert(info);
		var iw = info.getWidth();
		var fhpos = $('outer-wide-column').cumulativeOffset().left;
		var fhwid = $('outer-wide-column').getWidth();
		var infoleft = pos.left+(cw/2)-(iw/2);
		if(infoleft < fhpos+10) {
			var d = (fhpos+10)-infoleft;
			infoleft = infoleft+d;
			var pointer = $(info.getElementsByClassName('pointer')[0]);
			var pw = pointer.getWidth();
			pointer.setStyle({left: ((pos.left-fhpos)+cw/2-pw/2)+'px'});
		}
		if(infoleft+iw > fhpos+fhwid-10) {
			var d = (infoleft+iw)-(fhpos+fhwid-10);
			infoleft = infoleft-d;
			var pointer = $(info.getElementsByClassName('pointer')[0]);
			var pw = pointer.getWidth();
			pointer.setStyle({left: (iw-((fhpos+fhwid)-(pos.left+cw))-cw/2+pw/2)+'px'});
		}
		info.setStyle({top: (pos.top+h+10)+'px', left: infoleft+'px'});
		info.car = car;
	}
}

function carThumbOut(event) {
	if(!loadComplete) return;
	var car = this.getOffsetParent();
	if(!car.info) {
		if(car.car) {
			car = car.car;
		} else {
			while(car.getOffsetParent && (car = car.getOffsetParent())) {
				if(car.car) {
					car = car.car;
					break;
				}
				car = $(car);
				if(car.hasClassName && car.hasClassName('car')) {
					break;
				}
			}
		}
	}
	if(car.info) {
		car.info.removeClassName('contentpopup');
		car.insert(car.info);
		car.info = null;
	}
}

function initCars() {
	var eles = $$('.car img');
	if(eles) {
		eles.each(function(ele) {
			if(ele.obover) {
				ele.stopObserving('mouseover', ele.obover);
				ele.stopObserving('mouseout', ele.obout);
			}
			ele.obover = carThumbHover.bindAsEventListener(ele);
			ele.observe('mouseover', ele.obover);
			ele.obout = carThumbOut.bindAsEventListener(ele);
			ele.observe('mouseout', ele.obout);
		});
	}
}

function closeLinkPop(event) {
	var popup = $('selflinkpopup');
	if(!popup.closing && !popup.opening) {
		popup.closing = true;
		new Effect.Opacity(popup, {from: 1, to: 0.01, duration: 0.3, afterFinish: function() {
			popup.remove();
		}});
	}
	if(popup.opening) {
		popup.pleaseclose = true;
	}
	if(event) {
		Event.stop(event);
	}
}

function linkPop(event) {
	Event.extend(event);
	if(!$('selflinkpopup')) {
		var popup = new Element('div',{'class': 'contentpopup', 'id': 'selflinkpopup'});
		popup.opening = true;
		popup.update('<img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/><h4>Linkki tälle sivulle</h4><input type="text" style="width: 230px;" value="'+this.readAttribute('href')+'" onfocus="this.select()" onblur="closeLinkPop()"/>');
		$$('body')[0].insert(popup);
		popup.setStyle({width: '250px', opacity: 0.01, left: (event.pageX-(popup.getWidth()/2))+'px', top: (event.pageY+30)+'px'});
		new Effect.Opacity(popup, {from: 0.01, to: 1, duration: 0.4, afterFinish: function() {
			popup.getElementsBySelector('input')[0].select();
			popup.opening = false;
			if(popup.pleaseclose) {
				closeLinkPop(event);
			}
		}});
		popup.getElementsBySelector('input')[0].focus();
	} else {
		closeLinkPop(event);
	}
	Event.stop(event);
}

function fadingPopup(event) {
	Event.extend(event);
	var popup = new Element('div',{'class': 'contentpopup'});
	popup.update('<img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/>'+event.target.popup);
	$$('body')[0].insert(popup);
	popup.setStyle({opacity: 0.01, left: (event.pageX-(popup.getWidth()/2))+'px', top: event.pageY+'px'});
	new Effect.Opacity(popup, {from: 0.01, to: 1, duration: 0.4, afterFinish: function() {
		new Effect.Opacity(popup, {from: 1, to: 0.01, duration: 0.4, delay: 2, afterFinish: function() {
			popup.remove();
		}});
	}});
}

function parsePrice(price) {
	price = parseFloat(price);
	if(isNaN(price)) {
		price = '';
	} else {
		price = price.toFixed(0);
	}
	return price;
}

function blockSlide( o, dir, index, width, data, afunc, fileId) {
	if(slideActive) return false;
	var sbox = $(o.parentNode);
	sbox.setStyle({'height': sbox.getHeight()+'px'});
	var current = sbox.select('div.current')[0];
	var previous = sbox.select('div.previous')[0];
	var next = sbox.select('div.next')[0];
	var forward = sbox.select('div.forward')[0];
	var back = sbox.select('div.back')[0];
	var dims = current.getDimensions();
	dims.width = current.offsetWidth;
	if(!current.getStyle('width')) {
		current.setStyle({width: dims.width+'px'});
		previous.setStyle({width: dims.width+'px'});
		next.setStyle({width: dims.width+'px'});
	}
	switch(dir) {
		case('left'):
			if(next.empty()) return false;
			slideActive = true;
			next.setStyle({left: dims.width+'px', top: -dims.height+'px', width: dims.width+'px'});
			next.removeClassName('dnone');
			if(back.getStyle('opacity') < 1) {
				new Effect.Opacity(back, {from: 0.01, to: 1, afterFinish: function() {
					back.setStyle({'cursor': 'pointer'});
				}});
			}
			new Effect.Move(current, {x: -dims.width, y: 0, afterFinish: function() {
				var nexteles = next.childElements();
				var currenteles = current.childElements();
				previous.update();
				currenteles.each(function(ele) {
					previous.insert(ele);
				});
				nexteles.each(function(ele) {
					current.insert(ele);
				});
				next.update();
				current.setStyle({left: 0, top: 0, width: dims.width+'px'});
				next.addClassName('dnone');

				// populating next
				if(data) {
					// data loaded during page load
					if(data.length > index) {
						var start = index+width;
						var end = Math.min(start+width, data.length);
						for(var i = start; i < end; i++) {
							var c = data[i];
							var carname = c.otherCarMake;
							if(c.otherCarModel) carname += ' '+c.otherCarModel;
							if(c.type) carname += ' '+c.type;
							var car = new Element('div', {
								'class':	'car'
							});
							car.update('<a href="/cache?exit=show_car_used&id=' + c.id + '"><img src="'+c.mainPictureOrPlaceHolder+'" width="100" height="75"/></a><div class="info"><img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/><h4>'+carname+'</h4><div>'+parsePrice(c.price)+'&euro;&nbsp;&nbsp;'+c.manufactureYear+'&nbsp;&nbsp;'+c.mileage+'</div></div>');
							next.insert(car);
						}
					}
					// if data not found, hiding arrow
					if(next.empty()) {
						new Effect.Opacity(o, {from: 1, to: 0.01, duration: 0.4, afterFinish: function() {
							o.setStyle({'cursor': 'auto'});
						}});
					}
					forward.index = index+width;
					back.index = index-width;
					initCars();
					slideActive = false;
				} else if(afunc) {
					// data loaded by ajax
					this.popfunc = function() {
						var end = Math.min(5, searchListCars.length);
						for(var i = 0; i < end; i++) {
							var c = searchListCars[i];
							var carname = c.carname;
							var car = new Element('div', {
								'class':	'car'
							});
							var carUrl = '/cache?exit=show_car_used&id=' + c.id + '&fcid=' + fileId + '&s_index=1' +'&searchparams=' + searchparams;
							car.update('<a href="'+carUrl+'"><img src="'+c.resultListMainpicture+'" width="100" height="75"/></a><div class="info"><img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/><h4>'+carname+'</h4><div>'+parsePrice(c.salesprice)+'&euro;&nbsp;&nbsp;'+c.manfyear+'&nbsp;&nbsp;'+c.mileage+'</div></div>');
							next.insert(car);
						}
						// if data not found, hiding arrow
						if(next.empty()) {
							new Effect.Opacity(o, {from: 0.5, to: 0.01, duration: 0.4, afterFinish: function() {
								o.setStyle({'cursor': 'auto'});
							}});
						} else {
							new Effect.Opacity(o, {from: 0.5, to: 1, duration: 0.2, afterFinish: function() {
								o.setStyle({'cursor': 'pointer'});
							}});
						}
						forward.index = index+width;
						back.index = index-width;
						initCars();
						slideActive = false;
						$('searchlistsbox').stopObserving('search:resultsready', this.bpopfunc);
						$('searchlistsbox').stopObserving('search:dwrerror', this.berrfunc);						
					};
					this.bpopfunc = this.popfunc.bindAsEventListener(this);
					this.errfunc = function() {
						new Effect.Opacity(o, {from: 0.5, to: 0.01, duration: 0.4, afterFinish: function() {
							o.setStyle({'cursor': 'auto'});
						}});
						forward.index = index+width;
						back.index = index-width;
						initCars();
						slideActive = false;
						$('searchlistsbox').stopObserving('search:resultsready', this.bpopfunc);
						$('searchlistsbox').stopObserving('search:dwrerror', this.berrfunc);						
					};
					this.berrfunc = this.errfunc.bindAsEventListener(this);
					$('searchlistsbox').observe('search:resultsready', this.bpopfunc);
					$('searchlistsbox').observe('search:dwrerror', this.berrfunc);						
					var start = index+width;
					new Effect.Opacity(o, {from: 1, to: 0.5, duration: 0.2, afterFinish: function() {
						o.setStyle({'cursor': 'wait'});
					}});
					afunc(fileId, start, 5);
				} else {
					// no way to get more data!
				}
			}});
			new Effect.Move(next, {x: -dims.width, y: 0});
			break;
		case('right'):
			if(previous.empty()) return false;
			slideActive = true;
			previous.setStyle({'left': -dims.width+'px', 'top': -dims.height+'px', width: dims.width+'px'});
			previous.removeClassName('dnone');
			if(forward.getStyle('opacity') < 1) {
				new Effect.Opacity(forward, {from: 0.01, to: 1, afterFinish: function() {
					forward.setStyle({'cursor': 'pointer'});
				}});
			}
			new Effect.Move(current, {x: dims.width, y: 0, afterFinish: function() {
				var preveles = previous.childElements();
				var currenteles = current.childElements();
				next.update();
				currenteles.each(function(ele) {
					next.insert(ele);
				});
				preveles.each(function(ele) {
					current.insert(ele);
				});
				current.setStyle({left: 0, top: 0, width: dims.width+'px'});
				previous.addClassName('dnone');
				// populating previous
				if(data) {
					// data loaded during page load
					var start = index-width;
					var end = Math.min(index, data.length);
					if(start < 0) {
						end = Math.min(width+start, end);
						start = width;
					}
					for(var i = start; i < end; i++) {
						var c = data[i];
						var carname = c.otherCarMake;
						if(c.otherCarModel) carname += ' '+c.otherCarModel;
						if(c.type) carname += ' '+c.type;
						var car = new Element('div', {
							'class':	'car'
						});
						car.update('<a href="/cache?exit=show_car_used&id=' + c.id + '"><img src="'+c.mainPictureOrPlaceHolder+'" width="100" height="75"/></a><div class="info"><img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/><h4>'+carname+'</h4><div>'+parsePrice(c.price)+'&euro;&nbsp;&nbsp;'+c.manufactureYear+'&nbsp;&nbsp;'+c.mileage+'</div></div>');
						previous.insert(car);
					}
					// jos dataa ei löydy:
					if(previous.empty()) {
						new Effect.Opacity(o, {from: 1, to: 0.01, duration: 0.4, afterFinish: function() {
							o.setStyle({'cursor': 'auto'});
						}});
					}
					forward.index = index+width;
					back.index = index-width;
					initCars();
					slideActive = false;
				} else if(afunc) {
					// data loaded by ajax
					this.popfunc = function() {
						var end = Math.min(5, searchListCars.length);
						for(var i = 0; i < end; i++) {
							var c = searchListCars[i];
							var carname = c.carname;
							var car = new Element('div', {
								'class':	'car'
							});
							var carUrl = '/cache?exit=show_car_used&id=' + c.id + '&fcid=' + fileId + '&s_index=1' +'&searchparams=' + searchparams;
							car.update('<a href="'+carUrl+'"><img src="'+c.resultListMainpicture+'" width="100" height="75"/></a><div class="info"><img class="pointer" src="/static/images/popup_area_pointer.gif" alt=""/><h4>'+carname+'</h4><div>'+parsePrice(c.salesprice)+'&euro;&nbsp;&nbsp;'+c.manfyear+'&nbsp;&nbsp;'+c.mileage+'</div></div>');
							previous.insert(car);
						}
						// if data not found, hiding arrow
						if(previous.empty()) {
							new Effect.Opacity(o, {from: 0.5, to: 0.01, duration: 0.4, afterFinish: function() {
								o.setStyle({'cursor': 'auto'});
							}});
						} else {
							new Effect.Opacity(o, {from: 0.5, to: 1, duration: 0.2, afterFinish: function() {
								o.setStyle({'cursor': 'pointer'});
							}});
						}
						forward.index = index+width;
						back.index = index-width;
						initCars();
						slideActive = false;
						$('searchlistsbox').stopObserving('search:resultsready', this.bpopfunc);
						$('searchlistsbox').stopObserving('search:dwrerror', this.berrfunc);
					};
					this.bpopfunc = this.popfunc.bindAsEventListener(this);
					this.errfunc = function() {
						new Effect.Opacity(o, {from: 0.5, to: 0.01, duration: 0.4, afterFinish: function() {
							o.setStyle({'cursor': 'auto'});
						}});
						forward.index = index+width;
						back.index = index-width;
						initCars();
						slideActive = false;
						$('searchlistsbox').stopObserving('search:resultsready', this.bpopfunc);
						$('searchlistsbox').stopObserving('search:dwrerror', this.berrfunc);
					};
					this.berrfunc = this.errfunc.bindAsEventListener(this);
					$('searchlistsbox').observe('search:resultsready', this.bpopfunc);
					$('searchlistsbox').observe('search:dwrerror', this.berrfunc);						
					var start = index-width;
					new Effect.Opacity(o, {from: 1, to: 0.5, duration: 0.2, afterFinish: function() {
						o.setStyle({'cursor': 'wait'});
					}});
					afunc(fileId, start, 5);					
				} else {
					// no way to get more data!
				}				
			}});
			new Effect.Move(previous, {x: dims.width, y: 0});
			break;
	}
}

/* ===================== TAKUUVAIHTOAUTOT ===================== */
function openGuaranteeProgram( program, openNext ) {
    program = $( program );
    while( program.select( '.info' ).length < 1 ) program = program.up();
    var info = program.select( '.info' )[0];
    var link = info.up().select( '.moreinfo' )[0];

    // Open  
    if( info.open != true ) {
        var j = 0; // Finetune placement clearings

        program.up().select('.guaranteeprogram').each( function( i ) {
                if( j % 2 == 0 ) {
                    i.addClassName( "first" );
                    var c = new Element( 'div', { "class": "clear"} );
                    i.insert( { before: c } );  
                }
                j++;
        } );
        
        // See if one is already open and close it before opening this. If open is on the same row as one being opened, wait first for the last one to close
        var closeFirst = false;
        program.up().select('.guaranteeprogram .info').each( function( i ) {
            if( i.open == true ) {
                if( program.hasClassName( "first" ) && i.up() == program.next() || !program.hasClassName( "first" ) && i.up() == program.previous() ) {
                    closeFirst = i.up();
                    openGuaranteeProgram( i.up(), link );
                }
                else openGuaranteeProgram( i.up() );
                return;
            }
        } );
        if( closeFirst != false ) return false;

        // Update link information
        program.setStyle( { zIndex: '3' } );
        link.addClassName("open");
        link.originalText = link.innerHTML;
        link.update( "Sulje lis&auml;tiedot" );
        info.targetHeight = info.targetHeight ? info.targetHeight : info.getStyle( 'height' );

        // Add close button and pointer
        if( info.select( ".minimizebutton" ).length < 1 ) {
            var min      = new Element( 'img', { "src": imageBase + "button_minimize_g.gif", "alt": "Piilota lis&auml;tiedot", "class": "minimizebutton" } );
            min.onclick = function() { openGuaranteeProgram( min ); }
            var pointer = new Element( 'div', { "class": "pointer" } );
            info.insert( { top: min } );
            info.insert( { top: pointer } );
        }

        info.open = true;
        info.setStyle({ height: '0px',visibility: 'visible' } );
        new Effect.Morph( info, { style: { height: info.targetHeight }, duration: 0.5 } );
        new Effect.Morph( program, { style: { marginBottom: parseFloat( info.targetHeight ) + 20 + "px" }, duration: 0.5 } );
    }
    // Close
    else {
        info.open = false;
        link.removeClassName("open");
        link.update( link.originalText );
        new Effect.Morph( info, { style: { height: "0px" }, duration: 0.5, afterFinish: function(i) {
            program.setStyle( { zIndex: '' } );
            i.element.setStyle( { visibility: "hidden"} );
            if( openNext ) openGuaranteeProgram( openNext );
        } } );
        new Effect.Morph( program, { style: { marginBottom: "0px" }, duration: 0.5 } );
    }
}


