/**
 * @author Tom
 */

Event.observe(window, "load", function() {
    if($('amount') && !$('amount').value && $('orderFormFirstForm')) {
        $('amount').toggle = false;
        $('amount').interval = setInterval(toggleAmountStyle, 330);

        $('amount').onfocus =
        $('amount').onkeydown = function() {
            txtAmount = $('amount');
            clearInterval($('amount').interval);
            txtAmount.removeClassName('togglestyle');
        };

        $('orderFormFirstForm').onclick = function() {
            txtAmount = $('amount');
            clearInterval($('amount').interval);
            txtAmount.removeClassName('togglestyle');
        }
        //alert('set');
    }
});

document.observe('dom:loaded', function() {
    Load.loadPrefilledTextFields('quickSearchFrom');
    $$('.zoekPaneel').each(function(panel) {
        Load.loadPrefilledTextFields(panel);
    });
    $$('.zoekPaneel form, #quickSearchFrom').each(function(f) {
        $(f).observe('submit', function() {
            $A($(this).getElementsByClassName('prefilled')).each(function(e) {if($(e).value == $(e).start_value) {$(e).value = '';}});
        })
    });
    Load.loadActionSliders();
    if($('mailAFriend')) {
        loadPrefilledTextFields('mailAFriend');
    }
    if($('remark')) {
        loadPrefilledTextFields('remark');
    }
    if($('ordersteps')) {
        loadPrefilledTextFields('ordersteps');
    }
});

function toggleAmountStyle() {
    txtAmount = $('amount');
    txtAmount.toggle = !txtAmount.toggle;

    //alert('interval');
    if(txtAmount.toggle) {
        //style
        //manual styles
    } else {
        //style back to old style
        //manual styles
    }
    txtAmount.toggleClassName('togglestyle');
}
				
//lees cookie uit
function getCookie(naam) {
	var str = document.cookie;
	var zstr = naam + "=";
	var start = str.indexOf(zstr, 0);
	if(start == -1) {
		return false;
	} else {
		start += zstr.length;
		var eind = str.indexOf(";", start);
		if(eind == -1) eind = str.length;
		return unescape(str.substring(start, eind));
	}
}
			
//set een Cookie
function setCookie(naam, waarde) {
	//alert("blaat");
	document.cookie = naam+"="+escape(waarde)+";path=/";
}

/* snippet from Tom */
function loadPrefilledTextFields(element) {
	if(element) {
		element = $(element);
	} else {
		element = $(document.body);
	}
	var prefilled_color = '#EDC200';
	var prefilled_color_textarea = '#002c76';
	var filled = $A(element.getElementsBySelector('input.prefilled, textarea.prefilled'));
	filled.each( function (f) {
        f.normal_color = f.getStyle('color');

        if(!f.start_value) {
            if($(f).tagName.toLowerCase() != 'textarea' && !$('ordersteps')) {
                f.setStyle( {color:prefilled_color} );
            } else {
                f.setStyle( {color:prefilled_color_textarea} );
            }
        }
		f.onfocus = function() {
			if(!this.start_value || this.value.strip() == this.start_value.strip()) {
                if(this.id == undefined || !this.id.toString().startsWith("txtAflever") || (this.id.toString().startsWith("txtAflever") && !$('chkAfleveradresGelijk').checked)) {
                    this.start_value=this.value;
                    this.value='';
                    $(this).setStyle( {color:this.normal_color} );
                }
			}
		}
		f.onblur = function() {
			if($(this).value.strip() == '') {
                if(this.id == undefined || !this.id.toString().startsWith("txtAflever") || (this.id.toString().startsWith("txtAflever") && !$('chkAfleveradresGelijk').checked)) {
                    this.value = this.start_value;
                    if($(f).tagName.toLowerCase() != 'textarea' && !$('ordersteps')) {
                        f.setStyle( {color:prefilled_color} );
                    } else {
                        f.setStyle( {color:prefilled_color_textarea} );
                    }
                }
			}
		}
	});
};
/* end of snippet */

/* cancel the bubbling up the DOM tree of an event */
function onclick_CancelEventBubble(oEvent) {
	//check for the proper location of the event object
	if (!oEvent) {
		oEvent = window.event;
	}


	if(document.all) {
		oEvent.cancelBubble = true;
	} else {
		oEvent.stopPropagation();
		oEvent.preventDefault();
	}
	oEvent.returnValue = false;
	return false;
};



/* snippet from http://www.garyharan.com/index.php/2007/11/26/how-to-unobtrusively-scroll-a-div-with-prototype-scriptaculous/ */
/* adds Scroll animation to animation library of script.aculo.us  */
/* adds scrollTo function to Element methods of prototype library */
Element.addMethods({
  scrollTo: function(element, left, top){
    var element = $(element);
    if (arguments.length == 1){
      var pos = element.cumulativeOffset();
      window.scrollTo(pos[0], pos[1]);
    } else {
      element.scrollLeft = left;
      element.scrollTop  = top;
    }
    return element;
  }
});

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    this.start(Object.extend({x: 0, y: 0}, arguments[1] || {}));
  },
  setup: function() {
    var scrollOffsets = (this.element == window) 
                ? document.viewport.getScrollOffsets() 
                : Element._returnOffset(this.element.scrollLeft, this.element.scrollTop) ;
    this.originalScrollLeft = scrollOffsets.left;
    this.originalScrollTop  = scrollOffsets.top;
  },
  update: function(pos) {
    this.element.scrollTo(Math.round(this.options.x * pos + this.originalScrollLeft), Math.round(this.options.y * pos + this.originalScrollTop));
  }
});
/* end snippet */


/**
 *  @copyright the COW company © 2009
 *  @author Tom Niessink
 *  @package PackageName
 */
document.observe('dom:loaded', function() {
    //after dom is loaded
    //document.scrollMenu = new ScrollMenu('left_menu');
    Load.loadRollOverMenu();
    //Load.loadPrefilledTextFields();
    Load.loadAutoSuggest();
});

/**
 * @class Load
 */
Load = Class.create();

/**
 * @static
 */
Load.loadRollOverMenu = function() {
    if (typeof document.addEventListener != 'function') { //IE6 only
        $$('#top_menu > li').each(function (e) {
            $(e).onmouseover = function() {
                this.addClassName("over");
            };
            $(e).onmouseout = function() {
                this.removeClassName("over");
            };
        });
        $$('input.button').each(function (e) {
            $(e).onmouseover = function() {
                this.addClassName("button_over");
            };
            $(e).onmouseout = function() {
                this.removeClassName("button_over");
            };
        });
    }
}

/**
 * @static
 * @param {Element|string} element
 */
Load.loadPrefilledTextFields = function(element) {
	if(element) {
		element = $(element);
	} else {
		element = $(document.body);
	}
	var prefilled_color = '#a0b5c9';
	var prefilled_color_textarea = '#a0b5c9';
	var filled = $A(element.getElementsBySelector('input.prefilled, textarea.prefilled'));
	filled.each( function (f) {
        f = $(f);
        //console.log(f.inspect());
        f.normal_color = f.getStyle('color');
        f.normal_text_align = f.getStyle('textAlign');

        if(!f.start_value) {
            f.start_value=f.value;
            if($(f).tagName.toLowerCase() != 'textarea' && !$('ordersteps')) {
                f.setStyle( {color:prefilled_color, textAlign:"left"} );
            } else {
                f.setStyle( {color:prefilled_color_textarea, textAlign:"left"} );
            }
        }
		f.observe('focus', function() {
			if(!this.start_value || this.value.strip() == this.start_value.strip()) {
                if(this.id == undefined || !this.id.toString().startsWith("txtAflever") || (this.id.toString().startsWith("txtAflever") && !$('chkAfleveradresGelijk').checked)) {
                    this.start_value=this.value;
                    this.value='';
                    $(this).setStyle( {color:this.normal_color, textAlign:this.normal_text_align, position:'relative'} );
                    if(document.all) {
                        this.focus();
                        this.select();
                    }
                }
			}
		});
		f.observe('blur', function() {
			if($(this).value.strip() == '') {
                if(this.id == undefined || !this.id.toString().startsWith("txtAflever") || (this.id.toString().startsWith("txtAflever") && !$('chkAfleveradresGelijk').checked)) {
                    this.value = this.start_value;
                    if($(f).tagName.toLowerCase() != 'textarea' && !$('ordersteps')) {
                        f.setStyle( {color:prefilled_color, textAlign:"left"} );
                    } else {
                        f.setStyle( {color:prefilled_color_textarea, textAlign:"left"} );
                    }
                }
			}
		});
	});
}


/**
 * @static
 */
Load.loadAutoSuggest = function() {
    var stateSuggestions = new StateSuggestions();
    this.oTextbox = new AutoSuggestControl(
        $('quick_search'),
        stateSuggestions
    );

    if ($('advanced_search_1'))
    {
        this.oTextbox2 = new AutoSuggestControl(
            $('advanced_search_1'),
            stateSuggestions,
            true
        );
    }
}

/**
 * @static
 */
Load.loadActionSliders = function() {
    var sliders = $A($$('.actie_slider'));

    sliders.each(function(slider) {
        if($(slider).hasClassName('actie_slider')) {
            slider.actieSliderObject = new ActieSlider(slider);
        } else if(slider.hasClassName('small_slider')) {
            //slider.smallSliderObject = new Slider(slider);
        }
    });
}

/*
 *  @copyright the COW company © 2009
 *  @author Tom Niessink
 *  @package PackageName
 *  @class Slider
 */
Slider = Class.create();

/**
 * @static vars
 */
Slider.totalNumberOfSliders = 0;

/**
 * if alwaysStartWithFirst class is set in slider rootElement
 * then the slider doesn't take notice of the cookie that holds the current slider position
 * @copyright the COW company © 2009
 * @author Tom Niessink
 * @package PackageName
 * @class Slider
 */
ActieSlider = Class.create({
    ORIENTATION_HORIZONTAL: 1,
    ORIENTATION_VERTICAL: 2,
    DIRECTION_UP: 1,
    DIRECTION_DOWN: 2,
    DIRECTION_LEFT: 1,
    DIRECTION_RIGHT: 2,
    PREV: -1,
    NEXT: 1,

    initialize: function(element, interval, orientation, direction) {
        this.rootElement = $(element);

        this.isSliding = false;
        this.sliderID = ++Slider.totalNumberOfSliders;

        //not in use (yet)
        this.orientation = orientation != null ? orientation : this.ORIENTATION_HORIZONTAL;
        this.direction = direction != null ? direction : this.DIRECTION_DOWN;

        this.sliderDiv = $A($(element).getElementsByClassName('slider')).first();
        this.slideContainer = $A($(element).getElementsByClassName('slide_container')).first();
        this.intervalDelay = interval != null && interval > 0 ? interval * 1 : 6; //in seconden
        this.items = $A($(this.sliderDiv).childElements());
        this.numberOfItems = this.items.length;
        if(this.numberOfItems > 1) {
            this.navigationDiv = $A($(element).getElementsByClassName('navigation')).first();
            this.slideButtons = $A($A($(element).getElementsByClassName('slide_btns')).first().childElements());
            this.btnPrev = $A($(element).getElementsByClassName('prev')).first();
            this.btnNext = $A($(element).getElementsByClassName('next')).first();
            if(this.rootElement.hasClassName('alwaysStartWithFirst')) {
                this.currentSlide = 0;
            } else {
                this.currentSlide = this.getStartSlideFromCookies();
            }
            this.gotoSlide(null, this.currentSlide, false, false);
            this.registerEventhandlers();
            this.startInterval();
        } else if(this.numberOfItems == 0) {
            this.rootElement.hide();
        }
    },

    startInterval: function() {
        this.interval = setInterval(
            this.navigate.bindAsEventListener(this, this.NEXT, false),
            this.intervalDelay * 1000
        );
    },

    stopInterval: function() {
        clearInterval(this.interval);
    },

    getStartSlideFromCookies: function() {
        this.lastSlide = getCookie('lastSlide' + this.sliderID) ? getCookie('lastSlide' + this.sliderID) * 1 : this.numberOfItems - 1;
        this.lastSlide++;
        if(this.lastSlide >= this.numberOfItems) {
            this.lastSlide = 0;
        }
        setCookie('lastSlide' + this.sliderID, this.lastSlide);
        return this.lastSlide;
    },

    registerEventhandlers: function() {
        if(this.numberOfItems > 0) {
            this.navigationDiv.show();
            for(var i = 0; i < this.slideButtons.length; i++) {
            //this.slideButtons.each(function(button, i) {
                var button = this.slideButtons[i];
                if(i < this.numberOfItems) {
                    $(button).observe('click', this.gotoSlide.bindAsEventListener(this, i, true, true));
                    button.addClassName('act');
                } else {
                    $(button).observe('click', function(event) { Event.stop(event); });
                    button.setStyle({cursor: 'default'});
                }
            //});
            }
            this.btnPrev.observe('click', this.navigate.bindAsEventListener(this, this.PREV, true));
            this.btnNext.observe('click', this.navigate.bindAsEventListener(this, this.NEXT, true));
        }
    },

    navigate: function(event, stepPrevOrNext, isUserInput) {
        if(!this.isSliding) {
            this.gotoSlide(event, this.step(stepPrevOrNext), true, isUserInput);
        }
    },

    /**
     * @param {int} index
     * @param {bool} animate
     * @param {bool} isUserInput
     */
    gotoSlide: function(event, index, animate, isUserInput) {

        if(index == null) {
            index = this.currentSlide;
        }

        //calculate the future position
        var pos = 0;
        var anchor = 'left';
        switch(this.orientation) {
            case this.ORIENTATION_HORIZONTAL:
                anchor = 'left';
                if(this.direction == 1) {
                    anchor = 'right';
                }

                pos = index * this.slideContainer.offsetWidth * -1;
                break;
            case this.ORIENTATION_VERTICAL:
                anchor = 'top';
                if(this.direction == 1) {
                    anchor = 'bottom';
                }

                pos = index * this.slideContainer.offsetHeight * -1;
                break;
        }

        if(isUserInput) {
            this.stopInterval();
        }

        if(animate) {
            //animate normal
            this.isSliding = true;
            new Effect.Morph(this.sliderDiv, {
                style: anchor + ': ' + pos + 'px;',
                duration: 0.5,
                afterFinish: this.setCookieAfterFinish.bindAsEventListener(this, index, isUserInput)
            });
        } else {
            //set start position
            this.sliderDiv.setStyle(anchor + ': ' + pos + 'px;');
            this.setCookieAfterFinish(null, index, isUserInput);
        }

        if(event != null) {
            Event.stop(event);
        }
    },

    /**
     *
     */
    step: function(step) {
        this.currentSlide += step;

        if(this.currentSlide < 0) {
            this.currentSlide = this.numberOfItems - 1;
        } else if(this.currentSlide >= this.numberOfItems) {
            this.currentSlide = 0;
        }

        return this.currentSlide;
    },

    setCookieAfterFinish: function(event, index, isUserInput) {
        setCookie('lastSlide' + this.sliderID, index);
        this.slideButtons.each(function(button) {
            if($(button).hasClassName('current')) {
                button.removeClassName('current');
            }
        });
        this.slideButtons[index].addClassName('current');
        this.isSliding = false;
        if(isUserInput) {
            this.startInterval();
        }
    }
});

