$(function() {
    // tooltip
    $('.tooltip, .status').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        extraClass: "pretty-black2",
        fixPNG: true,
        opacity: 0.95,
        left: -120
    });
   
   //block UI 
    $('#notificationButton').click(function() {
        $.blockUI({ message: $('#notificationForm'),
                    css: { 
                        border: 'none', 
                        padding: '25px',
                        backgroundColor: '#00005f', 
                        '-webkit-border-radius': '10px', 
                        '-moz-border-radius': '10px', 
                        opacity: 1, 
                        color: '#fff' 
                    },
                    overlayCSS: { backgroundColor: '#fff' }                    
        }); 
 
        $('.blockOverlay').attr('title','Klikni pre návrat').click($.unblockUI);
        $('.closeButton').click($.unblockUI);
    }); 

    // password hider - doesn't work with checker
    //$('input#passwordCheck').dPassword();

    // password checker
    $('input#passwordCheck').keyup(function(){ $('#result').html(passwordStrength($('#passwordCheck').val(),$('#username').val())).show(); });

    $("#communeAutoComplete").autocomplete("/lib/autoComplete.lib.php", {
        width: 260,
        selectFirst: false
    });

    $("#state").change(function() {
        if ($(this).val() == 1)
        {
            $("#communeAutoComplete").autocomplete("/lib/autoComplete.lib.php", {
                width: 260,
                selectFirst: false
            });
        }
        else
        {
            $("#communeAutoComplete").unautocomplete();
        }
    });

    // idTabs
    $('#tabs').idTabs();
    
    //ticker
    //$("div#scrollingText").smoothDivScroll({scrollingSpeed: 1, autoScroll: "always", autoScrollDirection: "endlessloop", pauseAutoScroll: "mouseover", autoScrollSpeed: 1});

    try
    {
        var ticker_holder = $('.ticker-holder').get(0);
        var ticker_text = $('.ticker').get(0);
        var ticker_pos = ticker_text.parentNode.offsetWidth;
 
        var ticker_data = $(ticker_holder).html();
        $(ticker_text).parent().html('<marquee scrollamount="2" scrolldelay="40">' + ticker_data + '</marquee>');
 
        $('#ticker').hover
        (
            function() { $('marquee', this).get(0).stop();  },
            function() { $('marquee', this).get(0).start(); }
        );
 
         
    }
    catch (o) {}
    

    $("a#show-lost-password").click(function() { $("div#lost-password-wrapper").slideDown("slow"); });

    // hiding order details (in order list)
    $('tr.order-detail').hide();
    $('a.show-order-detail').toggle(function() { $(this).parent().parent().next().show(); }, function() { $(this).parent().parent().next().hide(); });

    // CASH
    // hide delivery pay divs
    $('div.delivery-pay-div').each(function() {
        if ($(this).find('input[@name=delivery]:checked, input[@name=pay]:checked').size() == 0) $(this).hide();
    });

    // hide delivery description
    $('div.delivery-description').hide();

    var fragment = window.location.href.split('#')[1];
    $('.hidingDiv').hide();
    if (fragment != '' && $('#' + fragment).size() > 0) $('#' + fragment).show();
    else $('.hidingDiv:first').show();

    $('.showDiv').click(function (e) {
        e.preventDefault();
        $('.hidingDiv').hide();
        $("#" + this.href.split('#')[1]).show();
    });

    // hiding form items (in registration form)
    if ($("input[name=AFClubJoinRequest]").is(':not(:checked)')) $("tr#AFClubJoinData").hide(); // hide on load
    $("input[name=AFClubJoinRequest]").change(function() {
        if ($(this).is(':checked')) $("tr#AFClubJoinData").show();
        else $("tr#AFClubJoinData").hide();
    });
});

function showDiv(id)
{
    $('div.delivery-pay-div').hide();
    $('div#' + id).show();
    uncheckRadios('pay');
    uncheckRadios('delivery');
}

function uncheckRadios(name)
{
    var radios = document.getElementsByName(name);
    for (var i = 0; i < radios.length; i++) {
        radios[i].checked = false;
    }
}

function submit_enter(event) {
    var key_code;

    if (window.event) key_code = window.event.keyCode;
    else if (event) key_code = event.which;
    else return true;

    if (key_code == 13) document.getElementById('change_count').click();
    else return true;

    return false;
}

function control_email(str)
{
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.indexOf(at,(lat+1))!=-1){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.indexOf(dot,(lat+2))==-1){
        alert("Chybná emailová adresa.")
        return false
    }

    if (str.indexOf(" ")!=-1){
        alert("Chybná emailová adresa.")
        return false
    }

    return true
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{
    var i;
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function trim(s)
{
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

function stripCharsInBag(s, bag)
{
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone)
{
    var bracket=3
    strPhone=trim(strPhone)
    if(strPhone.indexOf("+")>1) return false
    if(strPhone.indexOf("-")!=-1)bracket=bracket+1
    if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
    var brchr=strPhone.indexOf("(")
    if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
    if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateForm(Phone)
{

    if ((Phone.value==null)||(Phone.value=="")){
        alert("Prosím zadajte telefónne číslo")
        Phone.focus()
        return false
    }
    if (checkInternationalPhone(Phone.value)==false){
        alert("Neplatné telefónne číslo")
        Phone.value=""
        Phone.focus()
        return false
    }
    return true
}

function ucFirst(text)
{
    text += '';
    
    var ucFirstStr = text.charAt(0).toUpperCase();
    ucFirstStr = ucFirstStr + text.substr(1).toLowerCase();

    return ucFirstStr;
}

function formatPSC(text)
{
    var psc = text.replace(/ /g,"");

    if (isNaN(psc))
    {
        alert("PSČ musí obsahovať iba čísla!");
        return text;
    }

    psc = psc.charAt(0)+psc.charAt(1)+psc.charAt(2)+" "+psc.charAt(3)+psc.charAt(4)+"";
    return psc;
}


function formatMobil(text)
{
    var mobil = text.replace(/ /g,"");
    mobil = text.replace("-","");
    
    if (isNaN(mobil))
    {
        alert("Telefónne číslo musí obsahovať iba čísla!");
        return text;
    }

    mobil = mobil.charAt(0)+mobil.charAt(1)+mobil.charAt(2)+mobil.charAt(3)+" "+mobil.charAt(4)+mobil.charAt(5)+mobil.charAt(6)+mobil.charAt(7)+mobil.charAt(8)+mobil.charAt(9)+"";
    return mobil;
}

function formatMobil2(text)
{
    text=text.replace(/ /g,"");
    formatedMobil=text.charAt(0)+text.charAt(1)+text.charAt(2)+text.charAt(3)+" "+text.charAt(4)+text.charAt(5)+text.charAt(6)+text.charAt(7)+text.charAt(8)+text.charAt(9)+'';
    document.otherForm.mobil2.value=formatedMobil;
}

function formatPhone(text)
{
    text=text.replace(/ /g,"");
    formatedMobil=text.charAt(0)+text.charAt(1)+text.charAt(2)+" "+text.charAt(3)+text.charAt(4)+text.charAt(5)+text.charAt(6)+text.charAt(7)+text.charAt(8)+'';
    document.otherForm.phone.value=formatedMobil;
}


function control_data(a) {

    if(a.username.value=='') {
        alert('Doplnte prosím Váš email');
        return false;
    }
    if(a.password.value=='') {
        alert('Doplnte prosím heslo');
        return false;
    }
    if(a.password2.value=='') {
        alert('Podtvrďte prosím heslo');
        return false;
    }

    if(a.name.value=='') {
        alert('Doplnte prosím Vaše meno');
        return false;
    }
    if(a.surname.value=='') {
        alert('Doplnte prosím Vaše priezvisko');
        return false;
    }
    if(a.street.value=='') {
        alert('Doplnte prosím ulicu');
        return false;
    }
    if(a.city.value=='') {
        alert('Doplnte prosím mesto');
        return false;
    }
    if(a.psc.value=='') {
        alert('Doplnte prosím PSČ');
        return false;
    }
    if(a.name.value=='') {
        alert('Doplnte prosím Vaše meno');
        return false;
    }
    if(a.mobil1.value=='') {
        alert('Doplnte prosím telefonický kontakt');
        return false;
    }

    return (control_email(a.username.value)&&ValidateForm(a.mobil1));
}

// submit check function
function submit_check(form) {
    var return_value = true;
    $(form).find(".required input, .required select, .required textarea").each(function() {
        var value = "";
        if ($(this).get(0).tagName == 'SELECT') value = $(this).find('option:selected').val();
        else value = $(this).val();

        if (value == "") {
            return_value = false;
            $(this).css({'background-color' : '#fff7b6'});
        }
        else {
            $(this).css({'background-color' : 'transparent'});
        }
    });

    if (return_value == false) alert("Nevyplnili ste všetky povinné položky!");

    return return_value;
}

function fbs_click()
{
    u=location.href;
    t=document.title;
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
}
