//-------------------------

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 basketAddProduct(product)
{
    showLoadingOverlay();
    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);
        hideLoadingOverlay();   
    });
}

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, func)
{
    if (typeof func == 'undefined' ) func = 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
            func(data.basket);
    });
}

function updateBasket(basket)
{
    $("#basketinfo").html(basket);
}

function queryBasket()
{
    var sid = readCookie("sid");
    $.getJSON("ajdo.php", {
        type:"query-basket",
        sid:sid
    }, function(data) {
        if (data.rc=='fail')
            alert('Ошибка:'+rc.text);
        else
            updateBasket(data.basket);
    });
}

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 = ['shop/_basket.php','shop/_delivery.php','shop/_input.php','shop/_confirm.php','shop/_finish.php'];
var initFunc = [initOrderPage0, initOrderPage1, initOrderPage2, initOrderPage3, initOrderPage4];
var PAGE_BASKET = 0, PAGE_DELIVERY = 1, PAGE_INPUT = 2, PAGE_CONFIRM = 3, PAGE_FINISH = 4;


function initOrderPage0() 
{ 
    $('#gmap').hide();
    $("input[name^=qty_item_]").bind("keyup", basketRecalc);
    // run the calculation function now
    basketRecalc();
}
function initOrderPage1(){
    $('#gmap').hide();
    $(":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_index: {
                required: true,
                minlength: 6
            },
            post_address: {required: true}
        },
        messages: {
            toaddr: "Выберите куда доставлять заказ!"
        },
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                target: "#result",
                dataType: "json",
                beforeSend: function() {showLoadingOverlay();},
                success: function() {

                    enablePage(PAGE_CONFIRM);
                    loadOrderPage(PAGE_CONFIRM);
                },
                error: function() {alert("ajax error");}
            });
        }
    });
    $(":submit").button();
    if ($("#dwval").val()=="1")
        $("#dwork").click();
    //    $("#dwork").attr('checked', 'checked');
    if ($("#dhval").val()=="1")
        $("#dhome").click();
    //    $("#dhome").attr('checked', 'checked');

    var wAddr = $("#dwaddress").val();
    var hAddr = $("#dhaddress").val();
    var pAddr = $("#dpaddress").val();
    var showMap = false;
    if ( !(wAddr === undefined) ) showMap = true;
    if ( !(hAddr === undefined) ) showMap = true;
    if ( !(pAddr === undefined) ) showMap = true;

    if (showMap) {
        $('#gmap').show();
        $('#gmap').gmap3({
            action: 'init',
            options:{
                center:[55.753946,37.612651],   
                zoom:14,
                mapTypeControl: true,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                },
                navigationControl: true,
                scrollwheel: true,
                streetViewControl: true
            }
        });

        if ( !(wAddr === undefined)   && wAddr.length>0)
            $('#gmap').gmap3({ 
            action: 'addMarker',
            address: wAddr,
            map:{
                center: true,
                zoom: 14
            }
        });
        if ( !(hAddr === undefined)   && hAddr.length>0)
            $('#gmap').gmap3({ 
            action: 'addMarker',
            address: hAddr,
            map:{
                center: true,
                zoom: 14
            }
        });
        if ( !(pAddr === undefined)   && pAddr.length>0)
            $('#gmap').gmap3({ 
            action: 'addMarker',
            address: pAddr,
            map:{
                center: true,
                zoom: 14
            }
        });

        // $("select.metro").select_autocomplete();
        var jsonMetro = $("#acMetro").html();     
        var metroData = jQuery.parseJSON( jsonMetro );

        /*   $( "#idwmetro" ).autocomplete({
        minLength: 0,
        source: metroData,
        focus: function( event, ui ) {
        $( "#idwmetro" ).val( ui.item.label );
        return false;
        },
        select: function( event, ui ) {
        $( "#idwmetro" ).val( ui.item.label );
        $( "#dwmetroh" ).val( ui.item.value );
        return false;
        }
        });
        */   

        $('input.gmaddress').autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function(request, response) {
                $("#gmap").gmap3({
                    action:'getAddress',
                    address: request.term,
                    callback:function(results){
                        if (!results) return;
                        response($.map(results, function(item) {
                            return {
                                label:  item.formatted_address,
                                value: item.formatted_address,
                                latLng: item.geometry.location
                            }
                        }));
                    }
                });
            },
            //This bit is executed upon selection of an address
            select: function(event, ui) {
                $("#gmap").gmap3(
                {action:'clear', list:'marker'},
                {action:'addMarker',
                    latLng:ui.item.latLng,
                    map:{center:true}
                }
                );
            }

        });

    }
}
function initOrderPage3()
{
    $('#gmap').hide();
    $(":submit").button();    
}

var ajMessage = "";

function initOrderPage4()
{
    disablePage(PAGE_DELIVERY);    
    disablePage(PAGE_INPUT);    
    disablePage(PAGE_CONFIRM);    
    $("#message").html(ajMessage);
    ajMessage = "";
}

function enableDisableButton(id,chk)
{
    if (chk.checked)
        $(id).button("enable");
    else
        $(id).button("disable");
}

function showHideChkFields(obj,key,chkid)
{
    if ( $(chkid).prop('checked') ) {
        $(obj).show();
        $("#d"+key+"val").val(1);
        var m = $("#d"+key+"metroh").val();
        $("#d"+key+"metro").val(m);
    }
    else {
        $(obj).hide();
        $("#d"+key+"val").val(0);
    }
}



$(document).ready(function() 
{
    queryBasket();

    if ($("#orderbox")[0])
        {
        loadOrderPage(PAGE_BASKET);
        pagesUpdate();   
    }
} );



function pagesUpdate()
{
}

function isPageDisabled(n) 
{
    return $("#op"+n).hasClass("ob-disabled");
}
function isPageActive(n) 
{
    return $("#op"+n).hasClass("ob-active"); 
}
function enablePage(n)
{
    var a = $("#op"+n).hasClass("ob-disabled");
    if (a)
        $("#op"+n).removeClass("ob-disabled");
}
function disablePage(n)
{
    var a = $("#op"+n).hasClass("ob-disabled");
    if (!a)
        $("#op"+n).addClass("ob-disabled");
}
function setPageActive(n)
{
    for (var i=0; i<4; i++)
        {
        var a = $("#op"+i).hasClass("ob-active");
        if (i == n && !a)
            $("#op"+i).addClass("ob-active");
        if (i != n && a)
            $("#op"+i).removeClass("ob-active");
    }
}       
function loadOrderPage(n)
{
    if (isPageDisabled(n) || isPageActive(n)) return;
    showLoadingOverlay();
    setPageActive(n);
    if (n < PAGE_CONFIRM)
        disablePage(PAGE_CONFIRM);
    if (n < PAGE_INPUT)
        disablePage(PAGE_INPUT);
    /*
    if (n == PAGE_DELIVERY) {
    basketSetDelivery("", function(){doLoadOrderPage(n)});
    } else*/
    doLoadOrderPage(n);
}

function doLoadOrderPage(n)
{
    $("#orderbox").load(pages[n],function(){
        initFunc[n]();
        pagesUpdate();
        hideLoadingOverlay();
    });
}

function chooseDelivery(id)
{
    showLoadingOverlay();
    enablePage(PAGE_INPUT);
    var price = $("#price-"+id).val();
    basketSetDelivery(id, price, function(){
        loadOrderPage(PAGE_INPUT);
    });
}

function showLoadingOverlay()
{
    if (!$("#allbox")[0])
        $('<div id="allbox"></div>').prependTo('body');
    $("#allbox").css('height', $(window).height());
    $("#allbox").css('width', $(window).width()); 
    $("#loading").css('top', $(window).height()/2-$("#loading").height()/2);
    $("#loading").css('left', $(window).width()/2-$("#loading").width()/2); 
    $("#loading").show(); 
}
function hideLoadingOverlay()
{
    $("#allbox").remove(); 
    $("#loading").hide(); 
}

function sendOrder()
{
    showLoadingOverlay();
    var sid = readCookie("sid");
    var reg = $("#addme").prop("checked");
    $.getJSON("ajdo.php", {
        type:"send-order",
        sid:sid,
        register: reg
    }, function(data) {
        if (data.rc=='fail')
            alert('Ошибка:'+rc.text);
        else {
            updateBasket(data.basket);
            ajMessage = data.message;
            loadOrderPage(PAGE_FINISH);   
        }
    });
}
