/*
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */

/*
 * Register more initializations here
 */


function global_initialize() {
	DomUtils.styleFileUploadFields();
	main_navigation.init();
	
	var ua = navigator.userAgent.toLowerCase();
	if ((ua.indexOf('iphone') > 0) || (ua.indexOf('ipad') > 0) || (ua.indexOf('ipod') > 0) || (ua.indexOf('android') > 0)) {
		filter_navigation.buildMobileSelectNavigation();
	} else {
		filter_navigation.init();
	}
	
	minisitemap.init();

	try {				
		findEmail.init();
	} catch(err) { }
	
	try {
		countrySwitch.init();
	} catch(err) { }
	
	// enhancing the forms
	FormUtils.init();
	
	/* hack for ie6 and image-flickering */
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err) { }
}

Event.observe(window, 'load', function() {
	global_initialize();
});


function DOM_getText( div ) {
	if( null==div ) return null;
	return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
}

/** ---------------------------------------------------------
 *   Handy functions to work with the dom
 */
var DomUtils = {
		/**
		 * Takes an id and returns the possible json object, if the innerHTML of the div hast the format <!-- {-object definitons-} -->
		 * 
		 * @return the java script variable of the JSON string
		 */
		getInlineJson: function(id){
			var elem = $(id);
			if (elem) {
				// educing the comments
				var possibleJson = elem.innerHTML.split('<!--');
				if (possibleJson[1]) {
					var possibleJson = possibleJson[1].split('-->');
					if (possibleJson[0]) {
						// eval the string with the json definition
						return eval( '(' + possibleJson[0].replace('\'','\\\'') + ')' );
					}
				}
				
			}
			
			return null
		},
		
		// disables browser auto completion for the given element
		disableAutoComplete : function(elemId) {
			$(elemId).writeAttribute("autocomplete", "off");
		},
		
		// function to style a input class file
		styleFileUploadFields : function() {
			
			var btnClass = 'imagebutton browseButton';
			
			var fakeFileUpload = new Element('div').addClassName('fakefile');
			
			var input =  new Element('input', {'type': 'text'}).addClassName('inputbox');
			var btn = new Element('div').addClassName(btnClass);

			fakeFileUpload.insert(input);
			fakeFileUpload.insert(btn);
			
			var x = $$('input.file');
			
			for (var i = 0; i < x.length; i++) {
				if (! x[i].up(0).hasClassName('fileinputs')) continue;
				
				x[i].addClassName = 'file';
				var clone = fakeFileUpload.cloneNode(true);
				x[i].up(0).insert(clone);
				x[i].relatedElement = clone.select('input')[0];
				x[i].btn = clone.select('div')[0];
				
				x[i].onchange = function () {
					var filePath = this.value;
					if ( filePath.indexOf("\\") != -1 ) {
						this.relatedElement.value = filePath.substring( filePath.lastIndexOf("\\") + 1, filePath.length );
					} else {
						this.relatedElement.value = filePath;
					}
					this.btn.removeClassName('hover_file');
				}
					
				x[i].onmouseout = function () {
					this.btn.removeClassName('hover_file');
				}
				
				x[i].onmouseover = function(){
					this.btn.addClassName('hover_file');
				}
			}
		}
};

var FormUtils = {
		
	charcounters : new Array(),
		
	init : function() {
		// check for charcounters
		var counts = $$('.charCountField')
		
		for (var i = 0; i < counts.length; i++) {
			var elem = counts[i];
			var counterForm = elem.select('textarea')[0];
			if (counterForm) {
				var cc_field_id = elem.readAttribute('count_field_id');
				var cc_field = $(cc_field_id);
				var maxchars = parseInt(cc_field.innerHTML, 10);
				
				this.charcounters.push(new FormUtils.CharCounter(counterForm, cc_field, maxchars));
			}
		}
		
	},
	
	CharCounter : function(input, counterfield, maxchars) {
		this.input = input;
		this.counterfield = counterfield;
		this.maxchars = maxchars;
		
		this.currentChars = 0; 
		this.input.charcounter = this;
		
		this.input.observe('keyup', function() {
			this.charcounter.evalInput();
		});
		
		// start of functions
		
		this.evalInput = function() {
			var len = this.input.getValue().length;
			if (len <= maxchars) {
				this.currentChars = len;
				this.counterfield.innerHTML = maxchars - len;
				return true;
			} else {
				// cut the input
				this.input.setValue(this.input.getValue().substring(0, this.maxchars))
				this.counterfield.innerHTML = this.maxchars - this.input.getValue().length;
				return false;
			}
		};				

		// initial runs		
		this.evalInput();				
	}
};
	
var cookieUtil = {
	get : function( name ){
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );			
	},
	
	set : function( name, value, expires, path, domain, secure ){
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
			( ( path ) ? ';path=' + path : '' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );	
	}
};

var StringUtil = {


		// trims a prefix from a given string, this can be used to trim
		// a certain prefix from DOM element IDs for further processing on the ID
		trimPrefix : function(str, prefix) {
			return str.substring(prefix.length);
		},

		// appends the parameter with the given name and
		// value to the given url and returns the changed url
		appendParamToURL : function(url, name, value) {
			var c = "?";
			if(url.indexOf(c) != -1) {
				c = "&";
			}
			return url + c + name + "=" + encodeURIComponent(value);
		}
}
