/**
 * Calculer le total d'un article et mettre à jour quantite et cout total de l'article
 *
 * @param string cellule avec le prix unitaire
 * @param {Element} cellule avec la quantite
 * @param {Element} cellule avec le prix total
 */
function updItemTotal(unitPrice, quantity, total){
    if (unitPrice == null || quantity == null || total == null){
        return -1;
    }
    if (!isNaN(parseInt($(quantity).val())) ){
        if (parseInt($(quantity).val()) < 0) {
            $(quantity).val(1);
        }
        else {
            $(quantity).val(parseInt($(quantity).val()) );
        }
        total.text(parseFloat(unitPrice).toFixed(2) * parseInt($(quantity).val()) );
    }
    return 0;
}




/**
 * Calculer le total de la commande et mettre à jour le champs correspondant
 *
 * @param {Element[]} cellules avec les prix totaux par article
 * @param {Element} cellule avec le prix total de la commande
 * @param {String} discount sur le prix total
 */
function updTotalCart(pricesByItem, totalInvoice, discount){
    if (pricesByItem == null || totalInvoice == null){
        return false;
    }
    var oldTotal = $(totalInvoice).text();
    var total = 0.0;
    if($(pricesByItem).length == 1)
    {
        total = parseFloat($(pricesByItem).text());
    }
    else
    {
        pricesByItem.each(function(){
            //console.log($(priceForOneItem).text());
            total += parseFloat($(this).text());
        });
    }
    
    if(!isNaN(discount) && parseFloat(discount) > 0)
    {
        discount = parseFloat(discount);
        if(discount >= 1)
        {
            total = Math.max(total - discount, 0);
        }
        else
        {
            total = total * (1 - discount);
        }
    }

    $(totalInvoice).text('Total Price : $' + total.toFixed(2));
    if(oldTotal == 'Total Price : $' + total.toFixed(2))
    {
        return false;
    }
    else
    {
        return true;
    }
}

/**
 * Callback when an element of the carousel get visible
 * @param {Element} instance of the requesting carousel
 * @param {Element} <li> object itself
 * @param {int} index which indicates the position of the item in the list
 * @param {string} state of the carousel action (prev, next or init)
 */
function carouselSoftMenuOn(carousel, item, position, state)
{
    var titles = $("#carouselSoftwareTitle li");
    /*titles.each(function(){
        $(this).removeClass('active');
    });*/
    $(titles.get(position-1).firstChild ).addClass('active');
    //titles.get(position).addClass('active');
    return 0;
}

/**
 * Callback when an element of the carousel get invisible
 * @param {Element} instance of the requesting carousel
 * @param {Element} <li> object itself
 * @param {int} index which indicates the position of the item in the list
 * @param {string} state of the carousel action (prev, next or init)
 */
function carouselSoftMenuOff(carousel, item, position, state)
{
    var titles = $("#carouselSoftwareTitle li");
    $(titles.get(position-1).firstChild ).removeClass('active');
    return 0;
}

function carouselSoftInit(carousel)
{
    $('#carouselSoftwareTitle li a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('rel')));
        carousel.options.auto = 0; // Stopper le carousel après le premier click
        //console.log(carousel);
        return false;
    });
}

/**
 * Permettre un accordéon
 */
function accordeon(lastBlock, blocks, maxWidth, minWidth){
    blocks.hover(
      function(){
        if($(this).width() < maxWidth){
            $(lastBlock).animate({width: minWidth+"px"}, {queue:false, duration:400});
            $(this).animate({width: maxWidth+"px"}, {queue:false, duration:400});
            lastBlock = this;
        }
      }
    );
}

/**
 * Check if the cart total is 0 with at least 1 item
 */
function replaceStoreAction()
{
    var total = $('#totalPrice').text();
    total = total.substring(total.indexOf("$", 0)+1, total.length);

    if( $('#cartItems tbody tr').length > 0 && parseFloat(total) == 0 )
    {
        $('#paysecurelynow').css({"background-position":"0 -88px"});
        $('#paysecurelynow').hover(
            function(){$(this).css({"background-position":"0 -132px"});},
            function(){$(this).css({"background-position":"0 -88px"});});
        $('#step3 div p').html("Click on 'Free download' to download the free demo of MapInXL.");
    }
    else
    {
        $('#paysecurelynow').css({"background-position":"0 0"});
        $('#paysecurelynow').hover(
            function(){$(this).css({"background-position":"0 -44px"});},
            function(){$(this).css({"background-position":"0 0"});});
        $('#step3 div p').html("Click on '<span id=\"paysecurelynowlink\">Pay Securely Now</span>' to complete your purchase through PayPal.<br/>Both Credit Card and PayPal accounts are accepted.");
    }
}

$(document).ready(function() {

//    $("#dialogDemo").dialog({
//        bgiframe: true,
//        resizable: false,
//        height:140,
//        modal: true,
//        autoOpen: false,
//        overlay: {
//            backgroundColor: '#000',
//            opacity: 0.8
//        },
//        buttons: {
//            'OK': function() {
//                 $(this).dialog('close');
//            }
//        }
//    });

//    $('#demoMenu').click(function(e){
//        $("#dialogDemo").dialog('open');
//        mywindow = window.open("/store/downloadDemo","Download","directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=100,height=100");
//        mywindow.moveTo(0,0);
//        e.stopPropagation();
//        return false;
//    });
    
    if($("#tabs").length > 0){
        $("#tabs").tabs({
            event: 'mouseover'
        });
    }

    if($("#accordion").length > 0){
        $("#accordion").accordion({
            autoHeight: false,
            collapsible: true,
            header: 'dt'
        });
    }

    if($("#accordeonHomepage").length > 0){
        accordeon($("#discover .visible"), $(".visible"), 749, 96);
    }
    
	/*$("#slider").easySlider({
		auto:       true,
		continuous: true,
        prevText:   '<span>Previous</span>',
        nextText:   '<span>Next</span>',
        pause:      3000
	});*/
    /*$("#sliderScreenshot").jcarousel({
	wrap:   "both",
        scroll: 1
    });*/

    /*$("#carouselSoftwareImages").easySlider({
		auto:       true,
		continuous: true,
        vertical:   true,
        controlsShow: false,
        pause:      3000
	});*/
    $("#carouselSoftwareImages").jcarousel({
	vertical:   true,
        scroll:     1,
        auto:       4,
        wrap:       "both",
        itemVisibleInCallback:  {onBeforeAnimation: carouselSoftMenuOn},
        itemVisibleOutCallback: {onBeforeAnimation: carouselSoftMenuOff},
        initCallback:   carouselSoftInit,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    $(".lightbox").colorbox();
    $(".mediaobject a").colorbox();
    $(".videobox").colorbox({
        fixedWidth:     800,
        fixedHeight:    502
    });

    $(".qtipMap").each(function(){
        $(this).qtip({
            content: '<img src="' + $(this).attr('href') + '"/>',
            style: {
              background: '#1e8300',
              border: {color: '#1e8300', radius: 2, width: 2},
              tip: 'bottomMiddle',
              width: 67
            },
            position: {corner: {target: 'topMiddle', tooltip:'bottomMiddle'}}
        });
        $(this).click(function(e){
            e.stopPropagation();
            return false;
        });
    });

    $("#statisticalDisplay div").each(function(){
        $(this).qtip({
            content: $(this).children('p').eq(0).html(),
            style: { 
              background: '#e0f6d9',
              border: {color: '#1e8300', radius: 2, width: 2},
              tip: 'bottomMiddle',
              width: 300
            },
            position: {corner: {target: 'topMiddle', tooltip:'bottomMiddle'}}
        });
    });

    $(".downloadMapsDesc").each(function(){
        $(this).qtip({
            content: $(this).children('div').eq(0).html(),
            style: {
              background: '#e0f6d9',
              border: {color: '#1e8300', radius: 2, width: 2},
              tip: 'leftMiddle',
              width: 200
            },
            position: {corner: {target: 'rightMiddle', tooltip:'leftMiddle'}}
        });
    });

    // Page "purchase"
    $("#step1 input[type=submit]").hide();
    //$("#step1 tfoot tr").eq(0).hide();
    $("#cartItems tbody .quantity input[type=text]").keyup(function(elem){
        var pricesByItem = $('#cartItems td.total');
        var totalInvoice = $('#totalPrice');
        var discount     = $('#couponValue span').attr('rel');

        var bool = updItemTotal($(elem.target).parent().prev().attr('rel'), $(elem.target), $(elem.target).parent().next() );
        var change = updTotalCart(pricesByItem, totalInvoice, discount);
        if(change)
        {
            if($("#couponCart input[type=text]").attr('value') != "optional")
            {
                var bool2 = $("#couponCart a").eq(0).click();
            }
            totalInvoice.effect("highlight", {'color': '#cce6c5'}, 1000);
            replaceStoreAction();
        }
    });
    $("#couponCart input[type=text]").keypress(function(e){
        if(e.which == 13){$("#couponCart a").click();e.stopPropagation();return false;}
    });
    if($("#step1").length == 1){replaceStoreAction();}

/*    if(!$("#login").hasClass("logged") || $("#step1 form").length == 0){$("#step3").fadeTo("fast", 0.33);} */
    $("#step3 form").submit(function(){
        if($("#login").hasClass("logged") && $("#step1 form").length == 0) {
            return true;
        }
        else {
            return false;
        }
    });

    $("#multilicenses").dialog({
        bgiframe: true,
        resizable: false,
        height: 250,
        width: 400,
        modal: true,
        autoOpen: false,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.8
        },
        buttons: {
            'OK': function() {
                 $(this).dialog('close');
            }
        }
    });

    $('#quantityInfo').click(function(e){
        $("#multilicenses").dialog('open');
    });

    $('#purchaseyouritems, #paysecurelynowlink').click(function(e){
        $('#paysecurelynow').click();
    });
});
