var params = {
    buffertime: 30 * 60 * 1000,
    codenum: 6
};


jQuery.extend(
{
    t: function(x){
        return $.jx.lng[x] ? $.jx.lng[x] : x;
    },
    loc: function(l){location.href = l;},
    dt: function(s){
        if(s){
            return new Date(s.replace(/(\d{4})\-(\d{2})\-(\d{2})[\sT](\d{2})\:(\d{2})/,"$2/$3/$1 $4:$5"));
                //? new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3]),parseInt(t[4]),parseInt(t[4]))
                //: new Date(Date.parse(s));
        }
        return new Date();
    },
    req: function(d,callback)
    {
        return $.ajax({
            type: "POST",
            url: '/uajax.php',
            data: d,
            dataType: "json",
            success: function(data) {
                callback(data);
            }
        });
    },
    gen: function(l,q){
        q = q||0;
        var p = "",
            n = [10,36,62,70,84];
            s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+-=/<>?.,`~";
        for(var i= 0; i<l; i++)
        {
            p += s[Math.floor(Math.random() * (n[q]-1))];
        }
        return p;
    },
    clrform:function (el)
    {
        $(el).find(':input').each(function() {
            if(this.id == 'tAlias') return;
            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'hidden':
                case 'textarea':
                    $(this).val('');
                break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });
    },
    frmt: function(n,p)
    {
        p = p||0;
        if(p == -1) return n;
        p = Math.pow(10,p);
        return Math.round(parseFloat(n)*p)/p;
    },
    rplc: function(tmp,rules)
    {
        $.each(rules,function(n,v){
            var re = new RegExp('%'+n+'%','g');
            tmp = tmp.replace(re,v);
        });
        return tmp.replace(/\%\w+\%/g,'');
    },
    tmp: function(id,rules)
    {
        return $($.rplc($(id).html(),rules));
    }
});

$(document).ready(function(){
    // error
    if(error_alert) $.colorbox({opacity: 0.5, width:"500px", html: '<h1>'+error_alert+'</h1>'});

    // IMAGES module (gallery)
    $("a[rel='gallery']").colorbox({opacity: 0.5,maxWidth:1000,maxHeight:600,current:"{current} из {total}"});
    
    // CLIENT module
    $("#loader").ajaxStart(function(){$(this).show();}).ajaxStop(function(){$(this).hide();});
    $('#register,#register2').colorbox({opacity: 0.5, width:"500px", inline:true, href:"#clients-register"});
    
    $('#clients-register-button').click(function(){
        
        $.req("q=user::register&"+$(this).parents('form').find('input').serialize(),function(d)
        {
            
            if(d.res == 'OK')
            {
                $.colorbox({opacity: 0.5,width:"500px", html: '<h1>'+d.html+'</h1>'});
                setTimeout("location.href=''",10000);
                return;
            }
            $('#clients-register-error').html(d.html);
            setTimeout(function(){$('#clients-register-error').html('');},5000);
        });

    });
    
    $('#clients-login-button').click(function(){
        $.req("q=user::login&"+$(this).parents('form').find('input').serialize(),function(d)
        {
            if(d.res == 'OK')
            {
                location.href='';
                return;
            }
            $.colorbox({opacity: 0.5,width:"500px", html: '<h1>'+d.html+'</h1>'});
            setTimeout(function(){$.colorbox.close();},10000);
        });
    });
    
    $('#logout').click(function(){
        $.req("q=user::logout",function(d){location.href='';});
    });

    $('#forget').colorbox({opacity: 0.5, width:"500px", inline:true, href:"#clients-forget"});

    $('#clients-forget-button').click(function(){
        $.req("q=user::forget&"+$(this).parents('form').find('input').serialize(),function(d)
        {
            $.colorbox({opacity: 0.5, width:"500px", html: '<h1>'+d.html+'</h1>'});
            setTimeout(function(){$.colorbox.close();},10000);
        });
    });

    $('#change').colorbox({opacity: 0.5, width:"500px", inline:true, href:"#clients-change"});
    $('#clients-change-button').click(function(){
        var pass = $(this).parents('form').find('input[name=pass]').val(),
            pass2 = $(this).parents('form').find('input[name=pass2]').val();

        if(pass.length < 6)
        {
            $('#clients-change-error').html("Пароль меньше 6 символов");
            setTimeout(function(){$('#clients-change-error').html('');},5000);
            return;
        }

        if(pass != pass2)
        {
            $('#clients-change-error').html("Пароли не совпадают");
            setTimeout(function(){$('#clients-change-error').html('');},5000);
            return;
        }

        $.req("q=user::change&"+$(this).parents('form').find('input').serialize(),function(d)
        {
            $.colorbox({opacity: 0.5, width:"500px", html: '<h1>'+d.html+'</h1>'});
            setTimeout(function(){$.colorbox.close();},10000);
        });
    });

    //-----------------------------
    // CART module
    
    // init cart buttons
    $("a[href='#cart']").click(function(){
        // init cart list
        $.req({"q":"cart::inc","id": 0},function(d){
            if(d.res == 'OK')
            {
                cart_info(d.html);
                viewlist(d.json);
            }
            $.colorbox({opacity: 0.5, width:"850px", scrolling: true, inline:true, href:"#tmp-cart-container"});
        });
        return false;
    });
    
    // init cart list
    $.req({"q":"cart::inc","id": 0},function(d){
        if(d.res != 'OK') return;
        cart_info(d.html);
        viewlist(d.json);
    });
    
    // clear cart
    $('#cart-clear').click(function(){
        var p = {
            "q":"cart::clear"
        }
        $.req(p,function(d){
            if(d.res != 'OK') return;
            cart_info(d.html);
            viewlist(d.json);
        });
    });

    $('img.products-cart').click(function(){
        var p = {
            "q":"cart::add",
            "id": $(this).parent().attr('id')
        }
        $.req(p,function(d){
            if(d.res != 'OK') return;
            cart_info(d.html);
        });
    });

    $('#cart-next').click(function(){
        var con = $('#tmp-cart-container'), error = '';
        var p = {
            'adress': $("input[name='adress']",con).val(),
            'date': check_time(con)
        }

        if(p.adress.length < 6) error += "Короткий адресс\n\n";
        if(!p.date) error += "Неверное время\n\n";
        if(error)
        {
            alert(error);
            return;
        }

        p.q = "cart::order"
        $.req(p,function(d){
            if(d.res != 'OK'){
                alert(d.html)
                return;
            }
            $.colorbox({opacity: 0.5, width:"500px", html: '<h1>'+d.html+'</h1>'});
            setTimeout(function(){location.href=""},5000);
        });

    });
    
    //-------------------------------
    // functions
    
    function cart_info(inf) {
        $("#incart").html('Товар на сумму <br> <b>'+inf.sum.toFixed(2)+'</b> грн.');
        // inf.num,inf.rem
    }

    function viewlist(list)
    {
        var ul = $('#cart-container').empty();

        if(ul.length == 0) return;

        var sum = 0;
        $.each(list,function(i,e){
            e.id = i;
            e.summ = (e.price*e.count).toFixed(2);
            sum += e.price*e.count;
            var li = $.tmp('#tmp-cart-item',e).appendTo(ul);
            $('span.plus',li).click(cart_inc);
            $('span.minus',li).click(cart_dec);
            $('span.del',li).click(cart_del);
        });
        $('div.all-sum span').html((sum).toFixed(2));
    }

    function cart_inc()
    {
        var p = {
            "q":"cart::inc",
            "id": $(this).parent().parent().parent().attr('id')
        }
        $.req(p,function(d){
            if(d.res != 'OK') return;
            cart_info(d.html);
            viewlist(d.json);
        });
    }

    function cart_dec()
    {
        var p = {
            "q":"cart::dec",
            "id": $(this).parent().parent().parent().attr('id')
        }
        $.req(p,function(d){
            if(d.res != 'OK') return;
            cart_info(d.html);
            viewlist(d.json);
        });
    }


    function cart_del()
    {
        var p = {
            "q":"cart::del",
            "id": $(this).parent().parent().attr('id')
        }
        $.req(p,function(d){
            if(d.res != 'OK') return;
            cart_info(d.html);
            viewlist(d.json);
        });
    }

    function check_time(con)
    {
        var time = $("select[name='date']",con).val() + " "
                + $("select[name='hour']",con).val() + ":"
                + $("select[name='minute']",con).val() + ":00"
        var timen = new Date();
        timen.setTime(timen.getTime() + params.buffertime);
        timen = $.strftime('%Y-%m-%d %H:%M',timen)
        return time > timen ? time : false;
    }


    
/*
    slideSwitch('slideshow',2000);
*/
/*
    //Cufon.replace('', {fontFamily: 'myfont', hover: true });
    
    Cufon.replace('div.left', {textShadow: '#cecf8d -1px 0px'});
    Cufon.replace('div.menu', {textShadow: '#ccf 1px 1px,#ccf 1px -1px,#ccf -1px 1px,#ccf -1px -1px'});
    Cufon.replace('div#email a', {textShadow: '#fff 1px 1px,#fff 1px -1px,#fff -1px 1px,#fff -1px -1px'});
*/
/*
    $.gallerax({
        outputSelector:         '#output img',              // Output selector
        thumbnailsSelector:     '#thumbnails li img',       // Thumbnails selector
        captionSelector:        '#captions .line',          // Caption selector
        captionLines:           2,                          // Caption lines (3 lines)
        fade:                   'fast',                     // Transition speed (fast)
        navNextSelector:        '#nav a.navNext',           // 'Next' selector
        navPreviousSelector:    '#nav a.navPrevious',       // 'Previous' selector
        navFirstSelector:       '#nav a.navFirst',          // 'First' selector
        navLastSelector:        '#nav a.navLast',           // 'Last' selector
        navStopAdvanceSelector: '#nav a.navStopAdvance',    // 'Stop Advance' selector
        navPlayAdvanceSelector: '#nav a.navPlayAdvance',    // 'Play Advance' selector
        advanceFade:            'slow',                     // Advance transition speed (slow)
        advanceDelay:           4000,                       // Advance delay (4 seconds)
        advanceResume:          12000,                      // Advance resume (12 seconds)
        thumbnailsFunction:     function(s) {
            return s.replace(/ithumb/, 'image');
        }
    });
*/

});






