/*
 * lib.catalogue.js
 * gestion du panier
 */
function initRightTopCart(){
    if($('#span_panier_link').length>0){
        $.ajax({
            url:'/sites/kerzarch/theme/kerzarch/php/showCartCount.php',
            type:'post',
            success: function(reponse){
                if(reponse!="false")
                    $('#span_panier_link').html(reponse);
            }
        });
    }
        
}

function initQtyCart(){
    //alert($('#formToUpCart_link').length);
    $('#formToUpCart_link').unbind('click').bind('click',function(){
    	var oBtn = $(this);
    	var oForm = $('#formToUpCart');
    	var i=0;
    	
    	//alert($('input.change_qty',oForm).length);
        $('input.change_qty',oForm).each(function(){
        	var oInput = $(this);
            var lcom_id=$('#lcom_'+i).val();
            var lcom_qty=$('#qty_'+i).val();
            $.ajax({
            	url:'/sites/kerzarch/theme/kerzarch/php/upCart.php',
            	type:'post',
            	data:{'lcom_id':lcom_id,'lcom_qty':lcom_qty},
            	success: function(){
                    initCart();
                    initQtyCart();
                    initRightTopCart();
		}
            });
        	i++;
        });
        return false;
    });
}

//initialisation de la session
function initSession(){
    $.ajax({
        url:'/sites/kerzarch/theme/kerzarch/php/sessionstart.php',
        type:'post'
    });
}

/*
 * fonction initCart
 * génère la panier sur la page panier
 */
function initCart(){
    if( $("#blockContent").find("div#panier").length>0 ){
        $.ajax({
            url:'/sites/kerzarch/theme/kerzarch/php/showCart.php',
            type:'post',
            success:function(reponse){
                $("div#panier").html(reponse);
                initQtyCart();
                initLinkToComm();
            }
        });
    }
}

function initPopupIdClient(){
    if( $("#blockContent").find("div#info_client").length>0 ){
        
        $.ajax({
            url:'/sites/kerzarch/theme/kerzarch/php/formClient.php',
            type:'post',
            success:function(reponse){
                $("div#info_client").html(reponse);
                $("div#info_client").css("padding", "5px");
                initLinkToComm();
                
            }
        });
    }
}

function initLinkToComm(){
    //alert($('#go_com').length);
    $('#go_com').click(function(){
        $.ajax({
            type:'post',
            url:'/sites/kerzarch/theme/kerzarch/php/sessionClient.php',
            success: function(reponse){
                if(reponse=="true"){
                    $('#info#client').css({display:"none"});
                    window.location.href='/e-catalogue/confirmation.html';
                }else{
                    return false;
                }
            }
        });
    }).colorbox({width:"800", height:"550", inline:true, href:"#info_client", title:'&nbsp;'});
    initCopieAdresse();
    initValidateForms();
}

function initPopupUpClient(){
    if( $("#blockContent").find("div#recap_confirm").length>0 ){
        
        $.ajax({
            url:'/sites/kerzarch/theme/kerzarch/php/formUpClient.php',
            type:'post',
            success:function(reponse){
                $("div#divUpClient").html(reponse);
                $("div#divUpClient").css("padding", "5px");
                initLinkToUpClient();
                
            }
        });
    }
}

function initLinkToUpClient(){
    //alert($('#go_com').length);
    $('#goUpClient').click(function(){
        initCopieAdresse();
        initValidateForms();
    }).colorbox({width:"700", height:"500", inline:true, href:"#divUpClient", title:'&nbsp;'});
    
}


function initValidateForms(){
    //alert($('form#formNewClient').length);
    var oFormNew = $('form#formNewClient');
    oFormNew.bind('submit', function(){return false;})
    .bind("invalid-form.validate", function(){
        $("#erreurFormNew").css({display:"block"}).html("Le formulaire contient des erreurs. Veuillez vérifier votre saisie.");
    })
    .validate({
        rules:{email:{required:true, email:true}},
        submitHandler: function(form){
            var data = $(form).serialize();
            $.ajax({
                type:'post',
                url:'/sites/kerzarch/theme/kerzarch/php/recClient.php',
                data:data,
                success:function(reponse){
                    if(reponse=='existe')
                        $('#erreurFormNew').css({display:"block"}).html('Un compte avec cette adresse email existe déjà. Identifiez-vous plus bas.');
                    else if(reponse=="true")
                        window.location.href=$(form).attr("action");
                    /*else
                        alert(reponse+"\ncontactez l'administrateur");*/
                }
            });
        }
    });
    var oFormOld = $('form#formOldClient');
    oFormOld.bind('submit', function(){return false;})
    .bind("invalid-form.validate", function(){
        $("#oldErreurForm").css({display:"block"}).html("Le formulaire contient des erreurs. Veuillez vérifier votre saisie.");
    })
    .validate({
        rules:{email:{required:true, email:true}},
        submitHandler: function(form){
            var data = $(form).serialize();
            $.ajax({
                type:'post',
                url:'/sites/kerzarch/theme/kerzarch/php/identifyClient.php',
                data:data,
                success:function(reponse){
                    if(reponse=='false')
                        $('#oldErreurForm').css({display:"block"}).html('Aucun compte n\'est enregistré avec cette combinaison Email/Mot de passe. Vérifiez votre saisie, ou identifiez-vous en tant que nouveau client.');
                    else if(reponse=="true")
                        window.location.href=$(form).attr("action");
                    /*else
                        alert(reponse+"\ncontactez l'administrateur");*/
                }
            });
        }
    });
    var oFormUp = $('form#formUpClient');
    oFormUp.bind('submit', function(){return false;})
    .bind("invalid-form.validate", function(){
        $("#erreurFormUp").css({display:"block"}).html("Le formulaire contient des erreurs. Veuillez vérifier votre saisie.");
    })
    .validate({
        rules:{email:{required:true, email:true}},
        submitHandler: function(form){
            var data = $(form).serialize();
            $.ajax({
                type:'post',
                url:'/sites/kerzarch/theme/kerzarch/php/upClient.php',
                data:data,
                success:function(reponse){
                    if(reponse=='false')
                        $('#erreurFormUp').css({display:"block"}).html('Vérifiez votre saisie.');
                    else if(reponse=='password')
                        $('#erreurFormUp').css({display:"block"}).html('Saisissez votre mot de passe à nouveau pour continuer.');
                    else if(reponse=="true")
                        window.location.reload();
                    /*else
                        alert(reponse+"\ncontactez l'administrateur");*/
                }
            });
        }
    });
}

function addCart(art_ref){
    var oInput;
    if( $('li.pager input[name="add_cart_'+art_ref+'"]').length > 0){
        oInput = $('li.pager input[name="add_cart_'+art_ref+'"]');
    }else{
        oInput = $('input[name="add_cart_'+art_ref+'"]');
    }
    var qty= oInput.val();
    //alert("element sondé: "+$('li.pager input[name="add_cart_'+art_ref+'"]').length);
    //alert("quantité input: "+qty);
    
    if(!isNaN(qty) && (qty!="0") && (qty!=""))
        $.ajax({
           url:'/sites/kerzarch/theme/kerzarch/php/addCart.php',
           type:'post',
           data:{'art_ref':art_ref, 'qty':qty},
           success:function(reponse){
                $(".info_cart_"+art_ref).css({display:"block", margin:"5px 0 0 0"}).html(reponse);
                $('li.pager #add_cart_'+art_ref).val("0");
                $('li.pager #add_cart_'+art_ref).css({color:"grey"});
                initRightTopCart();
                setTimeout(function(){
                    $(".info_cart_"+art_ref).css({display:"none"}).html("&nbsp;");
                }, 10000);
           }
        });
    else if(qty=="0"){
        alert("la quantité est nulle.")
    }else{
        alert("La quantité est faussée: "+qty);
    }
}


function initCopieAdresse(){
    $('.fact').each(function(){
       var oInput = $(this);
       oInput.change(function(){
           var oInput = $(this);
           var name=oInput.attr("name");
           var value=oInput.val();
           $('input[name="'+name+'_liv"]').val(value);
       });
    });
}

function initRecapConfirmation(){
    if( $("#blockContent").find("div#recap_confirm").length>0 ){
        
        $.ajax({
            url:'/sites/kerzarch/theme/kerzarch/php/recapConfirm.php',
            type:'post',
            success:function(reponse){
                $("div#recap_confirm").html(reponse);
            }
        });
    }
}


function confirmCommande(){
    if( $('input[name="cgv"]').is(':checked')){
        $.colorbox({width:"550", height:"500", inline:true, href:"#divLoadingPaypal", title:'&nbsp;'});
        $.ajax({
            type:'post',
            url:'/sites/kerzarch/theme/kerzarch/php/sendCommande.php',
            success: function(reponse){
                if(reponse=="commandeOk"){
                    paiement();
                    //window.location.href="/e-catalogue/merci-de-votre-commande.html";
                }else{
                    alert(reponse);
                }
            }
        });
        return false;
    }else{
        $('#cgv_error').css({display:"block"}).html('Il est nécéssaire d\'accepter les conditions générales de vente pour continuer.');
        return false;
    }
}

function paiement(){
    $('form#payForm').submit();
}




//MAPPEMONDE
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
