var defaultFontsize = 1;
var sizecount = 3;
var prefs = { 
	currentFontsize: defaultFontsize,
	audio_active: true
};
var mo_timeout = null;
var current_id = null;
var current_href = null;
var play_mouseover_current_str = null;
var steffie_playing = false;
var tt_timeout = null;
$.validator.addMethod("is_changed" ,function (value,elem) {
	var el = $(elem);
	return  el.hasClass('changed') || el.hasClass('focus') && el.val()!='';
},$.validator.messages['required']); 

$(document).ready(function() {
	setUserOptions();
	// cms_edit_links
	$("*[data-rgd-cel]").each(show_edit_link);

	var tt = {
		position: "bottom center",
		relative: "true",
		onShow: function() {
			var self = this;
			if ( !tt_timeout && prefs.audio_active ) {
				tt_timeout = setTimeout(function() {
					self.getTip().parent().find('a.readspeaker').trigger('click');
					tt_timeout = null;
				},1000);
			}
		},
		onBeforeHide: function() {
			if ( tt_timeout ) {
				clearTimeout(tt_timeout);
				tt_timeout=null;
			}
			if ( prefs.audio_active ) {
				var rs_tip = this.getTip().parent().find('a.readspeaker');
				if ( current_id && rs_tip.length && rs_tip[0].href == current_href )	{
					rs.closepage(current_id);
					current_id = null;
					current_href = null;
				}
			}
		}
	};
	$('#navigatie li a, a#logo').tooltip(tt);
	$('#top form.search').tooltip($.extend(tt,{offset: [ 0,-25]}));
	
	$('.fix_mo').mouseenter(do_mo).mouseleave(do_ml);
	// p-issues
	$('.p-inline p:last-child').css({'margin-bottom':0,'display':'inline'});

	$("input.toggleval,textarea.toggleval").toggleVal({ focusClass: 'focus', changedClass: 'changed' });
	$("input.toggleval[required=true],textarea.toggleval[required=true],input.toggleval[validate*=required:true],textarea.toggleval[validate*=required:true]").each(function() {
		var val = $(this).attr('validate');
		if ( val && val.indexOf('required:true')>-1 ) {
			val = val ? val+',' : '';
			$(this).attr('validate',val+'is_changed:true');
		}
	});
	$('.search').each(function() {
		$(this).validate({ showErrors: function() {} });
	});

	$('#fontsize-menu span').click(function() {
		changeFontSize(this.id=='toggle' ? null : parseInt(this.id.substr(4)));
	});
	
	var rshlexit = rs.rshlexit;
	rs.rshlexit= function() {
		current_id = null;
		current_href = null;
		rs.closepage(current_id);
		rshlexit();
	}
	var rshlinit = rs.rshlinit;
	rs.rshlinit=function() {
		rshlinit();
		$('.p-inline p:last-child').css({'margin-bottom':0,'display':'inline'});
	}
	var closepage = rs.closepage;
	rs.closepage = function(id) {
		closepage(id);
		if (typeof(survey_data)!='undefined') {
			for (i in survey_data.surveys) {
				 location.reload();
				 break;
			}
		}
	}
	$('.block_home .block_content:eq(1)').addClass('selected');
});
function do_mo(str) {
	if ( prefs.audio_active ) {
		if ( $(this).attr('mo') ) {
			str = $(this).attr('mo');
		}
		if ( str ) {
			play_mouseover( str, 500 );
		} else {
			$('#rs_'+this.id).trigger('click');
		}
	}
}
function do_ml() {
	if ( prefs.audio_active ) {
		if ( $(this).attr('mo') ) {
			stop_mouseover();
		} else {
			var $b = $('#rs_'+this.id);
			if ( current_id && $b.length && $b[0].href == current_href )	{
				rs.closepage(current_id);
				current_id = null;
				current_href = null;
			}
		}
	}
}

$(window).unload( function () { 
	saveSettings();
	window.__flash__removeCallback=function(instance, name) {
		if (!instance || typeof(instance)!='object') return;
		instance[name]=null;
	}

});
function fill_homecontent( type, id ) {
	$('#home_mid #home_content')[type=='list'?'show':'hide']();
	$('#home_mid #steffie')[type=='list'?'hide':'show']();
	$('.block_home .block_content').removeClass('selected');
	$('#block_content'+id).addClass('selected');
	if ( type=='list' ) {
		$('#home_mid #home_content')
			.html($('#block_content'+id+' .text').html()||'')
			.append($('<div class="pijltje"/>'))
			.append($('<ul class="elements"/>'));
		$('#home_mid #home_content .elements').html($('#block_content'+id+' .block_elements').html());
		var pos = $('#block_content'+id).position();
		$('#home_mid #home_content .pijltje').css('top',21+pos.top);
		$('#home_mid #home_content .elements').css('top',Math.min(pos.top,$('#home_mid #home_content').outerHeight() - $('#home_mid #home_content .elements').outerHeight()));
		$('#home_mid #home_content *[data-rgd-cel]').each(show_edit_link);
	} else if (type=='steffie') {
		var conf = $('#block_content'+id+' .block_elements').html();
		if ($('#home_mid #steffie')[0].load_movie) {
			$('#home_mid #steffie')[0].load_movie(conf);
		} else {
			$.ajax( {
				url: '/steffie_parameters/module_'+conf.match(/\?conf=\/modules\/(.*)\/config\.xml/)[1]+'/only_content',
				success: function(data) { $('#no_flash').html(data); }
			});
		}
	}
}
function setRows( sel, cnt ) {
	// geef iedere 0e een clear om rijen te krijgen
	$(sel).each(function(i) { 
		if ( (i % cnt)==0 ) {
			$(this).before('<div style="clear:left"></div>').css({'margin-left':'0'});
			$(this).addClass('marge');
		}
	});
	$(sel).parent().append('<div style="clear:left"></div>');
}

function changeFontSize(i) {
	$('#fontsize-menu span#size'+prefs.currentFontsize).removeClass('selected');
	$('body').removeClass('fontsize'+prefs.currentFontsize);
	if ( i!=null ) prefs.currentFontsize = i;
	else prefs.currentFontsize = 1 + prefs.currentFontsize % sizecount;
	$('#fontsize-menu span#size'+prefs.currentFontsize).addClass('selected');
	$('body').addClass('fontsize'+prefs.currentFontsize);
}

function play_mouseover( str, delay ) {
	if (steffie_playing) return;
	if (mo_timeout) {
		clearTimeout(mo_timeout);
		mo_timeout = null;
	};
	if (delay) {
		mo_timeout = setTimeout("play_mouseover('"+str+"');", delay);
		return;
	}
	if ( str && play_mouseover_current_str!=str) {
		play_mouseover_current_str = str;
		$('#audio_player')[0].selectUrl('/blobs/mo-audio/'+encodeURIComponent(str.replace(/[^\w.]/g,'_'))+'.mp3');
	}
	return false;
}
function stop_mouseover() {
	if (mo_timeout) {
		clearTimeout(mo_timeout);
		mo_timeout = null;
	}; 
	if ( play_mouseover_current_str ) {
		$('#audio_player')[0].stop_play();
		play_mouseover_current_str = '';
	}
}
function toggleAudioButtons( state ) {
	// if readspeaker is playing, stop it
	if ( current_id )	{
		rs.closepage(current_id);
		current_id = null;
		current_href = null;
	}
	// if steffie is playing, stop
	if ( steffie_playing && $('#steffie').length ) {
		$('#steffie')[0].stop_play();
	}

	if ( state==null ) {
		prefs.audio_active = $('body').hasClass('audio_off');
	} else {
		prefs.audio_active = state;
	}
	$('body')[ prefs.audio_active ? 'removeClass' : 'addClass' ]('audio_off');
	
	return false;
}
function toggleReader(href, id) {
	// if steffie is playing, stop
	if ( steffie_playing && $('#steffie').length ) {
		$('#steffie')[0].stop_play();
	}
	if ( current_id )	{
		rs.closepage(current_id);
	}
	if ( href!=current_href ) {
		var purl = href;
		if ( typeof(survey_result_id)!='undefined' && survey_result_id ) {
			purl += (purl.indexOf('%3F')>-1 ? '%26' : '%3F') + 'surveyplus_result_id='+survey_result_id;
		}
		readpage( purl, id );
		current_id = id;
		current_href = href;
	} else {
		current_id = null;
		current_href = null;
	}
	return false;
}
function set_flash_playing(state) {
	steffie_playing = state;
}
function get_help() {
	if ( $('#home_mid #steffie').length ) {
		fill_homecontent('steffie',2);
	} else {	
		$('#steffie_help,#steffie_help_overlay').show();
		setTimeout("get_help_after();",500);
	}
}
function get_help_after() {
	if ($('#steffie_help #steffie')[0].dobutton) {
		$('#steffie_help #steffie')[0].dobutton('repeat');
	} else {
		$('#steffie_help,#steffie_help_overlay').click(function() {
			closeHelp();
			$('#steffie_help,#steffie_help_overlay').unbind('click');
		});
	}
}
function closeHelp() {
	$('#steffie_help,#steffie_help_overlay').hide();
}
// prefs saven/loaden
function createCookie(name,value,days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*3600000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function setUserOptions() {
	var data = readCookie("prefs");
	if ( data ) data = JSON.parse( data );	
	if ( data ) prefs = $.extend( prefs,data );
	changeFontSize( prefs.currentFontsize );
	toggleAudioButtons( prefs.audio_active );	
}
function saveSettings() {
	createCookie("prefs", JSON.stringify( prefs ), 365);
}
function show_edit_link(){
	var x = $(this).attr("data-rgd-cel").split(':');
	var qtip_class = (x.length > 2) ? x[2] : "qtip_"+x[0];
	if ($(this).attr("data-rgd-qtipclass")) {
		qtip_class = $(this).attr("data-rgd-qtipclass");
	}
	$(this).qtip({
		content: {
			text: "<a target='cel' href='/admin/"+x[0]+'/'+x[1]+"';\"><img src=\"/_rxextlib/jquery/plugins/qtip/images/edit.jpg\" title=\"Klik om dit item te wijzigen in het CMS\"/></a>"
		}
		,position: {
			my: "top left"
			,at: "top right"
		}
		,hide: {
			fixed: true
			,delay: 2000
		}
		,show : {
			solo: true
		}
		,style: {
			tip: false
			,classes : "ui-tooltip-rxedit " + qtip_class
		}
		,events: {
			show: function(event, api) {
				var elm = event.originalEvent.currentTarget;
				$(".qtip_border").removeClass("qtip_border");
				if (!$(this).hasClass("qtip_inblock")) {
					$(".qtip_borderblock").removeClass("qtip_borderblock");
					$(elm).addClass("qtip_borderblock");
				} else {
					$(elm).addClass("qtip_border");
				}
			}
			,hide: function(event,api) {
				var elm = event.originalEvent.currentTarget;
			}
		}
	});
};

