$(function() {
    // autocomplete
    $("#author").autocomplete("./lib/autocomplete2.lib.php", { max : 10, matchSubset : false, extraParams : { type : 'author' }});
    $("#publisher").autocomplete("./lib/autocomplete2.lib.php", { max : 10, matchSubset : false, extraParams : { type : 'publisher' }});

    // 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();});

    // city autocomplete
    $("#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) {}

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

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

    // USER
    // 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();
    });

    $("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
    $('.js-show').show();$('.js-hide').hide();
    
    // hide delivery description
    $('div.delivery-description').hide();

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

    // disable irrelevant options
    $('input[@name=delivery]:disabled, input[@name=payment]:disabled').parent().parent().addClass('disabled');

    // show delivery description (2)
    $('input[@name=delivery]:checked').parent().parent().find('.delivery-description2').show();

    // show category selected by fragment
    //var fragment = window.location.href.split('#')[1];
    if (fragment != null) {
        $("h4#" + fragment).next("div.delivery-pay-div").show();
        window.scrollTo(0, $("h4#" + fragment).offset().top);
    }

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

    // hide delivery/pay data on click
    $('.delivery-pay-title').click(function (e) {
        e.preventDefault();

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

        // show only selected div
        $('.delivery-pay-div').hide();
        var dp_div = $(this).parent().next();
        dp_div.show();


        // uhcheck, enable, unhide delivery/payment
        $('input[@name=delivery], input[@name=payment]').each(function() {
            if ($(this).parent().parent().not('.forbidden').size() == 1) {
                $(this).attr('checked', false).attr('disabled', false).parent().parent().removeClass('disabled');
            }
        });

        // check first items
        var d_cb = dp_div.find('input[@name=delivery]');
        if (d_cb.size() == 1) d_cb.attr('checked', true);

        var p_cb = dp_div.find('input[@name=payment]');
        if (p_cb.size() == 1) p_cb.attr('checked', true);
        
        // disable irrelevant options (benefit plus)
        if ((d_cb.size() != 0 && d_cb.not(':disabled').size() == 0) || (p_cb.size() != 0 && p_cb.not(':disabled').size() == 0)) {
             d_cb.attr('disabled', true).parent().parent().addClass('disabled');
             p_cb.attr('disabled', true).parent().parent().addClass('disabled');
        }
    });

    // disable irrelevant options on delivery choice
    $('input[@name=delivery]').click(function() {
        var id_delivery = $(this).val().split('|')[0];

        var pattern = new RegExp('\\(' + id_delivery + ',([0-9]+)\\)', 'g');
        var allowed_payment = allowed.match(pattern).join().replace(pattern, "$1").split(",");

        $('.delivery-description2').hide();
        $(this).parent().parent().find('.delivery-description2').show();

        $('input[@name=payment]').each(function() {
            var item = $(this);

            // enable
            if ($.inArray(item.val().split('|')[0], allowed_payment) >= 0) {
                if ($(this).parent().parent().not('.forbidden').size() == 1) {
                    item.attr('disabled', false);
                    item.parent().parent().removeClass('disabled');
                }
            }
            // disable
            else {
                item.attr('disabled', true);
                item.attr('checked', false);
                item.parent().parent().addClass('disabled');
            }
        });
    });

    // disable irrelevant options on payment choice
    $('input[@name=payment]').click(function() {
        var id_payment = $(this).val().split('|')[0];

        var pattern = new RegExp('\\(([0-9]+),' + id_payment + '\\)', 'g');
        var allowed_delivery = allowed.match(pattern).join().replace(pattern, "$1").split(",");

        $('input[@name=delivery]').each(function() {
            var item = $(this);

            // enable
            if ($.inArray(item.val().split('|')[0], allowed_delivery) >= 0) {
                if ($(this).parent().parent().not('.forbidden').size() == 1) {
                    item.attr('disabled', false);
                    item.parent().parent().removeClass('disabled');
                }
            }
            // disable
            else {
                item.attr('disabled', true);
                item.attr('checked', false);
                item.parent().parent().addClass('disabled');
            }
        });
    });
});

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 formatClubCardNumber(text)
{
    var ccn = text.replace(/ /g,"");

    if (isNaN(ccn))
    {
        alert("Číslo klubovej karty musí obsahovať iba čísla!");
        return text;
    }

    return ccn;
}

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;
}
