
/**
 * Static vars
 */
var systemRoar;
var advSearch;
var isLock = false;


/**
 * Onload event
 */
window.addEvent('domready', function() {

	/**
	 * Setup a Roar instance
	 */
	systemRoar = new Roar({
		duration: 5000,
		margin: {x: 0, y: 0},
		position: 'upperLeft',
		offset: 2
	});
	//container: 'layer-content-frame',


	/**
	 * Register tooltips in DOM
	 */
	if ($$('.tooltip')) {
		new Tips('.tooltip',{
			className: 'tooltip',
			fixed: false,
			offsets: {x:-70, y:17},
			showDelay: 50,
			hideDelay: 0
		});
	}


	/**
	 * Setup defaults for input fields
	 */
	if ($$('input.dwdefaults')) {
		new dwDefaults({
			collection: $$('input.dwdefaults')
		});
	}


	/**
	 * Advanced search tween
	 */
	if ($('search_form')) {
		$('search_form').addEvent('submit', function(evt){
			// Stops the submission of the form.
			new Event(evt).stop();

			if (this.q.value == 'f.eks. cafe, bager') this.q.value = '';
			if (this.w.value == 'adresse, by, postnr') this.w.value = '';
	
			// Sends the form to the action path,
			this.submit();
		});
	}


	/**
	* Setup formchecks
	*/
	if ($$('.cms_form')) {
		regularForms = $$('.cms_form');
		regularForms.each(function(item, index){
			new FormCheck(item, {
				display : {
					scrollToFirst : true
				},
				ajaxEvalScripts: 'true'
			});
		});
	}
	
	if ($$('.cms_form_ajax')) {
		ajaxForms = $$('.cms_form_ajax');
		ajaxForms.each(function(item, index){
			new FormCheck(item, {
				display : {
					scrollToFirst : true
				},
				submitByAjax: 'true',
				ajaxEvalScripts: 'true',
				onAjaxRequest: function() {
					doAjaxRequest();
				},
				onAjaxSuccess: function(str) {
					doAjaxSuccess(str);
				}
			});
		});
	}
	

	/**
	* That CSS selector will find all <a> elements with the
	* attribute rel="boxed"
	*
	* The second argument sets additional options.
	*/
	if($$('a[rel=boxed]')) {
		SqueezeBox.assign($$('a[rel=boxed]'), {
			size: {x: 400, y: 300},
			ajaxOptions: {
				method: 'get' // we use GET for requesting plain HTML
			}
		});
	}

	if ($$('.btn-sbox-tour')) {
		SqueezeBox.assign($$('.btn-sbox-tour'), {
			size: {x: 900, y: 350},
			parse: 'true',
			ajaxOptions: {
				method: 'get'
			}
		});
	}


	if ($('btn-sbox-login')) {
		SqueezeBox.assign($('btn-sbox-login'), {
			size: {x: 500, y: 300},
			parse: 'true',
			ajaxOptions: {
				method: 'get'
			}
		});
	}

	/**
	 * The CSS selector will find all input, textarea, and selects
	 * to make em fokusable.
	 */
	$$('input, select, textarea').addClass('idle');
	$$("input, select, textarea").addEvent('focus', function(e){
		$(this).addClass("active").removeClass("idle").addEvent('blur', function(e){
			$(this).removeClass("active").addClass("idle");
    	});						 
	});

});


// Basic function show/hide
function toggle_display(obj,flag) {
	if (flag) {
		obj.setStyle('display', flag);
	}

}

//This has to be declared before domready 
function checkusername(el){ 

	if(isLock){return true;} //If its locked return.. shouldn't this be void or checking..?
	isLock = true; //We're starting the check, lock the function
	var isLockCheck = getUserName(el);

	if(!isLockCheck.handshake) {
		el.errors.push(isLockCheck.response);
		isLock = false; // release the function we're done
		return false; //return the error message to the user
	}

	isLock = false; //release the function we're done
	return true; //no error message
}


function getUserName(el) {

	var isLockCheck = true; //default to no errors

	var myRequest = new Request.JSON({
		url: script_root + 'bruger/check_bruger', 
		method: 'post', //This can be post as well 
		evalResponse: true, //Evaluate the Requested pages response. 
		async: false, //IMPORTANT! STOP SCRIPTS FROM RUNNING UNTIL REQUEST IS DONE!!!! 
		data: {'email' : $(el).get('value')},
		onSuccess : function(json, text){
			isLockCheck = JSON.decode(text);
		}, 
		onFailure : function(json){ 
			isLockCheck = false; //There was an Error don't let the user submit... 
		} 
	}).send(); 

	return isLockCheck; //return our results
}

function doAjaxRequest(container) {
	//$('layer-content-frame').addClass('spinner');
}


function doAjaxSuccess(str) {
	
	//alert(str);
	// Start by decoding the JSON string into javascript
	json = JSON.decode(str);

	// If the redirect is defined
	if (json.redirect) location.href = json.redirect;

	// Update a specific list,
	// Inserts returned html into list
	if (json.update) {
		if (json.update.append) {

			// Create html tags here
			var parentItem;
			var createdItems = new Array();
			var doFunctions = new Array();
			var returnedItems = json.update.html;

			returnedItems.each(function(item, index){
				newElement = createdItems[item.id] = new Element(item.tag);
				
				if (item.id)			newElement.set('id', item.id);
				if (item.name)			newElement.set('name', item.name);
				if (item.text)			newElement.set('html', item.text);
				if (item.value)			newElement.set('value', item.value);
				if (item.type)			newElement.set('type', item.type);
				if (item.class_name)	newElement.set('class', item.class_name);
				if (item.title)			newElement.set('title', item.title);
				if (item.rel)			newElement.set('rel', item.rel);
				if (item.rows)			newElement.set('rows', item.rows);
				if (item.src)			newElement.set('src', item.src);
				
				if (item.click) {
					newElement.addEvent('click', function() {
						globalEval(item.click);
					});
				}

				if (item.parent != '') {
					newElement.inject(createdItems[item.parent]);
				}
				else {
					newElement.inject($(json.update.container), 'top');
					parentItem = newElement;
				}

				if (item.do_function != '') {
					globalEval(item.do_function);
				}
			});
			
			parentItem.flash('#F5F5E0','#ffffff',3); 
			
		}
		else {
			$(json.update.container).set('html', json.update.html);
		}

		// Hide all input_tems
		input_items = $$('.item_input');
		input_items.each(function(item, index){
			item.addClass('hidden');
		});
	}

	/**
	 * Fire event if defined
	 */
	if (json.do_function) {
		globalEval(json.do_function);
	}

	if (json.debug) alert(json.debug);
	
	
	// At last show a message on response
	if (json.response) {
		
		handshake = (json.handshake) ? json.handshake : 'failure';
		title = json.response.title;
		message = json.response.message;
		container = (json.response_container) ? json.response_container : 'layer-content-frame';

		if (json.response.roar) {
			systemRoar.alert(title, message, {handshake: json.handshake});
		}
		else {
			$(container).set('html', message);
			$(container).setStyle('display','block');
		}

	}
	
}

function globalEval(code) {
	if(window.execScript) {
		window.execScript(code);
	} else {
		eval(code);
	}
}


var adv_search_flag = false;
function toogleAdvSearch(obj) {

	if (adv_search_flag) {

		adv_search_text = 'Avanceret s&oslash;gning';
		adv_search_flag = false;
		adv_search_height = 20;

	} else {

		adv_search_text = 'Simpel s&oslash;gning';
		adv_search_flag = true;
		adv_search_height = 55;
	}
	
	advSearch.start('height', adv_search_height);

	$(obj).set('html',adv_search_text);

}


function selectState(obj) {

	if(obj.value == 'login')
	{
		formCheck.dispose($('create_name_first'));
		formCheck.dispose($('create_name_last'));
		formCheck.dispose($('create_sex_m'));
		formCheck.dispose($('create_sex_f'));
		formCheck.dispose($('create_birthyear'));
		formCheck.dispose($('create_zip'));
		formCheck.dispose($('create_checkemail'));
		formCheck.dispose($('create_checkemailconfirm'));
		formCheck.dispose($('create_checkemailconfirm'));
		formCheck.dispose($('create_password'));

		formCheck.register($('login_email'));
		formCheck.register($('login_password'));
	}
	else
	{
		formCheck.dispose($('login_email'));
		formCheck.dispose($('login_password'));

		formCheck.register($('create_name_first'));
		formCheck.register($('create_name_last'));
		formCheck.register($('create_sex_m'));
		formCheck.register($('create_sex_f'));
		formCheck.register($('create_birthyear'));
		formCheck.register($('create_zip'));
		formCheck.register($('create_checkemail'));
		formCheck.register($('create_checkemailconfirm'));
		formCheck.register($('create_checkemailconfirm'));
		formCheck.register($('create_password'));
	}

	$('userstate-login').style.display = (obj.value == 'login') ? 'block' : 'none';
	$('userstate-create').style.display = (obj.value == 'create') ? 'block' : 'none';
}


function urlencode(str) {

	str = str.replace(/ /gi, '-');
	str = str.replace(/\./gi, '');
	str = str.replace(/�/gi, 'ae');
	str = str.replace(/�/gi, 'oe');
	str = str.replace(/�/gi, 'aa');
	str = str.replace(/�/gi, 'AE');
	str = str.replace(/�/gi, 'OE');
	str = str.replace(/�/gi, 'AA');

	return str;
}