var addCommentBoxVisible = false;
var showCommentsVisible = false;
var iloscSzpitali = 0;

function getI18N(txt, debug) {
	if (!debug) var debug = false;
	else var debug = debug;
	
	if (debug == false)
		txt = ((global_I18N && global_I18N[txt]) ? global_I18N[txt] : txt);
	else
		txt = ((global_I18N && global_I18N[txt]) ? global_I18N[txt] : "[X]"+txt+"[/X]");
	return txt;
}

function getError(error_id) {
	return 'error '+error_id;
}

var global_I18N = {}


function prepare_newsletter(obj) {
	if (obj.className == 'input-text temporary-inactive') {
		obj.className = 'input-text';
		obj.value = '';
	}
}

function setSize(size) {
	var el = document.getElementById('article');
	if (size == 1) el.className = 'font-big';
	else if (size == 2) el.className = 'font-biggest';
	else el.className = '';
	
	var el = document.getElementById('article-info');
	if (size == 1) el.className = 'font-big';
	else if (size == 2) el.className = 'font-biggest';
	else el.className = '';
	
	var el = document.getElementById('comments');
	if (size == 1) el.className = 'font-big';
	else if (size == 2) el.className = 'font-biggest';
	else el.className = '';
	
	var els = document.getElementsByTagName('h1');
	for(var i in els) {
		if (size == 1) els[i].className = 'font-big';
		else if (size == 2) els[i].className = 'font-biggest';
		else els[i].className = '';
	}
	
	var els = document.getElementsByTagName('h3');
	for(var i in els) {
		if (size == 1) els[i].className = 'font-big';
		else if (size == 2) els[i].className = 'font-biggest';
		else els[i].className = '';
	}
}

function checkMonthsWeeks() {
	//alert(1);
}

function clearAddCommentForm() {
	jQuery('#new_nickname').val('');
	jQuery('#new_comment').val('');
}

function addCommentComplete(data) {
	unblockComments();
	addCommentBox();
	setTimeout("clearAddCommentForm();",300);
	setTimeout("if(Recaptcha) { Recaptcha.reload(); }",300);
	setTimeout("if (Recaptcha) { jQuery('#recaptcha_response_field').val(''); }",300);
	jQuery('#comment_save_button').removeClass('hidden');
	jQuery('#comment_loading_button').addClass('hidden');
	jQuery('#comments_was_added').fadeIn(1000,function(){
		jQuery('#comments_was_added').fadeOut(500);
	});
	jQuery('#show_comments').html(jQuery('#show_comments_box_loader').html().replace('Wczytuję komentarze ', ''));
	jQuery.get(baseURL+'html/countWithNames?article_id='+jQuery('#article_id').val(), null, function(o, textStatus) { jQuery('#show_comments').html(o); showCommentsBox() });
}

function blockComments(data) {
	if (Recaptcha && data) {
		var data = data;
		jQuery('#add_comment_form').fadeTo(500, 0.33, function() {
			postCaptcha(function() {
					jQuery.post(baseURL+'addComment', data, addCommentComplete);
				}, 
				function() {
					unblockComments();
				}
			);
		} );
	} else if (data) {
		var data = data;
		jQuery('#add_comment_form').fadeTo(500, 0.33, function() {
			jQuery.post(baseURL+'addComment', data, addCommentComplete);
		} );
	} else {
		jQuery('#add_comment_form').fadeTo(500, 0.33);
	}
	jQuery('#new_nickname').attr('readonly', 'readonly');
	jQuery('#new_comment').attr('readonly', 'readonly');
	if (Recaptcha) {
		jQuery('#recaptcha-comment').fadeTo(500, 0.33);
		jQuery('#recaptcha_response_field').attr('readonly', 'readonly');
		jQuery('#recaptcha_reload').hide();
		jQuery('#recaptcha_only_if_image').hide();
		jQuery('#recaptcha_only_if_audio').hide();
		jQuery('#recaptcha_help').hide();
	}
}
function unblockComments() {
	jQuery('#add_comment_form').fadeTo(1, 1);
	jQuery('#new_nickname').removeAttr('readonly');
	jQuery('#new_comment').removeAttr('readonly');
	if (Recaptcha) {
		jQuery('#recaptcha-comment').fadeTo(1, 1);
		jQuery('#recaptcha_response_field').removeAttr('readonly');
		jQuery('#recaptcha_reload').show();
		jQuery('#recaptcha_only_if_image').show();
		jQuery('#recaptcha_only_if_audio').show();
		jQuery('#recaptcha_help').show();
	}
}

function saveNewComment() {
	var comment = jQuery('#new_comment').val();
	var nickname = jQuery('#new_nickname').val();
	if (comment != '' && nickname != '') {
		var data = {
			article_id: jQuery('#article_id').val(),
			nickname: nickname,
			comment: comment
		};
		blockComments(data);
	} else if(comment != '') {
		alert(getI18N('Uzupełnij pole pseudonim.'));
	} else if(nickname != '') {
		alert(getI18N('Uzupełnij komentarz.'));
	} else {
		alert(getI18N('Uzupełnij komentarz i pseudonim.'));
	}
	return false;
}

function addCommentBox() {
	if (addCommentBoxVisible != true) {
		jQuery('#add_comment_box').fadeIn('1500');
		window.location = '#anchor_comment';
		addCommentBoxVisible = false;
	} else {
		jQuery('#add_comment_box').fadeOut('300');
		addCommentBoxVisible = false;		
	}
	return false;
}

function showCommentsComplete(data) {
	jQuery('#show_comments_box_loader').fadeOut('300');
	var ul = document.getElementById('list_of_comments');
		ul.innerHTML = '';
		
	var li, p;
	var i = 0;
	while (data[i]) {
		if (data[i].author) {
			li = document.createElement('li');
			
			p = document.createElement('p');
			p.appendChild(document.createTextNode(data[i].date));
			p.className = 'comment-date';
			li.appendChild(p);
						
			p = document.createElement('p');
			p.appendChild(document.createTextNode(data[i].author));
			if (data[i].is_registered == true) p.className = 'comment-author-registered'; else p.className = 'comment-author';
			li.appendChild(p);
						
			p = document.createElement('p');
			p.appendChild(document.createTextNode(data[i].content));
			p.className = 'comment-content';
			li.appendChild(p);
			
			ul.appendChild(li);
		}
		i++;
	}
	setTimeout("jQuery('#list_of_comments').fadeIn('1500');", 500);
}

function showCommentsBox() {
	if (showCommentsVisible == false) {
		jQuery('#show_comments_box_loader').fadeIn('50');
		jQuery('#show_comments_box').fadeIn('1500');
		showCommentsVisible = false;
		var data = {
			article_id: jQuery('#article_id').val()
		};
		jQuery.post(baseURL+'getComments', data, showCommentsComplete, 'json');
	} else {
		jQuery('#show_comments_box_loader').fadeOut('50');
		jQuery('#show_comments_box').fadeOut('500');
		setTimeout("document.getElementById('list_of_comments').innerHTML = '';", 500);
		showCommentsVisible = false;
	}
	return false;
}

function checkIfIsDate(txt) {
	if (txt)
		return txt <= currentYear ? txt.match(/^[12][0-9]{3}$/i) : null;
	else
		return null;
}

function checkIfIsWeeks(txt) {
	if (txt)
		return txt.match(/^[0-9]{1,2}$/i);
	else
		return null;
}

function checkIfIsMonths(txt) {
	if (txt)
		return txt.match(/^[0-9]{1,3}$/i);
	else
		return null;
}

function checkIfIsNumber(txt) {
	if (txt) {
		if (txt.match(/^[0-9]*$/i)) {
			setIloscSzpitali(txt);
			return true;
		} else {
			return false;
		}
	} else {
		setIloscSzpitali(0);
		return null;
	}
}

function setIloscSzpitali(ilosc) {
	var ilosc = ilosc;
	var val = jQuery('#osrodki-wzor').html();
	if (ilosc > iloscSzpitali) {
		for(var i = 0; i < ilosc-iloscSzpitali; i++) {
			jQuery('<li>'+val+'</li>').appendTo('ul#osrodki');
		}
	} else {
		for(var i = 0; i < iloscSzpitali-ilosc; i++) {
			jQuery('#osrodki li:last').remove();	
		}
	}
	iloscSzpitali = ilosc;
}

function prepareErrorTipsForSpisPowszechny() {

	var errors = {
		'2' : 'Wprowadź poprawny rok (np. 1999).',
		'5' : 'Wprowadź poprawną liczbę tygodni.',
		'6' : 'Wprowadź poprawną liczbę miesięcy.',
		'9': 'Wprowadź poprawną liczbę.',
		'18': 'Wprowadź poprawny rok (np. 1985).',
		'20': 'Wprowadź poprawny rok (np. 1985).',
		'22': 'Wprowadź poprawny rok (np. 1985).'
	};
	for(var i=1;i<30;i++) {
		jQuery('#input_'+i).attr('uid',i);
		jQuery('#error_tip_'+i).html('<p>'+errors[i]+'</p>'+'<p class="close"><a href="#close" onclick="jQuery(\'#error_tip_'+i+'\').hide(150);return false;">zamknij to okienko</a></p>');
	}
	jQuery('#input_2').change(function() {
		if(checkIfIsDate(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
		}
	});	
	jQuery('#input_9').change(function() {
		if(checkIfIsNumber(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
			if (jQuery(this).val() == '1') {
				jQuery('#osrodki-header-lp').show();
				jQuery('#osrodki-header-lm').hide();
			} else {
				jQuery('#osrodki-header-lp').hide();
				jQuery('#osrodki-header-lm').show();
			}
		}
		if (!(jQuery(this).val() > 0)) {
			jQuery("#osrodki-header").hide();
		} else {
			jQuery("#osrodki-header").show();
		}
	});
	jQuery('#input_5').change(function() {
		var mcy = Math.floor(parseInt(jQuery(this).val())/4)+'';
		jQuery('#input_6').val('');
		if(checkIfIsWeeks(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
			jQuery('#question_5').fadeOut(150);
			jQuery('#xmiesiecy').html('');
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
			jQuery('#question_5').fadeIn(250);
			if (mcy == '0') {
				mcy = null;
				jQuery('#question_5').fadeOut(150);
				jQuery('#xmiesiecy').html('');
			} else if (mcy == '1') {
				mcy = '1 miesiąc';
			} else if (mcy.match(/.*[023456789][234]$/i) || mcy.match(/^[234]$/i)) {
				mcy = mcy+' miesiące';
			} else {
				mcy = mcy+' miesięcy';
			}
			if (mcy) {
				jQuery('#xmiesiecy').html(mcy+' od rozpoznania choroby');
			}
		}
		checkMonthsWeeks();
	});	
	jQuery('#input_6').change(function() {
		var mcy = jQuery(this).val();
		jQuery('#input_5').val('');
		if(checkIfIsMonths(mcy) == null || parseInt(mcy) == 0) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
			jQuery('#question_5').fadeOut(150);
			jQuery('#xmiesiecy').html('');
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
			jQuery('#question_5').fadeIn(250);
			if (mcy == '1') {
				mcy = '1 miesiąc';
			} else if (mcy.match(/.*[023456789][234]$/i) || mcy.match(/^[234]$/i)) {
				mcy = mcy+' miesiące';
			} else {
				mcy = mcy+' miesięcy';
			}
			jQuery('#xmiesiecy').html(mcy+' od rozpoznania choroby');
		}
		checkMonthsWeeks();
	});
	jQuery('#input_18').change(function() {
		if(checkIfIsDate(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
		}
	});
	jQuery('#input_20').change(function() {
		if(checkIfIsDate(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
		}
	});
	jQuery('#input_22').change(function() {
		if(checkIfIsDate(jQuery(this).val()) == null) {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).show(500);
		} else {
			jQuery('#error_tip_'+jQuery(this).attr('uid')).hide(150);
		}
	});
	
	var hide = new Array('input_2A', 'input_3', 'input_4', 'input_7', 'question_5', 'input_8', 'input_17', 'input_18', "question_10", "question_10a"); i = 0;
	while(hide[i]) {
		jQuery('#'+hide[i]).hide();
		i++;
	}
	
	var references = {
		'input[name=Pytanie 2]': {
			"ktoś inny": {
				"show": ["input_3"],
				"hide": ["input_2A"]
			},
			"lekarz innej specjalizacji": {
				"show": ["input_2A"],
				"hide": ["input_3"]
			},
			"default": {
				"show": [],
				"hide": ["input_3", "input_2A"]
			}
		},		
		'input[name=Pytanie 3]': {
			"lekarz innej specjalizacji": {
				"show": ["input_4"],
				"hide": []
			},
			"default": {
				"show": [],
				"hide": ["input_4"]
			}
		},
		'input[name=Pytanie 4C]': {
			"nie rozpoczęto leczenia": {
				"show": ["question_13"],
				"hide": ["question_4_a", "question_5", "question_6", "question_7", "question_8", "question_9", "question_10", "question_11", "question_12", "question_7a", "question_10a"],
				"callback": function(type) {
					if (type == 'show' && (
							(checkIfIsMonths(jQuery("#input_6").val()) && parseInt(jQuery("#input_6").val()) > 0) ||
							(checkIfIsMonths(jQuery("#input_5").val()) && parseInt(jQuery("#input_5").val()) >= 4)							
						) ) {
						jQuery("#question_5").fadeIn(250);					
					}
				}			
			},
			"default": {
				"show": ["question_4_a", "question_6", "question_7", "question_8", "question_9", "question_10", "question_11", "question_12", "question_7a", "question_10a"],
				"hide": ["question_13"]
			}
		},
		'input[name=Pytanie 5]': {
			"inne": {
				"show": ["input_7"],
				"hide": []				
			},
			"default": {
				"show": [],
				"hide": ["input_7"]
			}
		},
		'input[name=Pytanie 7H]': {
			"inny specjalista": {
				"show": ["input_8"],
				"hide": []				
			},
			"default": {
				"show": [],
				"hide": ["input_8"]
			}
		},
		'input[name=Pytanie 9D]': {
			"przypisał leki": {
				"show": ["input_17"],
				"hide": []				
			},
			"default": {
				"show": [],
				"hide": ["input_17"]
			}
		},
		'input[name=Pytanie 8]': {
			"tylko NFZ": {
				"show": ["subquestion_1"],
				"hide": ["subquestion_2", "subquestion_3"]				
			},
			"tylko prywatnej": {
				"show": ["subquestion_2"],
				"hide": ["subquestion_1", "subquestion_3"]	
			},			
			"w prywatnej i NFZ": {
				"show": ["subquestion_3"],
				"hide": ["subquestion_1", "subquestion_2"]	
			}, 
			"default": {
				"show": [],
				"hide": ["subquestion_1", "subquestion_2", "subquestion_3"]
			}
		},
		'input[name=Pytanie 11]': {
			"tak": {
				"show": ["input_18"],
				"hide": []				
			},
			"default": {
				"show": [],
				"hide": ["input_18"]
			}
		},
		'input[name=Pytanie 9A]': {
			"operację": {
				"show": ["question_10", "question_10a"],
				"hide": []	
			}, 
			"default": {
				"show": [],
				"hide": ["question_10", "question_10a"]
			}
		}
	}
	
	
	if (jQuery.browser.msie) {
		jQuery('input[name=plec]').click(function(){
			if (jQuery(this).val() == 'kobieta') {
				jQuery('.kz').removeClass('hidden');
				jQuery('.km').addClass('hidden');
			} else {
				jQuery('.kz').addClass('hidden');
				jQuery('.km').removeClass('hidden');
			}
		});
		jQuery('input[name=plec]').keyup(function(){
			if (jQuery(this).val() == 'kobieta') {
				jQuery('.kz').removeClass('hidden');
				jQuery('.km').addClass('hidden');
			} else {
				jQuery('.kz').addClass('hidden');
				jQuery('.km').removeClass('hidden');
			}
		});
	} else {	
		jQuery('input[name=plec]').change(function(){
			if (jQuery(this).val() == 'kobieta') {
				jQuery('.kz').removeClass('hidden');
				jQuery('.km').addClass('hidden');
			} else {
				jQuery('.kz').addClass('hidden');
				jQuery('.km').removeClass('hidden');
			}
		});
	}
	
	for(i in references) {
		jQuery(i).attr('k', i);
		if (jQuery.browser.msie) {			
			jQuery(i).click(function() {
				var j = 0; var k = jQuery(this).attr('k');
				if (references[k] && references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['show'] && jQuery(this).attr('checked') == true) {
					while(references[k][jQuery(this).val()]['hide'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;					
					while(references[k][jQuery(this).val()]['show'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('hide');
					}
				} else if (references[k] && references[k]['default'] && references[k]['default']['show']) {
					while(references[k]['default']['hide'][j]) {
						jQuery('#'+references[k]['default']['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;
					while(references[k]['default']['show'][j]) {
						jQuery('#'+references[k]['default']['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('show');
					}
				}
			});
						
			jQuery(i).keyup(function() {
				var j = 0; var k = jQuery(this).attr('k');
				if (references[k] && references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['show'] && jQuery(this).attr('checked') == true) {
					while(references[k][jQuery(this).val()]['hide'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;					
					while(references[k][jQuery(this).val()]['show'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('hide');
					}
				} else if (references[k] && references[k]['default'] && references[k]['default']['show']) {
					while(references[k]['default']['hide'][j]) {
						jQuery('#'+references[k]['default']['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;
					while(references[k]['default']['show'][j]) {
						jQuery('#'+references[k]['default']['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('show');
					}
				}
			});
		} else {
			jQuery(i).change(function() {
				var j = 0; var k = jQuery(this).attr('k');
				if (references[k] && references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['show'] && jQuery(this).attr('checked') == true) {
					while(references[k][jQuery(this).val()]['hide'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;					
					while(references[k][jQuery(this).val()]['show'][j]) {
						jQuery('#'+references[k][jQuery(this).val()]['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('hide');
					}
				} else if (references[k] && references[k]['default'] && references[k]['default']['show']) {
					while(references[k]['default']['hide'][j]) {
						jQuery('#'+references[k]['default']['hide'][j]).fadeOut(150,function() { jQuery(this).val('') });
						j++;
					}
					j = 0;
					while(references[k]['default']['show'][j]) {
						jQuery('#'+references[k]['default']['show'][j]).fadeIn(250);
						j++;
					}
					if (references[k][jQuery(this).val()] && references[k][jQuery(this).val()]['callback']) {
						references[k][jQuery(this).val()]['callback']('show');
					}
				}
			});
		}
	}
}

window.onload = function() {
	jQuery('#add_comment').click(addCommentBox);
	jQuery('#show_comments').click(showCommentsBox);
	prepareErrorTipsForSpisPowszechny();
}

function unsubscribe(url, val) {
	if (val && val.match(/^.*@.*\..{2,}$/)) {
		window.location = url+'/email/'+val;
	} else {
		alert(getI18N('Podaj adres e-mail.'));
	}
}

function showWojewodztwoLoader() {
	jQuery('#osrodki').html('<li style="list-style: none"><div id="osrodki_loader">wczytuję dane...</div></li>');
}
function addWojewodztwo(name) {
	showWojewodztwoLoader();
	jQuery('#osrodki').load('amazonki/ladujOsrodkiZ', { 'wojewodztwo': name });
}

function remWojewodztwo(name) {
	showWojewodztwoLoader();
	jQuery('#osrodki').load('amazonki/ladujOsrodkiBez', { 'wojewodztwo': name });
}

function setWojewodztwo(name) {
	showWojewodztwoLoader();
	jQuery('#osrodki').load('amazonki/ladujOsrodki', { 'wojewodztwo': name });
}

function clearWojewodztwa() {
	showWojewodztwoLoader();
	jQuery('#osrodki').load('amazonki/ladujOsrodkiRanking');
}

function validate_zglos_problem() {
	var email = jQuery('#problem_email').val();
	var telefon = jQuery('#problem_telefon').val();
	var error = false;
	
	var email_match = new RegExp('.*?@.*?\..{2,}');
	var telefon_match = new RegExp('[0-9]{7,}');
	
	if(!email_match.test(email) && !telefon_match(telefon)) {
		alert('Podaj poprawny adres e-mail lub telefon...');
		return false;
	} else {
		return true;
	}
	
}

function validate_dolacz_do_nas() {
	var error = false; var tmp;
	
	tmp = jQuery('#imie_i_nazwisko').val();
	if (!tmp || tmp == '') { error = true; }
	
	tmp = jQuery('#adres').val();
	if (!tmp || tmp == '') { error = true; }
	
	tmp = jQuery('#data_urodzenia').val();
	if (!tmp || tmp == '') { error = true; }
	
	tmp = jQuery('#tel_kontaktowy').val();
	if (!tmp || tmp == '') { error = true; }
	
	tmp = jQuery('#email').val();
	if (!tmp || tmp == '') { error = true; }
		
	if (jQuery('#jestem_amazonka_tak').attr('checked') != true && jQuery('#jestem_amazonka_nie').attr('checked') != true) { error = true; }
	
	tmp = jQuery('#zgadzam-sie').attr('checked');
	if (!tmp || tmp != true) { error = true; }
	
	if(error !== false) {
		alert('Uzupełnij wszystkie pola formularza i zaakceptuj treść deklaracji.');
		return false;
	} else {
		return true;
	}
}
function send_grade(aid, kid) {	
	var data = {
		article_id: aid,
		keyword_id: kid
	};
	jQuery.post(baseURL+'articleGrade/grade', data, function(data) { alert(data) });
}
