// Loading
var loading = '<img src ="/images/loading-black.gif" />';
var loading2 = '<img class="loading" src="/images/loading-black.gif" alt="Chargement" />';

/* Lancer la fonction que lorsque la totalité de la page est chargée => évite les erreurs */
$(document).ready( function() 
{
    // Carousel INDEX Avant-premieres
    jQuery('#index-avant-premieres').jcarousel({
        auto: 10, // Specifies how many seconds to periodically autoscroll the content. If set to 0 (default) then autoscrolling is turned off.
        wrap: 'last',
        scroll: 1,  // The number of items to scroll by.
        initCallback: carouselAvtPremIndex_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    
    // Carousel INDEX Festivals
    jQuery('#index-festivals').jcarousel({
        auto: 10, // Specifies how many seconds to periodically autoscroll the content. If set to 0 (default) then autoscrolling is turned off.
        wrap: 'last',
        scroll: 1,  // The number of items to scroll by.
        initCallback: carouselFestivals_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

	// Carousel Avant-premieres (column-right)
	jQuery('#carousel-avant-premieres').jcarousel({
		auto: 10, // Specifies how many seconds to periodically autoscroll the content. If set to 0 (default) then autoscrolling is turned off.
		wrap: 'last',
		scroll: 1,  // The number of items to scroll by.
		initCallback: carouselAvtPremRight_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
	});
	
	/* Espace membre */
	var current_url = document.location.href;
    var reg = new RegExp("espace-membre.html", "g");
    var reg2 = new RegExp("espace-membre.html#form1", "g");
    
    if( reg.test(current_url) || reg2.test(current_url) )
    {
        displayMemberSpaceStep1();
        displayMemberSpaceStep2();
        displayMemberSpaceStep3();
        displayMemberSpaceStep4();
        displayMemberSpaceStep5();
        displayMemberSpaceStep6();
        
        displayMemberSpaceSubtotal();
        displayMemberSpaceTotal();
    }
    
    // Others
});

/* Configuration Carousel Avant premières (DROITE) */
function carouselAvtPremRight_initCallback(carousel)
{
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(
		function() {
			carousel.stopAuto();
		}, function() {
			carousel.startAuto();
		});

    $('#carousel-avant-premieres-prev').click(function() {
        carousel.prev();
        return false;
    });
	
    $('#carousel-avant-premieres-next').click(function() {
        carousel.next();
        return false;
    });
}

/* Configuration Carousel Avant premieres (INDEX) */
function carouselAvtPremIndex_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() { carousel.startAuto(0); });
    carousel.buttonPrev.bind('click', function() { carousel.startAuto(0); });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(
        function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });

    $('#index-avant-premieres-prev').click(function() {
        carousel.prev();
        return false;
    });
    
    $('#index-avant-premieres-next').click(function() {
        carousel.next();
        return false;
    });
}

/* Configuration Carousel Festivals (INDEX) */
function carouselFestivals_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() { carousel.startAuto(0); });
    carousel.buttonPrev.bind('click', function() { carousel.startAuto(0); });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(
        function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });

    $('#index-festivals-prev').click(function() {
        carousel.prev();
        return false;
    });
    
    $('#index-festivals-next').click(function() {
        carousel.next();
        return false;
    });
}

/* Configuration ShadowBox */
function setupShadowBow()
{
    Shadowbox.setup("a.mustang-gallery", {
        gallery: "mustang",
        continuous: true//,
        //counterType: "skip"
    });
}

/* Member Space */

// ---------- PROCESSUS DE MAJ ----------
// - Etape 1 : valide -> MAJ Sub -> MAJ etp 5 -> MAJ Total
// - Etape 2 : valide -> MAJ Sub -> MAJ etp 5 -> MAJ Total
// - Etape 3 : valide -> MAJ Sub -> MAJ etp 5 -> MAJ Total
// - Etape 4 : valide -> MAJ Sub -> MAJ etp 5 -> MAJ Total
// - Etape 5 : valide -> MAJ Total
// --------------------------------------


/* STEP 1 */
function displayMemberSpaceStep1()
{
    $('#member-space-step_1').html( loading2 );
    $.ajax({
       url: "/ajax.php",
       //url: "/includes/member-space-step1.inc.php",
       type: "POST",
       //data: "cmd=blkNewsletter&usr_email="+$("#usr_email").val(),
       data: 
       {
            cmd: 'memberSpaceStep1'
       },
       success: function( result ){
            $('#member-space-step_1').html( result );
       }
    });
}

/* STEP 1 : OnClick Submit btn */
function submitMemberSpaceStep1(form)
{
    var thisForm = document.forms[form];
    
    $('#member-space-step_1').html( loading2 );
    $.ajax({
       url: "/includes/member-space-step1.inc.php",
       type: "POST",
       data: 
       {
            //cmd: 'memberSpaceStep1',
            //usr_company: $("#usr_company").val()
            usr_company: thisForm.elements["usr_company"].value,
            usr_email: thisForm.elements["usr_email"].value,
            usr_phone: thisForm.elements["usr_phone"].value,
            usr_mobile: thisForm.elements["usr_mobile"].value,
            usr_fax: thisForm.elements["usr_fax"].value,
            
            usr_title: thisForm.elements["usr_title"].value,
            usr_firstname: thisForm.elements["usr_firstname"].value,
            usr_lastname: thisForm.elements["usr_lastname"].value,
            usr_address_1: thisForm.elements["usr_address_1"].value,
            usr_address_2: thisForm.elements["usr_address_2"].value,
            usr_address_3: thisForm.elements["usr_address_3"].value,
            usr_zip_code: thisForm.elements["usr_zip_code"].value,
            usr_city: thisForm.elements["usr_city"].value,
            
            usr_liv_title: thisForm.elements["usr_liv_title"].value,
            usr_liv_firstname: thisForm.elements["usr_liv_firstname"].value,
            usr_liv_lastname: thisForm.elements["usr_liv_lastname"].value,
            usr_liv_address_1: thisForm.elements["usr_liv_address_1"].value,
            usr_liv_address_2: thisForm.elements["usr_liv_address_2"].value,
            usr_liv_address_3: thisForm.elements["usr_liv_address_3"].value,
            usr_liv_zip_code: thisForm.elements["usr_liv_zip_code"].value,
            usr_liv_city: thisForm.elements["usr_liv_city"].value
            /*usr_liv_address_1: thisForm.elements[21].value,
            usr_liv_address_2: thisForm.elements[22].value,
            usr_liv_address_3: thisForm.elements[23].value,
            usr_liv_zip_code: thisForm.elements[24].value,
            usr_liv_city: thisForm.elements[25].value*/
       },
       success: function( result )
       {
            //window.parent.opener.location.reload();
            $('#member-space-step_1').html( result );
            
            // Actualise le Bon de commande
            displayMemberSpaceSubtotal();
       }
    });
}


/* STEP 2 */
function displayMemberSpaceStep2( id, quantity )
{
    $('#member-space-step_2').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        //data: "cmd=blkNewsletter&name="+$("#usr_email").val(),
        data: 
        {
            cmd: 'memberSpaceStep2',
            id: id,
            quantity: quantity
        },
        success: function( result )
        {
            $('#member-space-step_2').html( result );
            
            // Actualise le Bon de commande
            if( typeof( id ) != "undefined" ) {
                displayMemberSpaceSubtotal();
            }
        }
    })
}

/* STEP 3 */
function displayMemberSpaceStep3( id, quantity )
{
    $('#member-space-step_3').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        //data: "cmd=blkNewsletter&name="+$("#usr_email").val(),
        data: 
        {
            cmd: 'memberSpaceStep3',
            id: id,
            quantity: quantity
            
        },
        success: function( result )
        {
            $('#member-space-step_3').html( result );
            
            // Actualise le Bon de commande
            if( typeof( id ) != "undefined" ) {
                displayMemberSpaceSubtotal();
            }
        }
    })
}

/* STEP 4 */
function displayMemberSpaceStep4( id, quantity )
{
    $('#member-space-step_4').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        //data: "cmd=blkNewsletter&name="+$("#usr_email").val(),
        data: 
        {
            cmd: 'memberSpaceStep4',
            id: id,
            quantity: quantity
            
        },
        success: function( result )
        {
            $('#member-space-step_4').html( result );
            
            // Actualise le Bon de commande
            if( typeof( id ) != "undefined" ) {
                displayMemberSpaceSubtotal();
            }
        }
    })
}

/* STEP 5 */
function displayMemberSpaceStep5()
{
    $('#member-space-step_5').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        //url: "/includes/member-space-step5.inc.php",
        type: 'POST',
        data: 
        {
            cmd: 'memberSpaceStep5'
            
        },
        success: function( result )
        {
            $('#member-space-step_5').html( result );
        }
    })
}

/* STEP 5 : OnClick Submit btn */
function submitMemberSpaceStep5(form)
{   
    var thisForm = document.forms[form];
    var data = '';

    for (i=0 ; i<= thisForm.length-1 ; i++)
    {
        if(thisForm[i].checked == true)
            data = thisForm[i].value;
    }
    
    $('#member-space-step_5').html( loading2 );
    $.ajax({
       url: "/includes/member-space-step5.inc.php",
       type: "POST",
       data: 
       {
            //cmd: 'memberSpaceStep1',
            //usr_company: $("#usr_company").val()
            //postage: input_checked
            //postage: $("input[@type=radio][@checked]").val()
            shop_postage: data
       },
       success: function( result )
       {
            //window.parent.opener.location.reload();
            $('#member-space-step_5').html( result );
            
            // Actualise le Total
            displayMemberSpaceTotal();
       }
    });
}

/* STEP 6 */
function displayMemberSpaceStep6()
{
    $('#member-space-step_6').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        //url: "/includes/member-space-step5.inc.php",
        type: 'POST',
        data: 
        {
            cmd: 'memberSpaceStep6'
            
        },
        success: function( result )
        {
            $('#member-space-step_6').html( result );
        }
    })
}

/* STEP 6 : OnClick Submit btn */
function submitMemberSpaceStep6(form)
{   
    var thisForm = document.forms[form];
    //var data = '';
    var payment = '';
    var message = '';
    var cgv = 0;
    //var infos = '';

    //for (i=1 ; i<= thisForm.length-1 ; i++)
    /*for (i=0 ; i<=2 ; i++)
    {
        if(thisForm[i].checked == true) {
            payment = thisForm[i].value;
        }
        
        //if(thisForm[i].checked == true) {
            //data += i+thisForm[i].value;
        //}
        
        if(thisForm[i].name == 'message') {
            message = thisForm[i].value;
        }
    }*/
    
    
    //for (i=0 ; i<=4 ; i++)
    for( i=0 ; i<= thisForm.length-1; i++ )
    {
        //infos += thisForm[i].name+','+thisForm[i].value;
    
        if(thisForm[i].name == 'shop_payment')
        {
            if(thisForm[i].checked == true) {
                payment = thisForm[i].value;
            }
        }
        
        if(thisForm[i].name == 'message') {
            message = thisForm[i].value;
        }
        
        if(thisForm[i].name == 'cgv[]')
        {
            if(thisForm[i].checked == true) {
                cgv = thisForm[i].value;
            }
        }
    }
    
    $('#member-space-step_6').html( loading2 );
    $.ajax({
       url: "/includes/member-space-step6.inc.php",
       type: "POST",
       data: 
       {
            //infos: infos,
            payment_val: payment,
            message_val: message,
            cgv_val: cgv
       },
       /*beforeSend: function()
       {
           $("#Member").dialog();
       },*/
       success: function( result )
       {
            //$("#Member").dialog('destroy');
            
            //window.parent.opener.location.reload();
            $('#member-space-step_6').html( result );
       }
    });
}

/* SUBTOTAL */
function displayMemberSpaceSubtotal()
{
    $('#member-space-subtotal').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        data: 
        {
            cmd: 'memberSpaceSubtotal'
        },
        success: function( result )
        {
            $('#member-space-subtotal').html( result );
            
            // Actualise le Bon de commande
            submitMemberSpaceStep5('form-step-5');  // Met à jour la session des frais de port (pour valeur déclarée)
        }
    })
}

/* TOTAL */
function displayMemberSpaceTotal()
{
    $('#member-space-total').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        data: 
        {
            cmd: 'memberSpaceTotal'
        },
        success: function( result )
        {
            $('#member-space-total').html( result );
            
            // Actualise le Bon de commande
            //displayMemberSpaceStep6();  // Actualise les erreurs
        }
    })
}

function sendToFriend(title, url)
{
    //$("#register").dialog('destroy');
    //$("#getPass").dialog('destroy');

    var idDiv = 'sendToFriend';

    createElt(idDiv, '<img style="float:left; margin-right:5px;" img src="/src/icons/silk/email_open.png" /> '+title);

    $(function() {
        $("#"+idDiv).dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 100,
            width: 500,
            modal: true,
            resizable: false,
            show: 'blind'
        });

        $("#"+idDiv).dialog('open');

        $.ajax({
            type: "POST",
            data: 'url='+url,
            url: "/includes/box-sendtofriend.inc.php",
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            success: function(r){
            $("#"+idDiv).html(r);
        }
        });
    });
}

function forgetPass(title)
{
    //$("#register").dialog('destroy');
    //$("#sendToFriend").dialog('destroy');

    var idDiv = 'getPass';

    createElt(idDiv, '<img style="float:left; margin-right:5px;" src="/src/icons/silk/lock.png" /> '+title);

    $(function() {
        $("#"+idDiv).dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 200,
            width: 500,
            modal: true,
            resizable: false,
            show: 'blind'
        });

        $("#"+idDiv).dialog('open');

        $.ajax({
            type: "POST",
            url: "/includes/box-forget-pass.inc.php",
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            success: function(r){
                $("#"+idDiv).html(r);
            }
        });
    });
}

function validOrder(title)
{
    //$("#register").dialog('destroy');
    //$("#sendToFriend").dialog('destroy');
	//$("#validOrder").dialog('destroy');

    var idDiv = 'validOrder';

    createElt(idDiv, '<img style="float:left; margin-right:5px;" src="/src/icons/silk/lock.png" /> '+title);

    $(function() {
        $("#"+idDiv).dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 200,
            width: 800,
            modal: true,
            resizable: false,
            show: 'blind',
    		buttons: {
    			"Valider la commande": function() {
    				//$( this ).dialog( "close" );
		    		$.ajax({
		    			type: "POST",
		    			url: "/includes/member-space-order-confirm.php",
		    			//data: "cmd=deletePic&id="+id,
		    			success: function(r){
		    			//	$('#img'+id).hide('highlight');
		    				location.reload();
		    			}
		    		 });
		    		//location.reload();
    			},
    			"Modifier la commande": function() {
    				$( this ).dialog( "close" );
    			}
    		}
        
        	/*
	        buttons: {
	                'Envoyer': function() {
	                 $("#monid form").ajaxSubmit({
	                         url: monurl,
	                         type: "post",
	                         error: function(){
	                                 alert("theres an error with AJAX");
	                         },
	                         beforeSubmit:function(){},
	                         success: function(e){}
	                 });
	                 $(this).dialog('close');
	                 },
	                 Cancel: function() {
	                         $(this).dialog('close');
	                 }
    		}*/
        });

        $("#"+idDiv).dialog('open');

        $.ajax({
            type: "POST",
            url: "/includes/box-valid-order.inc.php",
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            success: function(r){
                $("#"+idDiv).html(r);
            }
        });
    });
}


function loadingBox(title)
{
    //$("#register").dialog('destroy');
    //$("#getPass").dialog('destroy');

    var idDiv = 'loadingOrder';

    //createElt(idDiv, '<img style="float:left; margin-right:5px;" img src="/src/icons/silk/email_open.png" /> '+title);
    createElt(idDiv, '<img style="float:left; margin-right:5px;" img src="/src/icons/zak/loading.gif" /> '+title);

    $(function() {
        $("#"+idDiv).dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 100,
            width: 500,
            modal: true,
            resizable: false,
            show: 'blind'
        });

        $("#"+idDiv).dialog('open');
        $("#"+idDiv).html( loading2 );

        /*$.ajax({
            type: "POST",
            data: 'url='+url,
            url: "/includes/box-sendtofriend.inc.php",
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            success: function(r){
            $("#"+idDiv).html(r);
        }
        });*/
    });
}

/*****************
 * FORM CONTACT
 ****************/
function contactRefreshFormByTypeOfContact( type )
{
	// Display lightbox LOADING
	/*if( type == 1 || type == 2 )
	{
		loadingBox( 'Chargement...' );
	}*/
	
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        data: 
        {
            cmd: 'contactRefreshFormByTypeOfContact',
            type: type
        },
        success: function( r )
        {
        	var redirect_url = "";
        	
        	// CE
            if( r == '1' ) {
            	var redirect_url = "/ce/contact.html";
            }
            // ENTREPRISE
            else if( r == '2' ) {
            	var redirect_url = "/entreprise/contact.html";
            }
        	
            // Redirection vers le formulaire
            if( redirect_url != "" )
            {
            	$(location).attr('href',redirect_url);
            }
        }
    });
}

/*###########################
#                           #
#   DIALOGBOX               #
#                           #
###########################*/

// Creation d'une div pour le titre de la dialogbox
function createElt(id, title)
{
    if(!document.getElementById(id))
    {
        var popup = document.createElement("div");
    
        popup.setAttribute('id', id);
        popup.setAttribute('title', title);
    
        document.body.appendChild(popup);
    }
}


function submitIn(form, div)
{
    var thisForm = document.forms[form];    

    var cache = document.createElement("div");
    
    cache.setAttribute('id','loadCache');
    cache.setAttribute('title', 'cache');
    

    thisForm.appendChild(cache);
    
    $('#loadCache').html("<img src='/src/icons/zak/loading.gif' />");
    
    
    var data = '';
            
    for (i=0 ; i<= thisForm.length-1 ; i++)
    {
        if(thisForm[i].name != '')
            data += thisForm[i].name+'='+thisForm[i].value+'&';
    }

    
    $.ajax({
        type: "POST",
        url: thisForm.action,
        data: 'income=popup&'+data,
        contentType : "application/x-www-form-urlencoded; charset=utf-8",
        success: function(r) // retour de la page php
        {
            $("#"+div).html(r);
            
            // OLD
            //if(r == '1')
            //{
                //showRegisterBox();
                /*if($('#baseForm').val() == "reload")
                    location.reload(true);
                else
                    document.forms[$('#baseForm').val()].submit();*/
                
            //}
            //else if(r == '0')
            //{
                //showRegisterBox();
            //}
            //else if(r == 'formAdressReload')
            //{
                //location.reload(true);
            //}
            //else
            //{
                //$("#"+div).html(r);
            //}
            // Fin OLD
        }
     });   
}

/*###############
#   BOX PART    #
###############*/
function submitPartChoise(part)
{   
    //$('#member-space-subtotal').html( loading2 );
    $.ajax({
        url : '/ajax.php',
        type: 'POST',
        data: 
        {
            cmd: 'sitePartChoise',
            part: part
        },
        success: function( r )
        {
        	// Ancien Système
            //location.reload();  // Pour charger la colonne gauche et droite voulue
            
        	//$(location).attr('href',"/ce/contact.html");
        	
            // Nouveau système
        	var redirect_url = "";
        	
            if( part == 1 )
            {
            	var redirect_url = "/ce/contact.html";
            }
            else if( part == 2 )
            {
            	var redirect_url = "/entreprise/contact.html";
            }
        	
            //$(location).attr('href',redirect_url);
            if( redirect_url != "" )
            {
            	$(location).attr('href',redirect_url);
            }
            
            //setTimeout('clearPage()', 5000);
            //$('.box-default').slideUp("slow", function(){ alert(r); });
            $('.box-default').slideUp("slow");
            $('.box-default-overlay').animate({ 
                height: "0%"//,
                //opacity: 0.4,
                //marginLeft: "0.6in",
                //fontSize: "3em", 
                //borderWidth: "10px"
            }, 4000 );
            
            //$('.box-default').slideUp("slow",function(){ alert(r); });
            //$('.box-default-overlay').fadeOut("100000");
            //$('.notice').fadeIn().delay(2000).fadeOut('slow');
            //setTimeout('alert(\'Surprise!\')', 5000)
            /*$('.box-default-overlay').animate({ 
                height: "0%"//,
                //opacity: 0.4,
                //marginLeft: "0.6in",
                //fontSize: "3em", 
                //borderWidth: "10px"
            }, 1500 ).delay(5000);*/
        }
    });
}

// Member space ( Display and Hide prd_description)
function displayPrdDesc( line, step )
{
    $("#"+step+" > tbody > tr.row_"+line+" > td.col_1 > div").css("display","block");
}

function hidePrdDesc( line, step )
{
    $("#"+step+" > tbody > tr.row_"+line+" > td.col_1 > div").css("display","none");
}

