$(document).ready(function(){
    $("#dialog-product-subscribe").dialog({ 
        resizable: true, 
        width:800, 
        height:350, 
        modal: true, 
        autoOpen: false, 
        buttons: {
            'Подписаться': function() {
                var dlg = $(this);
                if ($("#pSubscribeForm").valid()) {

                    var pid = $("#spid").val();
                    var email = $("#semail").val();
                    var amount = $("#samount").val();
                    var sanal = $("#sanal").prop("checked");

                    $("#dialog-ps-info").html("<br/>....Выполняется подписка...."); 

                    $.getJSON("ajdo.php", {
                        type:"user-subscribe-product",
                        pid:pid,
                        email:email,
                        amount:amount,
                        analog:sanal
                    }, function(data) {
                        if (data.rc=='fail') {
                            alert('Ошибка:'+rc.text);
                            dlg.dialog('close');
                        }
                        else {
                            //alert(""+data.text);
                            dlg.dialog('close'); 
                        }
                    });


                }

    }}});

    $.getScript('http://ayurvedic.ru/js/blogger.js', function(){     
        $.getScript('http://twitter.com/statuses/user_timeline/ayru.json?callback=twitterCallback2&amp;count=7');
    });

});   


function getrandom(max)
{
    var min_random = 1;
    var max_random = max;
    max_random++;
    var range = max_random - min_random;
    var n=Math.floor(Math.random()*range) + min_random;
    return n;
}

function doShopAdd(prod)
{
    basketAddProduct(prod); 
    var f = document.getElementById("hiddenform");
    f.action.value = "shopAdd";
    f.arg0.value = prod;
    f.submit();

    /*  $.getJSON("ajdo.php", {
    type:"XshopAdd",
    arg0:prod
    }, function(data) {
    if (data.rc=='fail')
    alert('Ошибка:'+rc.text);
    else
    alert("Товар добавлен в корзину!");
    });  */
}

function doShopSubscribe(prod)
{
    var hdr = '<img src="/shop/images/'+prod+'.gif" style="float:left;" vspace="10" hspace="10/"><h3>'+
    $("#ptitle-"+prod).html()+'</h3>';
    var info = $("#pdesc-"+prod).html();
    $("#spid").val(prod);
    $("#pSubscribeForm").validate({
        rules: {
            email: {
                required: true,
                email: true
            },
            amount: {
                required: true,
                minlength: 1
            }
    }});


    $("#dialog-ps-hdr").html(hdr);
    $("#dialog-ps-info").html(info);
    $("#dialog-product-subscribe").dialog('open');

    //w = window.open('subscribe.php?pid='+prod,'displayWindow','menubar=no,scrollbars=yes,status=no,width=500,height=300');

    /*  var f = document.getElementById("hiddenform");
    f.action.value = "shopSubscribe";
    f.arg0.value = prod;
    f.arg1.value = document.location;
    f.submit();*/
}

function doShopSelectManufacturer(selObj)
{

    var mfc = selObj.options[selObj.selectedIndex].value;
    var loc = document.location.href;

    var re = new RegExp("(http.*)(&pflt=[\\w\\-]+)(&?.*)");
    var res = re.exec(loc);
    var nloc; 

    if (res == null) {
        nloc= loc+"&pflt="+mfc;       
    } else {
        var pf = res[1];
        var sf = res[3];

        if (mfc == "")
            nloc= pf+sf;
        else
            nloc= pf+"&pflt="+mfc+sf;
    }

    window.location = nloc;

}

var n=getrandom(25);

function MM_jumpMenu(targ,selObj,restore){ //v3.0
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
    if (restore) selObj.selectedIndex=0;
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_jumpMenuGo(selName,targ,restore){ //v3.0
    var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
}


function doShopDeliveryChange(selObj)
{

}

function doAskQuestion(txtId)
{
    if (confirm("Вы действительно хотите задать вопрос?"))
        {
        var f = document.getElementById("hiddenform");
        var t = document.getElementById(txtId);
        f.action.value = "portalAsk";
        f.arg0.value = t.value;
        f.submit();
    }
}

function validateFormEmail(f) {

    if (f.email.value.indexOf('@',0)==-1 || f.email.value.indexOf('.',0)==-1)
        alert('\nВведите e-mail!');
    else f.submit(); // Отправляем на сервер
}

function isDigit(data) {
    numStr="0123456789";
    k = 0;
    for (i=0;i<data.length;i++) {
        thisChar = data.substring(i, i+1);
        if (numStr.indexOf(thisChar) != -1) k++;
    }
    if (k == data.length) return 1
    else return 0
}

function validFormDigit(f,id) {
    bcalc = document.getElementById("bcalc");
    bnext = document.getElementById("bnext");
    // errcnt = document.getElementById("errcnt");
    // e = 0;
    //.if (errcnt) e = errcnt.value;

    if (isDigit(f.value)) {
        color = "#ffffff";
        // if (errcnt) e++;
    } else {
        color = "#ffa0a0"; 
        // if (errcnt) e--;
    }

    //if (errcnt) errcnt.value = e;

    /* if (bcalc) bcalc.disabled = true;
    if (bnext) bnext.disabled = true;
    if (bcalc) bcalc.disabled = false;
    if (bnext) bnext.disabled = false;
    */
    document.getElementById(id).style.background = color;
}

function isEmailCorrect(formname, fieldname) { 

    var re = /^\w+([\.-]?\w+)*@(((([a-z0-9]{2,})|([a-z0-9][-][a-z0-9]+))[\.][a-z0-9])|([a-z0-9]+[-]?))+[a-z0-9]+\.([a-z]{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i; 
    //var re = /^\w+([\.-]?\w+)*@[a-z0-9]+([\.-]?[a-z0-9]+)+\.([a-z]{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i;     

    if(re.test(eval("document.forms['"+formname+"']."+fieldname+".value"))) 
        return true; 
    else { 
        alert("Вы ввели неправильный e-mail. Чтобы продолжить введите правильный адрес электронной почты!");
        eval("document.forms['"+formname+"']."+fieldname+".focus()");
        return false; 
    } 
} 

function validateOrderForm() {
    if (isEmailCorrect('orderform','email')) {
        return true;
    } else {
        return false;
    }
}

//-------------------------- new orders ----------------------------------

function openPreOrder()
{

}

function closePreOrder()
{

}

function dropPreOrder()
{

}

function basketAddProduct(product)
{
    var sid = readCookie("sid");
    $.getJSON("ajdo.php", {
        type:"basket-add-product",
        sid:sid,
        pid:product
    }, function(data) {
        if (data.rc=='fail')
            alert('Ошибка:'+rc.text);
        else
            updateBasket(data.basket);
    });
}

function basketSetAmount(product, amount)
{
    var sid = readCookie("sid");
    $.getJSON("ajdo.php", {
        type:"basket-set-amount",
        sid:sid,
        pid:product,
        amount:amount
    }, function(data) {
        if (data.rc=='fail')
            alert('Ошибка:'+rc.text);
        else
            updateBasket(data.basket);
    });
}

function basketSetDelivery(id, price, f)
{
    if (typeof f == 'undefined' ) f = updateBasket;
    var sid = readCookie("sid");
    $.getJSON("ajdo.php", {
        type:"basket-set-delivery",
        sid:sid,
        price:price,
        delivery:id
    }, function(data) {
        if (data.rc=='fail')
            alert('Ошибка:'+rc.text);
        else
            f(data.basket);
    });
}

function updateBasket(basket)
{

}

function createCookie(name,value,days) 
{
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) 
{
    createCookie(name,"",-1);
}

//-------------------------

function basketRecalc()
{
    $("[id^=total_item]").calc(
    // the equation to use for the calculation
    "qty * price",
    // define the variables used in the equation, these can be a jQuery object
    {
        qty: $("input[name^=qty_item_]"),
        price: $("[id^=price_item_]")
    },
    // define the formatting callback, the results of the calculation are passed to this function
    function (s){
        // return the number as a dollar amount
        return s.toFixed(0) ;
    },
    // define the finish callback, this runs after the calculation has been complete
    function ($this){
        // sum the total of the $("[id^=total_item]") selector
        var sum = $this.sum();
        if (sum == 0)
            {   disablePage(PAGE_DELIVERY); }
        else 
            {   enablePage(PAGE_DELIVERY);   }
        $("#grandTotal").text(
        // round the results to 2 digits
        sum.toFixed(0)
        );
    }
    );
}

function basketDeleteItem(pid)
{
    basketSetAmount(pid, 0);
    $("#row_"+pid).detach();
    basketRecalc();
    if ($("#grandTotal").text() == "0") 
        {
        $("#orderbox").html("Ваша корзина пуста.");
    }
}

function basketUpdateQty(pid)
{
    basketSetAmount(pid, $("#qty_item_"+pid).val());
}

var pages = ['_basket.php','_delivery.php','_input.php','_confirm.php'];
var initFunc = [initOrderPage0, initOrderPage1, initOrderPage2, initOrderPage3];
var PAGE_BASKET = 0, PAGE_DELIVERY = 1, PAGE_INPUT = 2, PAGE_CONFIRM = 3;


function initOrderPage0() 
{ 
    $("input[name^=qty_item_]").bind("keyup", basketRecalc);
    // run the calculation function now
    basketRecalc();
}
function initOrderPage1(){
    $(":submit").button();  
}
function initOrderPage2(){
    $("#orderForm").validate({

        rules: {
            name: {
                required: true,
                minlength: 2
            },
            email: {
                required: true,
                email: true
            },
            phone: {
                required: true,
                minlength: 7
            },
            toaddr: {
                required: true,
                minlength: 1
            },
            work_metro: {
                required: "#dwork:checked"
            },
            work_address: {
                required: "#dwork:checked",
                minlength: 10
            },
            home_metro: {
                required: "#dhome:checked"
            },
            home_address: {
                required: "#dhome:checked",
                minlength: 10
            },
            post_address: {required: true}
        },
        messages: {
            toaddr: "Выберите куда доставлять заказ!",
            email: "Неправильный e-mail!",
            phone: "Укажите правильный телефон!"
        },
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                target: "#result",
                beforeSend: function() {showLoadingOverlay();},
                success: function() {

                    enablePage(PAGE_CONFIRM);
                    loadOrderPage(PAGE_CONFIRM);
                }
            });
        }
    });
    $(":submit").button();
    if ($("#dwval").val()=="1")
        $("#dwork").click();
    //    $("#dwork").attr('checked', 'checked');
    if ($("#dhval").val()=="1")
        $("#dhome").click();
    //    $("#dhome").attr('checked', 'checked');
}
function initOrderPage3(){}

function showHideChkFields(obj,key,chk)
{
    if (chk.checked) {
        $(obj).show("blind",{},100);
        $("#d"+key+"val").val(1);
        var m = $("#d"+key+"metroh").val();
        $("#d"+key+"metro").val(m);

    }
    else {
        $(obj).hide("blind",{},100);
        $("#d"+key+"val").val(0);
    }
}

/* dosatest */

function dt_sum(d)
{
    var sum = 0;
    for (i=1;i <= 20; i++)
        {
        sum += eval( $("#q"+d+"_"+i).val());
    }
    $("#res"+d).html(sum);
}

/* login page */

$(document).ready(function() 
{

    if ($("#loginpage")[0])
        {
        $(":submit").button();

        $("#loginForm").validate({

            rules: {
                password: {
                    required: true,
                    minlength: 8
                },
                email: {
                    required: true,
                    email: true
                }
            }
        });
        $("#registerForm").validate({

            rules: {
                name: {
                    required: true,
                    minlength: 2
                },
                pwd1: {
                    required: true,
                    minlength: 8
                },
                pwd2: {
                    required: true,
                    minlength: 8
                },
                email: {
                    required: true,
                    email: true
                }
            }
        });
        $("#sendPwd").validate({
            rules: {
                email: {
                    required: true,
                    email: true
                }
            }
        });

    }
});


