var jsMail ='Nieprawidłowa składnia adresu e-mail';
var jsMailP ='Adres e-mail musi być uzupełniony!';
var jsPodpis   = 'Nie wypełniono pola Podpis';
var jsTresc   = 'Nie wypełniono treści';
var jsWyd   = 'Wydanie musi byc wypełnione!';

function CzyZapisac1() {
        if (document.getElementById('idwyd').value == '') {
        alert(jsWyd);
        document.getElementById('idwyd').focus();
        return false; }
        else {
         System=confirm("Czy zapisać zmiany?");
         if (System) { return true;}
         else { return false;} }
}

function CzyZapisac() {
         System=confirm("Czy zapisać zmiany?");
         if (System) { return true;}
         else { return false;}
}
function sprKsiega(form) {
   if (form.elements['nick'].value == '') {
      alert(jsNazwisko);
      form.elements['nick'].focus();
      return false;
   } else if (form.elements['tresc'].value == '') {
      alert(jsTresc);
      form.elements['tresc'].focus();
      return false;
   }
   return true;
}
function sprKontakt(form) {
   if (form.elements['mail'].value == '') {
      alert(jsMailP);
      form.elements['mail'].focus();
      return false;
   } else if (form.elements['podpis'].value == '') {
      alert(jsPodpis);
      form.elements['podpis'].focus();
      return false;
   }
   return true;
}

function sprMail(pole) {
   if (pole.value.search(/^[0-9a-zA-Z.-_]+\@[0-9a-zA-Z.-_]+\.[0-9a-zA-Z.]{2,3}$/) == -1) {
      alert(jsMail);
      return false;
   }
}

function sprJpg(pole) {
	if (pole.value.search(/\i*(jpg)|(jpeg)|(JPG)|(JPEG)$/) == -1) {
//    alert(pole.value);
		alert(jsJpg);
		return false;
	}
}


// live comment preview  - comment body

/*
   This function is from Jeff Minard - http://www.creatimation.net/
    adapted from code by Stuart Langridge at http://www.kryogenix.org/
 */

function superTextile(s) {
    var r = s;
    // quick tags first
    qtags = [['\\*', 'strong'],
             ['\\?\\?', 'cite'],
             ['\\+', 'ins'],  //fixed
             ['~', 'sub'],
             ['\\^', 'sup'], // me
             ['@', 'code']];
    for (var i=0;i<qtags.length;i++) {
        ttag = qtags[i][0]; htag = qtags[i][1];
        re = new RegExp(ttag+'\\b(.+?)\\b'+ttag,'g');
        r = r.replace(re,'<'+htag+'>'+'$1'+'</'+htag+'>');
    }
    // underscores count as part of a word, so do them separately
    re = new RegExp('\\b_(.+?)_\\b','g');
    r = r.replace(re,'<em>$1</em>');
	
	//jeff: so do dashes
    re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
    r = r.replace(re,'<del>$1</del>');

    // links
    re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)','g');
    r = r.replace(re,'<a href="$3" title="$2">$1</a>');
    re = new RegExp('"\\b(.+?)\\b":([^\\s]+)','g');
    r = r.replace(re,'<a href="$2">$1</a>');

    // images
    re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
    r = r.replace(re,'<img src="$1" alt="$2">');
    re = new RegExp('!\\b(.+?)\\b!','g');
    r = r.replace(re,'<img src="$1">');

    // block level formatting
	
		// Jeff's hack to show single line breaks as they should.
		// insert breaks - but you get some....stupid ones
//	    re = new RegExp('(.*)\n([^#\*\n].*)','g');
//	    r = r.replace(re,'$1<br />$2');
		// remove the stupid breaks.
//	    re = new RegExp('\n<br />','g');
//	    r = r.replace(re,'\n');
	
    lines = r.split('\n');
    nr = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i].replace(/\s*$/,'');
        changed = 0;
        if (line.search(/^\s*bq\.\s+/) != -1) { line = line.replace(/^\s*bq\.\s+/,'\t<blockquote>')+'</blockquote>'; changed = 1; }
		
		// jeff adds h#.
        if (line.search(/^\s*h[1-6]\.\s+/) != -1) {
	    	re = new RegExp('h([1-6])\.(.+)','g');
	    	line = line.replace(re,'<h$1>$2</h$1>');
			changed = 1;
		}
		
		if (line.search(/^\s*\*\s+/) != -1) { line = line.replace(/^\s*\*\s+/,'\t<liu>') + '</liu>'; changed = 1; } // * for bullet list; make up an liu tag to be fixed later
        if (line.search(/^\s*#\s+/) != -1) { line = line.replace(/^\s*#\s+/,'\t<lio>') + '</lio>'; changed = 1; } // # for numeric list; make up an lio tag to be fixed later
//        if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
        if (!changed && (line.replace(/\s/g,'').length > 0)) line = line;
        lines[i] = line + '\n';
    }
	
    // Second pass to do lists
    inlist = 0;
	listtype = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i];
        if (inlist && listtype == 'ul' && !line.match(/^\t<liu/)) { line = '</ul>\n' + line; inlist = 0; }
        if (inlist && listtype == 'ol' && !line.match(/^\t<lio/)) { line = '</ol>\n' + line; inlist = 0; }
        if (!inlist && line.match(/^\t<liu/)) { line = '<ul>' + line; inlist = 1; listtype = 'ul'; }
        if (!inlist && line.match(/^\t<lio/)) { line = '<ol>' + line; inlist = 1; listtype = 'ol'; }
        lines[i] = line;
    }

    r = lines.join('\n');
	// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
    r = r.replace(/li[o|u]>/g,'li>');

    return r;
}

function ReloadAllDivs() {
   ReloadTytulDiv();
   ReloadPodtytDiv();
   ReloadTextDiv();
   ReloadAutorDiv();
}

function ReloadTytulDiv() {
    var commentString = document.getElementById('tytul').value;
		var con = superTextile(commentString);

    document.getElementById('TytulDisplay').innerHTML = con;
}
function ReloadPodtytDiv() {
    var commentString = document.getElementById('podtyt').value;
		var con = superTextile(commentString);

    document.getElementById('PodtytDisplay').innerHTML = con;
}
function ReloadAutorDiv() {
    var commentString = document.getElementById('autor').value;
		var con = superTextile(commentString);

    document.getElementById('AutorDisplay').innerHTML = con;
}
function ReloadTextDiv() {
    var commentString = document.getElementById('text').value;
		var con = superTextile(commentString);

    document.getElementById('TextDisplay').innerHTML = con;
}

// live comment preview - author
function ReloadNameDiv()
{
var NewText = document.getElementById("name").value;
var DivElement = document.getElementById("NameDisplay");
DivElement.innerHTML = NewText;
}








// bbCode control by
// subBlue design
// www.subBlue.com

// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "Tekst pogrubiony: [b]tekst[/b]  (alt+b)";
i_help = "Tekst kursywą: [i]tekst[/i]  (alt+i)";
u_help = "Tekst podkreślony: [u]tekst[/u]  (alt+u)";
q_help = "Cytat: [quote]tekst[/quote]  (alt+q)";
c_help = "Pokaż kod: [code]kod[/code]  (alt+c)";
l_help = "Lista: [list]tekst[/list] (alt+l)";
o_help = "Lista uporządkowana: [list=]tekst[/list]  (alt+o)";
p_help = "Wstaw obrazek: [img]http://adres_obrazka[/img]  (alt+p)";
w_help = "Wstaw adres: [url]http://adres[/url] or [url=http://adres]Tekst adresu[/url]  (alt+w)";
a_help = "Zamknij wszystkie otwarte tagi bbCode";
s_help = "Kolor czcionki: [color=red]tekst[/color]  Rada: możesz także podać color=#FF0000";
f_help = "Rozmiar czcionki: [size=x-small]mały tekst[/size]";
pyt_help = "Pytanie w wywiadach: ";
// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('<b>','</b>','<i>','</i>','<u>','</u>','<br />','<br />','<div class="data">','</div>','<p class="pyt">','</p>','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.f.helpbox.value = eval(help + "_help");
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;

	if (document.f.message.value.length < 2) {
		formErrors = "Musisz wpisać wiadomość przed wysłaniem";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	var txtarea = document.f.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	var txtarea = document.f.message;

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}


function bbstyle(bbnumber) {
	var txtarea = document.f.tresc;

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.f.addbbcode' + butnumber + '.value');
			eval('document.f.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.f.addbbcode' + butnumber + '.value');
				eval('document.f.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.f.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.f.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function zmDate(znak,pole){
  var data=document.getElementById(pole).value;
  if (znak=='+') {dat=new Date(data.substr(0,4),data.substr(5,2)-1,parseInt(data.substr(8,2),10)+1);}
  else if (znak='-')  {dat=new Date(data.substr(0,4),data.substr(5,2)-1,parseInt(data.substr(8,2),10)-1);}
  document.getElementById(pole).value=dat.getFullYear()+"-"+digits(parseInt(dat.getMonth()+1))+"-"+digits(dat.getDate());
}
function digits(number)
{
  s = new String(number);
  if ((number<=9) && (s.length==1)) { return '0'+s } else {return s};
}

function generuj_link(){
  var x=document.getElementById('link_g').value;
  var nr=document.getElementById('idwyd').value;
  for (var i=0; i<document.getElementById("idwyd").options.length; i++){
    if (document.getElementById("idwyd").options[i].selected==true){
      var rokt=(document.getElementById("idwyd").options[i].text);
      break;
    }
  }
  rok=rokt.split("/");
  rok=rok[1].substring(0,4);
  if (nr=='') { alert('Należy wpierw określić numer gazety!!');}
  else if(document.getElementById('text').value!=''){
    alert('Linkować można tylko gdy nie jest podana treść!!');
  }
  else {
  if (x=='') link='';
  else if (x=='intencje') link=x+'.php?rok='+rok+'#rok';
  else link=x+'.php?nr='+nr;
  document.getElementById('link').value=link;
  }
}