var sbHeaders = {
	'pl': {
		'mathSymbols'	   : "Symbole matematyczne",
		"mathSubscripts"   : "Indeksy dolne",    
	    "mathSuperscripts" : "Indeksy górne",      
		"mathFractions"    : "Częste ułamki",       
		"cyryllicCapital"  : "Cyrylica wielka",      
		"cyryllicSmall"    : "Cyrylica mała",         
		"greekCapital"     : "Greka wielka",   
		"greekSmall"       : "Greka mała",         
		"other"            : "Inne",      
		"frac"			   : "indeksy i ułamki",
	},
	'en': {
		'mathSymbols'	   : "Math symbols",
		"mathSubscripts"   : "Subscripts",    
	    "mathSuperscripts" : "Superscripts",      
		"mathFractions"    : "Fractions",       
		"cyryllicCapital"  : "Cyryllic capital",      
		"cyryllicSmall"    : "Cyrylic small",         
		"greekCapital"     : "Greek capital",   
		"greekSmall"       : "Greek small",         
		"other"            : "Others",   
		"frac"			   : "fractions & sub/superscripts",
	},
};
var trans = {
	'pl' : {
		'attachmentDeletion': "Na pewno chcesz usunąć załącznik?",
	},
	'en' : {
		'attachmentDeletion': "Are you sure you want to delete that attachment?",
	},
};

var symbolBars = new Array(
   new Array( "mathSymbols"      , "<=>≤≥≈≠≡√∛²³±÷×∞αβγδµπωΔчФ←→∀∃∈∉∋∌∢∧∨∫∑∞"),
   new Array( "mathSubscripts"   , "₁₂₃₄₅₆₇₈₉₀₊₋"),
   new Array( "mathSuperscripts" , "¹²³⁴⁵⁶⁷⁸⁹⁰⁺⁻°"),
   new Array( "mathFractions"    , "¼½¾⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞"),
   new Array( "cyryllicCapital"  , "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"),
   new Array( "cyryllicSmall"    , "абвгдежзийклмнопрстуфхцчшщъыьэюя"),
   new Array( "greekCapital"     , "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"),
   new Array( "greekSmall"       , "αβγδεζηθικλμνξοπρςστυφχψω"),
   new Array( "other"            , "ÄÖÜßäöü€£¥¢ƒ®•™")
);

var webEditor = null;

var activeStar = '/img/star-active.gif';
var inActiveStar = '/img/star-inactive.gif';
var halfStar = '/img/star-inactive.gif';

function insertChar(chr) {
	if(webEditor==null){	
		var tarea = null;
		tarea = $('textarea.insertable:first').get(0);
		insertAtCursor(tarea, chr);
		return false;
	}
	else{
		var data = webEditor.getData();
		data+=chr;
		webEditor.setData(data);
		return false;
	}
	
}
/**
 * 
 * @param bars
 * @param area id obaszaru w ktorym zaczac szukać pola textarea jesli nie ustawione to szuka globalnie
 * @return
 */
function showBar(bars, area) {
    var i;
    for (i = 0; i < bars.length; i++) {
        var barIndex = bars[i];
	    var barId = symbolBars[barIndex][0];
	    var barName = sbHeaders[siteLocale][barId];
	    var chars = symbolBars[barIndex][1];
	    var domId = "symbols-" + barId;
	    if (document.getElementById(domId) == null) {
	        var barDiv = $("#symbolBars");
	        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);
	            appender += "<a href='#' onclick=\"return insertChar('" + chr + "', '"+area+"');\">" + chr + "</a>";
	            //alert(chars.charAt(j));
	        }
	        if (barIndex == 0) {
               appender += "<a href='#' onclick=\"return showBar(new Array(1, 2, 3));\">" +  sbHeaders[siteLocale]['frac'] + "</a>";
            }
	        appender += "</div></div>";
	        barDiv.append(appender);
	    }
	    $("#" + domId).slideToggle();
    }
    return false;
}
function linkAttDels() {
    
	$("div.thumbnail").each(function(index) {
        var thumb = this;
        var elem_id = this.id.split(".");
        var att_id = elem_id[1];
       
        $(thumb).find("div.delLink a").click(function(e) {
            if (confirm(trans[siteLocale]['attachmentDeletion'])) {
                $("div.thumbnail div.delLink a").fadeOut("slow");
                $.getJSON("/attachments/delete/" + att_id, undefined, function(deleted) {
                    if (deleted) {  
                        $(thumb).slideUp("slow");
                        $("div.thumbnail div.delLink a").fadeIn("slow");
                    }
                });
            }
            return false;
        });
	});
}
$(function() {
    $("#UserUsername").bind('focus', function(e) {
        if ($("#UserUsername").val() == "Nick lub email") {
            $("#UserUsername").val('');
        }
    });
    $("#UserPassword").bind('focus', function(e) {
        if ($("#UserPassword").val() == "ala123") {
            $("#UserPassword").val('');
        }
    });
     $("#flashMessage.success, .flashMessage.success").css({backgroundColor: "#E2F1A8"}).
        animate({ backgroundColor: "#BEDF5D" }, 1000).
        animate({ backgroundColor: "#E2F1A8" }, 1000).
        animate({ backgroundColor: "#BEDF5D" }, 1000).
        animate({ backgroundColor: "#E2F1A8" }, 1000);
    $("#flashMessage.failure, .flashMessage.failure").css({backgroundColor: "#F97D88"}).
        animate({ backgroundColor: "#ff2f3a" }, 1000).
        animate({ backgroundColor: "#F97D88" }, 1000).
        animate({ backgroundColor: "#ff2f3a" }, 1000).
        animate({ backgroundColor: "#F97D88" }, 1000);
    $("#flashMessage.info, .flashMessage.info").css({backgroundColor: "#7CB4FA"}).
        animate({ backgroundColor: "#ace1ff" }, 1000).
        animate({ backgroundColor: "#7CB4FA" }, 1000).
        animate({ backgroundColor: "#ace1ff" }, 1000).
        animate({ backgroundColor: "#7CB4FA" }, 1000);
    linkAttDels();
    var i;
});
function uploadifyCompleted(event, queueID, fileObj, response, data) {
    alert(response);
}

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 

/* loader ajaxa */
function ajaxInject(domId, url) {
    $("#" + domId + " div.loader").html('<div style="width:100%;text-align:center;"><img src="/img/loadingAnimation.gif" /></div>');
    $("#" + domId + " div.loader, " + "#" + domId).slideDown(500);
    $.get(url, null, function (data, textStatus) {
        $("#" + domId + " div.trueContent").html(data);
        $("#" + domId + " div.loader").slideUp(500);
        $("#" + domId + " div.trueContent").slideDown(500);
    });
    
}
function ajaxRawInject(domId, url) { // without loaders
    $.get(url, null, function (data, textStatus) {
        $("#" + domId).html(data);
        doCufon();
    });
}
function ajaxLoader(domId) {    
    //$("#" + domId + " div.loader").html('<div style="width:100%;text-align:center;"><img src="/img/loadingAnimation.gif" /></div>');
    $("#" + domId + " div.loader, " + "#" + domId).slideDown(500);
    $("#" + domId + " div.trueContent").slideUp(500);
}
function ajaxContent(domId) { 
    //$("#" + domId + " div.loader").html('<div style="width:100%;text-align:center;"><img src="/img/loadingAnimation.gif" /></div>');
    $("#" + domId + " div.loader").slideUp(500);
    $("#" + domId + " div.trueContent").slideDown(500);
}
function ajaxCleanup(domId) {
//alert('cleansing')
//    alert(domId)
    $("#" + domId).fadeOut(500);
    $("#" + domId + " div.trueContent").fadeOut(500);
    setTimeout('$("#' + domId + ' div.trueContent").empty();', 500);
}


/**
	cytowanie wypowiedzi innych ludzi
	@param sourceID object - id elementu który jest źródłem tekstu do skopiowania
	@param authorNick string - nick autora tekstu
	@param destID object - id obiektu textarea do ktorego wstawić tekst (tinyMCE)
 */
function quoteSmb(sourceID, authorNick, destID){
	source = $("#"+sourceID);
	content = source.find(".content span.bbcode").html();
	old = $("#"+destID).tinymce().getBody().innerHTML;	
	$("#"+destID).tinymce().execCommand("mceSetContent", false, old+"<blockquote><strong>"+authorNick+"</strong><br/>"+content+"</blockquote>\n\n  &nbsp;");
	//$("#"+destID).tinymce().execCommand("mceSetContent", false, old+"[quote][b]"+authorNick+"[/b]\n"+content+"[/quote]\n\n  &nbsp;");	
	//$("#"+destID).tinymce().execCommand("mceStartTyping", false); 
}
/**
 * dodanie youtube embed linku do tinyMCE na forum
 * @param destID - id obiektu textarea do ktorego wstawic tekst (tinyMCE)
 * @param sourceID - id obiektu textarea do ktorego wstawic tekst (tinyMCE)
 */
function addYouTubeVideo(sourceID, destID) {
	url = $("#"+sourceID).val();
	regex = /http\:\/\/www\.youtube\.com\/watch\?v=(\w{11})/;	
	id = url.match(regex);
	if(id == null) {
		alert('Link jest niepoprawny.');
		return false;
	}
	id = id[1];
	result = '<object width="320" height="265"><param name="movie" value="http://www.youtube.pl/v/'+ id +'" />'+
	'<param name="wmode" value="transparent" /><embed src="http://www.youtube.pl/v/'+ id +'" type="application/x-shockwave-flash" wmode="transparent" width="320" height="265" /></object>';
	old = $("#"+destID).tinymce().getBody().innerHTML;
	$("#"+destID).tinymce().execCommand("mceSetContent", false, old + '<br/>' + result);
	$("#"+sourceID).val('');
	alert('Pomyślnie dodano film. Zobaczysz go po wysłaniu postu.');
	return false;	 
}
/**
 * obsluga dynamicznego edytowania postów
 * @param string editID - id komórki tabeli, zawierajacej teresc postu i ukryty formularz
 */
function editPost(editID, url, userNick){
	body = "";
	id="";
	source = $("#"+editID);
	hiddenElem = source.find("div.editHidden");
	source.find("textarea").each(function(i) {
		tinyMCE.triggerSave();
		body=$(this).tinymce().getContent();		
	});
	source.find(":input[type=hidden]").each(function(i){
		if($(this).attr("name")!="_method")
			id=$(this).val();
	});
	
	params = [];
	params.push({name:'data[Post][content]', value:body});
	params.push({name:'data[Post][id]', value:id});
	$.post(url, params, function(data){
		if(data.success){
			//modyfikacja treści postu
			source.find(".content span").each(function(i){
				$(this).text('');
				$(this).append(data.body);
			});			
			updated = false
			source.find("span.editor span").each(function(i){
				$(this).text("Ciebie 1 sekundę temu");
				updated = true
			});
			if(!updated){//nie było wcześniej informacji o edycji
				source.find("span.editor").append("Ostatnio zmieniony przez: <span>Ciebie 1 sekundę temu</span>");
			}
			source.find("div.textarea").removeClass("error");
			source.find("div.error-message").remove();
			hiddenElem.hide(500);
		}
		else if(data.modelError){
			//hiddenElem.show(300);
			source.find("div.textarea").each(function(i){
				//alert(this);
				$(this).addClass("error");
				$(this).append("<div class='error-message'>"+data.msg+"</div>");
			});
		}
		else{
			alert(data.msg);
		}
		
	}, "json"
		
	);
}

function showEditBox(editBoxID){
	editBox = $("#"+editBoxID);
	title = $("span.threadTitle:first").text();	 
	editBox.find("input[type=text]").val(title);		
	editBox.show(500);
}
function editTitle(editBoxID, url, threadID){	
	title = "";
	editBox = $("#"+editBoxID); 
	title = editBox.find("input[type=text]").val();			
	params = [];
	params.push({name:'data[Thread][subject]', value:title});
	params.push({name:'data[Thread][id]', value:threadID});
	editBox.find("input[type=text]").attr("disabled", "disabled");
	$.post(url, params, function(data){
		editBox.find("input[type=text]").removeAttr("disabled");
		if(data.success){
			$("body	").find('span.threadTitle').text(title);			
			editBox.find("div.text").removeClass("error");
			editBox.find("div.error-message").remove();
			editBox.hide(500);
		}
		else if(data.modelError){
			editBox.find("div.text").each(function(i){				
				$(this).addClass("error");
				$(this).append("<div class='error-message'>"+data.msg+"</div>");
			});
		}
	}, "json");
}

function deleteComment(id, url){
	params = [];
	params.push({name:'data[ProfileComment][id]', value:id});
	$.post(url, params, function(data){
		$('#flashMessage').remove();
		if(data['success']){
			$('#mainRightPanel').prepend('<div id="flashMessage" class="success" style="background-color: #dbed9a">'+data['msg']+'</div>');
			$('#comment'+id).remove();
		}
		else{
			$('#mainRightPanel').prepend('<div id="flashMessage" class="failure" style="background-color: #dbed9a">'+data['msg']+'</div>');
		}
	}, "json");
}
function showStars(divID, fullStars, halfStars, emptyStars){
	$('#'+divID).find("img").each(function(i){
		if(i<fullStars)
			$(this).attr('src', activeStar);
		else if(i<fullStars+halfStars)
			$(this).attr('src', halfStar);
		else
			$(this).attr('src', inActiveStar);
	});
}
function turnOnStars(divID, starNr){
	//alert(divID);
	$('#'+divID).find("img").each(function(i){
		if(i<=starNr)
			$(this).attr('src', activeStar);
		else
			$(this).attr('src', inActiveStar);
	});
}
function vote(resp_id, vote, url){
	params = [];
	params.push({name:'data[Vote][response_id]', value:resp_id});
	params.push({name:'data[Vote][vote]', value:(vote+1)});
	$.post(url, params, function(data){
		
		voteID = '#vote'+resp_id;
		if(data.success){
			$(voteID).find("img").remove();
			$(voteID).prepend("Dziękujemy");
			mark = ''+data.mark;
			markN = data.mark;
			if(mark.length>4)
				markN = Math.round(markN*100)/100;
			$(voteID).find("div span").text(markN);
		}
		else{
			wrrID = "worn"+resp_id;
			$('#'+wrrID).remove();
			$(voteID).prepend("<div id="+wrrID+">"+data.msg+"</div>");
			//alert(data.msg);
		}
	}, "json");
}

function mainmenu(){
	$(" #nav ul ").css({display: "none"}); // Opera Fix
	$(" #nav li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(250);
		},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
		});
}
$(document).ready(function(){
	mainmenu();
});

function showStarsInForm(divID, fullStars, halfStars, emptyStars){
	$('#'+divID).find("input[type=image]").each(function(i){
		if(i<fullStars)
		  $(this).attr('src', activeStar);
		else if(i<fullStars+halfStars)
		  $(this).attr('src', halfStar);
		else
		  $(this).attr('src', inActiveStar);
	});
}
function turnOnStarsInForm(divID, starNr){
	//alert(divID);
	$('#'+divID).find("input[type=image]").each(function(i){
		if(i<=starNr)
		  $(this).attr('src', activeStar);
		else
		  $(this).attr('src', inActiveStar);
	});
}
