﻿function Finalizare()
{

    if ($("hChanged").value=="true")
    {
        alert (getJSPH("Comanda_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 += getJSPH("Comanda_- 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;
    }
    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;  
    }

}

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=="" || !isPozIntNum(inputs[i].value))
            {
                err=getJSPH("Comanda_Va rugam introduceti cantitati numere intregi pozitive");
            }
            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,optionID)
{
    var result=Netlogiq.Web.finalizareComanda.RemoveProduct(vID,optionID); 
    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)
//    {
//        writeShoppingCart(result);
//    }
//}


function writeShoppingCartAll(result, update){
    (function($) { 
         
        //totalPrice
        var totalPrice = 0;
        var totalQuantity = 0;
        
        var table = $('#shoppingCart > table > tbody').empty();
        $.each(result.value, function(i, l){
            var Price = formatPrice(eval(l.Price*l.Quantity))+' lei';
            
            $('<tr id="tr'+l.VariantID+l.OptionID+'"><td><h3><a href="/detaliuProdus.aspx?produs='+l.ProductID+'"><strong>'+l.ProductName+'</strong>'+l.VariantName+' ('+l.OptionName+')</a></h3></td><td><input class="txInput" name="txQuantity" id="txQty" type="text" maxlength="2" value="'+l.Quantity+'"/><a href="#sterge" onclick="RemoveLine('+l.VariantID+','+l.OptionID+')" class="sterge">'+getJSPH("Produs_sterge")+'</a></td><td class="aRight">'+formatPrice(l.Price)+' lei</td><td id="td'+l.VariantID+l.OptionID+'" class="aRight"><strong>'+Price+'</strong></td></tr>')
            .appendTo(table);
           
            //Force numeric
            table.find('input').numeric();
           
            //totalPrice
            totalPrice += eval(l.Price*l.Quantity);
            totalQuantity += l.Quantity;
        });
        
        doRecalculare();
        
        //totalPrice UPDATE
        if (totalPrice == 0) {
            //$('#noProducts').show(); 
            //$('#buyButtons').hide();
            $('#account').empty();
            $('#account').append('<h1>'+getJSPH("FinalizareComanda_Finalizare comanda")+'</h1><h2>'+getJSPH("FinalizareComanda_Nu aveti nici un produs in cosul de cumparaturi")+'</h2><p></p><p><a href="/listaproduse.aspx">'+getJSPH("FinalizareComanda_sa va intoarceti la magazin.")+'</a></p>');
            $('#shoppingCart').hide();
            $('#shoppingCart .total').hide();
            $('#shoppingCart .totaltva').hide();
            $('#shoppingCart .totalmintva').hide();
        } else {
			var tva = eval(totalPrice*0.19);
			var priceTva = eval(totalPrice*1.19);
            totalPrice = formatPrice(totalPrice)+ ' lei';
			var tvaPrice = tva.toFixed(2)+ ' lei';
			var totalPriceTva = priceTva.toFixed(2)+ ' lei';
            $('#shoppingCart .totalmintva').show().find('b').empty().append(totalPrice);
            if(document.getElementById('ctl00_cpBody_hLanguage').value=="ro-RO")
            {
                $('#shoppingCart .totaltva').show().find('b').empty().append(tvaPrice);
                $('#shoppingCart .total').show().find('b').empty().append(totalPrice);
            }
        }
        
        if (!$('#inlineCart').is(':visible') && (update == 'add')) {
            $('#inlineCartWrapper').addClass('active');
            $('#inlineCart').show();
        }
        
    })(jQuery);
}


function writeShoppingCart(result, update){
    (function($) { 
         
        //totalPrice
        var totalPrice = 0;
        var totalQuantity = 0;
        
        var table = $('#shoppingCart > table > tbody > tr > td > strong').empty();
        $.each(result.value, function(i, l){
            var Price = formatPrice(eval(l.Price*l.Quantity))+' '+getJSPH("Lei");
           
            $('#td'+l.VariantID+l.OptionID).append('<strong>'+Price+'</strong>');
            //Force numeric
            table.find('input').numeric();
           
            //totalPrice
            totalPrice += eval(l.Price*l.Quantity);
            totalQuantity += l.Quantity;
        });       
        
        //totalPrice UPDATE
        if (totalPrice == 0) {
            $('#shoppingCart .total').hide();
            $('#shoppingCart .totaltva').hide();
            $('#shoppingCart .totalmintva').hide();

        } else {
			var tva = eval(totalPrice*0.19);
			var priceTva = eval(totalPrice*1.19);
            totalPrice = formatPrice(totalPrice)+ ' '+getJSPH("Lei");
			var tvaPrice = tva.toFixed(2)+ ' '+getJSPH("Lei");
			var totalPriceTva = priceTva.toFixed(2)+ ' '+getJSPH("Lei");
            $('#shoppingCart .totalmintva').show().find('b').empty().append(totalPrice);
            if(document.getElementById('ctl00_cpBody_hLanguage').value=="ro-RO")
            {
                $('#shoppingCart .totaltva').show().find('b').empty().append(tvaPrice);
                $('#shoppingCart .total').show().find('b').empty().append(totalPriceTva);
            }
        }
        
        if (!$('#inlineCart').is(':visible') && (update == 'add')) {
            $('#inlineCartWrapper').addClass('active');
            $('#inlineCart').show();
        }
        
    })(jQuery);
}
	
function FinalizareCos(){
	if ($("hChanged").value != "") {
		alert(getJSPH("Comanda_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 (jQuery('#shoppingCart input').attr('value') != '0') 
    if(e!=13){
        Recalculare();
    }
}

jQuery(function(){
    RemoveLine(0);
});