/*
 * Gestion du panier simple
 * Créer le 27/01/2011 par Guillaume Roblès et Philippe Baranowicz
 */
var quantI = false;
var qIdI = '';
 
$(document).ready(function () {
    checkmontantcommande();//checkpanier(); 
    var timer;

    $("#panierLiveLien_old").hover(function(){
        if(timer) {
            clearTimeout(timer);
            timer = null
        }
        timer = setTimeout(function() {
            var urlBase = getBaseURL();
            var uri = urlBase + 'commandes/panier';
            $.ajax({
                url: uri,
                success: function(data) {
                    $('#panierLive').html(data);
                    $('#panierLive').show();
                }
            });
        }, 500);

    /*var urlBase = getBaseURL();
		var uri = urlBase + 'commandes/panier';
		$.ajax({
			url: uri,
			success: function(data) {
			$('#panierLive').html(data);
			$('#panierLive').show();
		  }
		});*/
    },
 
    function () {
        $('#panierLive').hide();
        if(timer) {
            clearTimeout(timer);
            timer = null
        }
    }
    );
	
});
function checkparams(){
    var quantite = $('input.quantite').val();
	alert(quantite)
	ajoutpanier(6,1);
	
}
function close_modal(id){
    var qte = document.getElementById("quantite").value;
    if(qte > 0 ){
        ajoutpanier(qIdI, qte);
    }
	if(!quantI){
		document.getElementById("popup_quantite").style.display = "none";
		document.getElementById("fade").style.display = "none";
	}

}

function checkNum(event)
{
    // Compatibilit� IE / Firefox
    if(!event&&window.event) {
        event=window.event;
    }
    // IE
    if((event.keyCode < 96 || event.keyCode > 105) && (event.keyCode < 48 || event.keyCode > 57) &&  event.keyCode != 8 && event.keyCode!=37 && event.keyCode!=38 && event.keyCode!=39 && event.keyCode!=40) {
        event.returnValue = false;
        event.cancelBubble = true;
    }
    // DOM
    if((event.which < 96 || event.which > 105) && (event.which < 48 || event.which > 57) &&  event.which != 8  && event.which!=37 && event.which!=38 && event.which!=39 && event.which!=40) {

        event.preventDefault();
        event.stopPropagation();
    }
}

function quantite(id)
{
    
	var form = '<div id="popup_quantite" class="popup_block">';
    form += '<form name="quantite_form" >';
    form += 'Indiquez la quantit&eacute;: <input type="text" id="quantite" size="2" value="1" onKeyDown="checkNum(event);" /><hr />';
    form +='<input type="button" name="theSubmitButton" id="theSubmitButton" value="Ajouter cette quantit&eacute; &agrave; mon panier" />';
    form +='</form></div><div id="fade"></div>';
    $('#container').before(form);
	
    $('#theSubmitButton').click(function(){
        close_modal(id);
    });
    document.getElementById("fade").style.display = "inline";
    document.getElementById("popup_quantite").style.display = "inline";
    document.getElementById("quantite").focus();
    quantI = true;
    qIdI = id;

}

function cgv_validation(v,m,f){
    if(v){
        $('#cgv_validator').attr('checked','checked');
    }
    else{
        var etat = $('#cgv_validator').attr('checked');
        if(etat){
            $('#cgv_validator').removeAttr('checked');
        }
    }
}


function cgv(){
    var urlBase = getBaseURL();
    var uri = urlBase + 'index/cgv';
        
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", uri, false);
    xmlhttp.send();
    if(xmlhttp.responseText != -1){
        $.prompt(xmlhttp.responseText,{
            prefix: 'validation_box',
            show:'slideDown',
            callback: cgv_validation,
            buttons: {
                Accepter:true,
                Refuser:false
            }
        });
    //return false;
    }
	
	
	
/*$.get(urlBase + 'index/cgv#top_cgv', function(data) {
		$.prompt(data,{
			prefix: 'validation_box',
			show:'slideDown',
			callback: cgv_validation,
			buttons: {Accepter:true, Refuser:false}
		});	
		return false;
	});
	*/
}

function checkmontantcommande()
{
    var montant = $('#totalPanier').html();
    if(montant==0.00)
        $('.commander').remove();
}

function ajoutpanier(id,qte)
{
    if(quantI){
        $('#fade').remove();
        $('#popup_quantite').remove();
    }
    var urlBase = getBaseURL();
    var uri = urlBase + 'layout/panier?id=' + id + '&qte=' + qte;
    //var uri = 'http://localhost/clientsite/public/index/panier?id=' + id + '&qte=' + qte;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", uri, false);
    xmlhttp.send();
    if(xmlhttp.responseText != -1)
    {
        document.getElementById('nombre_selection').innerHTML = xmlhttp.responseText;
        //alert('Le bien a été ajouté à votre sélection.');
        desactiveritem(id);
        return true;
    }
		
    else{
        $.prompt('La quantite demand�e n\'est pas disponible',{
            prefix: 'validation_boxx',
            show:'slideDown',
            buttons: {
                Fermer:true
            }
        });
        return false;
    }
}

function supprimerpanier(id)
{
    var urlBase = getBaseURL();

    var uri = urlBase + 'layout/supprimerpanier?id=' + id;
    //var uri = 'http://localhost/clientsite/public/index/supprimerpanier?id=' + id;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", uri, false);
    xmlhttp.send();
    document.getElementById('nombre_selection').innerHTML = xmlhttp.responseText;
    //alert('Le bien a été retiré de votre sélection.');
    //        var strBouton = 'bloc_liste_selection_' + id;
    //        var iOk = 0;
    //        if(document.getElementById(strBouton)==undefined)
    //        {
    //            strBouton = 'bloc_detail_selection_' + id
    //            if(document.getElementById(strBouton))
    //                iOk = 2;
    //        }
    //        else
    //            iOk =1;
    var strBouton = 'bloc_retirer_selection_' + id;
    var iOk = 0;
    if(document.getElementById(strBouton)==undefined)
    {
        strBouton = 'bloc_detail_retirer_selection_' + id
        if(document.getElementById(strBouton))
            iOk = 2;
    }
    else
        iOk =1;
    if(iOk>0)
    {
        activeritem(id,iOk);
    //document.getElementById(strBouton).getElementsByTagName('a')[0].href = "javascript:ajoutpanier("+id+",0)";
    //document.getElementById(strBouton).getElementsByTagName('a')[0].innerHTML = '<label>AJOUTER A LA SELECTION</label>';
    }
}

function supprimerAll()
{
    var urlBase = getBaseURL();
    var uri = urlBase + 'layout/supprimerpanier';
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", uri, false);
    xmlhttp.send();
    document.getElementById('nombre_selection').innerHTML = xmlhttp.responseText;
    $('.lineItem').remove();
    $('#totalPanier').html('');
    $('.commander').remove();
    location.reload();

//windows.refresh();
//$('.commander').remove();//document.getElementById('commander').style = "display:none;";
}



function supprimerpanierselection(id)
{
		
//document.getElementById('bloc_liste_bien_detail_' + id).parentNode.removeChild(document.getElementById('bloc_liste_bien_detail_' + id))
//supprimerpanier(id);
}
function calculTotal(){
    var itemTotal = 0;
    var total = 0;
    $('.totalItem').each(function () {
        itemTotal = $(this).children('span').html();
        total += parseFloat(itemTotal);
    });
    total = parseFloat(total);
    $('#totalPanier').html(total.toFixed(2));
}
$(function(){
    $('.supprimerItem').click(function(){
        var id = $(this).attr('name');
        ligne = $(this).parent().parent();
        $(ligne).remove();
        supprimerpanier(id);
        if(document.getElementById('tableau_panier').getElementsByTagName('tr').length==2)
        {
            $('.commander').remove();
            location.reload();
        }
    //alert(alert(document.getElementById('tableau_panier').getElementsByTagName('tr').length));
    //location.reload();
		
    });
    $('.quantItem').keyup(function(){
        var qnt = $(this).val();
        //prix unitaire
        var prix = $(this).parent().prev().html();
        if(isNaN(qnt) || isNaN(prix)){
            alert('NAN');
            return 0;
        }
        qnt = parseInt(qnt)
        if(qnt == 0 || isNaN(qnt)) qnt = 1;
        var totalItem;
        totalItem = qnt * prix;
        //prix total ligne
        var id = $(this).attr('id');
        var ok = ajoutpanier(id,qnt);
        if(ok){
            $(this).parent().next().children('span').html(totalItem.toFixed(2));
            calculTotal();
        }
        else{
            var totalItem = $(this).parent().next().children('span').html();
            var oldVal = totalItem / prix;
            $(this).val(parseInt(oldVal));
        }
    });
		
});



function checkpanier(quantB)
{
    quantI = quantB
    var urlBase = getBaseURL();

    // Cette fonction va récupérer les id du paniers ...
    var uri = urlBase +'layout/getpanier';
    //var uri = 'http://localhost/clientsite/public/index/getpanier';
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("POST", uri, false);
    xmlhttp.send();
    var idList = eval('('+xmlhttp.responseText+')');
    //alert(idList.length);
    for(i=0 ; i<idList.length;i++)
        desactiveritem(idList[i]);
    var elem = document.getElementById("nombre_selection");
    elem.innerHTML = idList.length;
}

function desactiveritem(id)
{
    var fiche = 1;
    var strBouton = 'bloc_liste_selection_' + id;
    if(document.getElementById(strBouton)==undefined)
    {
        fiche = 2;
        strBouton = 'bloc_detail_selection_' + id
    }
    if(document.getElementById(strBouton))
    {
        var oElement = document.getElementById(strBouton);
        //oElement.id = 'bloc_retirer_selection_'+id;
        if(fiche==1)
        {
            oElement.id = 'bloc_retirer_selection_'+id;
            oElement.className = 'bloc_retirer_selection';
        }
        else
        {
            oElement.id = 'bloc_detail_retirer_selection_'+id;
            oElement.className = 'bloc_detail_retirer_selection';
        }
        if(!quantI){
            oElement.getElementsByTagName('a')[0].href = "javascript:supprimerpanier("+id+")";
            oElement.getElementsByTagName('a')[0].innerHTML = 'RETIRER DE LA SELECTION';
        }
        else{
            oElement.getElementsByTagName('a')[0].href = "javascript:supprimerpanier("+id+")";
            oElement.getElementsByTagName('a')[0].innerHTML = 'RETIRER DU PANIER';
        }
    //        oElement.removeChild(oElement.getElementsByTagName('a')[0]);
    //        oElement.innerHTML = 'PRESENT DANS LA SELECTION';
    }
}

function paiement(){
    var cgv = $('#cgv_validator').attr('checked');
    if(cgv){
        $('#form_Commande').submit();
    }
    else{
        $.prompt('Pour continuer, acceptez les cgv.',{
            buttons: {
                Valider : true
            },
            prefix: 'validation_cgv',
            show:'slideDown'
        });
    }
}
function moyen(){
    $('#form_moyens_paiements').submit();
}
function activeritem(id,fiche)
{
    var str = '';
    if(fiche==1)
        str = 'bloc_retirer_selection_' + id;
    else
        str = 'bloc_detail_retirer_selection_' + id;
    if(document.getElementById(str))
    {
        var oElement = document.getElementById(str);
        str = 'bloc_liste_selection';
        if(fiche == 2)
            str = 'bloc_detail_selection'
        oElement.id = str+'_'+id;
        oElement.className = str;
        if(!quantI){
            oElement.getElementsByTagName('a')[0].href = "javascript:ajoutpanier("+id+",0)";
            oElement.getElementsByTagName('a')[0].innerHTML = 'AJOUTER A LA SELECTION';
        }
        else{
            oElement.getElementsByTagName('a')[0].href = "javascript:quantite("+id+");";
            oElement.getElementsByTagName('a')[0].innerHTML = 'AJOUTER AU PANIER';
        }

    }
}

