/*
 This file stores all AJAX requests as object used in Printle.com
 Requires jQuery library.
 */

function BasketManager() {
    this.ajaxType = "POST";
    this.url = "index.php";
    this.parameters = "";
    this.dataType = "json";
    this.redirectAfterUserSave = false;
    this.reloadingPaymentAndShipping = false;
    this.redirectAfterUserSaveURL = '';
    this.goToPaymentMessage = '';
    this.submitOrderMessage = '';
    this.paymentAdvancedMethods = new Array(4, 12);
    this.transitionalMethods = new Array(11, 5, 16);

    this.loadingImage = "images/ajax-loader.gif";
    this.loadingImage2 = "images/ajax-loader2.gif";

    this.loginErrorMessage = "";
    this.emptyBasketError = "";
    this.enterNewPassowrdMessage = "";
    this.logoutMessage = "";
    this.oldPasswordTitle = "";
    this.confirmOrderMessage = "";
    this.checkPricesMessage = "";
    this.confirmTitle = "";

    this.tempContent = "";
    this.HTMLErrorClass = "error";

    this.debug = false;
    this.debugMessage = "";
    this.date = new Date();
    
    this.setDebugMode = function() {
        this.debug = true;
    }

    this.log = function(message) {
        this.date = new Date();
        var curr_hour = this.date.getHours();
        var curr_min = this.date.getMinutes();
        var curr_sec = this.date.getSeconds();
        this.debugMessage += "[" + curr_hour + ":" + curr_min + ":" + curr_sec + "] " + message + "\n";
    }

    this.toString = function() {
        if (this.debug)
            return this.debugMessage;
        else
            return null;
    }

    this.setProductAmount = function (productId, amount) {
        this.log("Setting product#" + productId + " amount to " + amount + "!");

        this.productAmountUILoading(productId);
        this.totalsUILoading();

        this.parameters = "page=ajax/basket_ajax&command=setAjaxUpdateBasket&product2basketid=" + productId + "&amount=" + amount;
        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.populateALL(rsp);
        });
        return false;
    }

    this.removeProduct = function(productId) {
        this.log("Removing product#" + productId);
        this.parameters = "page=ajax/basket_ajax&command=setAjaxRemoveProduct&product2basketid=" + productId;

        this.productAmountUILoading(productId);
        this.totalsUILoading();

        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.populateALL(rsp);
            if(rsp.totals['productAmount'] == 0)
            {
                $(".products-table").remove();
                $(".totals").remove();
                $("#coupons").remove();
                $("#payment-method").remove();
                $("#shipping-method").remove();
                $("#user-details").remove();
                $("#user-info").remove();
                $("#submitOrderDiv").remove();
                
                $("#basket-content").html($("#basket-content").html() + '<div class="w100"><p class="'+basketManager.HTMLErrorClass+'">'+basketManager.emptyBasketError+'</p></div>');
            }
        });
       
        return false;
    }

    this.addCoupon = function(couponCode) {
        $("#coupon-discount").html("<img src='"+this.loadingImage+"'/>");
        this.log("Adding coupon");
        this.parameters = "page=ajax/basket_ajax&command=setAjaxCoupon&couponCode="+couponCode;
        this.totalsUILoading();

        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.populateALL(rsp);
        });
        return false;
    }

    this.logIn = function(email, password)
    {
        this.loginUILoading();
        $(".errorFromAjax").remove();
        this.parameters = "page=ajax/basket_ajax&command=setAjaxLogIn&email="+email+"&password="+password;
        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.loginUILoading();
            if(rsp.success){
                basketManager.allPricesUILoading();
                $("#first-password-paragraph").before('<p><label>'+basketManager.oldPasswordTitle+'</label>\n<input class="rounded-input need-for-reload" name="user[old_password]" id="user[old_password]" type="password" value="" /></p>');
                $("#enterPasswordLabel").html(basketManager.enterNewPassowrdMessage);
                $("#login-div, #new-customer").hide();$("#logged-user-info").show();
                $(".need-for-reload").wrap('<span class="rounded-input-beginning '+$(".need-for-reload").attr("class")+'" style="width: '+$(".need-for-reload").width()+'px"/>').wrap('<span class="rounded-input-end" />').removeClass("need-for-reload");
                $("#submitOrderDiv").show();
                basketManager.populateALL(rsp);
            } else {
                $("#login-error").show().html(basketManager.loginErrorMessage);
            }
        });
    }

    this.registerUser = function(serializedData)
    {
        $(".errorFromAjax").remove();
        this.registrationFormUILoading();
        this.parameters = "page=ajax/basket_ajax&command=setAjaxRegister&"+serializedData;
        $.getJSON(basketManager.url, basketManager.parameters, function(rsp) {
            basketManager.registrationFormUILoading();
            basketManager.clearPasswords();
            if(rsp.success)
            {
                $("#first-password-paragraph").before('<p><label>'+basketManager.oldPasswordTitle+'</label>\n<input class="rounded-input need-for-reload" name="user[old_password]" id="user[old_password]" type="password" value="" /></p>');
                $("#user-info").hide();
                $("#user-details").show();
                $("#login-div").hide();
                $("#new-customer").hide();
                $("#logged-user-info").show();
                $(".need-for-reload").wrap('<span class="rounded-input-beginning '+$(".need-for-reload").attr("class")+'" style="width: '+$(".need-for-reload").width()+'px"/>').wrap('<span class="rounded-input-end" />').removeClass("need-for-reload");
                $("#submitOrderDiv").show()

                basketManager.allPricesUILoading();
                basketManager.populateALL(rsp);
                basketManager.redirect();
            } else {
                for(var i in rsp.errors)
                    $('input[name='+i+']').after("<p class='"+basketManager.HTMLErrorClass+" errorFromAjax'>"+rsp.errors[i]+"<br/></p>");

                $('html,body').animate({scrollTop: $(".errorFromAjax").offset().top},'slow');
            }
        });
    }

    this.updateUser = function(serializedData)
    {
        $("#submitOrderDiv").hide();
        $(".errorFromAjax").remove();
        this.registrationFormUILoading();
        this.parameters = "page=ajax/basket_ajax&command=setAjaxUpdate&"+serializedData;
        $.getJSON(basketManager.url, basketManager.parameters, function(rsp) {
            basketManager.registrationFormUILoading();
            basketManager.clearPasswords();
            if(rsp.success)
            {
                $("#user-info").hide();
                $("#user-details").show();
                $("#submitOrderDiv").show()
                
                basketManager.allPricesUILoading();
                basketManager.populateALL(rsp);
                basketManager.redirect();
            } else {
                for(var i in rsp.errors)
                    $('input[name='+i+']').after("<p class='"+basketManager.HTMLErrorClass+" errorFromAjax'>"+rsp.errors[i]+"<br/></p>");

                $('html,body').animate({scrollTop: $(".errorFromAjax").offset().top},'slow');
            }
        });
    }
/*
    this.redirect = function()
    {
        if(!basketManager.reloadingPaymentAndShipping)
        {
            if(basketManager.redirectAfterUserSave && basketManager.redirectAfterUserSaveURL != '' && basketManager.redirectAfterUserSaveURL != 'undefined')
                if($("input[name=shipping-method]:checked").val() && $("input[name=payment-method]:checked").val() && $("#user_email").html() != "")
                    window.location.href = basketManager.redirectAfterUserSaveURL+'&shippingId='+$("input[name=shipping-method]:checked").val()+'&paymentId='+$("input[name=payment-method]:checked").val();
        }
        else
             setTimeout(function(){basketManager.redirect();}, 1000);
        
    }
    */
    this.clearPasswords = function()
    {
        $("input[name=user[old_password]]").attr("value", "");
        $("input[name=user[password]]").attr("value", "");
        $("input[name=user[password1]]").attr("value", "");
    }

    this.selectShipping = function(shippingId) {
        this.parameters = "page=ajax/basket_ajax&command=setAjaxShippingMethod&shippingId="+shippingId;
        this.totalsUILoading();
        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.populateALL(rsp);
        });
	}

    this.selectPayment = function(paymentId) {
        this.parameters = "page=ajax/basket_ajax&command=setAjaxPaymentMethod&paymentId="+paymentId;
        this.totalsUILoading();
        $.getJSON(this.url, this.parameters, function(rsp) {
            basketManager.populateALL(rsp);
        });
	}

    this.populateALL = function(rsp)
    {
        this.populateCheckPricesDialog(rsp);
        this.populateCouponDetails(rsp);
        this.populateCustomerData(rsp);
        this.populateShippingMethods(rsp);
        this.populatePaymentMethods(rsp);
        this.populateProductList(rsp);
        this.populateTopBasketDiv(rsp);
        this.populateTotals(rsp);
    }

    this.populateCheckPricesDialog = function(rsp)
    {
        if(rsp.checkPrices)
        {
            $("#osx-modal-title").html(this.confirmTitle);
            $('#osx-modal-data').html(this.checkPricesMessage);
            $("#osx").click();
        }
    }

    this.populateCustomerData = function(rsp)
    {
        if(rsp.userDetails['user']['email'])
        {
            $("#register-user").attr("id", "update-user");
            // change account tabs
            $("#login").html(rsp.userDetails['logoutLink']);
            $("#header #customer-details span.details").html(rsp.userDetails['userDetails']);
            $("#header #customer-details").show();
        }
        
        // populate users details
        for(var i in rsp.userDetails['user'])
            if(rsp.userDetails['user'][i])
                $("#user_"+i).html(rsp.userDetails['user'][i]);
        for(var i in rsp.userDetails['billing'])
            if(rsp.userDetails['billing'][i] != "null")
                $("#billing_"+i).html(rsp.userDetails['billing'][i]);
        for(var i in rsp.userDetails['shipping'])
            if(rsp.userDetails['shipping'][i] != "null")
                $("#shipping_"+i).html(rsp.userDetails['shipping'][i]);

        // populate details editing form
        for(var i in rsp.userDetails['user'])
            if(rsp.userDetails['user'][i])
                $('input[name=user['+i+']]').val(rsp.userDetails['user'][i]);
        for(var i in rsp.userDetails['billing'])
            if(rsp.userDetails['billing'][i]){
                if(i == "country")
                    $('#customer-form-data select').each(function(j){if($(this).attr("name") == "billing[country]") $(this).val(rsp.userDetails['billing'][i]);});
                else
                    $('input[name=billing['+i+']]').val(rsp.userDetails['billing'][i]);
            }
        if(rsp.userDetails['billing']['type'] && rsp.userDetails['billing']['type'] != 'both'){
            $("#different_shipping").attr('checked', true);
            $("#different_shipping_label").addClass("selected");
            $("#billingDetailsForm").attr("class", "w50 left");
            $("#shippingDetailsForm").css("display", "block");
        }
        else
        {
            $("#different_shipping").attr('checked', false);
            $("#different_shipping_label").removeClass("selected");
        }

        for(var i in rsp.userDetails['shipping'])
            if(rsp.userDetails['shipping'][i]){
                if(i == 'country')
                    $('#customer-form-data select').each(function(j){if($(this).attr("name") == "shipping[country]") $(this).val(rsp.userDetails['shipping'][i]);});
                else
                    $('input[name=shipping['+i+']]').val(rsp.userDetails['shipping'][i]);
            }

        if($("#billing_vat_nr").html() == "")
            $("#customer-vat-tr").hide();
        else
            $("#customer-vat-tr").show();

    }

    this.populateTopBasketDiv = function(rsp)
    {
        $("#basket #basket-amount-total").html(rsp.totals['productAmount']);
        $("#basket #basket-price-total").html(rsp.totals['cartTotalPrice']);
    }

    this.populateCouponDetails = function(rsp)
    {
        if(rsp.success && rsp.totals['couponDiscount']){
            $("#coupon-discount").html(rsp.totals['couponDiscount']);
        } else {
            $("#coupon-discount").html("");
        }
    }

    this.populatePaymentMethods = function(rsp)
    {
        $(".payment-methods").remove();
        var last = $('#payment-method tr');
        for (var i in rsp.paymentMethods) {
            var tr = "<tr class='payment-methods"+(rsp.paymentMethods[i]['checked'] ? " selected-method":"")+"'>" ;
                tr += "<td>" +
                        "<label class='radio"+(rsp.paymentMethods[i]['checked'] ? " radio-checked":"")+"' for='paymentMethod"+rsp.paymentMethods[i]['id']+"'>" +
                            "<input type='radio' id='paymentMethod"+rsp.paymentMethods[i]['id']+"' name='payment-method' value='"+rsp.paymentMethods[i]['id']+"' "+(rsp.paymentMethods[i]['checked'] ? "checked='checked'":"")+ "/>"+
                            rsp.paymentMethods[i]['name']+
                        "</label>" +
                      "</td>" +
                    "<td class='black' align='right'>" +rsp.paymentMethods[i]['price']+ "</td>";
            tr+="</tr>";
            last.after(tr);
            last = $('.payment-methods:last');

            if(rsp.paymentMethods[i]['checked'])
            {
                $("#paymentMethod"+rsp.paymentMethods[i]['id']).attr("checked", true);
            }
        }
    }

    this.populateProductList = function(rsp) {
        var last = $('#headers');
        $(".productDetails").remove();
        for (var i in rsp.products) {
            var tr = '<tr class="productDetails" style="cursor: auto">' +
                '<td>'+rsp.products[i]['image']+'</td>'+
                '<td>'+rsp.products[i]['title']+'</td>'+
                '<td class="center">'+rsp.products[i]['color_image']+'</td>'
                ;
            if (rsp.products[i]['free_ink'])
                tr += '<td class="center">' + rsp.products[i]['item_price'] + '</td><td class="center" id="amount'+rsp.products[i]['id']+'">' + rsp.products[i]['amount'] + '</td><td class="black" align="right" id="price'+rsp.products[i]['id']+'">' + rsp.products[i]['price'] + '</td>';
            else if (rsp.products[i]['cost_printrees'] > 0)
                tr += '<td class="center">' + rsp.products[i]['item_price'] + '</td><td class="center input" id="amount'+rsp.products[i]['id']+'">' + rsp.products[i]['amount'] + '<input type="hidden" name="amount" value="' + rsp.products[i]['amount'] + '" /></td><td class="black" align="right" id="price'+rsp.products[i]['id']+'">' + rsp.products[i]['price'] + '</td>';
            else
                tr += '<td class="center">' + rsp.products[i]['item_price'] + '</td><td id="amount'+rsp.products[i]['id']+'" class="center input"><button class="subtract" id="subtract-' + rsp.products[i]['id'] + '">&nbsp;</button> <input value="' + rsp.products[i]['amount'] + '" AUTOCOMPLETE=OFF id="amount' + rsp.products[i]['id'] + 'input" name="amount" type="text" maxlength="2" class="amount" /> <button class="add" id="add-' + rsp.products[i]['id'] + '">&nbsp;</button></td><td class="black" align="right" id="price'+rsp.products[i]['id']+'">' + rsp.products[i]['price'] + '</td>';
            if (rsp.products[i]['free_ink'])
                tr += '<td align="right"></td>';
            else
                tr += '<td align="right"><button class="remove" id="remove-'+rsp.products[i]['id']+'">&nbsp;</button></td>';
            tr += "</tr>";
            last.after(tr);
            last = $('.productDetails:last');
        }
    }

    this.populateShippingMethods = function(rsp)
    {
        $(".shipping-methods").remove();
        var last = $("#shipping-method tr:first");
        for (var i in rsp.shippingMethods) {
            var tr = "<tr class='shipping-methods"+(rsp.shippingMethods[i]['checked']?" selected-method":"")+"'>";
                tr += "<td>" +
                        "<label class='radio"+(rsp.shippingMethods[i]['checked'] ? " radio-checked":"")+"' for='shippingMethod"+rsp.shippingMethods[i]['id']+"'>" +
                            "<input type='radio' id='shippingMethod"+rsp.shippingMethods[i]['id']+"' name='shipping-method' value='"+rsp.shippingMethods[i]['id']+"' "+(rsp.shippingMethods[i]['checked'] ? "checked='checked'":"")+ "/>"+
                            rsp.shippingMethods[i]['name']+
                        "</label>" +
                      "</td>" +
                    "<td class='black' align='right'>" +rsp.shippingMethods[i]['price']+ "</td>";
            tr+="</tr>";
            last.after(tr);

            last = $('.shipping-methods:last');

            if(rsp.shippingMethods[i]['checked'])
            {
                $("#shippingMethod"+rsp.shippingMethods[i]['id']).attr("checked", true);
            }
        }
    }

    this.populateTotals = function(rsp) {
        $("#cartTotalPrice").html(rsp.totals['cartTotalPrice']);
        $("#shippingPrice").html(rsp.totals['shippingPrice']);
        if(rsp.totals['paymentPrice'])
        {
            $("#paymentPrice").html(rsp.totals['paymentPrice']);
            $("#paymentMethodPrice").show();
        }
        else
            $("#paymentMethodPrice").hide();
        
        if(rsp.totals['cartDiscount'])
        {
            $("#cart-discount-row").show();
            $("#cartDiscount").html(rsp.totals['cartDiscount']);
        }
        else
            $("#cart-discount-row").hide();

        $("#orderTotalPrice").html(rsp.totals['orderTotalPrice']);
        $("#taxPrice").html(rsp.totals['taxPrice']);
        $("#basket #total #basket-price-total").html(rsp.totals['cartTotalPrice']);
        $("#coupon-discount").html(rsp.totals['couponDiscount']);
    }
    
    // user interface methods
    this.productAmountUILoading = function(productId) {
        if ($("#amount" + productId).html().toLowerCase().indexOf(this.loadingImage) >= 0) { /* got loading image */
        }
        else {
            $("#amount" + productId).html("<img src='" + this.loadingImage + "' />");
        }
    }

    this.totalsUILoading = function() {
        $("#cartTotalPrice").html("<img src='" + this.loadingImage + "' />");
        $("#cartDiscount").html("<img src='" + this.loadingImage + "' />");
        $("#shippingPrice").html("<img src='" + this.loadingImage + "' />");
        $("#paymentPrice").html("<img src='" + this.loadingImage + "' />");
        $("#orderTotalPrice").html("<img src='" + this.loadingImage + "' />");
        $("#taxPrice").html("<img src='" + this.loadingImage + "' />");
        $("#basket #total #basket-price-total").html("<img src='" + this.loadingImage + "' />");
    }

    this.loginUILoading = function()
    {
        if( $(".login-form").html().toLowerCase().indexOf(this.loadingImage2)<0 ){
            this.tempContent = $(".login-form").html();
            $(".login-form").html("<p style='text-align:center;width:100%;margin-top:30px;vertical-align:middle;'><img src='"+this.loadingImage2+"'/></p>");
        } else {
            $(".login-form").html(this.tempContent);
        }
    }
    
    this.registrationFormUILoading = function()
    {
        if($("#customer-form-data").is(":hidden")){
            $("#customer-form-data").show();
            $("#loadingImage").remove();
        } else {
            $("#customer-form-data").hide();
            $("#user-info").append("<div id='loadingImage' style='width:100%; text-align:center;margin-top:50px;'><img src='"+basketManager.loadingImage2+"' /></div>");
        }
    }

    this.shippingPricesUILoading = function ()
    {
        $('.shipping-methods').each(function(i){
            $(this).children("td:last").html("<img src='"+basketManager.loadingImage+"' />");
        });
    }

    this.paymentPricesUILoading = function ()
    {
        $('.payment-methods').each(function(i){
            $(this).children("td:last").html("<img src='"+basketManager.loadingImage+"' />");
        });
    }

    this.productPricesUILoading = function()
    {
        $(".productDetails").each(function(){
            $(this).children("td:last").html("<img src='"+basketManager.loadingImage+"' />");
            $(this).children("td:nth-child(4)").html("<img src='"+basketManager.loadingImage+"' />");
        });
    }

    this.allPricesUILoading = function()
    {
        this.shippingPricesUILoading();
        this.paymentPricesUILoading();
        this.productPricesUILoading();
        this.totalsUILoading();
    }
}

var basketManager = new BasketManager();
basketManager.setDebugMode();
