﻿var TransportTaxaColet = 21;
var TransportTaxaKg = 1.2;

function Finalizare()
{
    if ($("hChanged").value=="true")
    {
        alert ("Pentru finalizarea comenzii va rugam actualizati cosul de cumparaturi");
        return false;
    }
    else
    {
        var errors = "";
        //Date pesonale
        if (trim($("txName").value).length == 0) 
        {
            errors += getJSPH("Login_completati campul Nume si prenume")+" \n";
        }
        if (!isEmail($("txEmail").value)) 
        {
            errors += getJSPH("Login_introduceti o adresa de e-mail valida")+" \n";
        }
        if (trim($("txPhone").value).length == 0)
        {
            errors += getJSPH("Login_completati campul Telefon cu un numar de telefon valid")+" \n"; 
        }
//        if (trim($("txBI").value).length == 0)
//        {
//            errors += getJSPH("Login_completati campul BI")+" \n"; 
//        }
        //Informatii firma
        try{
            if ($("ckIsCompany").checked)
            {
                if (trim($("txCompanyName").value) == "")
                {
                    errors += getJSPH("Login_campul Nume firma")+" \n";
                }
                if (trim($("txCF").value) == "")
                {
                    errors += getJSPH("Login_completati campul Cod fiscal")+" \n";
                }
                //Informatii  Sediul social (pentru facturare)
                if ($("ddCountry").selectedIndex == 0)
                {
                    errors += getJSPH("Login_alegeti un judet-sediu")+" \n";
                }
                if (trim($("txCity").value).length == 0) 
                {
                    errors += getJSPH("Login_completati campul Localitate-sediu")+" \n";
                }
                if (trim($("txAddress").value).length == 0) 
                {
                    errors += getJSPH("Login_completati campul Adresa-sediu")+" \n";
                }
            }
        }catch (ex){}
        //Informatii de livrare
        if ($("ddDeliveryCountry").selectedIndex == 0)
        {
            errors += getJSPH("Login_alegeti un judet")+" \n";
        }
        if (trim($("txDeliveryCity").value).length == 0) 
        {
            errors += getJSPH("Login_completati campul Localitate")+" \n";
        }
        if (trim($("txDeliveryAddress").value).length == 0) 
        {
            errors += getJSPH("Login_completati campul Adresa")+" \n";
        }
        
        //Alegeti modalitatea de livrare
        try{
            if (document.getElementById("rbDinMagazin").checked && $("ddMagazin").selectedIndex == 0)
            {
                errors += "- alegeti un magazin pentru a ridica produsele \n";
            }
        }catch(ex){}
        
        
        
        if (errors.length > 0)
        {
            alert(errors);
            return false;
        }
        else
        {
            $("hAction").value = "Finalizare";
            document.getElementsByTagName('form')[0].submit();
        }

        return false;
    }
}
function getStoreInfo()
{
    var storeID=$("ddMagazin").value;
    if (storeID != 0)
    {
        var result=Netlogiq.Web.finalizareComanda.GetStore(storeID); 
        if(result!=null && result.value!=null)
        {
            $("dvStoreInfo").innerHTML=result.value;
        }
    }
}

function setStore()
{   
    if(document.getElementById("rbDinMagazin").checked)
    {
        try{$("ddMagazin").disabled=false;}
        catch(ex){}
        //document.getElementById("rbCardLaRidicare").disabled=false;
        document.getElementById("rbNumerar").disabled=false;
        document.getElementById("rbNumerar").checked=true;
        document.getElementById("rbRamburs").disabled=true;
        //document.getElementById("rbWestern").disabled=true;
        document.getElementById("rbCuOrdin").disabled=true;
        document.getElementById("rbRamburs").checked=false;
        //document.getElementById("rbWestern").checked=false;
        document.getElementById("rbCuOrdin").checked=false;
        document.getElementById("rbCard").disabled=false;
        document.getElementById("rbCard").checked=false;
    }
    else
    {
        try{$("ddMagazin").disabled=true;}
        catch(ex){}
        //document.getElementById("rbCardLaRidicare").disabled=true;
        //document.getElementById("rbCardLaRidicare").checked=false;      
        document.getElementById("rbNumerar").disabled=true;
        document.getElementById("rbNumerar").checked=false;
        document.getElementById("rbRamburs").disabled=false;
        //document.getElementById("rbWestern").disabled=false;
        document.getElementById("rbCuOrdin").disabled=false;
        document.getElementById("rbRamburs").checked=true;
        document.getElementById("rbCuOrdin").checked=false;  
        document.getElementById("rbCard").disabled=false;
    }

}

function Recalculare()
{
    var err="";   var cant="";
    inputs = document.getElementById("aspnetForm").getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'text' && inputs[i].id =="txQty")
        {
           // console.log(inputs[i].value," -" );
            if(inputs[i].value=="" || inputs[i].value==0)
            {
                err="Va rugam introduceti cantitati numere intregi pozitive";
                inputs[i].value="";
            }
            else
            {
                cant+=inputs[i].value+",";
            }
         }
    }
    if(err!="")
    {
        alert(err);
    }
    else
    { 
        //$("dvLoading").style.display="inline";
        var result=Netlogiq.Web.finalizareComanda.UpdateSC(cant); 
        if(result!=null && result.value!=null)
        {
            writeShoppingCart(result);
            //document.getElementById("shoppingCart").innerHTML=result.value;
            $("hChanged").value = "false";
            try{
                //$("dvLoading").style.display="none";  
                //$("dvChanged").style.display="none";
            } catch (ex){}
        }
    }
    //doRecalculare();

}

function RemoveLine(vID)
{
    var result=Netlogiq.Web.finalizareComanda.RemoveProduct(vID); 
    if(result!=null && result.value!=null)
    {
        writeShoppingCartAll(result);
        //document.getElementById("shoppingCart").innerHTML=result.value;
        //$("hChanged").value = "false";
        //try{
           /* $("dvLoading").style.display="none";  
            $("dvChanged").style.display="none";*/
        //} catch (ex){}
    }
}

//function updateShoppingCart(vID,quantity)
//{
//    cant2=quantity+",";
//    var result=Netlogiq.Web.finalizareComanda.UpdateSC(cant2); 
//    if(result!=null && result.value!=null)
//    {
//        writeShoppingCartAll(result);
//    }
//}
function WriteTotal(totalPrice, totalWeight){
(function($) {
    //totalPrice UPDATE
    if (totalPrice == 0) {
        //$('#noProducts').show(); 
        //$('#buyButtons').hide();
        $('#account').empty();
        $('#account').append('<h1>Finalizare comanda</h1><h2>Nu aveţi niciun produs în coşul de cumpărături.</h2><p></p><p><a href="/default.aspx">Va rugam sa va intoarceti la magazin.</a></p>');
        $('#shoppingCart').hide();
        $('#shoppingCart .total').hide();
        $('#shoppingCart .totaltva').hide();
        $('#shoppingCart .totalmintva').hide();
        //$('#inlineCartBar .produseInCos').empty();
        //$('#inlineCartBar h4').addClass('noProducts');

    } else {
        //var tva = eval(totalPrice*0.19);
	    //var priceTva = eval(totalPrice*1.19); 
	    var totalTransport = TransportTaxaColet+(totalWeight*TransportTaxaKg);
	    totalTransport = totalTransport/10;
	    totalTransport = Math.ceil(totalTransport)*10;
        $('#shoppingCart .totalmintva').show().find('b').empty().append(totalPrice.toFixed(2).replace(".",",")+ ' LEI');
        $('#shoppingCart .totaltransport').show().find('b').empty().append(totalTransport.toFixed(2).replace(".",",")+ ' LEI');
        $('#shoppingCart .totalcutransport').show().find('b').empty().append((totalPrice+totalTransport).toFixed(2).replace(".",",")+ ' LEI');
        //$('#shoppingCart .totaltva').show().find('b').empty().append(tva.toFixed(2)+ ' LEI';);
        //$('#shoppingCart .total').show().find('b').empty().append(priceTva.toFixed(2)+ ' LEI';);
    }
    })(jQuery);
}
function writeShoppingCartAll(result, update){
    (function($) { 
        var totalPrice = 0;
        var totalQuantity = 0;
        var totalWeight=0;
        var table = $('#shoppingCart > table > tbody').empty();
        $.each(result.value, function(i, l){
			l.Price = l.Price.toFixed(2);
            var Price = eval(l.Price*l.Quantity).toFixed(2).replace(".",",")+' lei';
            $('<tr id="tr'+l.VariantID+'"><td><h3><a href="/detaliuProdus.aspx?produs='+l.ProductID+'"><strong>'+l.ProductName+'</strong>'+l.VariantName+'</a></h3></td><td id="tdv'+l.VariantID+'"><input class="txInput" name="txQuantity" id="txQty" type="text" maxlength="2" value="'+l.Quantity+'"/><a href="#sterge" onclick="RemoveLine('+l.VariantID+')" class="sterge">Sterge din cos</a></td><td class="aRight">'+l.Price.replace(".",",")+' lei'+'</td><td id="td'+l.VariantID+'" class="aRight"><strong>'+Price+'</strong></td></tr>')
            .appendTo(table);
            //Force numeric
            table.find('input').numeric();
            if (table.find('input').attr('value') == '0') RemoveLine(l.VariantID);
           
            totalPrice += eval(l.Price*l.Quantity);
            totalQuantity += l.Quantity;
            totalWeight+=eval(l.Attr1.replace(",",".")*l.Quantity);
        });
        doRecalculare();
        WriteTotal(totalPrice, totalWeight);
    })(jQuery);
}


function writeShoppingCart(result, update){
    (function($) { 
        var totalPrice = 0;
        var totalQuantity = 0;
        var totalWeight=0;
        var table = $('#shoppingCart > table > tbody > tr > td > strong').empty();
        $.each(result.value, function(i, l){
			l.Price = l.Price.toFixed(2);
            var Price = eval(l.Price*l.Quantity).toFixed(2).replace(".",",")+' lei';
            $('#td'+l.VariantID).append('<strong>'+Price+'</strong>');
            if (jQuery('#shoppingCart input').attr('value') == '0') RemoveLine(l.VariantID);
            totalPrice += eval(l.Price*l.Quantity);
            totalQuantity += l.Quantity;
            totalWeight+=eval(l.Attr1.replace(",",".")*l.Quantity);
        });
        WriteTotal(totalPrice, totalWeight);
    })(jQuery);
}
	
function FinalizareCos(){
	if ($("hChanged").value != "") {
		alert("Pentru finalizarea comenzii va rugam actualizati cosul de cumparaturi");
		return false;
	}
	else {
		$("dvLoadingFinalizare").style.display = "inline";
		document.location.href = "/finalizareComanda.aspx";
		return false;
	}
}


jQuery(document).ready(function($){
    //Initialize the element state
    toggleElement($('#companyToggler input'),$('#ctl00_cpBody_dvCompany'));

    $('#companyToggler input')
        .bind('click change',function(){
            toggleElement($('#companyToggler input'),$('#ctl00_cpBody_dvCompany'))
        });
        
    //Initialize the element state
    //toggleElement($('#companyToggler input'),$('#dvCompany'));

    $('#modificaDateLivrare input')
        .bind('click change',function(){
            toggleElement($('#modificaDateLivrare input'),$('#hiddenForm'),$('#dateInitiale'));
        });   
        
    //Pentru Inputuri din Cos
    doRecalculare();
});

function doRecalculare(){
    jQuery('#shoppingCart input').numeric()
        .keyup(function(e){ testKey(e.keyCode); });
}

function testKey(e) {
    if(e!=13){
        Recalculare();
    }
    //if (jQuery('#shoppingCart input').attr('value') == '0') RemoveLine(0);
}

//jQuery(function(){
//    RemoveLine(0);
//});
