var DcrCodeSearch = Class.create();

DcrCodeSearch.prototype	= {
 Version	: '1.0.2',
 _relative	: null,
 _errorDivId  : 'invalid_objectcode',
 _searchBoxDivId  : 'header-searchBoxWrap',
 _inputField	: null,
 _submitBtn	: null,
 _initialValue : null,
 
 
	/* init */
	initialize	: function( h_p ) {

		this._inputField = $('dcrcs_bookcode');
		this._submitBtn = $('btn-sb-submit');
		this._initialValue = this._inputField.getValue();

		Event.observe(this._inputField, 'focus', function() {
			this._inputField.focus();
			this._inputField.select();
			var objectCode = encodeURI(this._inputField.getValue());
			if(objectCode == encodeURI(this._initialValue)) {
				this._inputField.setValue('');
			}
		}.bind(this));

		/*
		Event.observe(this._inputField, 'blur', function() {
		}.bind(this));
		*/
		
		Event.observe(this._inputField, 'keydown', function() {
			this.hideErrorMsg();
		}.bind(this));
		
		Event.observe(this._inputField, 'click', function() {
			//this.hideErrorMsg();
		}.bind(this));

		Event.observe(this._submitBtn, 'click', function() {
			this.onSubmit();
		}.bind(this));
		
	},

	onSubmit	: function() {
		this.checkObjectCode();	
	},
	
	checkObjectCode	: function() {
		
		var objectCode = encodeURI(this._inputField.getValue());
		if(objectCode.length < 6 || objectCode == encodeURI(this._initialValue)) {
			this.showErrorMsg();
		} else {
			this.lookupObjectCode( objectCode );
		}
		
	},
	
	hideErrorMsg	: function() {
		if($('invalid_objectcode') != undefined) {
			new Effect.Morph(this._errorDivId, {
					  style: 'width: 0px;height:30px',
					  duration: 0.6
					});
		}
	},
	
	showErrorMsg	: function() {

		this._inputField.focus();
		this._inputField.select();
	
		if($('invalid_objectcode') == undefined) {
			$(this._searchBoxDivId).insert({top: '<div id="invalid_objectcode" style="width: 0px;"><span>Reise nicht vorhanden</span>'});
		}		
		new Effect.Morph(this._errorDivId, {
				  style: 'width: 230px;height:30px',
				  duration: 0.8
				});

	},

	lookupObjectCode	: function(objectCode) {

		var protocolString = (("https:" == document.location.protocol) ? "https://" : "http://");
		var url = protocolString + 'www.derclub-reisen.de/index.php';

		var pars = 'eID=qslookupObjectCode&objectCode=' + objectCode;
		var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: this.lookupObjectCode_onResponse.bind(this)});

	},
 
 
	lookupObjectCode_onResponse	: function(orgRequest) {

		var xmldoc = orgRequest.responseXML;

		if(!xmldoc.getElementsByTagName('productUrl')[0].firstChild) {
			this.showErrorMsg();
			return;
		}
		var result = xmldoc.getElementsByTagName('productUrl')[0].firstChild.data;
	
		if(result.length > 0) {
			var redirectURL = "http://" + window.location.hostname + "/" + result;
			window.location.href = redirectURL;
		} else {
			this.showErrorMsg();
			
		}

	}

	
};
Event.observe(window, 'load', function() {
	var dcrCodeSearch = new DcrCodeSearch();
});
