/* 
 * Funkcja pobiera i wyświetla wyniki sondy SMS, 
 * na wywołanym elemencie jQuery. Jeśli w linku
 * znajdzie się 'plebiscites' do pracy rusza nowy zestaw funkcji.
 * 
 * Parametry:
 * url - adres url serwisu dostarczającego danych z sondą w formacie JSON
 * opt/settings - tablica asocjacyjna, opcje wyświetlania
 * 
 * type - Typ wykresu - poziomy (horizontal) lub pionowy (vertical)
 * hideMainTitle - Ustaw na true, aby ukryć tytuł głosowania
 * hideMainCount - Ustaw na true, aby ukryć pole z sumą wszystkich głosów
 * hideMainGenerationDate - Ustaw na true, aby ukryć
 * hideCandidateNumber - Ustaw na true, aby ukryć nawias, z numerem kandadata
 * hideCandidateDescription - Ustaw na true, aby ukryć pole description przy nazwie kandadata
 * hidePercent - Ustaw na true, aby ukryć procent głosów oddanych na kandydata
 * hideCount - Ustaw na true, aby ukryć liczbę głosów oddanych na kandydata
 * hidePoints - Sondy Tak/Nie, ustaw na true, aby ukryć punkty kandydata (domyślnie ukryte)
 * hideYesNoSum - Sondy Tak/Nie, ustaw na true, aby ukryć sumę głosów oddanych na kandydata
 * hideSmsNumber - Ustaw na true, aby ukryć numer telefonu, pod króry wysyłamy SMS
 * hideSmsContent - Ustaw na true, aby ukryć treść SMSa do wysłania
 * hideBar - Ustaw na true, aby ukryć pasek obrazujący oddaną liczbę głosów
 * separatingChar - Znak oddzielajacy prefiks od sufiksu do głosowania
 * pollBarImgSrc - Ścieżka do obrazka z paskiem głosowania, tło pod paskiem zdefiowane jest w pliku CSS
 * pollBarImgSrcYes - Sondy Tak/Nie - tło pod paskiem głosów na tak 
 * pollBarImgSrcNo - Sondy Tak/Nie - tło pod paskiem głosów na nie
 * pollBarImgSrcEmpty - Sondy Tak/Nie - tło pod paskiem głosów, gdy żadne głosy nie zostały oddane
 * keywordYes - Stała 'tak', napisane w ten sposób aby w przyszłości łatwiej było rozszerzyć sondy na inne opcje niż tak/nie 
 * keywordNo - Stała 'nie', napisane w ten sposób aby w przyszłości łatwiej było rozszerzyć sondy na inne opcje niż tak/nie
 * width - Szerokość boxu z sondą. Dla sond ze zdjęciami paski zmniejszane są automatycznie.
 * widthPhotos - Szerokość boxu z obrazkiem kandydata (suma margin, padding i width dla <img />)
 * disablePhotos - Ustaw na true, aby wyłączyć obrazki, niezależnie od tego, czy w panelu są dodane.
 * pollMiss - Ustaw na true, aby zamiast "Nr kandydata" sonda pokazywała napis "Nr kandydatki"
 * useCandidateLinks - Ustaw na true, aby paski z kandydatami były podlinkowane wartością pola "url" z JSON 
 */
$.fn.smsPoll = function(urlOrId, opt) {
	var url = buildUrl(urlOrId);
	var el=$(this); 
	el.pollPreloader(true);
    $.getJSON(url+"&callback=?",function(data){
    	var poll = '';
    	if (url.indexOf('m2a') > 0) { /* alt */
    		poll = processJSON(data, opt, url);
    	}
    	if (url.indexOf('encoding=utf8') < 0) {
    		poll = utf2iso(poll);
    	} 
        if (opt.formattingFunction != null) {
            if (typeof(opt.formattingFunction) == "function") {
                poll = opt.formattingFunction(poll);
            }
        }
        el.append(poll);
        el.pollPreloader(false);
        return;
    });
    el.pollPreloader(false);
    return;
};

/*
 * Zbuduj adres URL do statystyk M2A.
 * Funkcja przetwarza przełącznik grupy i opcji /grupa/ /opcja/
 * i zamienia na odpowiednie parametry URL).
 */
function buildUrl(param) {
	var url = null;
	if (param.indexOf('http') == 0) {
		/* zamień link do XML na link do JSON */
		param = param.replace('f=xml', 'f=json');
		param = param.replace('type=json', 'type=json');
		/* parametr jest linkiem */
		if (param.indexOf('json') < 0) {
			reportError('Not found json type in given link: ' + param);
			return null;
		}
		/* link do statystyk M2A*/                                
		var regexpLink = new RegExp('(http://.*m2a.pl/.*)');
		m = regexpLink.exec(param);
		if (m == null) {
			reportError('Incorrect link to stats service: ' + param + '. Correct link matches http://*m2a.pl/');
			return null;
		}
		url = m[1];
		var regexpGroup = new RegExp('/grupa/([A-Za-z0-9_ĄĆĘŁŃÓŚŹŻąćęłńóśźż]+)');
		var m = regexpGroup.exec(param);
		if (m != null) {
			url = url.replace(m[0], '&g=' + m[1]);
		}
		var regexpOption = new RegExp('/opcja/([A-Za-z0-9_ĄĆĘŁŃÓŚŹŻąćęłńóśźż]+)');
		var m = regexpOption.exec(param);
		if (m != null) {
			url = url.replace(m[0], '&k=' + m[1]);
		}
		return url;
	}
	reportError('Unnkown error in poll: ' + param);
	return null;
}

/*
 * Przetwarza plik JSON i zwraca wynik w postaci HTML.
 */
function processJSON(feed, opt, url) {
    var poll='';
	if (feed != null) {
        var settings = {
            type: "horizontal",
            hideMainTitle: false,
            hideMainCount: false,
            hideMainGenerationDate: false,
            hideCandidateNumber: false,
            hideCandidateDescription: false,
            hidePercent: false,
            hideCount: false,
            hidePoints: true,
            hideYesNoSum: false,
            hideSmsNumber: false,
            hideSmsContent: false,
            hideBar: false,
            separatingChar: '.',
            pollBarImgSrc: "/images/poll_bar.jpg",
            pollBarImgSrcYes: "/images/poll_bar_yes.jpg",
            pollBarImgSrcNo: "/images/poll_bar_no.jpg",
            pollBarImgSrcEmpty: "/images/poll_bar_empty.jpg",
            keywordYes: 'tak',
            keywordNo: 'nie',
            width: 280,
            widthPhotos: 70,
            disablePhotos: false,
            pollMiss: false,
            useCandidateLinks : false,
            formattingFunction: null
        };
        
        /* dodaj do tablicy "settings" opcje domyśle, jeśli ich nie zdefiniowano */
        jQuery.extend(settings, opt);
        
        /* rozwiazanie m2a dla grup */
    	if (url.indexOf('groups=true') > 0) {
            settings.hideSmsContent = true;
            settings.hideSmsNumber = true;      
    	}

        if (!settings.hideMainTitle) {
            poll += '<h3>' + feed.eventName + '</h3>';
        }
        if (feed.options != null) {
        	
        	var pollWithPhotos = false;
        	if (!settings.disablePhotos) {
        		pollWithPhotos = checkIfPollWithPhotos(feed.options);
        	}

            poll += '<ul>';
            if (settings.type == "vertical") {
                poll += '<li id="caption">Nr ';
                if (settings.pollMiss) {
                	poll += 'kandydatki';
                } else {
                	poll += 'kandydata'; 	
                }
                poll += '</li>';
            }
            $.each(feed.options, function(i,option) {
            	/* Sprawdź czy sonda jest typu TAK/NIE, za pomocą istnienia wariantów 'tak' i 'nie' z wagami 1 i -1 */
            	var optionYesNo = checkIfYesNoOption(feed, option, settings); 
               
                if (settings.type == "horizontal") {
                	if (optionYesNo == true) {
                    	/* sonda TAK/NIE */
                		poll += drawOptionYesNo(feed, option, settings, pollWithPhotos);
                	} else {
                    	/* sonda klasyczna - liczba głosów na daną opcję */
                		poll += drawOptionClassic(feed, option, settings, pollWithPhotos);
                	}
                } else if (settings.type == "vertical") {
                    /* sonda pionowa - serwisy ST */
                	poll += drawOptionSTVertical(feed, option, settings, i);
                } else if (settings.type == "horizontal subgroup") {
              		poll += drawOptionClassicWithSubgroup(feed, option, settings, pollWithPhotos);                
                }
            });
            poll += '</ul>';
        }
        
        if (!settings.hideMainCount || !settings.hideMainGenerationDate) {
            poll += '<p>';
            if (!settings.hideMainGenerationDate) {
                if (feed.generationDate != null) {
                    poll += 'Czas wygenerowania danych: ' + feed.generationDate + '<br />';
                }
            }
            if (!settings.hideMainCount) {
                if (feed.votesTotal != null) {
                    poll += '<span>Liczba wszystkich głosów: ' + feed.votesTotal + '</span>';
                }
            }
            poll += '</p>';
        }
    };
    return poll;
}

/*
 * Pobiera numer SMS na który mają być wysyłane głosy.
 */
function getSmsNumber(feed) {
    if (feed.gatePairs != null) {
    	if (feed.gatePairs[0] != null) {
    		if (feed.gatePairs[0].gate != null) {
    			return feed.gatePairs[0].gate;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera pierwszy prefix sms. Powinien występować zawsze.
 */
function getSmsPrefix(feed) {
    if (feed.gatePairs != null) {
    	if (feed.gatePairs[0] != null) {
    		if (feed.gatePairs[0].prefix != null) {
    			return feed.gatePairs[0].prefix;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera drugi prefix sms. 
 */
function getSmsSubprefix(feed) {
    if (feed.gatePairs != null) {
    	if (feed.gatePairs[0] != null) {
    		if (feed.gatePairs[0].subprefix != null) {
    			return feed.gatePairs[0].subprefix;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera treść sms do wysłania na daną opcję.
 */
function getSmsContent(feed, option, settings) {
	var smsContent = null;
	var prefix = getSmsPrefix(feed);
	if (prefix != null) {
		smsContent = prefix + settings.separatingChar;
		var subprefix = getSmsSubprefix(feed);
		if (subprefix != null) {
			smsContent += subprefix + settings.separatingChar;
		}
		smsContent += option.optionKeyword;
	}
	return smsContent;
}

/*
 * Pobiera liczbę głosów na opcję określoną słowem kluczowym variantKeyword.
 */
function getOptionVariantsVotesTotal(feed, option, settings, variantKeyword) {
	var votesTotal = -1;
	
	$.each(option.optionVariants, function(i,optionVariant) {
		if (optionVariant.variantKeyword == variantKeyword) {
			votesTotal = optionVariant.votesTotal;
		}
	});
	if (votesTotal < 0) {
		var id = feed.eventName + '/' + option.optionKeyword;
		reportError('Błąd konfiguracji sondy SMS ' + id + ': nie odnaleziono liczby głosów dla wariantu ' + variantKeyword);
	}
	return votesTotal;
}

/*
 * Funkcja sprawdza, czy sonda jest sondą typu tak/nie.
 * Powinna wtedy zawierać dokładnie dwie opcje głosowania - 'tak' i 'nie
 * (ew. czasem dodawana jest opcja dla niepoprawnie oddanych głosów, ale jest ona
 * przed użytkownikami ukryta).
 */
function checkIfYesNoOption (feed, option, settings) {
	var foundYes = false;
	var foundNo = false;
	var counter = 0;
	
	if (option.optionVariants == null)
		return false;

	var id = feed.eventName + '/' + option.optionKeyword;
	$.each(option.optionVariants, function(i,optionVariant) {
		var sufix = optionVariant.variantKeyword;
		var factor = optionVariant.variantFactor;
		
		if ((sufix != null) && (factor != null)) {
			sufix = sufix.toLowerCase();
			factor = parseFloat(factor);
			
			if (sufix == 'tak') {
				if (foundYes) {
					reportError('Błąd konfiguracji sondy SMS ' + id + ': podwójna opcja tak. Sprawdź zgodność ustawień sondy z dokumentacją.');
					return false;
				}
				if (factor != 1) {
					reportError('Błąd konfiguracji sondy SMS ' + id + ': opcja na tak powinna zawierać współczynnik równy 1. Sprawdź zgodność ustawień sondy z dokumentacją.');
					return false;
				}
				foundYes = true;
				settings.keywordYes = optionVariant.variantKeyword;
			}
			if (sufix == 'nie') {
				if (foundNo) {
					reportError('Błąd konfiguracji sondy SMS ' + id + ': podwójna opcja nie. Sprawdź zgodność ustawień sondy z dokumentacją.');
					return false;					
				}
				if (factor != -1) {
					var id = feed.eventName + '/' + option.optionKeyword;
					reportError('Błąd konfiguracji sondy SMS ' + id + ': opcja na nie powinna zawierać współczynnik równy -1. Sprawdź zgodność ustawień sondy z dokumentacją.');
					return false;
				}
				foundNo = true;
				settings.keywordNo = optionVariant.variantKeyword;
			}
		}
		counter++;
	});
	if (counter > 0) {
		/* trzy - ponieważ każda opcja tworzy domyślny wariant dla smsów o błędnie rozpoznanej treści */
		if (counter > 3) {
			reportError('Błąd konfiguracji sondy SMS ' + id + ': sonda tak/nie powinna posiadać dokładnie dwa warianty nazwane "tak" i "nie". Sonda tradycyjna nie powinna posiadać żadnych wariantów. Sprawdź zgodność ustawień sondy z dokumentacją.');
			return false;
		}
		if (counter > 1) {
			if ((foundYes == false) || (foundNo == false)) {
				reportError('Błąd konfiguracji sondy SMS ' + id + ': sonda tak/nie powinna posiadać dokładnie dwa warianty nazwane "tak" i "nie". Sprawdź zgodność ustawień sondy z dokumentacją.');
				return false;
			} else {
				return true;
			}
		}
	}
	return false;
}

/*
 * Draw image attachments for option.   
 */
function drawOptionPhoto(feed, option, settings) {
	var pollPhoto = '';
	if (!settings.disablePhotos) {
		$.each(option.optionAttachments, function(i,optionAttachment) {
			if (optionAttachment.type == 2) { /* 2=image attachment */
				if (optionAttachment.url != null) {
					if (optionAttachment.url.substr(0, 7) == 'http://') {
						pollPhoto = '<img src="' + optionAttachment.url + '" class="smsPollPhoto" alt="kandydat" />';
					}
				}
			}
		});
	}
	return pollPhoto;
}

/*
 * Checks if any option contains photo attachment.
 */
function checkIfPollWithPhotos(options) {
	var pollWithPhotos = false;
	$.each(options, function(i,option) {
		$.each(option.optionAttachments, function(i,optionAttachment) {
			if (optionAttachment.type == 2) { /* 2=image attachment */ 
				if (optionAttachment.url != null) {
					if (optionAttachment.url.substr(0, 7) == 'http://') {
						pollWithPhotos = true;
					}
				}
			}
		});
	});
	return pollWithPhotos;
}

/*
 * Get url of attachment
 */
function getOptionUrl(feed, option, settings) {
	var optionUrl = null;
	if (settings.useCandidateLinks) {
		$.each(option.optionAttachments, function(i,optionAttachment) {
			if (optionAttachment.type == '') { /* =just url attachment */
				if (optionAttachment.url != null) {
					if (optionAttachment.url.substr(0, 7) == 'http://') {
                        optionUrl = optionAttachment.url;
					}
				}
			}
		});
	}
	return optionUrl;
}

/*
 * Przelicza szerokość paska (jeśli sonda zawiera obrazki - pasek będzie zmniejszony).
 */
function getPollBarWidth(pollWithPhotos, settings) {
	if (pollWithPhotos) {
		if (settings.width - settings.widthPhotos > 0) {
			return settings.width - settings.widthPhotos;
		}
	}
	return settings.width;
}
/* 
 * Sonda - wyświetla liczbę głosów oddanych na daną opcję. 
 */
function drawOptionClassic(feed, option, settings, pollWithPhotos) {
	var poll = '';
	var barWidth = getPollBarWidth(pollWithPhotos, settings);
	poll += '<li';
    var url = getOptionUrl(feed, option, settings);
    if (url != null) {
   		poll += ' onclick="window.location=\'' + url + '\';"';
    }
    poll += '>';
	poll += drawOptionPhoto(feed, option, settings);
	poll += '<div style="width: ' + barWidth + 'px">';
	poll += '<p>';
    poll += '<strong>' + option.optionName;
	if (!settings.hideCandidateDescription) {
		poll += ' ' + option.optionDescription;
	}
	poll += '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (' + option.optionKeyword + ')';
    }
    poll += '</p>';
    if (!settings.hideBar) {
        if (feed.topVotes > 0 && option.votesTotal > 0) {
        	/* height obrazka zaszyte w stylach */
        	var width = Math.round(option.votesTotal / feed.topVotes * barWidth);
        	poll += '<img src="' + settings.pollBarImgSrc + '" width="' + width + '" alt="sonda" /><br />'; 
        }
    }
    poll += '<span>';
    if (!settings.hidePercent) {
    	if (feed.votesTotal > 0) {
	    	var percent = Math.round(option.votesTotal * 100 / feed.votesTotal);
	        poll += '<strong>' + percent + '%' + '</strong>, ';
    	}
    }
    if (!settings.hideCount) {
        poll += option.votesTotal + ' głos';
        /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
        poll += getPolishNumeralEnding(parseInt(option.votesTotal));
        poll += ', '; 
    }
    poll += '<span>';
    if (!settings.hideSmsNumber || !settings.hideSmsContent) {
        poll += 'SMS';
        if (!settings.hideSmsNumber) {
        	var smsNumber = getSmsNumber(feed);
        	if (smsNumber != null) {
        		poll += ' pod nr <strong>' + smsNumber + '</strong>';
        	}
        }
        if (!settings.hideSmsContent) {
        	var smsContent = getSmsContent(feed, option, settings);
        	if (smsContent != null) {
        		poll += ' o treści <strong>' + smsContent + '</strong>';
        	}
        }
    }
    poll += '</span></span>';
    poll += '</div>';
    poll += '</li>';
    return poll;
}

/* 
 * Sonda Tak/Nie - wyświetla liczbę głosów pozytywnych i negatywnych 
 * oddanych na daną opcję. 
 */
function drawOptionYesNo(feed, option, settings, pollWithPhotos) {
	var poll = '';
	var barWidth = getPollBarWidth(pollWithPhotos, settings);
	poll += '<li';
    var url = getOptionUrl(feed, option, settings);
    if (url != null) {
   		poll += ' onclick="window.location=\'' + url + '\';"';
    }
    poll += '>';
	poll += drawOptionPhoto(feed, option, settings);
	poll += '<div style="width: ' + barWidth + 'px">';
    poll += '<p>';
    poll += '<strong>' + option.optionName + ' ' + option.optionDescription + '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (' + option.optionKeyword + ')';
    }
    poll += '</p>';
    poll += '<span>';

	var votesYes = getOptionVariantsVotesTotal(feed, option, settings, settings.keywordYes);
	var votesNo = getOptionVariantsVotesTotal(feed, option, settings, settings.keywordNo);
	var votesSum = votesYes + votesNo;
	var points = votesYes - votesNo;
	
    if (!settings.hideBar) {		
    	if ((barWidth > 0) && (votesSum > 0)) {
        	var widthYes = Math.round(votesYes / votesSum * barWidth);
        	var widthNo = barWidth - widthYes;
        	if (widthYes > 0) {
        		/* height obrazka zaszyte w stylach */
        		poll += '<img src="' + settings.pollBarImgSrcYes + '" width="' + widthYes + '" alt="głosy tak" title="głosy na tak" />';
        	}
        	if (widthNo > 0) {
        		/* height obrazka zaszyte w stylach */
        		poll += '<img src="' + settings.pollBarImgSrcNo + '" width="' + widthNo + '" alt="głosy nie" title="głosy na nie" />';
        	}
        } else {
       		/* nie oddano żadnych głosów */
       		poll += '<img src="' + settings.pollBarImgSrcEmpty + '" width="' + barWidth + '" alt="głosy brak" title="nie oddano głosów" />';        	
        }
        poll += '<br />';
    }

    var optionPercentYes = 0;
	var optionPercentNo = 0;
	if (votesSum > 0) {
		optionPercentYes = Math.round(votesYes * 100 / votesSum);
		optionPercentNo = Math.round(votesNo * 100 / votesSum);
	}
		
	if ((!settings.hidePercent) || (!settings.hideCount)) {
		poll += '<span class="smsPollYes">TAK: ';
        if (!settings.hidePercent) {
            poll += '<strong>' + optionPercentYes + '%' + '</strong>';
        }
        if (!settings.hideCount) {
        	if (!settings.hidePercent) {
        		poll += ' (';
        	}
            poll += votesYes + ' głos';
            /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */ 
            poll += getPolishNumeralEnding(votesYes);
        	if (!settings.hidePercent) {
        		poll += ')';
        	}
        }
        poll += '</span>, ';
        poll += '<span class="smsPollNo">NIE: ';
        if (!settings.hidePercent) {
            poll += '<strong>' + optionPercentNo + '%' + '</strong>';
        }
        if (!settings.hideCount) {
        	if (!settings.hidePercent) {
        		poll += ' (';
        	}
            poll += votesNo + ' głos';
            /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */ 
            poll += getPolishNumeralEnding(votesNo);
        	if (!settings.hidePercent) {
        		poll += ')';
        	}
        }
        poll += '</span>. ';
    }

    if (!settings.hideYesNoSum) {
    	poll += 'Oddanych głosów: ' + votesSum + '. ';
    }
    
    if (!settings.hidePoints) {
    	poll += 'Wynik: ' + points + '. ';
    }    

    if (!settings.hideSmsNumber || !settings.hideSmsContent) {    
    	var smsNumber = getSmsNumber(feed);
    	var smsContent = getSmsContent(feed, option, settings);

    	poll += '<br />'; 
    	if (smsNumber != null && smsContent!= null) {
	    	poll += 'Głos na TAK - SMS';
			if (!settings.hideSmsNumber) {
	            poll += ' pod nr <strong>' + smsNumber + '</strong>';
	        }
	        if (!settings.hideSmsContent) {
	            poll += ' o treści <strong>' + smsContent + settings.separatingChar + 'tak</strong>';
	        }
	
	        poll += '<br />';
	    	poll += 'Głos na NIE - SMS';
	        if (!settings.hideSmsNumber) {
	            poll += ' pod nr <strong>' + smsNumber + '</strong>';
	        }
	        if (!settings.hideSmsContent) {
	            poll += ' o treści <strong>' + smsContent + settings.separatingChar + 'nie</strong>';
	        }
    	} else {
    		var id = feed.eventName + '/' + option.optionKeyword;
    		reportError('Błąd konfiguracji sondy SMS ' + id +  ': nie znaleziony numer telefonu lub treść SMS do wysłania.');
    		return '';
    	}
    }

    poll += '</span>';
    poll += '</div>';
    poll += '</li>';
    return poll;
}


/* 
 * Sonda - wyświetla liczbę głosów oddanych na daną opcję wraz z podgrupą (serwis wyborczy). 
 */
function drawOptionClassicWithSubgroup(feed, option, settings, pollWithPhotos) {
	var poll = '';
	var barWidth = getPollBarWidth(pollWithPhotos, settings);
	poll += '<li';
    var url = getOptionUrl(feed, option, settings);
    if (url != null) {
   		poll += ' onclick="window.location=\'' + url + '\';"';
    }
    poll += '>';
	poll += drawOptionPhoto(feed, option, settings);
	poll += '<div style="width: ' + barWidth + 'px">';
	poll += '<p>';
    poll += option.optionName;
	if (!settings.hideCandidateDescription) {
		poll += ' ' + option.optionDescription;
	}
	poll += '<br /><strong>';
	poll += '(' + option.optionSubgroup + ')';
	poll += '</strong>';
	    
    if (!settings.hideCandidateNumber) {
        poll += ' (' + option.optionKeyword + ')';
    }
    poll += '</p>';
    if (!settings.hideBar) {
        if (feed.topVotes > 0 && option.votesTotal > 0) {
        	/* height obrazka zaszyte w stylach */
        	var width = Math.round(option.votesTotal / feed.topVotes * barWidth);
        	poll += '<img src="' + settings.pollBarImgSrc + '" width="' + width + '" alt="sonda" /><br />'; 
        }
    }
    poll += '<span>';
    if (!settings.hidePercent) {
    	if (feed.votesTotal > 0) {
	    	var percent = Math.round(option.votesTotal * 100 / feed.votesTotal);
	        poll += '<strong>' + percent + '%' + '</strong>, <br />';
    	}
    }
    if (!settings.hideCount) {
        poll += option.votesTotal + ' głos';
        /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
        poll += getPolishNumeralEnding(parseInt(option.votesTotal));
        poll += ', '; 
    }
    poll += '<span>';
    if (!settings.hideSmsNumber || !settings.hideSmsContent) {
        poll += 'SMS';
        if (!settings.hideSmsNumber) {
        	var smsNumber = getSmsNumber(feed);
        	if (smsNumber != null) {
        		poll += ' pod nr <strong>' + smsNumber + '</strong>';
        	}
        }
        if (!settings.hideSmsContent) {
        	var smsContent = getSmsContent(feed, option, settings);
        	if (smsContent != null) {
        		poll += ' o treści <strong>' + smsContent + '</strong>';
        	}
        }
    }
    poll += '</span></span>';
    poll += '</div>';
    poll += '</li>';
    return poll;
}

/*
 * Sonda 'klasyczna' w serwisach ST - pionowe paski z głosami.
 */
function drawOptionSTVertical(feed, option, settings, itemNumber) {
	var poll = '';
	
	var optionWidth;
	var percent;
	if (feed.topVotes > 0) {
		optionWidth = Math.round(option.votesTotal / feed.topVotes * settings.width);
	} else {
		optionWidth = 0;
	}
	if (feed.votesTotal > 0) {
		percent = Math.round(option.votesTotal * 100 / feed.votesTotal);
	} else {
		percent = 0;
	}

    poll += '<li id="item' + itemNumber + '" style="height: ' + optionWidth + 'px"';
    var url = getOptionUrl(feed, option, settings);
    if (url != null) {
   		poll += ' onclick="window.location=\'' + url + '\';"';
    }
    poll += '>';
    poll += '<span style="height: "' + optionWidth + 'px">' + percent + '%</span>';
    poll += '<p>' + option.optionKeyword + '</p>';
    poll += '<div>' + option.optionName + ' ' + option.optionDescription;
    if (!settings.hideCount) {
        poll += '<br/>' + option.votesTotal + ' głos';
        poll += getPolishNumeralEnding(option.votesTotal);
    }
    poll += '</div></li>';
    return poll;
}

/*
 * Funkcja dostawia końcówkę, aby utworzyć odmianę słowa, 
 * np.: "głos", "głosy" lub "głosów"
 */
function getPolishNumeralEnding(numeral) {
    var m = numeral % 10;
    var mm = numeral % 100;
    if (numeral == 1) { 
        /* 1 głos */
        return "";
    }
    else if (mm >= 11 && mm <= 19) {
        /* ...naście głosów */
        return "ów";
    } else {
        /* reszta regularnie */
        if (m >= 2 && m <= 4) {
            return "y";
        } else {
            return "ów";
        }
    }
}

/*
 * Pobiera z adresu URL zadany parametr, będący liczbą naturalną.
 */
function getUrlNumericalParam(url, param) {
    var re = new RegExp(param + '=([0-9]+)');
    var m = re.exec(url);
    if (m == null) {
      return null;
    } else {
      return m[1];
    }
}

/*
 * Jeśli jesteśmy na serwerze testowym - wyświetl wiadomość o błędzie.
 */
function reportError(message) {
	var loc = '' + window.location;
	if (loc.indexOf('test.saxotech.pl') > 0) {
		alert(message);
		return;
	}
}

/*
 * Dodaje bądź usuwa <div> z preloaderem sondy. 
 */
$.fn.pollPreloader = function(show) {
    if (show == true) {
        $container = $(this);
        $container.append('<div id="preloader"></div>');
        $preloader = $(this).find('#preloader');
        /* dodaj preloader */
        var preloaderImageSize = 32;
        var w = parseInt($container.css('width'));
        var x = w/2 - preloaderImageSize/2;
        var y = w/2 - preloaderImageSize/2;
        $preloader.css('float', 'left');
        $preloader.css('width', w+'px');
        $preloader.css('margin', '0');
        $preloader.css('padding', '10px 0');
        $preloader.css('text-align', 'center');
        $preloader.html('<img src="/images/preloader.gif" width="'+preloaderImageSize+'" height="'+preloaderImageSize+'" alt="loading" />');
    } else {
        /* usuń preloader */
        $(this).find('#preloader').remove();
    }
};

