var addId;
var addUrl;

$(document).ready(function(){ 
	startHome.init(); 
	feedSort.init();
	feedGallery.init(); 
	optionsOverlay.init();
	
	if( addId ){
		$('#feed-'+ addId).trigger('click');
	}else if( addUrl ){
		feedGallery.openAddCustomFeedDialog(addUrl);
	}

});

var startHome = {
	conf : {
		className: 'start-home',
		idPrefix: 'start-',
		registerIntro : '<h4>Registratie</h4>',
		passwordIntro : '<h4>Wachtwoord opvragen</h4>',
		regSucceeded: '<p class="added">De bron is toegevoegd</p>',
		regError: '<p class="error">Deze bron kon helaas niet worden toegevoegd - onjuist formaat</p>'
	},
	init: function(){
		if (!$('#register').length){return false;}
		$('#register').bind('click', startHome.openRegistrationDialog);
		$('#forgot_password').bind('click', startHome.openPasswordDialog);
	},
	openPasswordDialog: function(){
		var content = 	'<div class="start_home">' + 
						'Vul hieronder uw e-mailadres in. Uw wachtwoord wordt u dan per e-mail opgestuurd.<br/><br/><br/>' + 
						'<label>Emailadres:</label><input id="pass_email" type="text"/><br/>' + 
						'</div>' +
						'<p class="error invisible" id="pass_error"></p>';
		buttons = new Array();
		var okButton = $('<a></a>').addClass('button').addClass('ok').bind('click', function(){ startHome.doPassword() })
		var cancelButton = $('<a></a>').addClass('button').addClass('annuleren').bind('click', function(){ startHome.closePasswordDialog() })
		buttons.push(okButton);
		buttons.push(cancelButton);
		win.open( startHome.conf.passwordIntro + content, buttons);
	},
	openRegistrationDialog: function(){
		var content = 	'<div class="start_home">' + 
						'<label>Gebruikersnaam:</label><input id="reg_username" type="text"/>' + 
						'<label>Achternaam:</label><input id="reg_surname" type="text"/>' + 
						'<label>Voornaam:</label><input id="reg_name" type="text"/>' + 
						'<label>E-mail adres:</label><input id="reg_email" type="text"/>' + 
						'</div>' +
						'<p class="error invisible" id="reg_error"></p>';
		buttons = new Array();
		var addButton = $('<a></a>').addClass('button').addClass('ja-reg').bind('click', function(){ startHome.doRegister() })
		var cancelButton = $('<a></a>').addClass('button').addClass('nee-reg').bind('click', function(){ startHome.closeRegistrationDialog() })
		buttons.push(addButton);
		buttons.push(cancelButton);
		win.open( startHome.conf.registerIntro + content, buttons, 'register');
	},
	closePasswordDialog: function(){
		win._hide();
	},
	closeRegistrationDialog: function(){
		win._hide();
	},
	doRegister : function(){
		
		// Email checking
		var re = new RegExp("^[\w\d._%-]+@(?:[\w\d.-]+\.)[\w]{2,4}$");
		var post = true;
		
		if($('#reg_username').attr('value').length < 4){
			post = false;
			$('#reg_username').addClass('error');
		} else {
			$('#reg_username').removeClass('error');
		}
		
		if($('#reg_surname').attr('value').length < 2){
			post = false;
			$('#reg_surname').addClass('error');
		} else {
			$('#reg_surname').removeClass('error');
		}
		
		if($('#reg_name').attr('value').length < 2){
			post = false;
			$('#reg_name').addClass('error');
		} else {
			$('#reg_name').removeClass('error');
		}
		
		if($('#reg_email').attr('value').length < 7){
			post = false;
			$('#reg_email').addClass('error');
		} else {
			$('#reg_email').removeClass('error');
		}
		
		if(post){
			var data = 'username=' + $('#reg_username').attr('value');
			data += '&name=' + $('#reg_name').attr('value');
			data += '&surname=' + $('#reg_surname').attr('value');
			data += '&email=' + $('#reg_email').attr('value');
			$.post( '/ajax/register/', data, startHome.handleRegister, 'json'  );
		}
	},
	doPassword : function(){
		
		var post = true;
		
		if($('#pass_email').attr('value').length < 7){
			post = false;
			$('#pass_email').addClass('error');
		} else {
			$('#pass_email').removeClass('error');
		}
		
		if(post){
			var data = 'email=' + $('#pass_email').attr('value');
			$.post( '/ajax/remind/', data, startHome.handlePassword, 'json'  );
		}
	},
	handleRegister: function(resp){

		if(!resp.data.errormsg){
			var success = '<div class="start_home">Je gegevens zijn opgeslagen. Je ontvangt een e-mail met je wachtwoord.</div>'
			
			buttons2 = new Array();
			
			win.open( startHome.conf.registerIntro + success, buttons2);
			setTimeout('startHome.close();',2500);
		} else {
			$('#reg_error').html(resp.data.errormsg);
			$('#reg_error').removeClass('invisible');
		}
	},
	handlePassword: function(resp){

		if(!resp.data.errormsg){
			var success = '<div class="start_home">Uw wachtwoord is verstuurd naar uw e-mailadres.</div>'
			
			buttons2 = new Array();
			
			win.open( startHome.conf.passwordIntro + success, buttons2);
			setTimeout('startHome.close();',2500);
		} else {
			$('#pass_error').html(resp.data.errormsg);
			$('#pass_error').removeClass('invisible');
		}
	},
	close: function(){
		win._hide();
	}
}

var feedSort = {
	listId: 'source-list',
	handlerClass : 'drag-handle',
	initialized: false,
	list: null,
	init: function(){
		if (!$('#'+ this.listId).length){return false;}
		this.list = $('#'+ this.listId);
		var handlers = $('#' + this.listId + ' .' + this.handlerClass);
		handlers.hover(
			function(){	
				$(this).addClass('over');
			},
			function(){	
				$(this).removeClass('over');
			}
		);	
		feedSort.enable();
	},
	enable: function(){
		
		if( !this.initialized){
		
			var options = {
				start: function(e,ui){
					$(ui.item).addClass('dragging');
				},
				stop: function(e, ui){
					$(ui.item).removeClass('dragging').children('.' + feedSort.handlerClass).removeClass('over');
					feedSort.saveOrder();
					optionsOverlay.init();
				}
			};
			this.list.sortable(options);
			this.initialized = true;
		}else{
			this.list.sortable('enable');	
		}
		
	},
	saveOrder: function(){
		var orderStr = this.list.sortable('serialize');
		$.post( '/ajax/changeFeedOrder/', orderStr, null, 'json'  );
	}
}

var optionsOverlay = {
	box: null,
	currentFeedId: null,
	init : function(){
		if(!this.box){
			this.box = $('<div></div>').attr('id', 'feed-options').appendTo('body');		
		}
		$('#' + feedSort.listId + ' .options').bind('click', optionsOverlay.open);
		$('.chosen-feed').hover( 
			function(){
				$(this).nextAll('span').addClass('over');
			},  
			function(){
				$(this).nextAll('span').removeClass('over');
			}
		).bind('click', optionsOverlay.open);
	},
	open : function(){
		optionsOverlay.close();
		var link = $(this);
		var other = false;
		
		if(link.hasClass('chosen-feed'))
		{
			link2 = $('#my-feed-' + link.attr('id').replace('feed-', ''));

			if(link2.attr('id') == undefined)
			{
				link2 = $('#my-feed-' + link.attr('id').replace('feed2-', ''));
			}

			link = link2;
			other = true;
		}
		
		if(!link.hasClass('options')){
			return false;
		}
	
		optionsOverlay.currentFeedId = parseInt(link.parent('li').attr('id').replace('source-', ''));
		
		if(other)
		{
			var pos = $('#feed-'+optionsOverlay.currentFeedId).offset();
			pos.top += 20;
		} else {
			var pos = link.offset();
		}
		
		var feedName = link.siblings('span.name').html();
		var feedUrl = link.siblings('span.url').html();
		optionsOverlay.box.css({'top' : pos.top, 'left' : pos.left });
		var h3 = $('<h3>Opties voor : ' + feedName.substr(0,35) + '</h3>');
		var h4 = $('<h4>' + feedUrl + '</h4>');
		
		var form = $('<form></form>');
		// Create option to change amount of feeds to display
		var maxHeadlines = $('#max-headlines').val();
		var currentHeadlines = parseInt( link.parent('li').contents().find('span.headlines').html());
		var notify = parseInt( link.parent('li').children('span.notify').html());

		var selectLabel = $('<label for="headline-amount">Hoeveel koppen tonen?</label>');
		optionsOverlay.HLselect = $('<select id="headline-amount" name="headline-amount"></select>');
		for( var i=1; i<=maxHeadlines; i++){
			var opt = $('<option value="' + i + '">' + i + '</option>');
			if(currentHeadlines  == i ){ opt.attr('selected', 'selected'); }
			optionsOverlay.HLselect.append( opt );
		}

		var checkboxLabel = $('<label for="notify-me" class="for-checkbox">Ik wil een melding krijgen zodra er een nieuw artikel is.</label>');
		optionsOverlay.notifyMeCheckbox = $('<input class="checkbox" id="notify-me" name="notify-me" value="1" type="checkbox" />');
		if(notify){optionsOverlay.notifyMeCheckbox.attr('checked', true);}
		
		form.append(selectLabel).append(optionsOverlay.HLselect).append($('<br />')).append( optionsOverlay.notifyMeCheckbox ).append(checkboxLabel);
		
		// Buttons
		var saveButton = $('<a></a>').addClass('button').addClass('opslaan').bind('click', function(){ optionsOverlay.save(); });
		var cancelButton = $('<a></a>').addClass('button').addClass('annuleren').bind('click', optionsOverlay.close);
		var deleteButton = $('<a></a>').addClass('button').addClass('verwijder-deze-bron').bind('click', function(){
			if( confirm('Weet je zeker dat je deze nieuwsbron wil verwijderen?')){
				optionsOverlay.removeFeed();
			}
		});
		optionsOverlay.box
		.append(h3).append(h4).append(form)
		.append(saveButton).append(cancelButton).append(deleteButton).show();
		return false;
	},
	close: function(){
		optionsOverlay.currentFeedId = null;
		optionsOverlay.box.html('');
		optionsOverlay.box.hide();
	},
	save : function(){
		if(!optionsOverlay.currentFeedId){
			return false;		
		}
		var feedId = optionsOverlay.currentFeedId;
		var amount= parseInt(optionsOverlay.HLselect.val());
		var notify = optionsOverlay.notifyMeCheckbox.attr('checked') ? 1: 0;
		var data = 'feedId=' + feedId+ '&headlines=' + amount + '&notify=' + notify;
		$.post( '/ajax/saveFeedOptions/', data, optionsOverlay.handleSave, 'json'  );
	},
	handleSave: function(resp){
	
		if( !resp.usererror){
			if( !resp.data.feedId){
				return false;
			}
			optionsOverlay.updateFeedContents( resp.data.feedId, resp.data.feedName , resp.data.headlines, resp.data.notify )	
		}else{/* show error here? */}
		optionsOverlay.close();
	},
	updateFeedContents : function (id, name, headlines, notify){
		
		var li = $('#source-' + id);
		if(headlines){
			li.contents().find('.headlines').html(headlines);	
		}
		if(name){
			li.children('.name').html(name);
		}
		li.children('.notify').html(notify);
		
	},
	removeFeed : function(id){

		// comes from optionoverlay
		var data = 'feedId=' + optionsOverlay.currentFeedId; 
		$.post( '/ajax/removeFeed/',data, optionsOverlay.handleRemove, 'json' );
		return false;

	},
	handleRemove  :function(){
		$('#source-' + optionsOverlay.currentFeedId).remove();
		optionsOverlay.close();
		
		refresh();
	}
}
		
// All function related to Adding of feeds in javascript overlay
var feedGallery = {
	conf : {
		addFeedClassName: 'add-feed',
		addNotificonClassName: 'add-notificon',
		idPrefix: 'feed-',
		idPrefix2: 'feed2-',
		dIntro : '<h4>Nieuwsbron Toevoegen</h4><p>Kies voeg toe om onderstaande bron toe te voegen aan uw Nieuwsklikker. Wijzigingen worden binnen 10 minuten in uw Nieuwsklikker doorgevoerd.</p>',
		feedAdded: '<p class="added">De bron is toegevoegd</p>',
		feedError: '<p class="error">Deze bron kon helaas niet worden toegevoegd - onjuist formaat</p>',
		lastClickedLi: null,
		hasIt: 0
	},
	init : function(){
	
		// Attach events for adding predefined feeds
		$('a.' + this.conf.addFeedClassName).hover( 
			function(){
				$(this).nextAll('span').addClass('over');
			},  
			function(){
				$(this).nextAll('span').removeClass('over');
			}
		).bind('click', feedGallery.openAddFeedDialog );
		
		// Add a custom feed
		$('#add-custom-feed').bind('click', feedGallery.openAddCustomFeedDialog);
		
		// Add Hyves notificon using login...
		$('#add-hyves-login').bind('click', feedGallery.doAddHyvesLogin);
		
		// Open notification options in a new window instead of following link

		$('.' + this.conf.addNotificonClassName ).click( feedGallery.openNotificonOptions );
		
		
	},
	openAddFeedDialog: function(){
		
		var li = feedGallery.lastClickedLi = $(this);
		var index = li.attr('id').indexOf(feedGallery.conf.idPrefix) > -1 ? feedGallery.conf.idPrefix.length : 0;
		
		if(index == 0)
		{
			index = li.attr('id').indexOf(feedGallery.conf.idPrefix2) > -1 ? feedGallery.conf.idPrefix.length+1 : 0;
		}
		
		var feedId = li.attr('id').slice( index ) ;

		var content = 	'<div class="feed">' + li.attr('title') + 
						'<span>' + li.attr('rel') + '</span>' + 
						'</div>' ;
		buttons = new Array();

		var addButton = $('<a></a>').addClass('button').addClass('ja-voeg-toe').bind('click', function(){ feedGallery.doAddFeed(feedId) });
		var cancelButton = $('<a></a>').addClass('button').addClass('nee-toch-maar-niet').bind('click', function(){ feedGallery.closeAddFeedDialog() });
		buttons.push(addButton);
		buttons.push(cancelButton);
	
		win.open( feedGallery.conf.dIntro + content, buttons,'');
		return false;
	},
	closeAddFeedDialog: function(){
		win._setLoading(false);
		win._hide();
	},
	openAddCustomFeedDialog: function(url){
		
		var feed = typeof(url) == 'string' ? url : $('#custom-feed-url').val();
		
		if (feed == '') return false;
		
		var inputId = 'custom-feed';
		var content = 	'<div class="feed"><label>RSS url:</label><input id="' + inputId + '" type="text" value="' + feed + '" /></div><div id="feed-results"></id>' ;

		var buttons = new Array();
		var addButton = $('<a></a>').addClass('button').addClass('ja-voeg-toe').bind('click', function(){
			// Some url validating stuff?
			
			// This </ID> sh... is because of IE6
			if($('#feed-results').html() == '' || $('#feed-results').html() == '</ID>')
			{
				var url = $('#' + inputId).val();
				
				if(url.search(/:\/\//) == -1)
				{
					url = 'http://' + url;
				}
				
				if(  url != '' ){
					$('#feed-results').html('');
					
					feedGallery.doAnalyzeCustomFeed(url);
					//feedGallery.doAddCustomFeed(url);
				}
			} else {
				// Adding selected feeds...
				var list = $('#feed-results > input:checked');
				
				feedGallery.doAddMultipleFeeds(list);
			}
		});
		
		var cancelButton = $('<a></a>').addClass('button').addClass('annuleren').bind('click', function(){ feedGallery.closeAddCustomFeedDialog(); });
		buttons.push(addButton);
		buttons.push(cancelButton);
		win.open( feedGallery.conf.dIntro + content, buttons, 'notificon');
		$(document).keydown( function(e){
			if( e.keyCode == 13){
				// if user presses enter, we want to add the feed as well
				addButton.trigger('click');
				return false;
			}
			return true;
		});

	},
	closeAddCustomFeedDialog: function(){
		win._hide();
	},
	
	doAddFeed: function(feedId){
		win._setLoading(true);
		var data = 'feedId='+feedId;
		$.post( '/ajax/addFeed/', data, feedGallery.handleAddFeed, 'json'  );
		
	},
	doAddMultipleFeeds: function (list){
		var data = '';
		var cnt = 1;
		
		win._setLoading(true);
		
		var data = '';
		var cnt = 1;
		
		// jQuery object list...
		list.each( function(){
			//alert('Need  to adds feed: ' + $(this).val());
			if(cnt > 1)
			{
				data += '&';
			}
			data += 'feed' + cnt + '=' + $(this).val();
			cnt++;
		});
		
		$.post( '/ajax/addMoreUFeeds/', data, feedGallery.handleAddMultipleFeeds, 'json' );
	},
	handleAddMultipleFeeds: function(resp) {
		win._setLoading(false);
		if ( resp.status == 1){
			feedGallery.confirmFeedAdded();
		}else{
			var error_msg = '<p class="error">' + resp.text + '</p>';
			var button = $('<a></a>').addClass('button').addClass('sluiten').bind('click', function(){ feedGallery.closeAddCustomFeedDialog(); })
			win.open( feedGallery.conf.dIntro + error_msg , button );
		}
	},
	doAnalyzeCustomFeed: function(url) {
		var data = 'feedUrl='+url;
		win._setLoading(true);
		
		$.post( '/ajax/analyzeUrl/', data, function(resp){
			if (resp.data.isRSS){
				// Feed is RSS, so add it =)...
				feedGallery.doAddCustomFeed(url);
				win._setLoading(false);
			} else if(resp.data.isUrl)
			{
				win._setLoading(false);
				
				// If there are 
				if(resp.data.rez == undefined)
				{
					var error_msg = '<p class="error">Nieuwsklikker heeft op deze website geen nieuwsfeed kunnen vinden. Weet u de URL van de feed, dan kunt u deze handmatig invullen.</p>';
					var button = $('<a></a>').addClass('button').addClass('sluiten').bind('click', function(){ feedGallery.closeAddCustomFeedDialog(); })
					win.open( feedGallery.conf.dIntro + error_msg , button );
				} else {
					
					$('#win-content').attr('class','win-content-main win-content-feed-results');
					$('#win').attr('class','win-main win-feed-results');
					$('#win-loading').attr('class','win-main win-feed-results');
				
					var msg = 'Nieuwsklikker kon de volgende nieuwsfeeds vinden op deze website. Selecteer hier de feeds die aan uw Nieuwsklikker wilt toevoegen.<br/><br/>';
					
					for( var i in resp.data.rez )
					{
						msg += '<input type="checkbox" name="selection-' + i +'" id="feed-fo-selection-' + i + '"';
						msg += ' value="' + resp.data.rez[i]['url'] + '" />';
						msg += '<label for="feed-fo-selection-' + i +'">' + resp.data.rez[i]['title'] + '</label><br/>';
					} 
					
					$('#feed-results').html(msg);
				}
			}else{
				win._setLoading(false);
				var error_msg = '<p class="error">Nieuwsklikker heeft op deze website geen nieuwsfeed kunnen vinden. Weet u de URL van de feed, dan kunt u deze handmatig invullen.</p>';
				var button = $('<a></a>').addClass('button').addClass('sluiten').bind('click', function(){ feedGallery.closeAddCustomFeedDialog(); })
				win.open( feedGallery.conf.dIntro + error_msg , button );
			}
		}, 'json' );
	},
	// only pass isValid if we're certain about feed validity
	doAddCustomFeed: function(url, isValid ){
		feedGallery.lastClickedLi = null;
		if( isValid == undefined){ 
			// Not validated yet? validate feed first -> then come back here if it's a valid feed
			win._setLoading(true);
			var data = 'feedUrl='+url;
			$.post( '/ajax/validateFeed/', data, function(resp){
				
				if (resp.usererror || !resp.data.feedId ){
					// Feed not ok
					feedGallery.doAddCustomFeed(resp.url, false);
					win._setLoading(false);
				}else{
					// Feed ok
					feedGallery.doAddFeed(resp.data.feedId);
				}
			}, 'json' );

		}else if(!isValid){
			var button = $('<a></a>').addClass('button').addClass('sluiten').bind('click', function(){ feedGallery.closeAddCustomFeedDialog(); })
			win.open( feedGallery.conf.dIntro + feedGallery.conf.feedError , button );
		}

	},
	// Handles returned response that comes back after adding feed ( predefined or custom)
	handleAddFeed : function(resp){
		win._setLoading(false);
		if ( resp.status == 1){
			feedGallery.confirmFeedAdded();
		}else{
			return;
		}
	},
	confirmFeedAdded : function(){
		win._setContent(feedGallery.conf.dIntro + feedGallery.conf.feedAdded);
		
		var  okButton = $('<a></a>').addClass('button').addClass('ok').bind('click', function(){ 
			feedGallery.closeAddFeedDialog();
			
			if(feedGallery.lastClickedLi){
				// Disable list item
				feedGallery.lastClickedLi.removeClass('add-feed').addClass('chosen').unbind('click').unbind('mouseover').unbind('mouseout');
			}
			refresh();
		});
		win._setButtons(okButton);
	},
	
	
	/*****
	 * 
	 * 	Adding notificons trough javascript . new per 25th of March
	 * 
	 */
	openNotificonOptions: function(){
		
		// Create a function here to attach events after the window has loaded.
		var afterLoaded = function(){
			
			// Cancel
			$('#annuleren').click( function(){
				win._hide(); 
				return false;
			});
			
			
			
			// Save ( post the form )
			$('#opslaan').click(function(){
			
				var form = $(this).parents('form');
				var url = form.attr('action');
				
				// Create data string for post
				var els = $('.notify-options').children('input, select');
				var data = {};
				feedGallery.hasIt = $('#hasIt').val();
				
				// Notificon ID
				data['nid'] = $('#nid').val();
				// Form data
				els.each( function(){
					var el = $(this);
					
					if( el.attr('type') == 'checkbox' && el.attr('checked')){
						data[el.attr('id')] = el.attr('value');
					}
					else if( el.attr('type') != 'checkbox'){
						data[el.attr('id')] = el.attr('value');
					}
				});
				
				win._setLoading(true);
				
				$.post( url, data, feedGallery.doHandleAddNotificon, 'text');
				
				if(form.length != 1){ return false;}
				
				return false;
			});
			
			
			
			// Delete
			$('#verwijderen').click( function(){
				var form = $(this).parents('form');
				var url = form.attr('action');
				var data = {};
				// Notificon ID
				data['nid'] = $('#nid').val();
				data['uninstall'] = '1';
				
				win._setLoading(true);
				$.post( url, data, function(){
					win._setLoading(false);
					refresh();
					win._hide();
				} );

				return false;
			});
			
		};
		
		var type = $(this).attr('rel');
		
		if(type != '')
		{
			win.loadSpecUrl( this.href, afterLoaded, type );
		} else {
			win.loadUrl( this.href, afterLoaded);
		}
		
		return false;
	},
	
	
	
	doHandleAddNotificon: function(data, textStatus) 
	{
		var error = $('#win-content > .error');
		win._setLoading(false);
		
		if(textStatus == 'success')
		{
			if(data == 'Success')
			{
				if(feedGallery.hasIt == 0){ setTimeout('refresh()',100); }
				feedGallery.hasIt = 0;
				win._hide();
			} else {
				error.text(data);
				error.fadeIn('slow');
			}
		} else {
			error.text('Sorry, error occured.');
			error.fadeIn('slow');
		}
	},
	
	
	
	// Tryes to add Hyves feed by using login credentials...
	doAddHyvesLogin: function()
	{
		var uname = $('#hyves-username');
		var password = $('#hyves-password');
		var form = $('#hyves-form');
		var link = $(this);
		var proceed = true;
		
		if(uname.val().length < 4)
		{
			uname.addClass('error');
			proceed = false;
		} else {
			uname.removeClass('error');
		}
		
		if(password.val().length < 4)
		{
			password.addClass('error');
			proceed = false;
		} else {
			password.removeClass('error');
		}
		
		if(proceed)
		{
			link.unbind('click',feedGallery.doAddHyvesLogin);
			link.click(feedGallery.openNotificonOptions);
			link.attr('href',form.attr('action') + '&username=' + uname.val() + '&password=' + password.val());
			link.click();
			link.attr('href','');
			link.unbind('click',feedGallery.openNotificonOptions);
			link.click(feedGallery.doAddHyvesLogin);
		}
		
		return false;
	}
	
	
};


// Dialog Window
var win = {
	active : false,
	overlay : null,
	dialog : null, 
	content: null,
	ie6 : navigator.userAgent.indexOf("MSIE 6")>=0 ,
	winDialogClass : 'win',
	winContentClass : 'win-content',
	type : '',

	open : function ( message, buttons, type ){

		if( type != undefined && ( type == 'register' ||  type == 'notificon' ) ){
			this._setType('register');
		} else if (type != undefined) {
			this._setType(type);
		}

		if( !this.dialog ){	this._createDialog();}
	
		this._setContent( message );
		this._setButtons( buttons );
		this._show();
	},
	loadUrl : function( url, callback ){
		this._setType('notificon');
		if( !this.dialog ){this._createDialog();}
		win._setLoading( true );
		$.get( url, function(data){
			win._setContent( data );
			callback();
			win._show();
			win._setLoading ( false);
		}); 

	},
	loadSpecUrl : function( url, callback, type ){
		this._setType(type);
		if( !this.dialog ){this._createDialog();}
		win._setLoading( true );
		$.get( url, function(data){
			win._setContent( data );
			callback();
			win._show();
			win._setLoading ( false);
		}); 

	},
	_setType: function(type){
			this.type  = type;
	},
	_toggleAllSelects : function ( show ){	
		if(show){
			$('#site select').css('visibility', 'visible');
		}else{
			$('#site select').css('visibility', 'hidden');
		}
	},
	_setButtons: function(buttons){
		this.buttonContainer.html('');
		
		if( typeof(buttons) == 'object' && buttons.length){
			for( var i=0; i<buttons.length; i++){
				this.buttonContainer.append(buttons[i]);
			}
		}else{
			this.buttonContainer.append(buttons);
		}
		
	},
	_setContent : function( content ){
		this.winContent.html( content );
	},
	_clearContent : function(){
		this.winContent.html('');
		this.buttonContainer.html('');
	},
	_show : function(){
		if (win.ie6){
			$('body').addClass('js');
			win._toggleAllSelects(false);
		}
		win.overlay.show();
		this.dialog.attr('class','');
		this.dialog.addClass(this.winDialogClass + '-main');
		this.dialog.addClass(this.winDialogClass + '-' + this.type);
		this.winContent.attr('class','');
		this.winContent.addClass(this.winContentClass + '-main');
		this.winContent.addClass(this.winContentClass + '-' + this.type);
		this.winLoading.attr('class','');
		this.winLoading.addClass(this.winContentClass + '-main');
		this.winLoading.addClass(this.winContentClass + '-' + this.type);
		win.dialog.show();
		win.active = true;
	},
	_hide : function(){
		if (win.ie6){
			$('body').removeClass('js');
			win._toggleAllSelects(true);
		}
		win.overlay.hide();
		win.dialog.hide();
		win._clearContent();
		win.active = false;
		
	},
	_createDialog : function(){
		
		this.overlay = 	$('<div></div>').attr('id', 'overlay').appendTo('body').click( win._hide);
		this.winLoading = $('<div></div>').attr('id', 'win-loading').addClass('win-main').html('<p>Een ogenblik geduld aub...</p>').appendTo('body');
		this.winContent = $('<div></div>').attr('id', 'win-content').addClass('win-content-main');
		this.winContent.addClass(this.winContentClass);
		this.winLoading.addClass(this.winLoadingClass);

		if (this.winContentClass == 'register' || this.winContentClass == 'notificon'){
			this.winContent.addClass(this.winContentClass);
			this.winLoading.addClass(this.winContentClass);
		}else{
			this.winContent.removeClass('register notificon');
			this.winLoading.removeClass('register notificon');
		}
		
		this.buttonContainer = $('<div></div>').attr('id', 'button-container-dynamic');
		// Put it all together and append to body
		this.dialog = $('<div></div>').attr('id', 'win').append( this.winContent ).append( this.buttonContainer ).appendTo('body').addClass('win-main');
	},
	_setLoading : function( loading ){
		if(loading){
			this.winLoading.attr('class','');
			this.winLoading.addClass(this.winLoadingClass);
			this.winLoading.show();	
		}else{
			this.winLoading.hide();
		}
		
	}
	
}
function refresh(){
	// Remove '#' if needed
	var goTo = document.location.href;
	if ( document.location.href.indexOf('#') >= 0 ){
		goTo = document.location.href.slice( 0, document.location.href.lastIndexOf('#')) ;
	}
	document.location.href = goTo;
}
