jQuery.fn.fadeToggle = function(speed, easing, callback) { 
    return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};

var tablesorterPropertis = '';

$(document).ready(function() {
	$('#right .links a.fade').click(function() {
		if ($('#registerForm').is(':visible')) {
			box1 = '#registerForm';
			box2 = '#loginForm';
		} else {
			box2 = '#registerForm';
			box1 = '#loginForm';
		}
		$(box1).fadeToggle('normal', null, function() {
			$(box2).fadeToggle();
		});
		return false;
	});
	
	$('form.testForm input[type=checkbox]').live('click', function() {
		$('form.testForm input[type=checkbox]').not(this).attr('checked', false);
//		$(this).attr('checked', true);
		return true;
	});
	
    $("table.sortable").tablesorter(tablesorterPropertis); 
});

var time2 = 0;
function timer2(time) {
	time2 = time;
	_timer2();
}
function _timer2() {
	time = time2;
	seconds = time % 60;
	if (seconds < 10)
		seconds = '0' + seconds;
	minutes = (time-seconds) / 60;
	time = minutes;
	minutes = time % 60;
	hours = (time-minutes) / 60;
	time2 -= 1;
	if (hours > 0)
		$('#timer2 strong').html(hours + ':' + minutes + ':' + seconds);
	else
		$('#timer2 strong').html(minutes + ':' + seconds);
	if (time2 < 0) {
		$(location).attr('href', '/test/zakoncz');
	}
	setTimeout('_timer2()', 1000);
}


function getAJAX(element, div_id) {
	$.ajax({
		type: "POST",
		url: $(element).attr('href'),
		data: "ajax=true",
		async: false,
		success: function(msg) {
			$('#' + div_id).html(msg);
		}
	});
	return false;	
}

$(document).ready(function() {
	$('.thikbox_body .paging a').live('click', function() {
		$('.task').fadeOut(300);
		
		getAJAX($(this), 'thikbx');
		$('.task').hide();
		$('.task').fadeIn(300);
		return false;
	});

	
});

$(document).ready(function() {
	$(':button').live('click', function() {
		$(':button').not($(this)).attr('disabled', 'disabled');
		return true;
	});
});

if ($.browser.msie && parseInt($.browser.version, 10) < 8) {
	$(document).ready(function() {
		$('button').each(function () {
			$(this).click(function() {
				$(this).closest('form').submit();
			});
		});
		
	});
}
$.fn.preventSecondSubmit = function(e) {
	this.submit(function() {
		$(this).find(':button').hide();
		return true;
	});
	return this;
}
$.fn.ajaxSubmit = function(e) {
	this.submit(function() {
		if ($('button').filter(":enabled").size() == 1 && $('button').filter(":enabled").first().val() == 'finish') {
			if (!confirm("Czy chcesz zakończyć rozwiązywanie tego testu?\n Tej operacji nie można cofnąć")) {
				$(':button').attr('disabled', '');
				return false;
			}
		}
		
		$("#tasksbar").hide();
		$(":button").hide();
		
		$('.task').fadeOut(300, function() {
			$('.task').html('<div class="c" style="padding: 50px 0 0"><img src="/img/ajax-loader.gif" alt="" /></div>');
			$('.task').show();
		});
			
		var params = {};
		params['ajax'] = true;
		$(this).find('input[type="hidden"]').each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});

		$(this).find('input[type="text"], button').filter(":enabled").each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});
		
		
		$(this).find('input[type="checkbox"]').filter(":enabled").each(function() {
			if ($(this).attr('checked') === true) {
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
			}
		});
		
		$(this).find('textarea').filter(":enabled").each(function() {
			if(tinyMCE.get(this.id) != undefined) { 
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = tinyMCE.get(this.id).getContent();
			}
			else {
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
			}
		});
		//		var dum = '';
		//		for (var item in params) {
		//			dum += item + ': ' + params[item] + "\n";
		//		}
		//alert(dum);
		

		$.post(this.getAttribute("action") + "?call=ajax", params, function(data) {
			$('.task').hide();
			$('#thikbx').html(data);
			$('.task').fadeIn(500);
		});
		return false;
	});
	
	return this;
}

$(document).ready(function() {
	$('.thikbox_finish a').live('click', function() {
		if ($(this).html() == 'Zamknij' || $(this).html() == 'powrót' || confirm("Czy chcesz zakończyć rozwiązywanie tego testu?\n Tej operacji nie można cofnąć")) {
			$('.thikbox_bx').fadeOut(500, function() { return true; });
			setTimeout('window.location.replace("' + $(this).attr('href') + '");', 600);
		}
		return false;
	});
});
function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();

        //in effect we are creating a text range with zero
        //length at the cursor location and replacing it
        //with myValue
        sel = document.selection.createRange();
        sel.text = myValue;

    //Mozilla/Firefox/Netscape 7+ support
    } else if (myField.selectionStart || myField.selectionStart == '0') {

        myField.focus();
        //Here we get the start and end points of the
        //selection. Then we create substrings up to the
        //start of the selection and from the end point
        //of the selection to the end of the field value.
        //Then we concatenate the first substring, myValue,
        //and the second substring to get the new value.
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
        myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
    } else {
        myField.value += myValue;
    }
}
function insertChar(chr, area) {
	var tarea = null;
	if (area == 'null'){
		tarea = $('textarea.insertable:first');
	} else {
		tarea = $('#'+area);
	}
	
	if (typeof tarea.tinymce == 'function' && tarea.tinymce() != undefined) { // Edytor to instancja tinymce
		tarea.tinymce().execCommand('mceInsertContent', false, chr);
	} else { // Edytor to zwyczajny textarea
		tarea = tarea.get(0);
		insertAtCursor(tarea, chr);
	}
	return false;
}

var symbolBars = new Array(
   new Array( "mathSymbols"      , "<=>≤≥≈≠≡√∛²³±÷×·∞αβγδµπωΔчФφ∀∃∈∉∋∌∢∧∨⇒⇐⇔∫∑"), //0
   new Array( "mathSubscripts"   , "₁₂₃₄₅₆₇₈₉₀₊₋"), //1
   new Array( "mathSuperscripts" , "¹²³⁴⁵⁶⁷⁸⁹⁰⁺⁻°"), //2
   new Array( "mathFractions"    , "¼½¾⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞"), //3
   new Array( "cyryllicCapital"  , "АБВГДЕЖЗЁИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"), //4
   new Array( "cyryllicSmall"    , "абвгдежзёийклмнопрстуфхцчшщъыьэюя"), //5
   new Array( "greekCapital"     , "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"), //6
   new Array( "greekSmall"       , "αβγδεζηθικλμνξοπρςστυφχψω"), //7
   new Array( "frenchSmall"		 , "àâçéèêëîïôŕûùüÿœæ"), //8
   new Array( "frenchCapital"	 , "ÉČÁŔÂÎÔŰÇ"), //9
   new Array( "spainSmall"		 , "áéíúñü¿¡"), //10
   new Array( "italySmall"       , "éèàìíîòùú"), //11
   new Array( "deutschSmall"     , "äöüß"), //12
   new Array( "deutschCapital"   , "ÄÖÜ€"), //13
   new Array( "other"            , "ÄÖÜßäöü€£¥¢ƒ®•™") //14
);

var sbHeaders = {
	"mathSymbols"	   : "Matematyczne",
	"mathSubscripts"   : "Indeks dolny",    
	"mathSuperscripts" : "'Indeks górny",      
	"mathFractions"    : "Ułamki",       
	"cyryllicCapital"  : "Cyrylica - duże litery",      
	"cyryllicSmall"    : "Cyrillic - małe litery",         
	"greekCapital"     : "Greckie - duże litery",   
	"greekSmall"       : "Greckie - małe litery",
	"frenchSmall"      : "Francuskie - małe litery",
	"frenchCapital"    : "Francuskie - duże litery",
	"deutschSmall"     : "Niemieckie - małe litery",
	"deutschCapital"   : "Niemieckie - duże litery",
	"spainSmall"       : "Hiszpańskie - małe litery",
	"spainCapital"     : "Hiszpańskie - duże litery",
	"italySmall"       : "Włoskie - małe litery",
	"italyCapital"     : "Włoskie - duże litery",       
	"other"            : "inne",      
	"frac"			   : "indeksy i ulamki"
}

function showLangs(event, element) {
	event.preventDefault();
	$(element).parent().parent().next().toggle();
}

function showBar(bars, area, symbolBarId) {
    var i;
    for (i = 0; i < bars.length; i++) {
        var barIndex = bars[i];
	    var barId = symbolBars[barIndex][0];
	    var barName = sbHeaders[barId];
	    var chars = symbolBars[barIndex][1];
	    var domId = "symbols-" + barId;
	    if (area != undefined && area != null){
	    	domId += area;
	    }
	    if (document.getElementById(domId) == null) {
	        var barDiv = $("#"+symbolBarId);
	        barDiv.show();
	        var appender = "<div id='" + domId + "' style='display:none;' class='symbolBar'><div class='name text'>" + barName + ":</div><div class='chars text'>";
	        var j;
	        for (j = 0; j < chars.length; j++) {
	            var chr = chars.charAt(j);
	            var clearer = '';
	            if (chr == 'Δ' && barIndex == 0) { // opera fix
	            	clearer = 'clear:left;'
	            }
	            appender += "<a href='#' style='float:left;" + clearer + "' onclick=\"return insertChar('" + chr + "', '"+area+"');\">" + chr + "</a>";
	            //alert(chars.charAt(j));
	        }
	        if (barIndex == 0) {
	        	areaText = 'null';
	        	if(alert != null){
	        		areaText = '\''+area+'\'';
	        	}
               appender += "<a href='#' style='width:auto;font-size:12px;padding:0 5px 0 5px;' onclick=\"return showBar(new Array(1, 2, 3),"+areaText+",'"+symbolBarId+"');\">" +  sbHeaders['frac'] + "</a>";
            }
	        appender += "<div class='cleaner'></div></div></div>";
	        barDiv.append(appender);
	    }
	    $("#" + domId).slideToggle();
    }
    return false;
}


