/* 
 * 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
 * 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 Panoramixa są dodane.
 */
$.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('plebiscites') > 0) {
    		poll = newProcessPanoramix(data, opt, url);
    	} else {
    		poll = processPanoramix(data, opt, url);
    	}
        poll = utf2iso(poll);
        el.append(poll);
        el.pollPreloader(false);
        return;
    });

    el.pollPreloader(false);
    return;
};

/*
 * Zbuduj adres URL odnoszący się do starego lub nowego panelu Panoramix
 * na podstawie parametru podanego funkcji.
 * 
 * Jeśli param jest linkiem do nowego panelu Panoramix - zwróć go,
 * przetwarzając ew. dodatkowy przełącznik grupy i opcji /grupa/ /opcja/
 * (zamiana na odpowiednie parametry URL).
 * 
 * Jeśli param jest identyfikatorem sondy, załóż że jest
 * to sonda odnosząca się do starego panelu Panoramix. Zbuduj wtedy link w postaci
 *  http://pub.panoramix.fm/results.php?id=&type=json&sortby=votes&order=desc&width=480&group=&text=
 * Parametr id jest obowiązkowy, parametry group i text są opcjonalne, jeśli w param
 * po id znajdzie się przełącznik, np. d1pcgdrdbebfoblm8cygm4tn95pts9sv/grupa/burmistrz
 */
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 nowego panelu Panoramix */                                
		var regexpLink = new RegExp('(http://public\.panoramix\.fm/plebiscites/stats/[A-Za-z0-9]+/.f=json[A-Za-z0-9_=&/]*)');
		var m = regexpLink.exec(param);
		if (m != 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;
		} else {
			/* link do starego panelu Panoramix */
			var regexpOldLink = new RegExp('http://pub\.panoramix\.fm/results\.php\?');
			var m = regexpOldLink.exec(param);
			if (m != null) {
				return param;
			} else {
				reportError('Incorrect link to panoramix service: ' + param + '. ' +
						    'Correct link matches http://public.panoramix.fm/plebiscites/stats/([A-Za-z0-9_]+)/?f=json ' +
						    'or http://pub.panoramix.fm/results.php?.');
				return null;			
			}
		}
	} else {
		/* parametr to samo ID sondy, z ew /opcja/ /grupa/ */ 
		var regexpIdOnly = new RegExp('^([A-Za-z0-9_]+)$');
		var m = regexpIdOnly.exec(param);
		if (m != null) {
			/* samo ID sondy */
			url = 'http://pub.panoramix.fm/results.php?id=' + m[1] + '&type=json&sortby=votes&order=desc&width=480';
			return url;
		} else {
			/* sprawdź czy grupa lub opcja */
			var regexpGroup = new RegExp('([A-Za-z0-9_]+)/grupa/([A-Za-z0-9_ĄĆĘŁŃÓŚŹŻąćęłńóśźż]+)');
			var regexpOption = new RegExp('([A-Za-z0-9_]+)/opcja/([A-Za-z0-9_ĄĆĘŁŃÓŚŹŻąćęłńóśźż]+)');
			var m = regexpGroup.exec(param);
			if (m != null) {
				/* grupa */
				url = 'http://pub.panoramix.fm/results.php?id=' + m[1] + '&type=json&sortby=votes&order=desc&width=480';
				url += '&group=' + m[2];
				return url;
			}
			var m = regexpOption.exec(param);
			if (m != null) {
				/* opcja */
				url = 'http://pub.panoramix.fm/results.php?id=' + m[1] + '&type=json&sortby=votes&order=desc&width=480';
				url += '&text=' + m[2];				
				return url;
			}
		}
	}
	reportError('Unnkown error in poll: ' + param);
	return null;
}

/*
 * Sonda w starej wersji panelu Panoramixa.
 */
function processPanoramix(data, opt, url) {
    var poll='';
	if (data != null) {
        var settings = {
            type: "horizontal",
            hideMainTitle: false,
            hideMainCount: false,
            hideMainGenerationDate: false,
            hideCandidateNumber: 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"
        };

        /* dodaj do tablicy "settings" opcje domyśle, jeśli ich nie zdefiniowano */
        jQuery.extend(settings, opt);

        if (!settings.hideMainTitle) {
            poll += '<h3>' + data.name + '</h3>';
        }

        if (data.options != null) {
            poll += '<ul>';
            if (settings.type == "vertical") {
                poll += '<li id="caption">Nr kandydatki</li>';
            }
            $.each(data.options, function(i,option) {

            	/* sprawdź czy sonda jest typu TAK/NIE, za pomocą istnienia pól: positive, negative, points */
            	var optionYesNo = false; 
                if ((option.positive != null) && (option.negative != null) && (option.points != null)) {
                	optionYesNo = true;
                }
                
                /* pobierz szerokość boxu z sondą z adresu url, uwaga: może być null */
                var optionsWidth = getUrlNumericalParam(url, 'width');

                /* nazwy tych pól są różne dla panoramix i mobiltek */
                var optionText = "";
                if (url.indexOf("mobiltek") > 0) {
                    optionText = option.number;
                } else { /* panoramix i inne zawierają pola <text> */
                    optionText = option.text;
                }

                if (settings.type == "horizontal") {
                	if (optionYesNo == true) {
                    	/* sonda TAK/NIE */
                		poll += drawOptionYesNo(settings, data, option, optionText, optionsWidth);
                	} else {
                    	/* sonda klasyczna - liczba głosów na daną opcję */
                		poll += drawOptionClassic(settings, data, option, optionText);
                	}
                } else if (settings.type == "vertical") {
                    /* sonda pionowa - serwisy ST */
                	poll += drawOptionSTVertical(settings, data, option, i);
                }
            });
            poll += '</ul>';
        }

        if (!settings.hideMainCount || !settings.hideMainGenerationDate) {
            poll += '<p>';
            if (!settings.hideMainGenerationDate) {
                if (data.generationDate != null) {
                    poll += 'Czas wygenerowania danych: ' + data.generationDate + '<br />';
                }
            }
            if (!settings.hideMainCount) {
                if (data.votes != null) {
                    poll += '<span>Liczba wszystkich głosów: ' + data.votes + '</span>';
                }
            }
            poll += '</p>';
        }
    };
    return poll;
}

/*
 * Sonda w nowej wersji panelu Panoramixa.
 */
function newProcessPanoramix(panoramix, opt, url) {
    var poll='';
	if (panoramix != null) {
        var settings = {
            type: "horizontal",
            hideMainTitle: false,
            hideMainCount: false,
            hideMainGenerationDate: false,
            hideCandidateNumber: 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
        };

        /* dodaj do tablicy "settings" opcje domyśle, jeśli ich nie zdefiniowano */
        jQuery.extend(settings, opt);

        if (!settings.hideMainTitle) {
            poll += '<h3>' + panoramix.eventName + '</h3>';
        }
        if (panoramix.options != null) {
        	
        	var pollWithPhotos = false;
        	if (!settings.disablePhotos) {
        		pollWithPhotos = newCheckIfPollWithPhotos(panoramix.options);
        	}

            poll += '<ul>';
            if (settings.type == "vertical") {
                poll += '<li id="caption">Nr kandydatki</li>';
            }
            $.each(panoramix.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 = newCheckIfYesNoOption(panoramix, option, settings); 
               
                if (settings.type == "horizontal") {
                	if (optionYesNo == true) {
                    	/* sonda TAK/NIE */
                		poll += newDrawOptionYesNo(panoramix, option, settings, pollWithPhotos);
                	} else {
                    	/* sonda klasyczna - liczba głosów na daną opcję */
                		poll += newDrawOptionClassic(panoramix, option, settings, pollWithPhotos);
                	}
                } else if (settings.type == "vertical") {
                    /* sonda pionowa - serwisy ST */
                	poll += newDrawOptionSTVertical(panoramix, option, settings, i);
                }
            });
            poll += '</ul>';
        }
        
        if (!settings.hideMainCount || !settings.hideMainGenerationDate) {
            poll += '<p>';
            if (!settings.hideMainGenerationDate) {
                if (panoramix.generationDate != null) {
                    poll += 'Czas wygenerowania danych: ' + panoramix.generationDate + '<br />';
                }
            }
            if (!settings.hideMainCount) {
                if (panoramix.votes != null) {
                    poll += '<span>Liczba wszystkich głosów: ' + panoramix.votesSms + '</span>';
                }
            }
            poll += '</p>';
        }
    };
    return poll;
}

/*
 * Z adresu nowej sondy Panowamix wyciąga jej ID i zwraca link do starego serwisu Panoramix.
 * Używane dla sond, które były założone w starym panelu.
 */
function translateRequestFromNewToOld(newUrl, opt) {
	var oldUrl = newUrl;
	if (newUrl.indexOf('plebiscites') > 0) {
	    var re = new RegExp('plebiscites/stats/([^/\?]+)');
	    var m = re.exec(newUrl);
	    if (m != null) {
	    	if (m[1] != null) {
	    		oldUrl = 'http://pub.panoramix.fm/results.php?id=' + m[1] + '&type=json&sortby=votes&order=desc&width=' + opt.width;		
	    	}
	    }
	}	
	return oldUrl;
} 

/*
 * Pobiera numer SMS na który mają być wysyłane głosy.
 */
function getSmsNumber(panoramix) {
    if (panoramix.gatePairs != null) {
    	if (panoramix.gatePairs[0] != null) {
    		if (panoramix.gatePairs[0].gate != null) {
    			return panoramix.gatePairs[0].gate;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera pierwszy prefix sms. Powinien występować zawsze.
 */
function getSmsPrefix(panoramix) {
    if (panoramix.gatePairs != null) {
    	if (panoramix.gatePairs[0] != null) {
    		if (panoramix.gatePairs[0].prefix != null) {
    			return panoramix.gatePairs[0].prefix;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera drugi prefix sms. 
 */
function getSmsSubprefix(panoramix) {
    if (panoramix.gatePairs != null) {
    	if (panoramix.gatePairs[0] != null) {
    		if (panoramix.gatePairs[0].subprefix != null) {
    			return panoramix.gatePairs[0].subprefix;
    		}
    	}
    }
    return null;
}

/*
 * Pobiera treść sms do wysłania na daną opcję.
 */
function getSmsContent(panoramix, option, settings) {
	var smsContent = null;
	var prefix = getSmsPrefix(panoramix);
	if (prefix != null) {
		smsContent = prefix + settings.separatingChar;
		var subprefix = getSmsSubprefix(panoramix);
		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 getOptionVariantsVotesSms(panoramix, option, settings, variantKeyword) {
	var votesSms = -1;
	
	$.each(option.optionVariants, function(i,optionVariant) {
		if (optionVariant.variantKeyword == variantKeyword) {
			votesSms = optionVariant.votesSms;
		}
	});
	if (votesSms < 0) {
		var id = panoramix.eventName + '/' + option.optionKeyword;
		reportError('Błąd konfiguracji sondy SMS ' + id + ': nie odnaleziono liczby głosów dla wariantu ' + variantKeyword);
	}
	return votesSms;
}

/*
 * 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 newCheckIfYesNoOption (panoramix, option, settings) {
	var foundYes = false;
	var foundNo = false;
	var counter = 0;
	
	if (option.optionVariants == null)
		return false;

	var id = panoramix.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 = panoramix.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 newDrawOptionPhoto(panoramix, 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 newCheckIfPollWithPhotos(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;
}

/*
 * Przelicza szerokość paska (jeśli sonda zawiera obrazki - pasek będzie zmniejszony).
 */
function newGetPollBarWidth(pollWithPhotos, settings) {
	if (pollWithPhotos) {
		if (settings.width - settings.widthPhotos > 0) {
			return settings.width - settings.widthPhotos;
		}
	}
	return settings.width;
}
/* 
 * Nowa Sonda - wyświetla liczbę głosów oddanych na daną opcję. 
 */
function newDrawOptionClassic(panoramix, option, settings, pollWithPhotos) {
	var poll = '';
	var barWidth = newGetPollBarWidth(pollWithPhotos, settings);
	poll += '<li>';
	poll += newDrawOptionPhoto(panoramix, option, settings);
	poll += '<div style="width: ' + barWidth + 'px">';
	poll += '<p>';
    poll += '<strong>' + option.optionDescription + '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (' + option.optionKeyword + ')';
    }
    poll += '</p>';

    if (!settings.hideBar) {
        if (panoramix.topVotes > 0 && option.votesSms > 0) {
        	/* height obrazka zaszyte w stylach */
        	var width = Math.round(option.votesSms / panoramix.topVotes * barWidth);
        	poll += '<img src="' + settings.pollBarImgSrc + '" width="' + width + '" alt="sonda" /><br />'; 
        }
    }
    poll += '<span>';
    if (!settings.hidePercent) {
    	if (panoramix.votesSms > 0) {
	    	var percent = Math.round(option.votesSms * 100 / panoramix.votesSms);
	        poll += '<strong>' + percent + '%' + '</strong>, ';
    	}
    }
    if (!settings.hideCount) {
        poll += option.votesSms + ' głos';
        /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
        poll += getPolishNumeralEnding(parseInt(option.votesSms));
        poll += ', '; 
    }
    poll += '<span>';
    if (!settings.hideSmsNumber || !settings.hideSmsContent) {
        poll += 'SMS';
        if (!settings.hideSmsNumber) {
        	var smsNumber = getSmsNumber(panoramix);
        	if (smsNumber != null) {
        		poll += ' pod nr <strong>' + smsNumber + '</strong>';
        	}
        }
        if (!settings.hideSmsContent) {
        	var smsContent = getSmsContent(panoramix, option, settings);
        	if (smsContent != null) {
        		poll += ' o treści <strong>' + smsContent + '</strong>';
        	}
        }
    }
    poll += '</span></span>';
    poll += '</div>';
    poll += '</li>';
    return poll;
}


/* 
 * Sonda 'klasyczna' - wyświetla liczbę głosów oddanych na daną opcję. 
 */
function drawOptionClassic(settings, data, option, optionText) {
	var poll = '';
	
    poll += '<li><div>';
    poll += '<p>';
    poll += '<strong>' + option.name + '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (nr ' + optionText + ')';
    }
    poll += '</p>';

    if (!settings.hideBar) {
        if (option.width > 0) {
       	/* height obrazka zaszyte w stylach */
        poll += '<img src="' + settings.pollBarImgSrc + '" width="' + option.width + '" alt="sonda" /><br />'; 
        }
    }
    poll += '<span>';
    if (!settings.hidePercent) {
        poll += '<strong>' + option.percent + '%' + '</strong>, ';
    }
    if (!settings.hideCount) {
        poll += option.votes + ' głos';
        /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
        poll += getPolishNumeralEnding(parseInt(option.votes));
        poll += ', '; 
    }
    poll += '<span>';
    if (!settings.hideSmsNumber || !settings.hideSmsContent) {
        poll += 'SMS' ;
        if (!settings.hideSmsNumber) {
            poll += ' pod nr <strong>' + data.premiumNumber + '</strong>';
        }
        if (!settings.hideSmsContent) {
            poll += ' o treści <strong>' + data.prefix + settings.separatingChar + optionText + '</strong>';
        }
    }
    poll += '</span></span>';
    poll += '</div></li>';
    return poll;
}

/* 
 * Sonda Tak/Nie - wyświetla liczbę głosów pozytywnych i negatywnych 
 * oddanych na daną opcję. 
 */
function newDrawOptionYesNo(panoramix, option, settings, pollWithPhotos) {
	var poll = '';
	var barWidth = newGetPollBarWidth(pollWithPhotos, settings);
	poll += '<li>';
	poll += newDrawOptionPhoto(panoramix, option, settings);
	poll += '<div style="width: ' + barWidth + 'px">';
    poll += '<p>';
    poll += '<strong>' + option.optionDescription + '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (' + option.optionKeyword + ')';
    }
    poll += '</p>';
    poll += '<span>';

	var votesYes = getOptionVariantsVotesSms(panoramix, option, settings, settings.keywordYes);
	var votesNo = getOptionVariantsVotesSms(panoramix, 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(panoramix);
    	var smsContent = getSmsContent(panoramix, 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 = panoramix.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 Tak/Nie - wyświetla liczbę głosów pozytywnych i negatywnych 
 * oddanych na daną opcję. 
 */
function drawOptionYesNo(settings, data, option, optionText, optionsWidth) {
	var poll = '';
    poll += '<li><div>';
    poll += '<p>';
    poll += '<strong>' + option.name + '</strong>';
    if (!settings.hideCandidateNumber) {
        poll += ' (nr ' + optionText + ')';
    }
    poll += '</p>';

    poll += '<span>';
    if (!settings.hideBar) {
       	if ((option.width) != null && (option.width > 0) && (option.width <= optionsWidth)) {
        	var widthYes = option.width;
        	var widthNo = optionsWidth - option.width;
        	/* height obrazka zaszyte w stylach */
        	if (widthYes > 0) {
        		poll += '<img src="' + settings.pollBarImgSrcYes + '" width="' + widthYes + '" alt="głosy tak" title="głosy na tak" />';
        	}
        	if (widthNo > 0) {
        		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="' + optionsWidth + '" alt="głosy brak" title="nie oddano głosów" />';
       	}
       	poll += '<br />';
    }

    var sumPosNeg = parseInt(option.positive) + parseInt(option.negative);
    var optionPercentYes = 0;
	var optionPercentNo = 0;
	if (sumPosNeg > 0) {
		optionPercentYes = Math.round(parseInt(option.positive) * 100 / sumPosNeg);
		optionPercentNo = Math.round(parseInt(option.negative) * 100 / sumPosNeg);
	}
	
	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 += option.positive + ' głos';
            /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
            poll += getPolishNumeralEnding(parseInt(option.positive));
        	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 += option.negative + ' głos';
            /* dostaw końcówkę, aby utworzyć "głos", "głosy" lub "głosów" */
            poll += getPolishNumeralEnding(parseInt(option.negative));
        	if (!settings.hidePercent) {
        		poll += ')';
        	}
        }
        poll += '</span>. ';
    }

    if (!settings.hideYesNoSum) {
    	poll += 'Oddanych głosów: ' + sumPosNeg + '. ';
    }
    
    if (!settings.hidePoints) {
    	poll += 'Wynik: ' + option.points + '. ';
    }    

    if (!settings.hideSmsNumber || !settings.hideSmsContent) {
    	poll += '<br />'; 
    	poll += 'Głos na TAK - SMS';

		if (!settings.hideSmsNumber) {
            poll += ' pod nr <strong>' + data.premiumNumber + '</strong>';
        }

        if (!settings.hideSmsContent) {
            poll += ' o treści <strong>' + data.prefix + settings.separatingChar + optionText + settings.separatingChar + 'tak</strong>';
        }
    	
        poll += '<br />';
    	poll += 'Głos na NIE - SMS';
        if (!settings.hideSmsNumber) {
            poll += ' pod nr <strong>' + data.premiumNumber + '</strong>';
        }
        if (!settings.hideSmsContent) {
            poll += ' o treści <strong>' + data.prefix + settings.separatingChar + optionText + settings.separatingChar + 'nie</strong>';
        } 
    }

    poll += '</span>';
    poll += '</div></li>';
    return poll;
}

/*
 * Sonda 'klasyczna' w serwisach ST - pionowe paski z głosami.
 */
function newDrawOptionSTVertical(panoramix, option, settings, itemNumber) {
	var poll = '';
	
	var optionWidth = Math.round(option.votesSms / panoramix.topVotes * settings.width);
	var percent = Math.round(option.votesSms * 100 / panoramix.votesSms);

    poll += '<li id="item' + itemNumber + '" style="height: ' + optionWidth + 'px">';
    poll += '<span style="height: "' + optionWidth + 'px">' + percent + '%</span>';
    poll += '<p>' + option.optionKeyword + '</p>';
    poll += '<div>' + option.optionDescription;
    if (!settings.hideCount) {
        poll += '<br/>' + option.votesSms + ' głos';
        poll += getPolishNumeralEnding(option.votesSms);
    }
    poll += '</div></li>';
    return poll;
}

/*
 * Sonda 'klasyczna' w serwisach ST - pionowe paski z głosami.
 */
function drawOptionSTVertical(settings, data, option, itemNumber) {
	var poll = '';
    poll += '<li id="item' + itemNumber + '" style="height: ' + option.width + 'px">';
    poll += '<span style="height: "' + option.width + 'px">' + option.percent + '%</span>';
    poll += '<p>' + option.text + '</p>';
    poll += '<div>' + option.name;
    if (!settings.hideCount) {
        poll += '<br/>' + option.votes + ' głosów';
    }
    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();
    }
};

