/**
 * Funkcje dla studia 2009
 * @author Grzegorz Szefka <kashub@wp-sa.pl>
 * @version $Revision: 1.11 $
 * @id $Id: fcj.js,v 1.11 2009/11/16 12:35:34 golabek Exp $
 */

// konfiguracja popupa
var dispInfoParam = 1;

// id otwartego popupa
// jesli jest zamkniety to ustawiamy 0
var idVisibleInfo = 0;

// funkcje do ustawiania pozycji kursora
var IE = document.all?true:false

if (!IE) document.captureEvents(Event.MOUSEMOVE)
	document.onmousemove = getMouseXY;
	document.onclick = getMouseXYClick;

var tempX = -1000;
var tempY = -1000;
var screenX;
var screenY;

// wielkosc ekranu
if (typeof(window.innerWidth) == 'number') {
	screenX = window.innerWidth;
	screenY = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	screenX = document.documentElement.clientWidth;
	screenY = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	screenX = document.body.clientWidth;
	screenY = document.body.clientHeight;
}

// parametr pozwala zmieniac polozenie diva
var getXY = true;

function getMouseXYClick(e) {
	getMouseXY(e);
	getXY = false;
}

// ustawienie przesuniecia skrola
function getScrollXY() {

	var scrollX = 0;
	var scrollY = 0;

	if (typeof(window.pageYOffset) == 'number') {
		scrollY = window.pageYOffset;
		scrollX = window.pageXOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		scrollY = document.body.scrollTop;
		scrollX = document.body.scrollLeft;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		scrollY = document.documentElement.scrollTop;
		scrollX = document.documentElement.scrollLeft;
	}

	return [scrollX, scrollY];
}

function getMouseXY(e) {

	if (false == getXY) {
		return true;
	}

	var scroll = getScrollXY();

	if (IE) {
		if (event == null) {
			return;
		}

		tempX = event.clientX + scroll[0];
		tempY = event.clientY + scroll[1];
	} else {
		if (e == null) {
			return;
		}

		tempX = e.pageX;
		tempY = e.pageY;
	}

	if (tempX < 0) {
		tempX = 0;
	}

	if (tempY < 0) {
		tempY = 0;
	}


	if (1 == dispInfoParam) {
	} else if (2 == dispInfoParam) {
		tempX = tempX - 270;
	} else if (3 == dispInfoParam) {
		tempY = tempY - 210;
	} else if (4 == dispInfoParam) {
		tempX = tempX - 270;
		tempY = tempY - 210;
	}

	if ((tempY+270) > (screenY+scroll[1])) {
		//              tempY = screenY + scroll[1] - 270;
	}

	var obj = document.getElementById('info');
	if (obj == null) {
		return false;
	}

	obj.style.top = tempY+'px';
	obj.style.left = tempX+'px';

	return true;
}

function ajaxAction(opt) {
	ajx = new ajaxActionPrepare();
	ajx.opcje(opt);
	ajx.start();
}

var ajaxResponse = '';

function ajaxActionPrepare() {
	var axp        = new Object();
	axp.funcAfter  = null;
	axp.ajxDiv     = null;
	axp.action     = '';
	axp.extraparam = '';
	axp.formName   = null;
	axp.view       = '';

	axp.opcje = function(opt) { for(i in opt) if(typeof(axp[i])=='undefined') axp.param[i]=opt[i]; else axp[i]=opt[i];	}

	axp.start = function() {

		// jesli dostalismy nazwe formularza to preparujemy posta i wysylamy ajaxem
		if (axp.formName) {

			//var poststr = '';
			var f = document.forms[axp.formName];
			var params = new Array();
			
			for (i=0; i<f.length; i++) {
				params[f.elements[i].name] = f.elements[i].value;				
			}

			if (axp.funcAfter && typeof('function' == axp.funcAfter)) {
				WP.ajax.post({ url: document.URL, params: params, 'onSuccess':function(ax) { ajaxResponse = ax.text; axp.funcAfter(); }});
			} else {
				WP.ajax.post({ url: document.URL, params: params });
			}

		// w przeciwnym wypadku sprawdzamy preperujemy get i wysylamy
		} else {

			if (axp.view) {
				var url = axp.view;
			} else {
				var url = document.URL;
			}
			
			var last   = url.lastIndexOf(',');
			var prefix = '';
			
			if (last > 0) {
			    var prefix = url.substring(0, last);
			}

			if (axp.action) {
				prefix += ',_action,'+axp.action;
			}
			
			if (axp.extraparam) {
				prefix += axp.extraparam;
			}

			if (last > 0) {
			    url = prefix + url.substring(last, url.length);
			} else {
			    url = 'true,1' + prefix + ',' + url;
			}

			if (axp.funcAfter && typeof('function' == axp.funcAfter)) {
				WP.ajax.get({ url: url, 'onSuccess':function(ax) { ajaxResponse = ax.text; axp.funcAfter(); }});
			} else {
				WP.ajax.get({ url: url });
			}
		}
	}

	return axp;
}

/**
 * addToSession dodawanie materialow do sesji w administracji
 * by pamietac zaznaczone/odznaczone materialy na kolejnych podstronach
 * 
 * @param string varName - nazwa zmiennej w sesji
 * @param int value - wartosc (id materialu)
 * @param int type - typ materialu
 * @param object obj - zaznaczony obiekt checkboxa
 */
function addToSession(varName, value, type, obj) {
	var extraparam = ',varName,'+varName+',value,'+value+',type,'+type;
	if (true == obj.checked) {
		extraparam += ',act,add';
	} else {
		extraparam += ',act,delete';
	}
	ajaxAction({'view':'addtosession.html', 'extraparam':extraparam });
}

/**
 * checkButtonVisible funkcja na podstawie zadanych parametrow
 * ukrywa lub pokazuje przycisk do usuwania div
 * jesli w nadrzednym div-ie (parentDiv) nie ma elementow podrzednych 
 * to ukrywa div-a (divDeleteButton) w kturym znajduje sie button, 
 * a jesli sa jakies inne div-y to pokazuje div-a z przyciskiem
 * 
 * @param divDeleteButton - div w ktorym znajduje sie przycisk do usuwania
 * @param parentDiv       - nadrzedny div w ktorym znajduja sie div-y elementy
 */
function checkButtonVisible(divDeleteButton, parentDiv, visibleType) {
	parentObj = d.getElementById(parentDiv);
	if(null == parentObj) {
		return;
	}
	var countDiv = parentObj.getElementsByTagName('div').length;

	if (0 != countDiv) {
		if (!visibleType) {
			$(divDeleteButton).style.display = 'block';
		} else {
			$(divDeleteButton).style.display = visibleType;
		}
	} else {
		$(divDeleteButton).style.display = 'none';
	}

}

// ustawiamy id albumu jesli jest by nie przekazywac za kazdym razem
// podczas zmiany materialu w albumie
var albumId = 0;

/**
 * getComments zwraca za pomoca funkcji ajaxowej liste komentarzy danego typu
 * 
 * @param int type    - typ komentarza:
 *                      1 - komentarze do materialu
 *                      3 - komentarze do profilu
 *                      4 - komentarze do pojedynku
 * @param int id      - id materialu lub uzytkownika
 * @param string view - widok z ktorego weszlismy
 * @param int mType   - type materialu lub 0 jesli komentarze dotyczza profilu
 * @param int aid     - id albumu lub 0 jesli ogladamy material nie w albumie
 * @param int page    - strona wynikow w liscie komentarzy domyslnie 1
 */
function getComments(type, id, view, mType, aid, page) {

	if (aid) {
		albumId = aid;
	}
	var idName = getCommentName(type);
	var divInfo = $('comments');
	
	if (divInfo == null) {
		return;
	}
	
	var str = 'komentarze.html?'+idName+'='+id+'&page='+page+'&view='+view+'&mtype='+mType+'&aid='+albumId;
	divInfo.innerHTML = '<br /><br /><br /><br />Trwa pobieranie komentarzy...<br /><br /><br /><br />';
	WP.ajax.get({ url: str, 'onSuccess':function(ax) { divInfo.innerHTML = ax.text; }});
}

/**
 * addCommentForm wyswietla za pomoca funkcji ajaxowej formularz
 * umozliwiajacy komentowanie uzytkownika i materialu
 * 
 * @param int type    - typ komentarzy
 *                      1 - materialow
 *                      3 - usera
 * @param int id      - id materialu lub uzytkownika
 * @param string view - widok z ktorego weszlismy
 * @param int mType   - typ materialu lub 0 jesli komentujemy uzytkownika
 */
function addCommentForm(type, id, view, mType) {
	var idName = getCommentName(type);
	var divInfo = $('comments');
	
	if (divInfo == null) {
		return;
	}
	
	WP.ajax.get({ url: 'dodajkomentarz.html?'+idName+'='+id+'&view='+view+'&mtype='+mType+'&aid='+albumId, 'onSuccess':function(ax) { divInfo.innerHTML = ax.text; }});
}

/**
 * addComment za pomoca funkcji ajaxowej wysyla postem formularz do dodawania opini
 * 
 * @param int type    - typ komentarza
 *                      1 - materialu
 *                      3 - uzytkownika
 * @param int id      - id materialu lub uzytwkonika
 * @param int ownerId - jesli komentujemy uzytkownika to jest to jego id,
 *                      jesli komentujemy material to jest to id wlasciciela materialu
 */
function addComment(type, id, ownerId, receiverId, receiverNick, thumb) {

	var idName  = getCommentName(type);
	var url     = 'dodajkomentarz.html?'+idName+'='+id;
	var divInfo = $('comments');

	if (divInfo == null) {
		return;
	}

	var params = new Array();
	params['_action']	= 'addComment';
	params['ownerId']	= ownerId;
	params['title']		= $('inptTitle').value.replace(/&/g, "%26");
	params['comment']	= $('txtComment').value.replace(/&/g, "%26");
	params['view']		= $('inptView').value;
	
	params['receiverId']   = receiverId;
	params['receiverNick'] = receiverNick;
	params['thumb'] 	   = thumb;	
	
	if ($('inptName') && $('inptName').value) { params['name'] = $('inptName').value.replace(/&/g, "%26"); }
	if ($('inptEmail') && $('inptEmail').value) { params['email'] = $('inptEmail').value; }
	if ($('inptMType') && $('inptMType').value) { params['mtype'] = $('inptMType').value; }
	if (albumId) { params['aid'] = albumId; }

	WP.ajax.post({ url: url, params: params, 'onSuccess':function(ax) { divInfo.innerHTML = ax.text; }});
}

/**
 * getCommentName na podstawie typu komentarza pobiera nazwe dla id
 * 
 * @param int infoType - typ kometarzy
 */
function getCommentName(infoType) {
	var idName = '';
	switch(infoType) {
		case '1':
			idName = 'mid';
			break;
		case '2':
			idName = 'aid';
			break;
		case '3':
			idName = 'uid';
			break;
		case '4':
			idName = 'pid';
			break;
	}
	return idName;
}

function addCommentToModerate(id, type) {
	var answer = confirm(dictModerateConfirm);
	if (answer) {
		ajaxAction({'action':'addCommentToModerate', 'extraparam':',id,'+id+',type,'+type, 'funcAfter': function() { commentInfo(id);}});
	}
}

function commentInfo(id) {
	$('addCommToMod_'+id).style.display = 'none';
	$('addedCommToMod_'+id).style.display = 'block';
	$('commentsComm').innerHTML = ajaxResponse;
	showElement('commentsComm', 'block');
}


function commentIsModerated() {
	$('commentsComm').innerHTML = '<p>'+dictModerateSent+'.</p>';
	showElement('commentsComm', 'block');
}



function blockLink(showLink, hideLink) {
	$('actionComm').innerHTML = ajaxResponse;
	showElement('actionComm', 'block');
	/*hideElement('notifyFriend');
	hideElement('addToAlbum');*/
	hideElement('toModerate');
	changeVisibleDiv(showLink, hideLink, 'inline');
}


function addToFavourite(id, mtype) {
	ajaxAction({'action':'addToFavourite', 'extraparam':',actType,ajax,mid,'+id+',mtype,'+mtype, 'funcAfter': function() { blockLink('addToFavNoAct', 'addToFavAct');}});

	var cookie = readCookie('favMaterials');
	if (cookie) {
		cookie += ':' + id;
	} else {
		cookie = id;
	}
	setCookie('favMaterials', cookie, 7);
}


function addToModerate(id) {
	ajaxAction({'action':'addToModerate', 'extraparam':',actType,ajax', 'funcAfter': function() { blockLink('addToModNoAct', 'addToModAct');}});
	var cookie = readCookie('modMaterials');
	if (cookie) {
		cookie += ':' + id;
	} else {
		cookie = id;
	}
	setCookie('modMaterials', cookie, 7);
}

function addUserToModerate() {
	if ('' == document.sendToModerate.description.value) {
		alert('Podaj powód zgłoszenia.');
	} else if (10 > document.sendToModerate.description.value.length) {
		alert('Zbyt krótki opis powodu zgłoszenia.');
	} else {
		ajaxAction({'formName':'sendToModerate', 'funcAfter': function() { hideForm('userToModerate') }});
		$('actionComm').innerHTML = ajaxResponse;
		showElement('actionComm', 'block');
		changeVisibleDiv('addToModNoAct', 'addToModAct', 'inline');
	}
}

function addToModerateForm() {
	hideElement('actionComm');
	hideElement('notifyFriend');
	hideElement('addToAlbums');
	showElement('toModerate', 'block');
}


function addToModerate() {
	if ('' == document.sendToModerate.description.value) {
		alert(dictModerateMaterialGiveReason);
	} else if (10 > document.sendToModerate.description.value.length) {
		alert(dictReasonTooShort);
	} else {
		ajaxAction({'formName':'sendToModerate', 'funcAfter': function() { hideForm('toModerate') }});
		$('actionComm').innerHTML = ajaxResponse;
		showElement('actionComm', 'block');
		changeVisibleDiv('addToModNoAct', 'addToModAct', 'inline');
	}
}


function addToAlbumForm() {
	hideElement('actionComm');
	hideElement('notifyFriend');
	hideElement('toModerate');
	hideElement('addToDuel');
	showElement('addToAlbum', 'block');
}

function addToDuelForm() {
	hideElement('actionComm');
	hideElement('notifyFriend');
	hideElement('toModerate');
	hideElement('addToAlbum');
	showElement('addToDuel', 'block');
}

function addToAlbum() {
	ajaxAction({'formName':'materialToAlbums', 'funcAfter': function() { hideForm('addToAlbums') }});
}

function addToDuel() {
	ajaxAction({'formName':'materialToDuels', 'funcAfter': function() { hideForm('addToDuel') }});
}

function sendToFriendForm() {
	hideElement('actionComm');
	hideElement('addToAlbums');
	hideElement('toModerate');
	showElement('notifyFriend', 'block');
}


function sendToFriend() {
	ajaxAction({'formName':'sendEmailToFriend', 'funcAfter': function() { hideForm('notifyFriend') }});
	$('emailsParent').innerHTML = '';
	hideElement('delEm');
}


function hideForm(formName) {
	hideElement(formName);
	if('addToAlbums'!=formName)
		$('actionComm').innerHTML = ajaxResponse;
	showElement('actionComm', 'block');
}


function getComm(idCom, loginUrl) {
	/*hideElement('notifyFriend'); 	
	hideElement('addToDuel');
	hideElement('toModerate');*/
	hideElement('addToAlbums');
	var com = '';
	switch(idCom) {
		case 1:
			com = dictOptionAfterLogin+'. <a href="' + loginUrl + '">'+dictLogin+'</a>';
			break;
		case 2:
			com = dictNoAlbumsToAdd;
			break;
		case 3:
			com = dictMaterialAddedToModerate;
			break;
		case 4:
			com = 'Ten materiał już znajduje się w Twoich ulubionych.';
			break;
		case 5:
			com = dictNoDuelsToAdd;
			break;
	}

	$('actionComm').innerHTML = com;
	showElement('actionComm', 'block');
}

function showPlayList() {
	showElement('userPlayList', 'block');
	var cookie = readCookie('playList');
	if (cookie) {
		showElement('playListOpt', 'block');
	}
	showElement('hideListLink', 'block');
	hideElement('showListLink');
	setCookie('playListVisible', 'true', 30);
}


function hidePlayList() {
	hideElement('userPlayList');
	hideElement('playListOpt');
	hideElement('hideListLink');
	showElement('showListLink', 'block');
	setCookie('playListVisible', 'false', 30);
}


/**
 * changeVisibleDiv 	ukrywa/pokazuje podane w parametrach divy
 * 			oraz czysci pola typu input w ukrywanym divie
 * 
 * @param showDivId		- div do pokazania
 * @param hideDivId		- div do ukrycia
 * @param visibleType 	- styl jaki mamy przypisac dla odkrywanego diva 
 * 			  np.(block, inline) domyslnie block
 * @param clear 	- jesli ustawiony na true to czysci wszystkie inputy
 * 			  w ukrywanym elemencie
 */
function changeVisibleDiv(showDivId, hideDivId, visibleType, clear) {

	if (!visibleType) {
		$(showDivId).style.display = 'block';
	} else {
		$(showDivId).style.display = visibleType;
	}

	var hideDivObj = $(hideDivId);
	hideDivObj.style.display = 'none';

	if (true == clear) {
		clearInputsForm(hideDivId);
	}

	return false;
}


/**
 * showElement pokazuje element o podanym id
 * 
 * @param idElement  - id elementu do pokazania
 * @param type $type - okresla styl pokazywanego elementu
 */
function showElement(idElement, type) {
	$(idElement).style.display = type;
	return false;
}


/**
 * hideElement ukrywa element o podanym id
 * 
 * @param idElement id elementu do ukrycia
 */
function hideElement(idElement) {
	if('object' == typeof($(idElement))) {
		$(idElement).style.display = 'none';
	}
	return false;
}


/**
 * showElementIfTrue 	pokazuje/ukrywa element jesli dwie podane wartosci 
 * 										sa takie same
 * 
 * @param value1    - pierwsza wartosc
 * @param value2    - druga wartosc
 * @param idElement - id elementu do pokazania/ukrycia
 * @param type      - sposob pokazania
 */
function showElementIfTrue(value1, value2, idElement, type) {
	if (true == checkValue(value1, value2)) {
		showElement(idElement, type);
	} else {
		hideElement(idElement);
	}
	return false;
}


/**
 * setCookie ustawia cookie
 * 
 * @param name - nazwa
 * @param value - wartosc 
 * @param nDays - ilosc dni
 * @access public
 * @return 
 */
function setCookie(name,value,days) {
	var minutes = 1440 * days; // ilosc minut w podanych dniach 
	WP.cookie.set(name, value, WP.cookie.expire(minutes));
}

/**
 * readCookie czyta zawartosc cookie 
 * 
 * @param name $name 
 * @access public
 * @return 
 */
function readCookie(name) {
	return WP.cookie.get(name);
}

/**
 * eraseCookie - czysci cookie
 * 
 * @param string name - nazw cookie
 */
function eraseCookie(name) {
	WP.cookie.erase(name);
}

/**
 * unsetCookie usuwa cookie
 * potem to zmienie na jakas lepiej napisana narazie wystarczy 
 *
 * by pamietac! wykorzystane w usuwaniu cookie podczas dowiazywanie zrodel 
 * i copyrightow w galeriach
 * 
 * @param name   - nazwa cookie
 * @param path   - sciezka
 * @param domain - domena
 */
function unsetCookie(name) {
	WP.cookie.erase(name);
}

function scrollingList(divParent, actElement) {

	if (null == actElement) {
		return;
	}

	var element = $(actElement);

	var div = $(divParent);

	var parentElement = element.offsetParent;

	var elementY = 0;
	while (element != null) {
		elementY += element.offsetTop;
		element = element.offsetParent;
	}
	element = div;
	while (element != null) {
		elementY -= element.offsetTop;
		element = element.offsetParent;
	}

	elementY -= 85;

	div.scrollTop = Math.max(0, elementY);
}

function checkMaterialsInPlayList() {

	var	cookie = readCookie('playList');

	if (cookie) {
		var materials = cookie.split(',');

		for (var i=0; i<materials.length; i++) {

			var mid = materials[i];

			if ($('addToList_'+mid)) {
				// staly kod z urlem
				$('addToList_'+mid).style.background = 'url(http://i.wp.pl/a/i/wideohosting/ico_plus_g.gif) 10% 10% no-repeat';
			}
		}
	}
}


var ic = new Array();

for(var i=0;i<=5;i++) {
	ic[i]=new Image();
	// staly kod z urlem
	ic[i].src = 'http://i.wp.pl/a/i/funmobile/i/gw'+i+'.gif';
};

var cOb=new Array();
var timer;

function rOv(obj, evt) {
	if(!cOb[obj.name])
		cOb[obj.name]=obj.src;

	if(document.all && !window.opera)
		evt=event;

	on=getM(getCCWT(evt).x);
	obj.style.cursor="pointer";
	
	if (document[obj.name].src != ic[on].src) {
		document[obj.name].src = ic[on].src;
	}
}


function rOf(obj) {
	if(cOb[obj.name]) {
		obj.src=cOb[obj.name];
	}
}


var markCount = 0;
var actMark = 0;

function rOc(obj,evt, id, mcCount, markFloat) {
	if (document.all && !window.opera) {
		evt=event;
	}

	markCount    = mcCount + 1;
	on   = getM(getCCWT(evt).x);
	form = $('votingForm');

	var cookie = readCookie('voting');
	if (cookie) {
		cookie += ':' + id + '=' + on;
	} else {
		cookie = id + '=' + on;
	}
	setCookie('voting', cookie, 7);
	form.mark.value = on;

	actMark = Math.ceil((markFloat * (markCount-1) + on) / markCount);
	$('actVote').src = ic[actMark].src
	$('imgVoteBlock').src = ic[on].src;
// 	$('imgVoteBlock').show();
	showElement('imgVoteBlock', 'inline');
	$('imgVote').hide();
	
	//changeVisibleDiv('imgVoteBlock', 'imgVote', 'inline');
	$('actMarcCount').innerHTML = '[ ' + markCount + ' glosów ]';
	ajaxAction({'formName':'votingForm'});
}


function getM(objMX) {
	on=0;
	if(objMX>=0 && objMX<=13) on=1;
	if(objMX>=14 && objMX<=25) on=2;
	if(objMX>=26 && objMX<=39) on=3;
	if(objMX>=40 && objMX<=52) on=4;
	if(objMX>=53 && objMX<=67) on=5;
	return on;
}


function getCCWT(evt) {
	var coords = { x: 0, y: 0};
	if(document.all && !window.opera) {
		evt = window.event;
		coords.x=evt.offsetX;
		coords.y=evt.offsetY;
	} else {
		var Element=evt.target;
		var cTLeft=0;
		var cTTop=0;
		while (Element.offsetParent) {
			cTLeft+=Element.offsetLeft; 
			cTTop+=Element.offsetTop;
			Element = Element.offsetParent ;
		}
		coords.x=evt.pageX-cTLeft;
		coords.y=evt.pageY-cTTop;
	}
	return coords;
}

/**
 * addSimpleItem Funkcja dodaje nowy element do elementu rodzica.
 * Umozliwia odczytanie i zapis tylko jednego pola (input lub select)
 * Nowy element zawiera uryte pole z danymi potrzebnymi do zapisu do BD,
 * checkbox wraz z wygenerowanym opisem umozliwiajacy usuniecie elementu
 * 
 * @param parentDiv    - element do ktorego dodajemy nowe elementy
 * @param childDiv     - nazwa elementu dodawanego (podstawa nazwy do ktorego 
 *                       zostanie doklejony identyfikator)
 * @param hidName      - nazwa elementu ukrytego (zawiera dane potrzebne do
 *                       zapisu do BD)
 * @param cbxName      - nazwa checkboxa ktory ma zostac dodany do nowego elementu
 *                       by umozliwic usuniecie dodanego elementu
 * @param newElementId - id elementu z ktorego pobierana zostaje wartosc do dodania
 * @param typeElement  - typ elementu z ktorego odczytamy wartosc (input, select)
 * @param typeCheck    - typ sprawdzania
 * @param divDeleteButton - id buttonu do usuwania elementow
 */
function addSimpleItem(parentDiv, childDiv, hidName, cbxName, newElementId, typeElement, typeCheck, divDeleteButton) {

	var inputName = hidName + '[New][]';

	var value = _getValue(newElementId);
	var text = ' ' + _getText(newElementId, typeElement);

	if (!value) {
		alert(dictCantAddNewElem);
		return false;
	}

	if (typeCheck) {
		switch (typeCheck) {
			case 'email':
			if (false == checkEmail(value)) {
				alert(dictIncorrectEmail);
				return false;
			}
			break;
		}
	}

	if (true == _checkElementExist(parentDiv, cbxName, text)) {
		alert(dictElementExists);
		return false;
	}

	var count = _countAddedDiv(parentDiv, childDiv);

	var newDivId = _createChildDiv(parentDiv, childDiv, count);

	_addHiddenValue(newDivId, inputName, value);

	_addCheckbox(newDivId, cbxName, count);

	_addDescription(newDivId, text);

	checkButtonVisible(divDeleteButton, parentDiv, 'block');

	return true;
}


/**
 * removeSimpleItem usuwa element wskazany za pomoca parametru childDiv
 * z nadrzednego elementu rodzica podanego w parametrze parentDiv. 
 * Usuwa te elementy, ktorych checkboxy o nazwie przekazanej w parametrze 
 * cbxName sa zaznaczone. Pobiera z nich wartosc i dopisuje do ukrytej tablicy 
 * elementy do usuniecia z BD.
 * 
 * @param parentDiv       - element glowny z ktorego usuwamy elementy
 * @param childDiv        - podstawa nazwy elemntu do usniecia (do niej zostanie 
 *                          doklejony, pobrany identyfikator z zaznaczonych checkboxow
 *                          i na tej podstawie zostana usuniete elementy)
 * @param cbxName         - nazwa checkboxow do sprawdzenia
 * @param deleteArrayName - nazwa tablicy do ktorej dopisujemy usuniete elementy
 */
function removeSimpleItem(parentDiv, childDiv, cbxName, deleteArrayName, divDeleteButton) {

	var removeArray = new Array();
	var j = 0;

	var parentObj = $(parentDiv);

	var inputsObj = parentObj.getElementsByTagName('input');

	for (i=0; i<inputsObj.length; i++) {
		if (inputsObj[i].getAttribute('type') == 'checkbox' && 
				inputsObj[i].getAttribute('name') == cbxName && 
				inputsObj[i].checked == true) {

			var value = inputsObj[i].getAttribute('value');

			if (!isNaN(value)) {
				_addHiddenValue(parentDiv, deleteArrayName, value);
			}

			var divId = childDiv + value;

			var removeDiv = $(divId);
			removeArray[j] = removeDiv;
			j += 1;

		}
	}

	for (k=0; k<removeArray.length; k++) {
		rem = parentObj.removeChild(removeArray[k]);
	}

	checkButtonVisible(divDeleteButton, parentDiv, 'block');

	return false;
}

/**
 * clearInput - funkcja czysci inputa o podanym w parametrze id
 * 
 * @param idInput - id inputa ktory ma zostac wyczyszczony 
 */
function clearInput(idInput) {
	$(idInput).value = '';
	return false;
}


/**
 * _getValue Funkcja pobiera vartosc danego elementu 
 * 
 * @param idElement - id elementu
 */
function _getValue(idElement) {
	return $(idElement).value;
}


/**
 * _getText Funkcja pobiera wartosc tekstowa wskazanego elementu
 * 
 * @param idElement   - id elementu z ktorego pobieramy opis
 * @param elementType - typ elementu
 */
function _getText(idElement, elementType) {
	var text = '';
	var elementObj = $(idElement);

	if ('select' == elementType) {
		var selInd = elementObj.selectedIndex;
		text = elementObj[selInd].text;
	} else if ('checkbox' == elementType) {
		alert(elementObj.nextSibling.nodeValue);
	} else {
		text = elementObj.value;
	}
	return text;
}

/**
 * checkEmail funkcja sprwadza poprawnosc adresu email 
 * 
 * @param value - adres email
 * @return boolen
 */
function checkEmail(value) {
	var reg = new RegExp("[^@]{1,}[@]{1}[^@.]{1,}[.]{1}[^@]{1,}","gi");
	if (null == value.match(reg)) {
		return false;
	}
	return true;
}

/**
 * _checkElementExist sprawdzenie czy dodawany element istnieje juz 
 * w nadrzednym elemnecie podanym jako parentDiv
 * 
 * @param parentDiv - element glowny w ktorym umieszczamy nowe elementy
 * @param cbxNam    - nazwa checkboxa
 * @param value     - wartosc
 */
function _checkElementExist(parentDiv, cbxName, value) {

	var prtObj = $(parentDiv);
	var inputsObj = prtObj.getElementsByTagName('input');

	for (i=0; i<inputsObj.length; i++) {
		if (inputsObj[i].getAttribute('type') == 'checkbox' && 
				inputsObj[i].getAttribute('name') == cbxName) {
			var testValue = inputsObj[i].nextSibling.nodeValue;
			if (testValue == value) {
				return true;
			}
		}
	}
	return false;
}

/**
 * _countAddedDiv funkcja zwraca ilosc dodanych div-ow (dzieci) do diva rodzica.
 * Podczas pierwszego dodania dziecka tworzy ukryty input o wartosci 1
 * a podczas kolejnych zwieksza jego wartosc o jeden
 *  
 * @param parentDiv - id rodzica
 * @param childDiv  - podstawa nazwy elemntow dodawanych
 */
function _countAddedDiv(parentDiv, childDiv) {

	var count = 0;
	counterId = childDiv + 'CountNewDiv';

	if (!$(counterId)) {
		var parentObj = $(parentDiv);
		var newInput = document.createElement('input');
		newInput.setAttribute('type', 'hidden');
		newInput.setAttribute('id', counterId);
		newInput.setAttribute('value', 1);
		parentObj.appendChild(newInput);
		count = 1;
	} else {
		var count = parseInt($(counterId).value) + 1;
		$(counterId).value = count;
	}

	return count;
}

/**
 * _createChildDiv tworzy w elemencie rodzica kolejny element dziecko 
 * z unikalnym id podanym jako parametr count
 * 
 * @param parentDiv - id rodzica do ktorego dodajemy element
 * @param childDiv  - nazwa dodawanego elementu
 * @param count     - identyfikator
 */
function _createChildDiv(parentDiv, childDiv, count) {

	var newDivId = childDiv + 'New' + count;

	var parentObj = $(parentDiv);

	var newDiv = document.createElement('div');
	newDiv.setAttribute('id', newDivId);
	parentObj.appendChild(newDiv);

	return newDivId;
}

/**
 * _addHiddenValue dodaje do elementu dziecka ukryty element hidden
 * zawierajacy dane do dodanie do BD.
 * 
 * @param divId     - id elementu
 * @param inputName - nazwa ukrytego elementu zawierajacego dane do dodania
 * @param value     - wartosc do dodania
 */
function _addHiddenValue(divId, inputName, value) {

	var newDivObj = $(divId);

	var newInput = document.createElement('input');
	newInput.setAttribute('type', 'hidden');
	newInput.setAttribute('name', inputName);
	newInput.setAttribute('value', value);
	newDivObj.appendChild(newInput);

	return false;
}


/**
 * _addCheckbox dodaje checkbox do elementu dziecka ktory umozliwia usuniecie
 * dodanego elementu
 * 
 * @param newDivId - id elementu dziecka
 * @param cbxName  - nazwa checkboxa
 * @param count    - identyfiaktor
 */
function _addCheckbox(newDivId, cbxName, count) {

	var newDivObj = $(newDivId);

	var val = 'New' + count;

	var newInput = document.createElement('input');
	newInput.setAttribute('type', 'checkbox');
	newInput.setAttribute('name', cbxName);
	newInput.setAttribute('value', val);
	newDivObj.appendChild(newInput);

	return false;
}


/**
 * _addLabel funkcja dodaje label do checkboxa 
 * 
 * @param newDivObj 
 * @param idName 
 * @param text 
 */
function _addLabel(newDivObj, idName, text) {

	var newLabel = document.createElement('label');
	newLabel.setAttribute('for', idName);
	newLabel.innerHTML = text;
	newDivObj.appendChild(newLabel);

	return false;
}


/**
 * _addDescription dodaje opis do dodanego wczesniej checkboxa 
 * 
 * @param newDivId - id elementu dziecka 
 * @param text     - tekst do dodania
 */
function _addDescription(newDivId, text) {

	var newDivObj = $(newDivId);

	var textNode = document.createTextNode(text);
	newDivObj.appendChild(textNode);

	return false;
}

//sprawdzenie czy system to windows
function isWin() {
	return WP.isWin;
}


/**
 * checkAllMatAndAdd - zaznacza wszystkie materialy i zapisuje do sesji
 * 
 * @param string formName - nazwa formularza
 */
function checkAllMatAndAdd(formName, matSes) {

	changeVisibleDiv('uncheck','check','inline');

	var extraparam = ',varName,'+matSes+',act,add';

	var form = document.forms[formName];
	var urlRawparams = '';
	for (i=0; i<form.length; i++) {
		if ('checkbox' == form[i].type) {
			form[i].checked = true;
			if(urlRawparams.length) {
				urlRawparams += '&';
			} else {
				urlRawparams += '?';
			}
			urlRawparams += form[i].name + '=' + form[i].value;
		}
	}

	ajaxAction({'view':'addtosession.html'+urlRawparams, 'extraparam':extraparam});
}


/**
 * uncheckAllMatAndRem - odzaznacza wszystkie materialy i zapisuje do sesji
 * 
 * @param string formName - nazwa formularza 
 */
function uncheckAllMatAndRem(formName, matSes) {

	changeVisibleDiv('check','uncheck','inline');
	
	var extraparam = ',varName,'+matSes+',act,delete';

	var form = document.forms[formName];
	var urlRawparams = '';
	for (i=0; i<form.length; i++) {
		if ('checkbox' == form[i].type) {
			form[i].checked = false;
			if(urlRawparams.length) {
				urlRawparams += '&';
			} else {
				urlRawparams += '?';
			}
			urlRawparams += form[i].name + '=' + form[i].value;
		}
	}

	ajaxAction({'view':'addtosession.html'+urlRawparams, 'extraparam':extraparam});
}


/**
 * checkAll zaznacza wszystkie checkboxy 
 * 
 * @param string formName - nazwa formularza
 */
function checkAll(formName) {
	var form = document.forms[formName]
	for (i=0; i<form.length; i++) {
		if ('checkbox' == form[i].type) {
			form[i].checked = true;
		}
	}
}


/**
 * uncheckAll odznacza wszystkie checkboxy 
 * 
 * @param string formName - nazwa formularza
 */
function uncheckAll(formName) {
	var form = document.forms[formName];
	for (i=0; i<form.length; i++) {
		if ('checkbox' == form[i].type) {
			form[i].checked = false;
		}
	}
}


/**
 * uncheckAllMaterials - odzaznacza wszystkie materialy
 * 
 * @param string formName - nazwa formularza 
 */
function checkAllMaterials(formName) {
	changeVisibleDiv('uncheck','check','inline');
	checkAll(formName);
}


/**
 * uncheckAllMaterials - odzaznacza wszystkie materialy
 * 
 * @param string formName - nazwa formularza 
 */
function uncheckAllMaterials(formName) {
	uncheckAll(formName);
	changeVisibleDiv('check','uncheck','inline');
}

function show(id) {
	$(id).show();
}


function showDisp(id, howdisplay) {
    var obj = $(id);
    obj.style.display = howdisplay;
}


function hide(id) {
	$(id).hide();
}


function showInParent(div) {
	parent.$(div).show();
}


function hideInParent(div) {
	parent.$(div).hide();
}

function acceptContent(backUrl, type, id) {
	if (true == $('remember').checked) {
		setCookie('eroticContent', 'accept', '100');
	} else {
		var cookie = readCookie(type+'Accepted');
		if (cookie) {
			cookie += ':' + id;
		} else {
			cookie = id;
		}
		setCookie(type+'Accepted', cookie, 100);
	}
	location = backUrl;
}


function resign(backUrl, type, id) {
	if (true == $('remember').checked) {
		setCookie('eroticContent', 'block', '100');
	} else {
		var cookie = readCookie(type+'Blocked');
		if (cookie) {
			cookie += ':' + id;
		} else {
			cookie = id;
		}
		setCookie(type+'Blocked', cookie, 100);
	}
	if(-1 != backUrl.indexOf('?')) {
		location=backUrl+'&accept=0';
	} else {
		location=backUrl+'?accept=0';
	}
}

function chooseCover(imgId, imgUrl) {
	$('audioCoverImgUrl').value = imgUrl;
	$('imgThumb').src = imgUrl;
	hideElement('popUpContainer');
}

function changePage(targetUrl, extraparam) {
	getUrl = targetUrl+extraparam+'&ax=1';
	$('materialsContainer').innerHTML = 'Pobieranie materiałów...';
	WP.ajax.get({
		url: getUrl,
		onSuccess: function(ajax){
			$('materialsContainer').innerHTML = ajax.text;
		}
	});
}


// parametr pozwala zmieniac polozenie diva
var getXY = true;

function getMouseXYClick(e) {
	getMouseXY(e);
	getXY = false;
}

function getMouseXY(e) {

	if (false == getXY) {
		return true;
	}

	var scroll = getScrollXY();

	if (IE) {
		if (event == null) {
			return;
		}

		tempX = event.clientX + scroll[0];
		tempY = event.clientY + scroll[1];
	} else {
		if (e == null) {
			return;
		}

		tempX = e.pageX;
		tempY = e.pageY;
	}

	if (tempX < 0) {
		tempX = 0;
	}

	if (tempY < 0) {
		tempY = 0;
	}


	if (1 == dispInfoParam) {
	} else if (2 == dispInfoParam) {
		tempX = tempX - 270;
	} else if (3 == dispInfoParam) {
		tempY = tempY - 210;
	} else if (4 == dispInfoParam) {
		tempX = tempX - 270;
		tempY = tempY - 210;
	}

	if ((tempY+270) > (screenY+scroll[1])) {
		//              tempY = screenY + scroll[1] - 270;
	}

	var obj = document.getElementById('info');
	if (obj == null) {
		return false;
	}

	obj.style.top = tempY+'px';
	obj.style.left = tempX+'px';

	return true;
}

function getHint(hintVal) {
	getXY = true;
	dispInfoParam = 2;
	var divInfo = $('info');
	if (divInfo == null) {
		return;
	}

	divInfo.innerHTML = '<p class="hintText">'+hintVal+'</p>';
	divInfo.style.display = 'block';
}

function closeHint() {
	getXY = false;
	var divInfo = $('info');
	if (divInfo == null) {
		return;
	}
	divInfo.innerHTML = '';
	divInfo.style.display = 'none';
}

function editProfile(form) {

	$('formAction').value = 'userEdit';
	form.submit();

}

function getAlbumContent(aid, mid, mtype, seq) {
	if (seq <= 0) {
	    seq = 0;
	}
	
	var extraparam = ',aid,'+aid+',mid,'+mid+',mtype,'+mtype+',seq,'+seq;
	ajaxAction({'view':'album_prezentacja.html', 'extraparam':extraparam, 'funcAfter': function() { setAlbumContent(mid, mtype); }});
}


function setAlbumContent(id, type) {
	mid = id;
	mtype = type;
	$('bxMatUz').innerHTML = ajaxResponse;
}

function dispN(n) {
        document.getElementById(n).style.display='none';

        if (null != document.getElementById('zwin'+n)) {
                document.getElementById('zwin'+n).style.display='none';
                document.getElementById('rozwin'+n).style.display='';
        }
        return false;
}

function dispY(n) {
        document.getElementById(n).style.display='';

        if (null != document.getElementById('zwin'+n)) {
                document.getElementById('zwin'+n).style.display='';
                document.getElementById('rozwin'+n).style.display='none';
        }
        return false;
}

function smallUploadNext() {
	var r = new String(Math.random()).substring (2, 11);
	document.getElementById('iframe_upload').src = 'uploadmulti.html?rand=' + r + '&isSmall=1';
	document.getElementById('material_desc').src = 'dodajmaterialmulti.html?rand=' + r;
	changeIframeSize('iframe_upload');
}

function addToAlbumClick(elm) {
	var newAlbumId = elm.value;
	if(elm.checked) {
		if(null != document.getElementById('newAlb'+newAlbumId)) {
			alert(dictElementExists);
			return false;
		} else if(null != document.getElementById('delAlb'+newAlbumId)) { // jesli zaznaczono taki predzej do usuniecia, to usuwamy stamtad
			document.getElementById('delAlb'+newAlbumId).parentNode.removeChild(document.getElementById('delAlb'+newAlbumId));
		} else {
			var parentObj = $('addAlbum');
			var newInput  = document.createElement('input');
			newInput.setAttribute('id', 'newAlb'+newAlbumId);
			newInput.setAttribute('value', newAlbumId);
			newInput.setAttribute('name', "T[album][New]["+newAlbumId+"]");
			newInput.setAttribute('type', 'hidden');
			parentObj.appendChild(newInput);
		}
	} else {
		if(null != document.getElementById('delAlb'+newAlbumId)) {
			alert(dictElementExists);
			return false;
		} else if(null != document.getElementById('newAlb'+newAlbumId)) { // jesli zaznaczono taki predzej do dodania, to usuwamy stamtad
			document.getElementById('newAlb'+newAlbumId).parentNode.removeChild(document.getElementById('newAlb'+newAlbumId));
		} else {
			var parentObj = $('addAlbum');
			var newInput  = document.createElement('input');
			newInput.setAttribute('id', 'delAlb'+newAlbumId);
			newInput.setAttribute('value', newAlbumId);
			newInput.setAttribute('name', "T[deleteAlbums]["+newAlbumId+"]");
			newInput.setAttribute('type', 'hidden');
			parentObj.appendChild(newInput);
		}
	}
}

function addToDuelClick(elm) {
	var newDuelId = elm.value;
	if(elm.checked) {
		if(null != document.getElementById('newDuel'+newDuelId)) {
			alert(dictElementExists);
			return false;
		} else {
			var parentObj = $('addDuel');
			var newInput  = document.createElement('input');
			newInput.setAttribute('id', 'newDuel'+newDuelId);
			newInput.setAttribute('value', newDuelId);
			newInput.setAttribute('name', "T[duel][New]["+newDuelId+"]");
			newInput.setAttribute('type', 'hidden');
			parentObj.appendChild(newInput);
		}
	} else {
		alert('Nie możesz usuwać materiałów z pojedynku.\nMożesz jedynie usunąć cały pojedynek.');
		elm.checked = true;
	}
}

/**
 * removeConfirm - potwierdzenie usuniecia
 * 
 * @param string formName - nazwa formularza
 * @param string message - komunikat
 */
function removeConfirm(formName, message) {
	var answer = confirm(message);
	if (answer) {
		document.forms[formName].submit();
	}
}

/**
 * changeDisplayAlbums zmienia dlugosc listy albumow i zapamietuje wybor w cookie
 * 
 * @param uid $uid - id uzytkownika
 * @param value $value - zaznaczony/odznaczony checkbox
 */
function changeDisplayAlbums(uid, value) {
	if (value) {
		var url = 'moje_albumy.html?uid='+uid+'&ps=20';
		setCookie('albPageSize', '20', '30');
	} else {
		var url = 'moje_albumy.html?uid='+uid+'&ps=5';
		setCookie('albPageSize', '5', '30');
	}
	location.href=url;
}

function removeAlbum(id) {
	var answer = confirm('Czy na pewno chcesz usunąć ten album? Materiały w nim zawarte nie zostaną usunięte.');
	if (answer) {
		var objForm = document.forms['albumsList'];
		var hid = document.createElement('input');
		hid.setAttribute('type', 'hidden');
		hid.setAttribute('name', 'album[]');
		hid.setAttribute('value', id);
		objForm.appendChild(hid);
		objForm.submit();
	}
}

function useGal(type) {
	var galleryId = document.getElementById('galleryRow');
	var elementsList = galleryId.getElementsByTagName("span");
	var listLength = elementsList.length;
	if (type == 'prev') {
		var temp = elementsList[0].innerHTML;
		for (i=0; i<= listLength-1; i++ ) elementsList[i].innerHTML = (i==listLength-1)?temp:elementsList[i+1].innerHTML;
	} else {
		var temp = elementsList[listLength-1].innerHTML;
		for (i=listLength-1; i>=0 ; i-- ) elementsList[i].innerHTML = (i==0)?temp:elementsList[i-1].innerHTML;
	}
}


function delMaterial(matId, mType) {
	var answer = confirm('Czy na pewno chcesz usunąć ten materiał?');
	if (answer) {
		var objForm = document.createElement('form');
		objForm.setAttribute('action', '');
		objForm.setAttribute('method', 'post');
		var hid = document.createElement('input');
		hid.setAttribute('type', 'hidden');
		hid.setAttribute('name', 'delete');
		hid.setAttribute('value', 1);
		objForm.appendChild(hid);
		var hid1 = document.createElement('input');
		hid1.setAttribute('type', 'hidden');
		hid1.setAttribute('name', 'material[' + matId + ']');
		hid1.setAttribute('value', mType);
		objForm.appendChild(hid1);
		var hid2 = document.createElement('input');
		hid2.setAttribute('type', 'hidden');
		hid2.setAttribute('name', '_action');
		hid2.setAttribute('value', 'userMaterialsEdit');
		objForm.appendChild(hid2);
		var hid3 = document.createElement('input');
		hid3.setAttribute('type', 'hidden');
		hid3.setAttribute('name', 'm');
		hid3.setAttribute('value', '1');
		objForm.appendChild(hid3);
		document.getElementsByTagName('body')[0].appendChild(objForm);
		objForm.submit();
	}
}
