var uniquAjaxRequestSender = "";

function ajax_execute_post(ajax_send_url, form, feedback_div, extrapost_data) {
    core_login_auth_infos = $(form).serialize()+"&return_cmd_div="+feedback_div+extrapost_data;
    $("body").css("cursor", "progress");
    if(uniquAjaxRequestSender == core_login_auth_infos+ajax_send_url) {
        alert("Requete en cours de traitement");
        return false;
    } 
    uniquAjaxRequestSender = core_login_auth_infos+ajax_send_url; 
     
     $.ajax({
      type: "POST",
      url: ajax_send_url,
      data: core_login_auth_infos,
      success: function(ajax_returned_data) {
          var init_uniquid = UUID.generate();
          $("#commander_master_website").append('<div id="commander_master_website_child_'+init_uniquid+'">'+ajax_returned_data+'</div>');
          $('#commander_master_website_child_'+init_uniquid).html('<script type="text/javascript"> $("#commander_master_website_child_'+init_uniquid+'").remove();</script>');
      },
      error: function(ajax_error_data) {
           alert("Le traitement de la requète a échoué");
      },
      timeout: 20000
     });
     $("body").css("cursor", "auto");
     uniquAjaxRequestSender = "";
     return false;  
}

function ajaxHref(new_req) {
    var server_lang = jQuery("html").attr('lang');
    
    //détection du début de l'url cible.
    var str_split = new_req.split("/");
    if(str_split[1].length == 2) {
        //Lang in url
        new_req = "/" + server_lang + new_req.substr(3);
    } else {
        //No lang in url
        new_req = "/" + server_lang + new_req;
    }
    window.location.href=new_req;
    return false;
    
    $.ajax({
      type: "GET",
      url: new_req,
      success: function(ajax_returned_data) {
        $("#main_dynamic_webpage").html(ajax_returned_data);
        history.pushState({ path: this.path }, '', new_req);
        hookHrefReload();
      },
      error: function(ajax_error_data) {
           alert("Le traitement de la requète a échoué");
      },
      headers : {"X-STREAMTUBE-partialcontent": "true"},
      timeout: 20000
     });
     return false;
}
var isLogoNeagativeModEnabled = false;
function manualShowHide(isMenuShow, disable_effect) {
    createCookie("menu_showhide", isMenuShow);
    if(disable_effect == true) var effect_timer = 1; else var effect_timer = 400;
    if(isMenuShow == false) { //On masque le menu
        if(isLogoNeagativeModEnabled) {
            jQuery('#header-logo-image').attr('src', '/ressources/png/logo_lara_white.png');
        }
        
        $(".menu-navigatorcontainer").slideUp(effect_timer, function() {
            $("#headmenu-showhide-button-hide").hide();
            $("#headmenu-showhide-button-show").show();
            //$(".menu-navigatorcontainer").hide(); //Affichage de la bare avec les liens
            $(".headmenu-bottombigline").hide();
            //$("#headmenu-maincontainer").css("position", "absolute"); //On remet la div dans le dom
            //$("#headmenu-maincontainer").show(); //On masque le menu 
            $("#headmenu-maincontainer").css("background-color", "none");
            
        });
        $('.homesplash-picture').animate({ 'marginTop': '0'}, effect_timer);
        $('.homesplash-video').animate({ 'marginTop': '0'}, effect_timer);
        
    } else { //On affiche le menu
        if(isLogoNeagativeModEnabled) {
            //Si le mode négatif est activé, on switch
            jQuery('#header-logo-image').attr('src', '/ressources/png/logo_lara.png');
        }
        
        //$("#headmenu-maincontainer").hide(); //On masque le menu 
        //$(".menu-navigatorcontainer").show(); //Affichage de la bare avec les liens
        
        //$("#headmenu-maincontainer").css("position", "static"); //On remet la div dans le dom
        $(".menu-navigatorcontainer").slideDown(effect_timer, function() {
            $("#headmenu-showhide-button-hide").show();
            $("#headmenu-showhide-button-show").hide();
            $(".headmenu-bottombigline").show();
            //$(".homesplash-picture").css("margin-top", '150px');
        });
        $('.homesplash-picture').animate({ 'marginTop': '150px' }, effect_timer);
        $('.homesplash-video').animate({ 'marginTop': '150px' }, effect_timer);
        $("#headmenu-maincontainer").css("background-color", "#ffffff");
    }
    return true;
}

function switchToNegativeColor(want_negative) {
    if(want_negative) {
        //Set logo to white
        jQuery('#headmenu-showhide-button-show').css('color', '#ffffff');
        jQuery('#headmenu-showhide-button-show img').attr('src', '/ressources/png/icon_menu_barres_white.png');
        jQuery('#header-logo-image').attr('src', '/ressources/png/logo_lara_white.png');
        isLogoNeagativeModEnabled = true;
    } else {
        //set logo to black
        jQuery('#headmenu-showhide-button-show').css('color', '#000000');
        jQuery('#headmenu-showhide-button-show img').attr('src', '/ressources/png/icon_menu_barres.png');
        jQuery('#header-logo-image').attr('src', '/ressources/png/logo_lara.png');
        isLogoNeagativeModEnabled = false;
    }
    
}
function menuShowHide(disable_effect) {
    var isMenuShow = ($(".menu-navigatorcontainer").css("display") != "none");
    manualShowHide(!isMenuShow);
    return false;
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function autoAddLangToUrl() {
    if(window.location.pathname == "/") {
        //Si on est sur la racine > ajout de la langue en JS
        var server_lang = jQuery("html").attr('lang');
        history.pushState({ path: this.path }, '', '/' + server_lang + '/');
    }
}

function buttonStatut(dst_id, btn_statut) {
    jQuery(dst_id).addClass(btn_statut);
    setTimeout(function() {
        jQuery(dst_id).removeClass(btn_statut);
    }, 1500);
}

var Hook = {
  hooks: [],
 
  register: function ( name, callback ) {
    if( 'undefined' == typeof( Hook.hooks[name] ) )
      Hook.hooks[name] = []
    Hook.hooks[name].push( callback )
  },
 
  call: function ( name, arguments ) {
    if( 'undefined' != typeof( Hook.hooks[name] ) )
        for( i = 0; i < Hook.hooks[name].length; ++i ) {
            console.log(Hook.hooks[name]);
            if(typeof(Hook.hooks[name][i]) != "undefined") {
                if( true != Hook.hooks[name][i]( arguments ) ) { 
                }
                delete Hook.hooks[name][i];
            }
        }
        
  }
}

function switchBlogEditorLang(lang_prefix) {
    jQuery(".article_lang_main_container").hide();
    jQuery("#article_lang_container_"+lang_prefix).show();
    jQuery(".article_editor_lngmenu_global").removeClass('active');
    jQuery("#article_editor_lngmenu_"+lang_prefix).addClass('active');
}


function hookHrefReload() {
    //Gestion du menu 
    //var menuState = readCookie("menu_showhide");
    //manualShowHide((menuState == "true"), true);
    Hook.call( 'jsready', [ 'All Done' ] );
    autoAddLangToUrl(); //Ajoute automatiquement la langue sur l'url
    
}

/**
 * Gestion de la partie youtube
 * @param {type} youtube_link
 * @returns {getYoutubeId.qs|Array|String}
 */
function getYoutubeId(youtube_link) {
    var key = "v";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(youtube_link);
    if(qs == null) return "";
    return qs[1];
}

/**
 * Gestion de la grille
 */

var picturesGridSystem = {
    calcSize: function() {
        /**
         * Redétecte les proportions
         */
        var containerWidth = jQuery('#gallery_main_container').width();
        this.lastWidth = containerWidth; //On stock la denrière taille
        this.wUnit = Math.round(containerWidth / WEBSITE_GRIDSTACK_WIDTH);
        
        console.log('WUNIT: '+this.wUnit + 'fwidth: ' + containerWidth);
        
   
    },rebuild: function() {
        /**
         * Fixe la hauteur de la grille sur base de la largeur
         */
        
        var gridstackmanager = $('.grid-stack').data('gridstack');
        var weight = this.wUnit;
        if(this.wUnit * WEBSITE_GRIDSTACK_WIDTH < 700) {
            weight = weight * 2;
        }
        gridstackmanager.cell_height(weight);
        
    }, init: function() {
        this.calcSize();
        this.rebuild();
        self = this;
        jQuery(window).resize(function() {
            if(jQuery('#gallery_main_container').width() != self.lastWidth) {
                self.calcSize();
                self.rebuild();
            }
            
           
        });
       
    }, 
    wUnit: null,
    lastWidth: null,
    unitMultiplicator: null,
    hUnit: null,
    saveGalleryCoords: function(gallery_id) {
         var res = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
            el = $(el);
            var node = el.data('_gridstack_node');
            return {
                id: el.attr('data-custom-id'),
                x: node.x,
                y: node.y,
                width: node.width,
                height: node.height
            };
        });
        xajax_xj_aSavGrPos(gallery_id, JSON.stringify(res));
    },
    galleryInit: function(gallery_id) {
        self = this;
        $('.grid-stack').on('change', function (e, items) {
            self.saveGalleryCoords(gallery_id);
        });
    },
    saveGalleryGroupsCoords: function() {
         var res = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
            el = $(el);
            var node = el.data('_gridstack_node');
            return {
                id: el.attr('data-custom-id'),
                x: node.x,
                y: node.y,
                width: node.width,
                height: node.height
            };
        });
        xajax_xj_aSavGrGalleriesPos(JSON.stringify(res));
    },
    galleryGroupsInit: function() {
        self = this;
        $('.grid-stack').on('change', function (e, items) {
            self.saveGalleryGroupsCoords();
        });
    }
    //xj_aSavGrGalleriesPos
    
}



function strrev(string) {
  //       discuss at: http://phpjs.org/functions/strrev/
  //      original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //      bugfixed by: Onno Marsman
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //        example 1: strrev('Kevin van Zonneveld');
  //        returns 1: 'dlevennoZ nav niveK'
  //        example 2: strrev('a\u0301haB') === 'Baha\u0301'; // combining
  //        returns 2: true
  //        example 3: strrev('A\uD87E\uDC04Z') === 'Z\uD87E\uDC04A'; // surrogates
  //        returns 3: true

  string = string + '';

  // Performance will be enhanced with the next two lines of code commented
  //      out if you don't care about combining characters
  // Keep Unicode combining characters together with the character preceding
  //      them and which they are modifying (as in PHP 6)
  // See http://unicode.org/reports/tr44/#Property_Table (Me+Mn)
  // We also add the low surrogate range at the beginning here so it will be
  //      maintained with its preceding high surrogate
  var grapheme_extend =
    /(.)([\uDC00-\uDFFF\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065E\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C82\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D02\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F90-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B6-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAA\u1C24-\u1C37\u1DC0-\u1DE6\u1DFE\u1DFF\u20D0-\u20F0\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA67C\uA67D\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA926-\uA92D\uA947-\uA953\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uFB1E\uFE00-\uFE0F\uFE20-\uFE26]+)/g;
  string = string.replace(grapheme_extend, '$2$1'); // Temporarily reverse
  return string.split('')
    .reverse()
    .join('');
}

function gGroupSetDateFromTimestamp(curr_timestamp) {
    if(curr_timestamp <1) {
        jQuery('#gpubtime').val('');
        return false;
    }
    var d = new Date(curr_timestamp*1000);
    var output_date = d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes();
    jQuery('#gpubtime').val(output_date);
    return false;
}

$(document).ready(function() {
    //Activation du master commander div
    hookHrefReload();         
    $("body").append('<div id="commander_master_website"></div>');
   
});


