//tinysort By: http://tinysort.sjeiti.com/
(function(b){b.tinysort={id:"TinySort",version:"1.0.4",defaults:{order:"asc",attr:"",place:"start",returns:false}};b.fn.extend({tinysort:function(h,j){if(h&&typeof(h)!="string"){j=h;h=null}var e=b.extend({},b.tinysort.defaults,j);var p={};this.each(function(t){var v=(!h||h=="")?b(this):b(this).find(h);var u=e.order=="rand"?""+Math.random():(e.attr==""?v.text():v.attr(e.attr));var s=b(this).parent();if(!p[s]){p[s]={s:[],n:[]}}if(v.length>0){p[s].s.push({s:u,e:b(this),n:t})}else{p[s].n.push({e:b(this),n:t})}});for(var g in p){var d=p[g];d.s.sort(function k(t,s){var i=t.s.toLowerCase?t.s.toLowerCase():t.s;var u=s.s.toLowerCase?s.s.toLowerCase():s.s;if(c(t.s)&&c(s.s)){i=parseFloat(t.s);u=parseFloat(s.s)}return(e.order=="asc"?1:-1)*(i<u?-1:(i>u?1:0))})}var m=[];for(var g in p){var d=p[g];var n=[];var f=b(this).length;switch(e.place){case"first":b.each(d.s,function(s,t){f=Math.min(f,t.n)});break;case"org":b.each(d.s,function(s,t){n.push(t.n)});break;case"end":f=d.n.length;break;default:f=0}var q=[0,0];for(var l=0;l<b(this).length;l++){var o=l>=f&&l<f+d.s.length;if(a(n,l)){o=true}var r=(o?d.s:d.n)[q[o?0:1]].e;r.parent().append(r);if(o||!e.returns){m.push(r.get(0))}q[o?0:1]++}}return this.pushStack(m)}});function c(e){var d=/^\s*?[\+-]?(\d*\.?\d*?)\s*?$/.exec(e);return d&&d.length>0?d[1]:false}function a(e,f){var d=false;b.each(e,function(h,g){if(!d){d=g==f}});return d}b.fn.TinySort=b.fn.Tinysort=b.fn.tsort=b.fn.tinysort})(jQuery);


(function( $ ){
	$.fn.popper = function(o){
		o = $.extend({
			content:false,
			form:false,
			//^- not used in dialog
			modal:true,
			closeOnEsc:true,
			width:'450px',	
			open:function(e,ui){
				//setup the background to close our dialog onclick
				$('.ui-widget-overlay').click(function(){
					$(o.content).dialog('close');									  
				});	  
			}
		},o);
		
		if(o.content){
			$(o.content).dialog(o);	
			return this;
		}
		else{
			$('body').append('<div id="'+this.attr('id')+'Popper" class="popper"></div>');	
			o.content = '#'+this.attr('id')+'Popper';
		}
						
		if(o.form){
			$(o.content).formify({
				formName:$(this).attr('id')+'Form',
				form:o.form,	
			});
		}

		$(o.content).dialog(o);
							
		return this;
	};
	$.fn.formify = function(o){
		o = $.extend({
			formName:$(this).attr('id')+'Form',
			form:false,
		},o);
		
		var formHTML = '';
		
		$.each(o.form,function(section,elements){
			formHTML += '<div class="section"><h2>'+section+'</h2>';
		
			if(elements.hint)
				formHTML += '<span class="hint">'+elements.hint+'</span>';
			
			
		
			$.each(elements,function(element,data){
				if(element == 'hint') return;
				
				if(!data.value) 
					data.value = '';
				
				if(data.type == 'text')
					formHTML += '<div class="element"><label for="'+data.name+'" class="leftLabel">'+element+'</label><input id="'+o.formName+data.name+'" name="'+data.name+'" value="'+data.value+'"></div>';
				else if(data.type == 'longtext')
					formHTML += '<div class="element"><label for="'+data.name+'" class="leftLabel">'+element+'</label><textarea id="'+o.formName+data.name+'" name="'+data.name+'">'+data.value+'</textarea></div>';
				else if(data.type == 'checks'){
					class = data;
					
					formHTML += '<div class="element">';
					
					$.each(data.values,function(chTitle,chData){
						checkboxClass = chData.checked?'checked':'unchecked';
						
						formHTML += '<label class="'+checkboxClass+'">'+chTitle+'<input id="'+o.formName+data.name+'" type="checkbox" name="'+data.name+'[]" value="'+chData.value+'" '+(chData.checked?'checked':'')+'></label>';
					});
					
					formHTML += '</div>';	
				}
				else if(data.type == 'date'){
					formHTML += '<div class="date"><label>'+element+'</label><input class="datepicker" id="'+o.formName+data.name+'" name="'+data.name+'" value="'+data.value+'"></div>';	
				}
				else if(data.type == 'html'){
					formHTML += '<div class="html"><label>'+element+'</label><textarea class="htmlEditor" name="'+data.name+'" id="'+o.formName+data.name+'"></textarea></div>';
				}
			});
			
			formHTML += '</div>';
		});
		
		$(this).html('<form id="'+o.formName+'" name="'+o.formName+'" class="popper">'+formHTML+'</form>');
		$('.datepicker').datepicker({ changeMonth: true, changeYear:true});
		$('.htmlEditor').each(function(){
			window['cke'+$(this).attr('id')] = CKEDITOR.replace($(this).attr('id'),{filebrowserBrowseUrl: '/filemanager/index.html',height:400}); 
		});
		
		return this;
	};

	// wrapper to use the bacon.php handler
	$.bacon = function(o){
		o = $.extend({
			data:false,
			success:function(result){
				alert(result);	
			},
			error:function(result){
				err0r(result.error);
			}
		},o);
		
		if(!o.data)
			err0r('Nothing to be sent!');	

		$.ajax({
			type: "POST",
			url: "/bacon.php",
			dataType:'json',
			data:o.data,
			success: function(result){
				if(result.status == 'success'){
					o.success(result);
				}else{
					o.error(result);	
				}
			}
		});
	};
})( jQuery );

//wrapper, but will be used later
var err0r = function(str){
	if(!str) str = 'An unspecified error occured, sorry :|';
	alert(str);
}

//onload stuff
$(function(){	
//setup search stuff
	$('#search_input_display').focus(function(){
		$(this).hide();
		$('#search_input_real').show();
		$('#search_input_real').focus();
	});
	$('#search_input_real').blur(function(){
		if($(this).val() == ''){
			$(this).hide();
			$('#search_input_display').show();
		}
	});
	
	//$("select, input:checkbox, input:radio, input:file").uniform();
	$('.top_menu_link').each(function(){		
		if($(this).attr('href') != '/' && window.location.href.indexOf($(this).attr('href')) != -1)
			$(this).addClass('top_menu_link_down');	
	});
	
//form controls
	$('.unchecked input[type=checkbox],.checked input[type=checkbox]').live('change',function(){
		var l = $(this).parent();
		
		if(l.hasClass('unchecked'))
			l.addClass('checked').removeClass('unchecked');
		else
			l.addClass('unchecked').removeClass('checked');
	});
	$('.radioUnchecked input[type=radio],.radioChecked input[type=radio]').live('change',function(){
		$('input[name='+$(this).attr('name')+']').parent().each(function(){
			$(this).removeClass('radioChecked').addClass('radioUnchecked');		
		});
		$(this).parent().addClass('radioChecked');
	});

//setup buttons
	$('.butter').each(function(){
		$(this).html('<span>'+$(this).text()+'</span>');	
	});

//enable sorters
	$('.sorter').click(function(){	
		var sortOrder = $(this).attr('data-sort-order'); 
	
		$($(this).attr('data-sort')).tsort({
			attr:$(this).attr('data-sort-by'),
			order:sortOrder
		});
		
		if(sortOrder == 'asc')
			$(this).attr('data-sort-order','desc');
		else if(sortOrder == 'desc'){
			$(this).attr('data-sort-order','asc');
		}
		
		return false;
	});

//enable voters
/* example
<div class="voter" data-vote-type="'.$vote_type.'" data-vote-id="'.$vote_id.'">
	<a href="#" class="vote_up'.($user_voted==1?' active':'').'"></a>
	<div class="current_rating">'.$score.'</div>
	<a href="#" class="vote_down'.($user_voted==0?' active':'').'"></a>
</div>*/
            
    $('.voter a').click(function(){
		if($(this).hasClass('active')){
			//unvoting
			$(this).removeClass('active').html($(this).html()-1);
			var VoterCurrentScore = $(this).parent().find('.current_rating');
			
			if($(this).hasClass('vote_up')) VoterCurrentScore.html(VoterCurrentScore.html()-1);
			else VoterCurrentScore.html(VoterCurrentScore.html()-0+1);
			
			$.bacon({
				data:'s=voting&o=unvote&vote_type='+$(this).parent().attr('data-vote-type')+'&vote_id='+$(this).parent().attr('data-vote-id'),
				success:function(result){
					//nothing really to do, but we'll keep it anyway :)
				}
			});
			return;
		}
	
		$(this).addClass('active').html($(this).html()-0+1);
	
		var voting = 0;
		if($(this).hasClass('vote_up')) voting = 1;
		
		var Voter = $(this).parent();
		var VoterCurrentScore = Voter.find('.current_rating');

		if(voting){
			var otherVoter = Voter.find('.vote_down');
			if(otherVoter.hasClass('active')){
				otherVoter.removeClass('active').html(otherVoter.html()-1);	
				VoterCurrentScore.html(VoterCurrentScore.html()-0+2);
			}
			else{
				VoterCurrentScore.html(VoterCurrentScore.html()-0+1);	
			}
		}else{
			var otherVoter = Voter.find('.vote_up');
			if(otherVoter.hasClass('active')){
				otherVoter.removeClass('active').html(otherVoter.html()-1);	
				VoterCurrentScore.html(VoterCurrentScore.html()-2);
			}
			else{
				VoterCurrentScore.html(VoterCurrentScore.html()-1);	
			}
		}
		
		$.bacon({
			data:'s=voting&o=vote&vote_type='+$(this).parent().attr('data-vote-type')+'&vote_id='+$(this).parent().attr('data-vote-id')+'&voting='+voting,
			success:function(result){			
				//nothing to do
			}
		});
	});

	//CKEDITOR
	/* default
config.toolbar_Full =
[
    ['Source','-','Save','NewPage','Preview','-','Templates'],
    ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
    ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
    '/',
    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
    ['BidiLtr', 'BidiRtl' ],
    ['Link','Unlink','Anchor'],
    ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
    '/',
    ['Styles','Format','Font','FontSize'],
    ['TextColor','BGColor'],
    ['Maximize', 'ShowBlocks','-','About']
];
*/
//configuration
	CKEDITOR.config.toolbar_Full =[
		['Source','-','NewPage','Preview','-'],
		['Cut','Copy','Paste','PasteText','-','Print', 'SpellChecker', 'Scayt'],
		['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
		'/',
		['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
		['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
		['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
		['BidiLtr', 'BidiRtl' ],
		['Link','Unlink','Anchor'],
		['Image','Flash','Table','HorizontalRule','SpecialChar','PageBreak'],
		'/',
		['Styles','Format','Font','FontSize'],
		['TextColor','BGColor'],
		['Maximize', 'ShowBlocks']
	];
/*
    $('.editButton').click(function(){
		var myId = $(this).attr('data-edit-target');
		var pageId = $(this).attr('data-page-id');
		var handler = $(this).attr('data-handler');
		
		if(!window[myId+'editor']){
			window[myId+'editor'] = CKEDITOR.replace(myId);
			$(this).html('Save Changes');
		}else{	
			var newData = window[myId+'editor'].getData();
			
			$.post("/y_testy.php",
				{reference:$(this).attr('data-editref'),data: newData},
				function(data){
					if(data.status == 'success'){

					}
					else
						alert('an error occured!');
				},'json'
			);
			window[myId+'editor'].destroy();
			window[myId+'editor'] = null;
			
			$('#'+myId).show();
			$(this).html('Edit');
		}
		return false;
	});*/

	//menu stuff
	$(document).click(function(){	
		$('.menuopen').removeClass('menuopen');
	})
	//konamic
	.keydown(function(event){
		var code = window.konamic;
		if(!code) code = [];
		else if(code.length == 10) code = code.slice(1,10);
		code[code.length] = event.keyCode;
		window.konamic = code;

		if(code.join('') == '38384040373937396665'){
			$(document).unbind('keydown');
			$('body').append('<script src="/templates/bamboo/includes/asteroids.4.js"></script>');
		}
	});
});



