var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
function quote(postId, data)
{
	selection = window.getSelection();
	if( selection != "" ) {
		content = selection.toString().replace(/^\s+|\s+$/g, '');
	} else {
		content = $('#post' + postId).text().replace(/^\s+|\s+$/g, '');
	}
	
	$('#gtp_text').val( $('#gtp_text').val() + '[quote]' + data + "\n\n" + content + '[/quote]' + "\n\n");
	alert('Cytat został zapamiętany. Zjedź na dół strony');
}
function addFriend(friend) {
	$('#special_overlay_dane').html('Trwa wysyłanie danych.<br />Proszę czekać.');
    $('#special').show();
	$.get(basePath + '/friends/add_new/fn_friend_id/' + friend, function() {
		window.location = requestUri;
	}); 
}
$(document).ready(function() {
	$('#polecamy ol a').each(function(i, obj) {
		$(obj).click(function() {
			$('#polecamy div').hide();
			$('#polecamy ol a').each(function(j, obj2) {
				if(j == 0) {
					$(obj2).parent().removeClass('first-on');
					$(obj2).parent().addClass('first');
				} else {
					$(obj2).parent().removeClass('on');
				}
			});
			if(i == 0) {
				$(this).parent().addClass('first-on');
			} else {
				$(this).parent().addClass('on');
			}
			$('#polecamy div.polecamy-' + $(this).attr('_id')).show();
			return false;
		});
	});
	$('#file_val_submit').click(function(){
		$('#ud_key_file').click().change(function(){
			$('#file_val').text($('#ud_key_file').val());
		}).mouseout(function(){
			$('#file_val').text($('#ud_key_file').val());
		}).mousemove(function(){
			$('#file_val').text($('#ud_key_file').val());
		});
		return false;
	}).mouseout(function(){
			$('#file_val').text($('#ud_key_file').val());
	}).mousemove(function(){
			$('#file_val').text($('#ud_key_file').val());
	});
	$('body').mouseout(function(){
			$('#file_val').text($('#ud_key_file').val());
	}).mousemove(function(){
			$('#file_val').text($('#ud_key_file').val());
	})
	if($('.select-special').length) {
		$('.select-special').each(function() {
			var classWithHash = '#' + $(this).attr('id') + ' ';
			var width = '165px'; 
			var float = 'none'; 
			if($(classWithHash + ' select').css('width')) {
				width = $(classWithHash + ' select').css('width');
			}
			if($(classWithHash + ' select').css('float')) {
				float = $(classWithHash + ' select').css('float');
			}
			$(classWithHash + ' select').hide();
			var valSelected = '';
			html = '<div class="select-center" style="width:' + width + '; float:' + float + '"><div class="select-left"><div class="select-right"><span class="select-text">';
			/** Pobranie tekstu do zaznaczenia **/
			$(classWithHash + ' select option').each(function() {
				if($(this).attr('selected')) {
					html += $(this).text();			
				}
			});
			valSelected = $(classWithHash + ' select').val();
			html += '</span><a href="" class="select-more"><img src="' + basePath + '/files/images/select-more.png" /></a></div></div></div><div class="select-list">';
			/** Pobranie listy opcji **/
			$(classWithHash + ' select option').each(function() {
				var selected = '';
				if(valSelected == $(this).attr('value')) {
					selected = ' class="select-selected"'; 
				}
				html += '<a href=""' + selected + ' value="' + $(this).attr('value') + '">' + $(this).text() + '</a>';
			} );
			html += '</div>';
			$(classWithHash + ' select').after(html);
			$(classWithHash + '.select-more').click(function() {
				if($(classWithHash + '.select-list').css('display') == 'block') {
					$(classWithHash + '.select-list').slideUp();
				} else {
					$(classWithHash + '.select-list').slideDown();
				}
				return false;
			});
			$(classWithHash + '.select-list a').click(function() {
				$(classWithHash + '.select-list a').removeClass('select-selected');
				$(this).addClass('select-selected');
				$(classWithHash + '.select-list').slideUp();
				$(classWithHash + '.select-text').text($(this).text());
				$(classWithHash + ' select').val($(this).attr('value'));
				$(classWithHash + ' select').change();
				return false;
			});
		});
	}
});

function createTopic(urlAddTopic, urlAddPost, urlShowTopic) 
{
	$('#special_overlay_dane').html('Trwa wysyłanie danych.<br />Proszę czekać.');
    $('#special').show();
	$('#form_createTopic').submit(function() {
		//alert('eee');
	//	alert(urlAddTopic);
		$.post(urlAddTopic, {
			'gt_title'	:	$('input[name=gt_title]', this).val(),
			'gt_sticky'	:	$('input[name=gt_sticky]', this).attr('checked') == true ? $('input[name=gt_sticky]', this).val() : 0,
			'_type_response' : 'json'
		}, function(data) {	
		//	alert(data);
			if(data.errors && data.errors['gt_title']) {
				$('#form_createTopic #errors').html('<p class="error">Musisz podać tytuł</p>');
				$('#special').hide();
			}
		//	alert(data);
			if(data.addedTopicId) {
				var addedTopicId = data.addedTopicId;
			//	alert(addedTopicId)
				urlAddPost = urlAddPost.replace(/:gt_id/, data.addedTopicId);
			//	alert(urlAddPost);
				$.post(urlAddPost, {
					'gtp_text'	:	$('#form_createTopic textarea[name=gtp_text]').val(),
					'_type_response' : 'json'
				}, function(data) {
					if(data.errors && data.errors['gtp_text']) {
						$('#form_createTopic #errors').html('<p class="error">Musisz podać treść</p>');
					} else {
						urlShowTopic = urlShowTopic.replace(/:gt_id/, addedTopicId);
						document.location = urlShowTopic;
					}
					$('#special').hide();
				}, 'text');
			}
		}, 'json');
		return false;
	});
	$('#form_createTopic').submit();
	return false;
}
function ajaxFileUpload(obj, finishFunction)
{
	var type = $('[name=_type_response]').val() == 'json' ? 'json' : 'text';
    $(obj).ajaxForm({
    	dataType:  'text', 
        beforeSubmit: function(a,f,o) {
        //	o._type_response = $('[name=_type_response]').val();
        //	o.f_title = $('[name=f_title]').val();
        	$('#special_overlay_dane').html('Trwa wysyłanie danych.<br />Proszę czekać.');
            $('#special').show();
    //var queryString = $.param(a); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    //alert('About to submit: \n\n' + queryString); 
        },
        success: function(data) {
        //	alert(data);
            $('#special').hide();
           	finishFunction(data);
        }
    });
}  
var nameFile = '';
function appendAttachment(obj, form)
{
	form = $(form);
	nameFile = $('#ud_key_file').val();
	// ukryte, ważne pola
	hiddenFields = '<input type="text" name="f_title" value="' + $('title').text() + '" />';
	hiddenFields += '<input type="text" name="f_text" value="' + basePath + requestUri + '" />';
	hiddenFields += '<input type="text" name="f_tags" value="załączniki" />';
	hiddenFields += '<input type="text" name="filesAdd" value="send" />';
	hiddenFields += '<input type="text" name="_type_response" value="xml" />';
	// przeniesienie elementu do formularza
	form.html($('#ud_key_file').attr('id', ''));
	form.append(hiddenFields);
	// dodanie do starego miejsca inputa
	$('#input_attachment').html('<input name="f_file" type="file" id="ud_key_file"  class="file" /><div class="fakefile" style="float: left;">' + 
		'<img id="file_val_submit" src="' + basePath + '/files/images/browse_file.png" alt="" /></div>');
	form.submit();
}
function sendAttachment(data)
{
	var errors = false;
	$('errors:eq(0)', data).children().each(function(){
		if($('[name=' + this.tagName + ']', this).length) {
			errors = true;
		}
	});

	if(errors) {
		alert('Wysłanie pliku było nie możliwe. Obsługiwane pliki: jpg, png, gif');
		return;
	}
	filesUploadedFile = Base64.decode($('filesUploadedFile', data).html());
	url = basePath + '/files/uploaded/' + filesUploadedFile;
	title = nameFile;
	ext = filesUploadedFile.substring(filesUploadedFile.indexOf('.') + 1, 40);
	if(ext == 'jpg' || ext == 'jpeg' || ext == 'gif' || ext == 'png') {
		code = '[img=' + url + ']' + title + '[/img]'
	} else {
		code = '[url=' + url + ']' + title + '[/url]';
	}
	$('#gtp_text').val($('#gtp_text').val() + code);
	//alert(data.filesUploadedFile);
	//alert(data.filesUploadedFile.substring(data.filesUploadedFile.indexOf('.') + 1, 40));
	//alert(nameFile);
	
}
function SetLogo(id, tag, order)
{
	$.post(requestUri, {
		'ftt_order' : order,
		'_f_id' : id,
		'_ft_id' : tag,
		'_type_response' : 'json'
	}, function(data) {
		//alert(data);
		document.location = requestUri;
	}, 'json');
}
function sendLogo(data)
{
	if(!data.errors || typeof data.errors == "undefined") {
		document.location = requestUri;
		return;
	}
	$('.ajax_errors').hide();
	for(k in data.errors) {
		if(k == 'f_title') {
			message = "Podanie tytułu loga jest obowiązkowe";
		} else {
			message = "Wysłanie loga było nie możliwe. Obsługiwane formaty: jpg, png, gif";
		}
    	$('[name=' + k + ']').parent().parent().before('<tr class="ajax_errors"><td class="errorTd" colspan="2"><p class="error">' + message + '</p></td></tr>');
	}
}