//ogolne funkcje sterujce dla calej strony
function Hide(id) 
{
        
    obj = document.getElementById(id);
    obj.style.display = "none" ;
}
function show(id) 
{
        
    obj = document.getElementById(id);
    obj.style.display = "block";
}
function showInline(id) {

    obj = document.getElementById(id);
    obj.style.display = "inline";
}
        
 function  destroy(id)
{
    document.getElementById(id).innerHTML = "";
}    
      
function showHide(id) 
{
        
   obj = document.getElementById(id);
   obj.style.display = (obj.style.display == "block" ? "none" : "block"); 
}
function showHideTr(id)
{
   obj = document.getElementById(id);
   obj.style.display = (obj.style.display == "table-row" ? "none" : "table-row");
 }
function showHideTrJQ(id)
{
    if(jQuery.browser.msie){
        if($('#'+id+' div.main_details_jq').is(':hidden')){
            $('#'+id+' div.main_details_jq').fadeIn('slow');
        }else{
            $('#'+id+' div.main_details_jq').fadeOut('slow');
        }
    }else{
        $('#'+id+' div.main_details_jq').toggle('slow');
    }
}

//pobiera wartosc elementu o podanym id
function getValue(id)
{
    var value = document.getElementById(id).value;
    return value;  
}
//pobiera wartosc innerHTML elementu o podanym id
function getText(id)
{
    var value = document.getElementById(id).innerHTML;
    return value;
}

//ustawia wartosc elementu o podanym id
function setValue(id, val)
{
    document.getElementById(id).value = val;
  
}

//sprawdzaie poprawnosci formularze rejestracyjnego
function checkForm()
{

   var username = document.reg_form.username.value;
   var email = document.reg_form.email.value;
   var email2 = document.reg_form.email_confirm.value;
   var password = document.reg_form.password.value;
   var password2 = document.reg_form.password_confirm.value;
   var testResult = document.reg_form.test_result.value;
   var recomUser = document.reg_form.recom_user.value;     
   //do weryfikacji adresu email
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; 
    
    if(username == "")
    {  
        showError('username', lang['data_wpisz_login']);
        return false;
        
    }
    else if(email == "")
    {  
        showError('email', lang['wpisz_adr_email']);
        return false;
    }
    else if(reg.test(email) == false) //jesli zostal wpisany bledny adres email
    {
         showError('email', lang['wpisz_praw_email']);
         return false;      
        
    }
    else if(email2 == "") 
    {
         showError('email_confirm', lang['wpisz_ponownie_email'] );
         return false;      
        
    }
    else if(email2 != email) 
    {
         showError('email_confirm', lang['niezgodne_email']);
         showError('email', lang['niezgodne_email']);
         return false;
               
    }
    else if(password == "") 
    {
         showError('password', lang['data_wpisz_haslo']);
         return false;     
        
    }
    else if(password2 == "") 
    {
         showError('password_confirm', lang['data_wpisz_ponownie_haslo']);
         return false;       
        
    }
    else if(password != password2) 
    {
         showError('password', lang['data_hasla_nie_zagodne']);
         showError('password_confirm', lang['data_hasla_nie_zagodne']);
         return false;     
    }
    else if (recomUser != '' && recomUser.length != 8){
        showError('recom_user', lang['bledny_polec_id']);
        return false;
    }
    else if(testResult != 5) 
    {
        showError('test_result', lang['data_zly_wynik_dzialania']);
        return false;
    }
    
    else if(document.reg_form.terms_accept.checked==false) 
    {
        showError('terms_accept', lang['data_zaakceptuj_reg']);
        return false;
    }
    
    
    xajax_fx.regUser(xajax.getFormValues('reg_form'), 0);
    return false;
  

}

//obsluga bledu w formualrzu rejestracji
function showError(id, text)
{
    var currentBorder = document.getElementById(id).style.border;
    var pustePole = '<span style="color:white;">-</span>';
    document.getElementById(id).focus();
    document.getElementById(id).style.border='2px solid #900';
    document.getElementById("formInfo").innerHTML=text;
    show('formInfo');

    setTimeout( function() {
        document.getElementById(id).style.border=currentBorder;
        document.getElementById("formInfo").innerHTML=pustePole;
        }, 5000);
      
}

//pokazywanie bledu logowania
function showLogError()
{
    show('logInfo');
    document.getElementById('container').style.opacity=0.6;
  
}

//ukrywanie bledu logowania
function hideLogError()
{
    Hide('logInfo');
    document.getElementById('container').style.opacity=1;
  
}

//przywracanie domyslnej wartosci pola z loginem,
//jesli nic nie zostalo wpisane
function valueUsername(lang)
{
       
    if(getValue('log_username')=="")
    {
        if(lang == 'pl')
            setValue('log_username', 'Login');
        else
            setValue('log_username', 'Username');
    }
    
}

//czyszczenie pola z loginem jesli jest domyslna wartosc
function clearUsername(id)
{
   if(getValue(id)=='Login' || getValue(id)=='Username')
     setValue(id, '');
}


//pokazuje wlasciwe pole z haslem do logowania
function showPasswordField(id_pass, id_pass_field)
{

  Hide(id_pass);
  show(id_pass_field);
  document.getElementById(id_pass_field).focus();
  
}

//ukrywa wlasciwe pole z haslem jesli nic nie zostalo wpisane
function hidePasswordField(id_pass, id_pass_field)
{
    
    if(getValue(id_pass_field)=="")  
    { 
      Hide(id_pass_field);
      show(id_pass);
    }
       
}


//sprawdzaie poprawnosci formularza w profilu uzytkownika
function checkFormProfile()
{   
    var email = document.user_profile.email.value;
    var email2 = document.user_profile.email_confirm.value;
    
    var password = document.user_profile.current_password.value;
    var newPassword = document.user_profile.new_password.value;
    var newPassword2 = document.user_profile.new_password_confirm.value;
    var smsNum = document.user_profile.smsNum.value;
    smsNum = smsNum.replace(' ','');

    //do weryfikacji adresu email
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; 
    
    if(email == ""){ 
     
        showError('email', lang['wpisz_adr_email']);
        return false;
    }
    else if(reg.test(email) == false){ //jesli zostal wpisany bledny adres email
    
         showError('email', lang['wpisz_praw_email']); 
         return false;      
    }
    else if(email2 == "") {
    
         showError('email_confirm', lang['wpisz_ponownie_email']);
         return false;      
    }
    else if(email2 != email) {
    
         showError('email_confirm', lang['niezgodne_email']);
         showError('email', lang['niezgodne_email']);
         return false;    
    }
    else if(password == ""){
      
        showError('current_password', lang['wpisz_obecne_haslo']);
        return false;
    }
    else if(newPassword  != ""){ //jesli jest wpisane nowe haslo
            
        if(newPassword2 == ""){
        
            showError('new_password_confirm', lang['potw_nowe_haslo']);
            return false;
        }
        else if(newPassword != newPassword2){
        
            showError('new_password_confirm', lang['data_hasla_nie_zagodne']);
            showError('new_password', lang['data_hasla_nie_zagodne']);
            return false;
        }
    }
    else if (smsNum.length > 0 && lang['page_lang'] == 'pl') {   // jesli user podaje numer do SMS
        if (smsNum[0] == '0' || isNaN(smsNum) || smsNum == '602950000' || smsNum.length < 9) {
            showError('smsNum', lang['numer_sms_niepraw']);
            return false;
        }
    }
    
     xajax_fx.changeUserProfile(xajax.getFormValues('user_profile'));
    return false;
}

//sprawdzanie poprawnosci formularza z przypomnieniem hasla
function checkFormRemind()
{

    var email = document.pass_reminder.email.value;
    //do weryfikacji adresu email
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; 
    
    if(email == "")
    {  
        showError('email', lang['wpisz_adr_email']);
        return false;
    }
    else if(reg.test(email) == false) //jesli zostal wpisany bledny adres email
    {
         showError('email', lang['wpisz_praw_email']);
         return false;      
        
    }
    xajax_fx.remindPassword(xajax.getFormValues('pass_reminder'));
    return false;
}

//sprawdzanie formularza kontaktowego
function checkContactForm()
{
    var name = document.contact_form.name.value;
    var email = document.contact_form.email.value;
    var message = document.contact_form.message.value;   
    
    //do weryfikacji adresu email
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; 
    
    if(name == "")
    {  
        showError('name', lang['data_wpisz_imie_nazw']);
        return false;
    }
    else if(email == "")
    {  
        showError('email', lang['data_wpisz_swoj_email']);
        return false;
    }
    else if(reg.test(email) == false) //jesli zostal wpisany bledny adres email
    {
         showError('email', lang['wpisz_praw_email']);
         return false;      
        
    }
    else if(message == "")
    {  
        showError('message', lang['data_wpisz_tresc_wiad']);
        return false;
    }
    xajax_fx.contactForm(xajax.getFormValues('contact_form'));
    return false;
}

//sprawdzanie danych w kalkulatorze surebet
function checkCalculator()
{
    
  var overallStake = getValue('overallStake'); 
  var radioLength = document.surebetCalculator.surType.length;
  //pobieranie wartosci zaznaczongo radio
  for(var i = 0; i < radioLength; i++ )
  {
    if( document.surebetCalculator.surType[i].checked == true )
    {
      type = document.surebetCalculator.surType[i].value;
      break;
    }
  }

    if(overallStake == "") //brak stawki calkowitej
    {
       showError('overallStake', lang['data_wprow_stawke']);
       return false;
    }
  
    if(type == '3way') //surebet trzydrogowy
    {

        var oddX = getValue('3oddX');
        var odd1 = getValue('3odd1');   
        var odd2 = getValue('3odd2');
        var error = false;
        
        if(odd1 == "")
        {
          showError('3odd1', lang['data_wpisz_kurs']);
          error = true;
        }
        if(oddX == "")
        {
          showError('3oddX', lang['data_wpisz_kurs']);
          error = true;
        }
        if(odd2 == "")
        {
          showError('3odd2', lang['data_wpisz_kurs']);
          error = true;
        }

        if(error){
            return false;
        }
        calculateSurebet3way('');
    
    }
    else if(type == '2way') //surebet dwudrogowy
    {
        var odd1 = getValue('2odd1');   
        var odd2 = getValue('2odd2');
        var error = false;

        if(odd1 == "")
        {
          showError('2odd1', lang['data_wpisz_kurs']);
          error = true;
        }
        if(odd2 == "")
        {
          showError('2odd2', lang['data_wpisz_kurs']);
          error = true;
        }

        if(error){
            return false;
        }

        calculateSurebet2way('');
    }
    
    return false;
}

//sprawdzanie poprawnosci formularza z przypomnieniem o meczu
function checkFormMatchRemind()
{
   
   var days = getValue('days');
   var hours = getValue('hours');   
   var minutes = getValue('minutes'); 
   
    if(days != "" && (isNaN(days) || days < 0))
    {  
        showError('days', lang['data_wpisz_licz_dni']);
        return false;
    }
    if(hours != "" && (isNaN(hours) || hours < 0))
    {  
        showError('hours', lang['data_wpisz_licz_godzin']);
        return false;
    }
    if(minutes != "" && (isNaN(minutes) || minutes < 0))
    {  
        showError('minutes', lang['data_wpisz_licz_min']);
        return false;
    }
    if(minutes != "" && minutes > 60)
    {  
        showError('minutes', lang['data_wpisz_licz_min']);
        return false;
    }
    if(days == "" && hours == "" &&  minutes == "")
    {  
        showError('days', '');
        showError('hours', '');
        showError('minutes', lang['data_podaj_przyn_jed_wart']);
        return false;
    }
    
    xajax_fx.saveMatchRemind(xajax.getFormValues('match_reminder'));
    return false;
}

function checkNotifForm (userId, newUser) {

        inputID = $('#userProfit').val().replace(",", ".");
        $('#userProfit').val(inputID);
        inputID_max = $('#userMaxProfit').val().replace(",", ".");
        $('#userMaxProfit').val(inputID_max);
        var account_type = $('#userMaxProfit').attr('account');

        inputID =  parseFloat(inputID);
        inputID_max = parseFloat(inputID_max);

        if (inputID <= 0 || isNaN(inputID)){
            document.getElementById('formInfo').style.color = '#990000';
            document.getElementById('formInfo').innerHTML = lang['data_niepraw_wart_min_zysk'];
            setTimeout("document.getElementById('formInfo').innerHTML = '&nbsp;'",3000);
            return false;
        }
        else if (inputID_max <= 0 || isNaN(inputID_max)){
            document.getElementById('formInfo').style.color = '#990000';
            document.getElementById('formInfo').innerHTML = lang['data_niepraw_wart_max_zysk'];
            setTimeout("document.getElementById('formInfo').innerHTML = '&nbsp;'",3000);
            return false;
        }
        else if (inputID_max < inputID){
            document.getElementById('formInfo').style.color = '#990000';
            document.getElementById('formInfo').innerHTML = lang['data_max_musi_wiek_min'];
            setTimeout("document.getElementById('formInfo').innerHTML = '&nbsp;'",3000);
            return false;
        }else if (inputID_max > 20){
            document.getElementById('formInfo').style.color = '#990000';
            document.getElementById('formInfo').innerHTML = lang['data_za_duzy_max_zysk'];
            setTimeout("document.getElementById('formInfo').innerHTML = '&nbsp;'",3000);
            return false;
        }else if(account_type == 0){
            if(inputID > 1){
                $('#formInfo').css('color', '#990000').html(lang['data_za_duzy_zysk_test']);
                setTimeout("$('#formInfo').html('&nbsp;')",3000);

                return false;
            }else if(inputID_max > 1){
                $('#formInfo').css('color', '#990000').html(lang['data_za_duzy_max_zysk_test']);
                setTimeout("$('#formInfo').html('&nbsp;')",3000);

                return false;
            }

            
        }

        setTimeout("xajax_fx.saveUserProfit(xajax.getFormValues('notifForm'), '"+userId+"', '"+newUser+"')",0);
        return false;
        


        return false;

}

function checkMiniCalc (marginDiv) {
    var typ = $(':hidden[name=surType_'+marginDiv+']').val();
    var field = document.getElementById('overallStake_'+marginDiv+'').value.replace(",", ".");
  
    if (isNaN(field) || field <=0){
        document.getElementById('calcError_'+marginDiv+'').innerHTML = lang['data_niep_wartosc'];
        setTimeout("document.getElementById('calcError_"+marginDiv+"').innerHTML = ''", 3000);
        return false;
    }
  
    if(typ == '2way'){
        calculateSurebet2way(marginDiv);
    }else if(typ =='3way'){
        calculateSurebet3way(marginDiv)
    }

    return false;
}

function checkOrderForm() {
    var first_name = getValue('first_name');
    var last_name = getValue('last_name');
    var city = getValue('city');
    var country = getValue('country');

    if(first_name == "" || first_name.length < 3)
    {
        showError('first_name', lang['data_wpisz_imie']);
        return false;
    }
    else if(last_name == "" || last_name.length < 3)
    {
        showError('last_name', lang['data_wpisz_nazwisko']);
        return false;
    }
    else if(city == "" || city.length < 4)
    {
         showError('city', lang['data_wpisz_miasto']);
         return false;
    }
    else if(country == "")
    {
         showError('country', lang['data_wybierz_kraj']);
         return false;
    }
    else if(document.orderForm.terms_accept.checked==false)
    {
        showError('terms_accept', lang['data_zaakceptuj_reg']);
        return false;
    }
    xajax_fx.orderStepOne(xajax.getFormValues('orderForm'));
    return false;
 
}
//sprawdzanie formularza na stronie OTO
function checkOtoForm(displayReg){

   var first_name = getValue('first_name');
   var last_name = getValue('last_name');
   var city = getValue('city');
   
   if(displayReg == 1){
       var password = getValue('password');
       var password2 = getValue('password_confirm');
       if(getValue('username') == "" && displayReg == 1){
            showError('username', lang['data_wpisz_login']);
            return false;
        }
        else if(password == "" && displayReg == 1){
             showError('password', lang['data_wpisz_haslo']);
             return false;
        }
        else if(password2 == "" && displayReg == 1){
             showError('password_confirm', lang['data_wpisz_ponownie_haslo']);
             return false;
        }
        else if(password != password2 && displayReg == 1){
             showError('password', lang['data_hasla_nie_zagodne']);
             showError('password_confirm', lang['data_hasla_nie_zagodne']);
             return false;
        }
    }

    if(first_name == "" || first_name.length < 3){  
        showError('first_name', lang['data_wpisz_imie']);
        return false;
    }
    else if(last_name == "" || last_name.length < 3){
        showError('last_name', lang['data_wpisz_nazwisko']);
        return false;
    }
    else if(city == "" || city.length < 4){
         showError('city', lang['data_wpisz_miasto']);
         return false;
    }
    else if(getValue('country') == ""){
         showError('country', lang['data_wybierz_kraj']);
         return false;
    }
    else if(document.orderForm.terms_accept.checked==false) {
        showError('terms_accept', lang['data_zaakceptuj_reg']);
        return false;
    }

    if(displayReg == 1){ //rejestrowanie uzytkownika, bo wczesniej nie byl
        xajax_fx.regUser(xajax.getFormValues('orderForm'), 1);
    } else { //przejscie od razu do drugiego kroku zamowienia, bo byl juz zarejestrowany
       xajax_fx.logUser(xajax.getFormValues('orderForm'), 0); //logowanie uzytkownika
       xajax_fx.orderStepOne(xajax.getFormValues('orderForm'));
    }


    return false;
}

//sprawdzanie formularza z zakresem spadkow dla powiadomien o spadkach
function checkDroppingAlerts(){
  
    var drop_min = parseFloat($('#drop_range_from').val().replace(',', '.').replace('-', ''));
    var drop_max = parseFloat($('#drop_range_to').val().replace(',', '.').replace('-', ''));

    var odd_min = parseFloat($('#odd_range_from').val().replace(',', '.').replace('-', ''));
    var odd_max = parseFloat($('#odd_range_to').val().replace(',', '.').replace('-', ''));

    if (drop_min <= 0 || isNaN(drop_min)){
        showError('drop_range_from', lang['min_spadek_blad']);
        return false;
    }
    else if (drop_max <= 0 || isNaN(drop_max)){
        showError('drop_range_to', lang['max_spadek_blad']);
        return false;
    }
    else if (drop_max < drop_min){
        showError('drop_range_from', lang['max_spadek_wiekszy_min']);
        showError('drop_range_to', lang['max_spadek_wiekszy_min']);
        return false;
   }
   else if (odd_min <= 0 || isNaN(odd_min)){
        showError('odd_range_from', lang['xajax_wpisz_popr_kurs']);
        return false;
   }
   else if (odd_max <= 0 || isNaN(odd_max)){
        showError('odd_range_to', lang['xajax_wpisz_popr_kurs']);
        return false;
   }
   else if (odd_max < odd_min){
        showError('odd_range_to', lang['max_kurs_wiekszy_min']);
        showError('odd_range_from', lang['max_kurs_wiekszy_min']);
        return false;
   }
   else {
       xajax_fx.setDropRange(xajax.getFormValues('droppingAlertsForm'));
       return false;
   }     
}

function valid_order_form() {

    var content = document.getElementById('form_tresc_wiad').tresc_wiad.value;
    if (content == "" || content.length < 3){
        document.getElementById('order_kom').innerHTML = lang['data_wpisz_tresc_wiad'];
        setTimeout("document.getElementById('order_kom').innerHTML=''",3000);
    }
    else
        xajax_fx.admin_orderProblem(xajax.getFormValues('form_tresc_wiad'));

    return false;
}

function checkNan(field) {

    if (isNaN(field) || field == '') {
        document.getElementById('notifContent').innerHTML='Nieprawidłowy identyfikator surebeta.';
        setTimeout("document.getElementById('notifContent').innerHTML='&nbsp;'", 3000);
        return false;
    }

    xajax_fx.checkSurebet(xajax.getFormValues('surebetForm'));
    return false;
}

function delUser() {

    var field = document.getElementById('userList').options[document.getElementById('userList').selectedIndex].text;
    var array = field.split(': ');
    var username = array[1];
    var conf = confirm('Czy na pewno chcesz usunąć użytkownika "'+username+'"?');
    
    if (conf) xajax_users.del(xajax.getFormValues('userForm'));

    return false;
}

function delTeam(sport, teamId, leagueId, field, bookId){

    var conf = confirm('Czy na pewno chcesz usunąć ten błąd?');
    if (conf) xajax_teams.removeError(sport, teamId, getText('errCount_'+sport), leagueId, field, bookId);

    return false;
}

function logUser() {

    document.getElementById('submitButton').disabled = true;
    xajax_fx.logUser(xajax.getFormValues('log_form'));
}

//ustawianie cookie
function setCookie(c_name,value,expiredays){

    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());

}

//pobieranie cookie
function getCookie(c_name) {

if (document.cookie.length>0){
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1){

    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
  }
}
return "";
}

/*
 * FUNKCJE PRZELICZANIA CZASU
 *
 */
/**
 * Date.format()
 * string format ( string format )
 * Formatting rules according to http://php.net/strftime
 *
 * Copyright (C) 2006  Dao Gottwald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact information:
 *   Dao Gottwald  <dao at design-noir.de>
 *
 * @version  0.7
 * @todo     %g, %G, %U, %V, %W, %z, more/better localization
 * @url      http://design-noir.de/webdev/JS/Date.format/
 */

//var _lang = (navigator.systemLanguage || navigator.userLanguage || navigator.language || navigator.browserLanguage || '').replace(/-.*/,'');
var _lang = lang['page_lang'];
switch (_lang) {
	case 'de':
		Date._l10n = {
			days: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			months: ['Januar','Februar','M\u00E4rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
			date: '%e.%m.%Y',
			time: '%H:%M:%S'};
		break;
        case 'pl':
		Date._l10n = {
			days: ['niedziela','poniedzialek','wtorek','środa','czwartek','piątek','sobota'],
			months: ['stycznia','lutego','marca','kwietnia','maja','czerwca','lipca','sierpnia','września','października','listopada','grudnia'],
			date: '%e.%m.%Y',
			time: '%H:%M:%S'};
		break;
	case 'es':
		Date._l10n = {
			days: ['Domingo','Lunes','Martes','Mi�rcoles','Jueves','Viernes','S\u00E1bado'],
			months: ['enero','febrero','marcha','abril','puede','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'],
			date: '%e.%m.%Y',
			time: '%H:%M:%S'};
		break;
	case 'fr':
		Date._l10n = {
			days: ['dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi'],
			months: ['janvier','f\u00E9vrier','mars','avril','mai','juin','juillet','ao\u00FBt','septembre','octobre','novembre','decembre'],
			date: '%e/%m/%Y',
			time: '%H:%M:%S'};
		break;
	case 'it':
		Date._l10n = {
			days: ['domenica','luned\u00EC','marted\u00EC','mercoled\u00EC','gioved\u00EC','venerd\u00EC','sabato'],
			months: ['gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre'],
			date: '%e/%m/%y',
			time: '%H.%M.%S'};
		break;
	case 'pt':
		Date._l10n = {
			days: ['Domingo','Segunda-feira','Ter\u00E7a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S\u00E1bado'],
			months: ['Janeiro','Fevereiro','Mar\u00E7o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
			date: '%e/%m/%y',
			time: '%H.%M.%S'};
		break;
	case 'en':
	default:
		Date._l10n = {
			days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
			months: ['January','February','March','April','May','June','July','August','September','October','November','December'],
			date: '%Y-%m-%e',
			time: '%H:%M:%S'};
		break;
}
Date._pad = function(num, len) {
	for (var i = 1; i <= len; i++)
		if (num < Math.pow(10, i))
			return new Array(len-i+1).join(0) + num;
	return num;
};
Date.prototype.format = function(format) {
	if (format.indexOf('%%') > -1) { // a literal `%' character
		format = format.split('%%');
		for (var i = 0; i < format.length; i++)
			format[i] = this.format(format[i]);
		return format.join('%');
	}
	format = format.replace(/%D/g, '%m/%d/%y'); // same as %m/%d/%y
	format = format.replace(/%r/g, '%I:%M:%S %p'); // time in a.m. and p.m. notation
	format = format.replace(/%R/g, '%H:%M:%S'); // time in 24 hour notation
	format = format.replace(/%T/g, '%H:%M:%S'); // current time, equal to %H:%M:%S
	format = format.replace(/%x/g, Date._l10n.date); // preferred date representation for the current locale without the time
	format = format.replace(/%X/g, Date._l10n.time); // preferred time representation for the current locale without the date
	var dateObj = this;
	return format.replace(/%([aAbhBcCdegGHIjmMnpStuUVWwyYzZ])/g, function(match0, match1) {
		return dateObj.format_callback(match0, match1);
	});
}
Date.prototype.format_callback = function(match0, match1) {
	switch (match1) {
		case 'a': // abbreviated weekday name according to the current locale
			return Date._l10n.days[this.getDay()].substr(0,3);
		case 'A': // full weekday name according to the current locale
			return Date._l10n.days[this.getDay()];
		case 'b':
		case 'h': // abbreviated month name according to the current locale
			return Date._l10n.months[this.getMonth()].substr(0,3);
		case 'B': // full month name according to the current locale
			return Date._l10n.months[this.getMonth()];
		case 'c': // preferred date and time representation for the current locale
			return this.toLocaleString();
		case 'C': // century number (the year divided by 100 and truncated to an integer, range 00 to 99)
			return Math.floor(this.getFullYear() / 100);
		case 'd': // day of the month as a decimal number (range 01 to 31)
			return Date._pad(this.getDate(), 2);
		case 'e': // day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
			return Date._pad(this.getDate(), 2);
		/*case 'g': // like %G, but without the century
			return ;
		case 'G': // The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead
			return ;*/
		case 'H': // hour as a decimal number using a 24-hour clock (range 00 to 23)
			return Date._pad(this.getHours(), 2);
		case 'I': // hour as a decimal number using a 12-hour clock (range 01 to 12)
			return Date._pad(this.getHours() % 12, 2);
		case 'j': // day of the year as a decimal number (range 001 to 366)
			return Date._pad(this.getMonth() * 30 + Math.ceil(this.getMonth() / 2) + this.getDay() - 2 * (this.getMonth() > 1) + (!(this.getFullYear() % 400) || (!(this.getFullYear() % 4) && this.getFullYear() % 100)), 3);
		case 'm': // month as a decimal number (range 01 to 12)
			return Date._pad(this.getMonth() + 1, 2);
		case 'M': // minute as a decimal number
			return Date._pad(this.getMinutes(), 2);
		case 'n': // newline character
			return '\n';
		case 'p': // either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
			return this.getHours() < 12 ? 'am' : 'pm';
		case 'S': // second as a decimal number
			return Date._pad(this.getSeconds(), 2);
		case 't': // tab character
			return '\t';
		case 'u': // weekday as a decimal number [1,7], with 1 representing Monday
			return this.getDay() || 7;
		/*case 'U': // week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
			return ;
		case 'V': // The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.)
			return ;
		case 'W': // week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
			return ;*/
		case 'w': // day of the week as a decimal, Sunday being 0
			return this.getDay();
		case 'y': // year as a decimal number without a century (range 00 to 99)
			return this.getFullYear().toString().substr(2);
		case 'Y': // year as a decimal number including the century
			return this.getFullYear();
		/*case 'z':
		case 'Z': // time zone or name or abbreviation
			return ;*/
		default:
			return match0;
	}
}

function showHideSurebetsStatisticCharts(){
    charter_foot();
    charter_mlb();
    charter_hoc();
    charter_basket();
    $('#hide_charts').toggle('blind');
}



/**********************
 * GLOWNE FUNKCJE JQ
 ***********************
 ***********************/
$().ready(function(){init()});


function init(){
    var pathname = window.location.pathname;
    var pathTable = pathname.split('/');

    //MRUGANIE
    //Non-Plugin Function
    var doBlink = function(obj,start,finish) {
        jQuery(obj).fadeOut(500).fadeIn(500);if(start!=finish) {
            start=start+1;doBlink(obj,start,finish);
        }}

    //jQuery Blink Plugin
    jQuery.fn.blink = function(start,finish) {
        return this.each(function() {
            doBlink(this,start,finish)});
    }

    //END MRUGANIE
//////////////////////////////
///////MENU//////////////////
////////////////////////////
    $("#categories").addClass("ui-accordion ui-widget ui-helper-reset")
        .find("span")
            .click(function() {
                    var parent = $(this).parent('div');
                    var divs = $(parent).children('div');
                    var ilosc_wpisow = $(divs[0]).children('ul.s').length;
                    var id = $(divs[0]).attr('id');
                   // alert($(divs[0]).attr('id')+' ul='+$(divs[0]).children('ul.s').length);

                    if(ilosc_wpisow == 0){
                        /*Pobranie danych z bazy jezeli nie ma wczytanych*/
                        if(id == 'menu_football'){
                          xajax_fx.getMenu('football');
                          return false;
                        }else if(id == 'menu_hockey'){
                          xajax_fx.getMenu('hockey');
                          return false;
                        }else if(id == 'menu_basket'){
                          xajax_fx.getMenu('basket');
                          return false;
                        }else if(id == 'menu_tennis'){
                          xajax_fx.getMenu('tennis');
                          return false;
                        }
                    }

                    $(this).toggleClass("menu-state-active")
                           .toggleClass("ui-corner-bottom")
                    .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s")
                    .end()
                    .next().next()
                    .toggleClass("ui-accordion-content-active").toggle('blind');

                    $('div.g').attr('class','o');
                    $('div:has(.menu-state-active)').attr('class','g');
                    return false;
            })
            .next().next().hide();




    /*ustawienie aktywnego odpowiedniego menu*/
    if(pathTable[1] == 'football-odds' || pathTable[1] == 'kursy-pilka-nozna' || pathTable[1] ==''){
        $('#menu_football').toggleClass("ui-accordion-content-active").show();
        $('#s_menu_football').toggleClass("menu-state-active");
        $('div:has(.menu-state-active)').attr('class','g');
    }else if(pathTable[1] == 'hockey-odds' || pathTable[1] == 'kursy-hokej'){
        $('#menu_hockey').toggleClass("ui-accordion-content-active").show();
        $('#s_menu_hockey').toggleClass("menu-state-active");
        $('div:has(.menu-state-active)').attr('class','g');
    }else if(pathTable[1] == 'mlb-odds' || pathTable[1] == 'kursy-mlb'){
       //$('#menu_mlb').toggleClass("ui-accordion-content-active").toggle('blind');
       $('#s_menu_mlb').toggleClass("menu-state-active");
       $('div:has(.menu-state-active)').attr('class','g');
    }else if(pathTable[1] == 'basketball-odds' || pathTable[1] == 'kursy-koszykowka'){
       $('#menu_basket').toggleClass("ui-accordion-content-active").show();
       $('#s_menu_basket').toggleClass("menu-state-active");
       $('div:has(.menu-state-active)').attr('class','g');
    }
    else if(pathTable[1] == 'tennis-odds' || pathTable[1] == 'kursy-tenis'){
       $('#menu_tennis').toggleClass("ui-accordion-content-active").show();
       $('#s_menu_tennis').toggleClass("menu-state-active");
       $('div:has(.menu-state-active)').attr('class','g');
    }
    /*menu zawsze otwarte*/
    $('#menu_surebets').toggleClass("ui-accordion-content-active").show();
    $('#s_menu_surebets').toggleClass("menu-state-active");

    $('#menu_bookmakers').toggleClass("ui-accordion-content-active").show();
    $('#s_menu_bookmakers').toggleClass("menu-state-active");

    $('#menu_dropping').toggleClass("ui-accordion-content-active").show();
    $('#s_menu_dropping').toggleClass("menu-state-active");

    $('div:has(.menu-state-active)').attr('class','g');

    /*kalkulator*/

    $('#surType3').click(function(){
        if(jQuery.browser.msie){
            $('#3waySurebet').show();
            $('#2waySurebet').hide();
        }else{
            if($('#3waySurebet').is(':hidden')){
                $('#3waySurebet').show('blind', 700);
                $('#2waySurebet').hide('slow');
            }
        }
        
    });
    $('#surType2').click(function(){
        if(jQuery.browser.msie){
            $('#2waySurebet').show();
            $('#3waySurebet').hide();
        }else{
            if($('#2waySurebet').is(':hidden')){
                $('#2waySurebet').show('blind',700);
                $('#3waySurebet').hide('slow');
            }
        }
    });
    /*Nadawanie title do pozycji menu z info zeby kliknac w celu rozwinięcia*/
    $('#categories>div>span').attr('title',lang['rozwin_menu']);
    /*Rozwijanie informacji o surebets (mini kalkulator)*/
    $('a.redLink').click(function(){
        $(this).next().toggle('blind');
    });

    //dla strony polecania znajomego
    $('p.faqq').click(function(){
        $(this).next('div').toggle('blind');
    });

     ///////////////////////////////////////
    //filstrowanie spadkow
    /////////////////////////////////
    $('#id_spadek_filter').click(function(){
        $(':radio[name=fsporty]:checked').click();
    });
    //ukrywanie panelu filtra
    $('#data_filter_bt').click(function(){
        $('#filter_body').toggle('blind');
    });
    $('#dropping_notifs').click(function(){
        $('#dropping_notifs_body').toggle('blind');
    });
    //ikony zamiast radio
    $('img.filter_ico, span.sp_label').click(function(){
        //usuniecie bolda z ostatniego przycisku
        $(':radio[name=fsporty]:checked').parent().removeClass('bold').removeClass('mouseOver');
        //zaznaczenie przycisku
        $(this).parent().find(':radio').attr('checked', 'checked');
        $(this).parent().addClass('bold').addClass('mouseOver');
        //wykonanie filtracji
        $(':radio[name=fsporty]:checked').click();
    });

     $('a#setTime').click(function(){
        $('span#setTimeForm').toggle('blind', 300);
     });

     $('select#time_from').change(function(){

         var value_from = this.value;
         value_from = parseInt(value_from);
         var value_to = document.getElementById('time_to').value;
         value_to = parseInt(value_to);

         $('select#time_to').html('');

         for (var i=0; i<=23; i++){
             var sel = '';
             if (i == value_to) sel = 'selected="selected"';
             if (i != value_from)
                $('select#time_to').append('<option '+sel+' value="'+i+'">'+i+'</option>');
         }
     });

     //test zmiany koloru daty aktualizacji
     $('.down_time').each(function(){
         var czasPobrania = $(this).attr('mili');
         var o = $(this);
         changeColor(czasPobrania, o);
     });

//alert(new Date(1274865025*1000));
     //funkcja odpowiedzialna za ustalanie koloru z zaleznosci od czasu
     function changeColor(czasPobrania, o){
        setTimeout(function(){
            var aktCzas = Math.round(new Date().getTime()/1000.0);
            var roznica = aktCzas - czasPobrania;
            var flag = true; //flaga sprawdzajaca czy jest jeszcze potrzeba sprawdzania czasu uploadu
            o.removeClass(function(){
                return $(this).attr('class');
            });
            if(roznica < 300){
                o.addClass('down_time box_g');
            }else if (roznica < 600){
                o.addClass('down_time box_y');
            }else{
                o.addClass('down_time box_r');
                flag = false;
            }
            if(flag){//jezeli jest kolor inny niz czerwony
                changeColor(czasPobrania, o);
            }
         }, 10000);
     }

     //podmiana czasow na aktualna strefe czasowa
     $('[ts]').each(function(){
         var format = null;
         if($(this).hasClass('YmdHM')){
             format = '%Y-%m-%d %H:%M';
         }else if ($(this).hasClass('dmHM')){
             format = '%d-%m %H:%M';
         }else if($(this).hasClass('hM')){
             format = '%H:%M';
         }else if($(this).hasClass('dBY')){
             format = '%d %B %Y';
         }

         var t = (new Date($(this).attr('ts')*1000)).format(format);
         $(this).text(t);
     });

     ///////////////////////////////////////////////
     //////////////////////////////////////////////
     ////////USTAWIANIE STREFY CZASOWEJ PROFILU///
     ////////////////////////////////////////////
     var strefa_zal_uzytkownik = $('#time_zone').attr('time');
     $('#time_zone option[value='+strefa_zal_uzytkownik+']').attr('selected','selected');
     //alert($.getUrlVar('q'));
     ///////////////////////////////////////////
     ///////WYSZUKIWARKA///////////////////////
     /////////////////////////////////////////
     $('#menu_finder_field').val(lang['wpisz_nazwe_druzyny']);

     $("#finder_field, #menu_finder_field").autocomplete({
            source: '/files/search.php',
            minLength: 2,
            select: function(event, ui) {
                var text = $(this).val();
                if(text == 'Brak danych' || text == 'No data'){
                     $(this).val(' ');
                     
                }else{
                    finder_submiter = true;
                    //$(this).val(encodeURIComponent(text));
                    $(this).parent('form').submit();
                }
            },
            close: function (){
               var text = $(this).val();
               if(text == 'Brak danych' || text == 'No data'){
                     $(this).val(' ');

                }
            }
    }).click(function(){
        var text = $(this).val();
        if(text == '(enter team name)' || text == '(wpisz nazwę drużyny)'){
            $(this).val('');
        }
    });

     $('span.buk_powiad').click(function() {
         $(this).parent().parent().parent().children('div.notifBooks').toggle();
     });

     ////////////////////////////////////////
     /////////SUREBETS STATS////////////////
     //////////////////////////////////////
     $('table.s_stats tbody tr:even').css('background-color', '#FAFAFA');
     $('table.s_stats tbody tr:odd').css('background-color', '#ECECEC');
     $('table.s_stats').tablesorter({sortList: [[5,1]]});
     //////////////////////////////////////
     /////END SUREBETS STATS//////////////
     ////////////////////////////////////

    //USTAWIENIE OKNA POMOCY
    $("#help_window").dialog({
        resizable: false,
        autoOpen: false,
        width: 270,
        open:function() {
                $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
              }
    });
    setHelpPopup();
    $("#help_window").parent().css('padding', '2px');
    $("#help_window").parent()
                     .find('div.ui-dialog-titlebar').css('padding' , '5px')
                                                    .removeClass('ui-widget-header')
                                                    .addClass('red_ui-widget-header');
    $("#help_window").removeClass('ui-widget-content');

   paintButtons();


    ////////////////////////////////////////////
    ////////PROFIL///////////////////
    ////////////////////////////////
    if($('#smsNum').val() != ''){
        $('#free_sms_package_info').hide();
    }

}

$(document).ready(function(){
	$(".fb_likebox1").hover(function(){ $(this).stop(true,false).animate({right:  0}, 700); },function(){ $(".fb_likebox1").stop(true,false).animate({right: -294}, 700); });
});

//Sprawdzanie czy mozna wyszukac fraze
var finder_submiter = false;
function checkFinder(){
    return finder_submiter;
}

function paintButtons(){
    $(".yellow_button").addClass('ui-widget')
                      .addClass('ui-button-text-only')
                      .addClass('ui-corner-all')
                      .addClass('yellow_ui-button')
                      .addClass('yellow_ui-state-default')
                      .mouseover(function(){
                          $(this).addClass('yellow_ui-state-hover');
                      }).mouseout(function(){
                          $(this).removeClass('yellow_ui-state-hover');
                      }).css('fontSize','12px');

    $(".red_button").addClass('ui-widget')
                      .addClass('ui-button-text-only')
                      .addClass('ui-corner-all')
                      .addClass('yellow_ui-button')
                      .addClass('red_ui-state-default')
                      .mouseover(function(){
                          $(this).addClass('red_ui-state-hover');
                      }).mouseout(function(){
                          $(this).removeClass('red_ui-state-hover');
                      }).css('fontSize','12px');
}

function filtrowaniePoSpadkach(){
    var min = parseFloat($('#zakres_spadku_od').val().replace(',', '.').replace('-', ''));
    var max = parseFloat($('#zakres_spadku_do').val().replace(',', '.').replace('-', ''));
    //sprawdzanie wprowadzonych wartosci


    //ukrywanie wierszy
    if(min > 0 && max > 0){
        if(min < max){
            $('#zakres_spadku_od').val(max);
            $('#zakres_spadku_do').val(min);
            max = min;
            min = $('#zakres_spadku_od').val();
        }
        min *= -1;
        max *= -1;

        $('table.tble tbody td.r').each(function(){
            var val = parseFloat($(this).text());
            if(val < min || val > max){
                $(this).parent().hide();
            }
        });
    }

    if($('table.tble tbody tr:visible').length < 1){
        $('#filter_footer_error').show();
    }else{
        $('#filter_footer_error').hide();
    }
}

function filtrowaniePoSportach(){

}

function showMenuItems(span_id){
    $('#'+span_id).toggleClass("ui-accordion-header-active").toggleClass("menu-state-active")
                .toggleClass("menu-state-default").toggleClass("ui-corner-bottom")
        .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s")
        .end()
        .next().next()
        .toggleClass("ui-accordion-content-active").toggle('blind');

    $('div.g').attr('class','o');
    $('div:has(.menu-state-active)').attr('class','g');

}


function calculateSurebet3way(miniCalcName){
    var add = '';
    if (miniCalcName != ''){
        add = '_'+miniCalcName;
    }
    var overallStake = $('#overallStake'+add).val().replace(",", ".");
    var odd1 = $('#3odd1'+add).val().replace(",", ".");
    var oddX = $('#3oddX'+add).val().replace(",", ".");
    var odd2 = $('#3odd2'+add).val().replace(",", ".");
   // alert('1= '+odd1+' x= '+oddX+' 2= '+odd2+' add='+add);
    var error = '';
    var margin = 0;
    var loss = 0;
    var text = '';
    var stake1 = 0;
    var stakeX = 0;
    var stake2 = 0;
    var win1 = 0;
    var winX = 0;
    var win2 = 0;
    var netProfit1 = 0;
    var netProfitX = 0;
    var netProfit2 = 0;
    var netProfitRate = 0;



    if(isNaN(odd1) || odd1 < 1){
       error = lang['xajax_wpisz_popr_kurs'];
       showError('3odd1'+add, error);
    }
    if(isNaN(oddX) || oddX < 1){
       error = lang['xajax_wpisz_popr_kurs'];
       showError('3oddX'+add, error);
    }
    if(isNaN(odd2) || odd2 < 1){
       error = lang['xajax_wpisz_popr_kurs'];
       showError('3odd2'+add, error);
    }

    if(error != ''){
        if($('#surebetInfo3'+add).is(':visible')){
            $('#surebetInfo3'+add).hide('blind');
        }
        return false;
    }

    margin = 1/odd1 + 1/oddX + 1/odd2;
    //alert('margin '+margin);
    if(margin >= 1){
        loss = ((margin-1) * 100).toFixed(2);
        text = lang['xajax_brak_surbeta_strata']+' '+loss+'%';
        showError('3odd1'+add, text);
        showError('3oddX'+add, text);
        showError('3odd2'+add, text);
        if($('#surebetInfo3'+add).is(':visible')){
            $('#surebetInfo3'+add).hide('blind');
        }
    }else{
        if(isNaN(overallStake) || overallStake <= 0){
           text = lang['xajax_wprow_stawke'];
           showError('overallStake'+add, text);
           if($('#surebetInfo3'+add).is(':visible')){
               $('#surebetInfo3'+add).hide('blind');
           }
        }else{ //jest stawka calkowita, liczmy stawki na poszczegolne rozstrzygniecia
            stake1 = surebetStake(margin,odd1,overallStake);
            stakeX = surebetStake(margin,oddX,overallStake);
            stake2 = surebetStake(margin,odd2,overallStake);

            win1 =  (stake1 * odd1).toFixed(2);
            netProfit1 = (win1 - overallStake).toFixed(2);
            netProfitRate =(netProfit1/overallStake*100).toFixed(2);

            winX =  (stakeX * oddX).toFixed(2);
            netProfitX = (winX - overallStake).toFixed(2);

            win2 =  (stake2 * odd2).toFixed(2);
            netProfit2 = (win2 - overallStake).toFixed(2);

            if (miniCalcName == '') {// tylko dla pełnej wersji kalkulatora
                $('#formInfo'+add).hide();
            }

            $('#surebetProfit3'+add).html(netProfitRate+'%');
            if($('#surebetInfo3'+add).is(':hidden')){
                $('#surebetInfo3'+add).show('blind');
                $('#surebetStakes3'+add).show('blind');
            }
            $('#3stake1'+add).html(stake1);
            $('#3stakeX'+add).html(stakeX);
            $('#3stake2'+add).html(stake2);
            $('#surebetWin3_1'+add).html(win1);
            $('#netProfit3_1'+add).html(netProfit1);
            $('#surebetWin3_X'+add).html(winX);
            $('#netProfit3_X'+add).html(netProfitX);
            $('#surebetWin3_2'+add).html(win2);
            $('#netProfit3_2'+add).html(netProfit2);
        }
    }

    return false;
}

function calculateSurebet2way(miniCalcName){
    var add = '';
    if (miniCalcName != ''){
        add = '_'+miniCalcName;
    }
    //escapowanie kropki w id atrybutu, bo inaczej nie dziala, jesli id zawiera kropke
    add = add.replace(".", "\\.");
    
    var overallStake = $('#overallStake'+add).val().replace(",", ".");
    var odd1 = $('#2odd1'+add).val().replace(",", ".");
    var odd2 = $('#2odd2'+add).val().replace(",", ".");
    var error = '';
    var margin = 0;
    var loss = 0;
    var text = '';
    var stake1 = 0;
    var stake2 = 0;
    var win1 = 0;
    var win2 = 0;
    var netProfit1 = 0;
    var netProfit2 = 0;
    var netProfitRate = 0;
  
    if(isNaN(odd1) || odd1 < 1){
       error = lang['xajax_wpisz_popr_kurs'];
       showError('2odd1'+add, error);
    }
    if(isNaN(odd2) || odd2 < 1){
       error = lang['xajax_wpisz_popr_kurs'];
       showError('2odd2'+add, error);
    }
    if(isNaN(overallStake) || overallStake <= 0){
       text = lang['xajax_wprow_stawke'];
       showError('overallStake'+add, text);
       if($('#surebetInfo3'+add).is(':visible')){
           $('#surebetInfo3'+add).hide('blind');
       }
    }

    if(error != ''){
        if($('#surebetInfo2'+add).is(':visible')){
            $('#surebetInfo2'+add).hide('blind');
        }
        return false;
    }

    margin = 1/odd1 + 1/odd2;
    //alert('margin '+margin);
    if(margin >= 1){
        loss = ((margin-1) * 100).toFixed(2);
        text = lang['xajax_brak_surbeta_strata']+' '+loss+'%';
        showError('2odd1'+add, text);
        showError('2odd2'+add, text);
        if($('#surebetInfo2'+add).is(':visible')){
            $('#surebetInfo2'+add).hide('blind');
        }
    }else{
        if(isNaN(overallStake) || overallStake <= 0){
           text = lang['xajax_wprow_stawke'];
           if($('#surebetInfo2'+add).is(':visible')){
                $('#surebetInfo2'+add).hide('blind');
           }
        }else{ //jest stawka calkowita, liczmy stawki na poszczegolne rozstrzygniecia
            stake1 = surebetStake(margin,odd1,overallStake);
            stake2 = surebetStake(margin,odd2,overallStake);

            win1 =  (stake1 * odd1).toFixed(2);
            netProfit1 = (win1 - overallStake).toFixed(2);
            netProfitRate =(netProfit1/overallStake*100).toFixed(2);

            win2 =  (stake2 * odd2).toFixed(2);
            netProfit2 = (win2 - overallStake).toFixed(2);

            if (miniCalcName == '') {// tylko dla pełnej wersji kalkulatora
                $('#formInfo'+add).hide();
            }

            $('#surebetProfit2'+add).html(netProfitRate+'%');

            if($('#surebetInfo2'+add).is(':hidden')){
                $('#surebetInfo2'+add).show('blind');
                $('#surebetStakes2'+add).show('blind');
            }
            $('#2stake1'+add).html(stake1);
            $('#2stake2'+add).html(stake2);
            $('#surebetWin2_1'+add).html(win1);
            $('#netProfit2_1'+add).html(netProfit1);
            $('#surebetWin2_2'+add).html(win2);
            $('#netProfit2_2'+add).html(netProfit2);
        }
    }

    return false;
}

//obliczanie stawki w surebecie
function surebetStake(margin,odd,capital){
     return (1/margin/odd*capital).toFixed(2);
}

function checkUncheckValidNotification(id, isChecked){
    var icon = $('#'+id).attr('src');
    if((icon == '/images/remove.png' && isChecked == true) || (icon == '/images/check.gif' && isChecked == false)){
        $('#'+id).click();
    }
}


function setHelpPopup(){
    $("span.ui-icon-info").mouseover(function(e){
        var text = $(this).attr('help');
        var title = $(this).attr('header');
        $("#help_window").html(text);
        $("#help_window").dialog('option', 'title', title);
        $("#help_window").dialog('open');
        $("#help_window").dialog({position: [e.clientX+20, e.clientY]});

    }).mouseout(function(e){
         $("#help_window").dialog('close');
    });
}

function hideFreeSmsPackageInfo(){
   $('#free_sms_package_info').hide('blind');
}

