/**
 * Utility javascript functions
 */

//====================================== Domain & URL ======================================//

/**
 * Get current domain name.
 */
function getDomain() {
    return (window.location.href.match(/:\/\/(.[^/]+)/)[1]).replace('www.','');
}

/**
 * Set cookie
 * @param name Cookie name
 * @param value Cookie Value
 * @param expiredays Number of days this cookie expires
 */
function setCookie(name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + ";domain=." + getDomain() + ";path=/" + (expiredays == null ? "" : ";expires=" + exdate.toUTCString());
}

/**
 * Get cookie value
 * @param name Cookie name
 */
function getCookie(name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

//====================================== Formatting ======================================//

/**
 * Is a valid email address.
 * @return bool
 */
function isEmail(str) {
    return /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)(\.)+([a-zA-Z0-9]{2,4})+$/.test(str);
}

/**
 * Is a valid URL.
 * @return bool
 */
function isURL(str) {
    return /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/.test(str);
}

/**
 * Format decimal number to French number.
 * @example "1250.75" to "1 250,75"
 * @param number Decimal number
 * @return string French number
 */
function format_french_number(number) {

    number += '';
    var x = number.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ' ' + '$2');
    }
    var with_space = x1 + x2;

    return with_space.replace(".", ",");
}

//====================================== Various Functions ======================================//

/**
 * Show bookmark/favorite dialog.
 * @param url Absolute URL
 * @param title Title
 */
function bookmark(url, title) {
    // IE
    if (document.all) {
        window.external.AddFavorite(url, title);
    }
    // Firefox
    else if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    }
}

/**
 * Trim all text inputs and texareas in specified form.
 * @param form Form DOM Element, Form jQuery Object or Form ID
 */
function trimForm(form) {

    if (form instanceof HTMLFormElement || form instanceof jQuery) {
        form = jQuery(form)
    }
    else {
        form = jQuery("#" + form);
    }

    // trim all fields
    form.find(":text,textarea").each(function(index, domElement) {
        jQuery(this).val(jQuery.trim(jQuery(this).val()));
    });
}

function back(){
    history.back();
}

function submit(id){
    $('#'+id).submit();
}

function isNull(str){
  if(str == '' || str == ' ' || str == null || str == undefined ){
    return true;
  }else{
    return false ;
  }
}

function addValue(id){
    var or = $("#"+id);
    var num = or.val()-1;
    or.val(num+2);
    updateTotalPrice(id);
}

function minusValue(id){
    var or = $("#"+id);
    var num = or.val()-1;
    if(num<1){
        alert('La quantité doit être supérieure à 1.');
    }else{        
        or.val(num);
    }
    updateTotalPrice(id);
}

function updateTotalPrice(id){
    //update product price
    var quan = $("#"+id);
    var price = parseFloat($("#price"+id).html());
    quan = parseInt(quan.val());
    //alert('quab->'+(quan)+' price->'+price +'All '+ (quan*price));
    $("#hidden"+id).html((quan*price).toFixed(2));
    $("#total"+id).html(format_french_number((quan*price).toFixed(2)));
    updateAllPrice();
}

function updateAllPrice(){
    var sumPrice = 0;
    $(".price span:first-child").map(function () {
        sumPrice += (parseFloat(this.innerHTML));
    });
    
    var tva = (sumPrice/19.60).toFixed(2);//
    var price = (sumPrice - tva).toFixed(2);
    var sumPriceTran = (sumPrice + 7).toFixed(2);
    $("#total").html(format_french_number(price));
    $("#tva").html(format_french_number(tva));
    $("#ttc").html(format_french_number(sumPrice.toFixed(2)));
    $("#totalAll").html(format_french_number(sumPriceTran));
    
}
function delProductCart(id){    
    $("#"+id).remove();
    updateAllPrice();
}

function alertObj(obj){
    var output = '';
    for (property in obj) {
        output += property + ': ' + obj[property]+';\n ';
    }
    alert(output);
}

function gotoURL(url){
  if(url != '' && url != null){
    window.open(url, '_blank'); return false;
  }else{
    return false;
  }  
}

