Drupal.behaviors.DiVABehavior = {
    attach: function (context, settings) {
//$(function(){

    // Declare Common functions

   /*$.diva_maintenance_page = function() {
  
    var pathname = window.location.pathname;
    if(pathname == "maintenance" || $("body").hasClass("maintenance-page")){
        
        $('.cloud_mask').css("opacity",0.07);
        $('.cloud_mask_1').css("opacity",0.05);
        $('.cloud_mask').animate({
            opacity: 0.05,
            left: '-=350'
        }, 15000, function() {});
        $('.cloud_mask_1').animate({
            opacity: 0.02,
            left: '+=350'
        }, 18000, function() {});

    }
   }*/
    
    $.diva_reload_event = function(){
        
        console.log(window.location.hash);
        
        
        // Menu
        $.menuEvent();
        // Isotope
        $.isotopeInsert();
        //Cycle script
        $.slideShow();
        // Banner
        if(window.location.hash == "/" || window.location.hash == "/home") $.showBanner();
        // Page offre
        $.showOffers();
        // Uniform
        $("select, input:checkbox, input:radio:not(.subscribe-type), input:file, input:text, input:submit, textarea").not(".page-node-edit input, .admin-se input, .admin-se select, .more").uniform();

        // ServStore
        //if($("body").find("#shopping-div")) $("#shopping-div").ServStore();
        
        // tipsy remove (hack)
        $(".tipsy").remove();
        
        // Asy nav (launched more than once, in content)
        //console.log("[COMMON] > Asylink : create asy live event - on links in the content (reloaded)");
        $("a.asy").diva_asyLinks();
        $("#header-menu-inside a").diva_asyLinks();

    }
    
    /*
     * Asylinks : add event on links
     */
    $.fn.diva_asyLinks = function() {
        $(this).click(function(){
            var url = $(this).attr("href");
            if(url.indexOf("#") != -1) return false;
            // anchor is placed, wait for setInterval to change page
            $(this).attr("href", "#"+url);
        });
    }
    
    /*
     * Asyload : event on links when clicked
     */
    $.fn.diva_asyLoad = function(page) {
        

        //var page = $(this).attr("href");
        
        jQuery('html, body').animate({scrollTop:0}, 800);
        var mask = $("<div id='load_mask'></div>").hide();
        var loader = $("<div id='load'><span class='title' >Chargement...</span><br /><img width=80 height=10 src='/sites/all/themes/divatheme/images/load.gif'/></div>").hide();
        jQuery("body").append(loader, mask);
        mask.css({opacity: "0.3", filter : "alpha(opacity=30)"});
        mask.fadeIn("fast");
        loader.fadeIn("fast");
        
         jQuery("#content-inside").animate({
            opacity: 0.5,
            left: '-=2050'
            }, 500, function() {

                // reload content & menu
                $.get(page, function(data) {

                  // hide content
                  $("#content").css({opacity: "0", filter : "alpha(opacity=0)"});
                  
                  // cart radio val
                  var month_checked = $("#subscribe-month").attr("checked") == "checked"?true:false;
                  
                  // reload content & menu (weird bug : it uncheck the cart radios)
                  $('#content').html($('#content-inside',data));
                  $('#header-menu-inside').html($('#header-menu-inside',data).html());
                  
                  // recheck radios
                  if(month_checked) $("#subscribe-month").attr("checked","checked");
                  else $("#subscribe-hour").attr("checked","checked");
                  
                  // place content
                  $("#content-inside").css({opacity: "1", filter : "alpha(opacity=100)", left:"2050px"});
                  $("#content").css({opacity: "1", filter : "alpha(opacity=100)"});
                  
                  // animate content
                  jQuery("#content-inside").animate({
                        opacity: 1,
                        left: '0'
                    }, 500, function() {});
                  
                  // remove loader
                  $("#load_mask, #load").delay(800).fadeOut("fast").remove();
                  
                  // launch javascript
                  $.diva_reload_event();
                  
                  // set ready state
                  $("#content-inside").data("state","ready");
                  
                });

            });
            
            
        return false;
    } 

    $.isotopeInsert = function(){
        // Isotope start
        //console.log("[COMMON] > Launch Isotope catalogue");
        
        $('#container_isotope').isotope({
          itemSelector : '.item',
          //resizable : true,
          //layoutMode : 'masonryHorizontal' // need height on container
          layoutMode : 'fitRows'
        });
        


        // Isotope menu
        $('#isotop_form').change(function(){
            var iso_type = "";
            var num = 0;
            $('#isotop_form input:checked').each(function(){
                if(num == 0) iso_type += "." + $(this).val().toLowerCase();
                //else iso_type += ", ." + $(this).val().toLowerCase();
                else iso_type += "." + $(this).val().toLowerCase();
                num += 1;
            });
            
            //$('#container_isotope').isotope({filter: iso_type});
            $('#container_isotope').isotope({filter: iso_type}); /*,{animationOptions: {duration: 750,easing: 'linear',queue: true}}*/
        });
    }
    
    $.slideShow = function(){
        //$('#slideshow').off('cycle');
        $("#slideshow").cycle({
            fx: "scrollHorz",
            speed: "slow",
            timeout: "10000",
            pager: "#slider-navigation",
            pagerAnchorBuilder: function(idx, slide) {
                // specific software page
                if($(".side_image").length > 0){
                    return  ".side_image img:eq(" + (idx) + ")";
                }
                // other pages
                else return "#slider-navigation li:eq(" + (idx) + ") a";
            },
            after: function(curr, next, opts, fwd){
                var $ht = $(this).height();
                $(this).parent().animate({height: $ht});
                if($(".side_image").length > 0){
                    $(".side_image img").siblings("p").css("color","#ccc");
                    $(".side_image img:eq(" + (opts.currSlide) + ")").siblings("p").css("color","#1487D4");
                    //$('.side_image img').eq(opts.currSlide).tipsy("show");
                }
            }
        });
    }
    
    $.showBanner = function(){
        $("#banner").show();
        $("#banner_inside").delay(3000).slideDown("slow", function(){
            //console.log("[COMMON] > Banner ready");
        });
        $(".close_popup").click(function(){
            $("#banner_inside").slideUp("fast");
        });
    }
    $.showOffers = function(){
        
        $(".encart").each(function(){
            $(this).attr("ori-width", $(this).width());
            $(this).click(function(){
                 if($(this).hasClass("closed")){
                    $(this).animate({
                            width: 687
                        }, 
                        {
                        duration: 800, 
                        specialEasing: {width: 'easeOutQuint',height: 'easeOutQuint'}, 
                        complete: function() {  $(this).removeClass("closed"); $('#node-25').isotope( 'reLayout' ); 
                        }
                    });
                }else{
                    $(this).animate({
                            width: parseInt($(this).attr("ori-width"))
                        }, 
                        {
                        duration: 800, 
                        specialEasing: {width: 'easeOutQuint',height: 'easeOutQuint'}, 
                        complete: function() {  $(this).addClass("closed"); $('#node-25').isotope( 'reLayout' ); 
                        }
                    });
                }
            });
        });
        /*
         $(".encart .more").each(function(){
            var encart = $(this).parent(".encart");
            encart.attr("ori-width", encart.width());
                console.log($(this),encart);
            encart.click(function(){
                if(encart.hasClass("closed")){
                    encart.animate({
                        width: parseInt(encart.attr("ori-width"))
                    }, 300, function() { encart.removeClass("closed"); $('#node-25').isotope( 'reLayout' ); });
                }else{
                    encart.animate({
                        width: 720
                    }, 300, function() { encart.addClass("closed"); $('#node-25').isotope( 'reLayout' ); });
                }
            });
        });*/

        $(".encart").css("width","320px");
        $(".encart").addClass("closed");
        
        $('#node-25').isotope({
          itemSelector : '.encart',
          /*cellsByRow: {
            columnWidth: 300
          }*/
          //masonry : {columnWidth : 330}
          layoutMode : 'fitRows'
        });
    }
    
    $.menuEvent = function(){
        $("li.expanded").hover(
            function(){
                var li = $(this);
                if(li.hasClass('on')) return;
                else $(this).children("div").slideDown("fast", function(){ li.addClass('on'); });
            },
            function(){
                var li = $(this);
                if(li.hasClass('on')) $(this).children("div").slideUp("fast", function(){ li.removeClass('on'); });
                else $(this).children("div").delay(1000).slideUp("fast", function(){ li.removeClass('on'); });
            }
        );
    }  
    
 
 
    // INIT
    
    
    // test
    /*$("#container_isotope .item").click(
    function(){
        
        if(!$(this).hasClass("open")){
            $(this).addClass("open");
            
            // item & child
            $(this).css({"height":"380px","width":"460px"});
            $(this).children("div").css({"height":"360px","width":"440px"});
            //
            $(this).children(".mask-move").css({"height":"360px","width":"440px"});
            $(this).children(".start").css({"height":"360px","width":"440px"});
            
            //$(this).css({"height":"560px","width":"675px"});
            //$(this).children("div").css({"height":"540px","width":"642px"});
            //$(this).css({"height":"190px","width":"675px"});
            //$(this).children("div").css({"height":"180px","width":"642px"});
            $('#container_isotope').isotope( 'reLayout' );
        }else{
            $(this).removeClass("open");
            
            $(this).css({"height":"190px","width":"225px"});
            $(this).children("div").css({"height":"180px","width":"214px"});
            $('#container_isotope').isotope( 'reLayout' );
        }
    });*/
    
    
    
    /*
     *   Events on Cloud menu (once : not-reloaded)
     */
    $("#cart").click(function(){
      $("#cart_popup").slideToggle("fast","swing");
    });

    $(".close_popup_cart").click(function(){
      $("#cart_popup").slideUp("fast");
    });
 
 
    /*
     *  Ajax listener
     */
    var shop = new $.shop();
    
    console.log("[COMMON] > Asy listener launched");
    
    // first, debug chromium timout
    setTimeout(function() {console.log("timeout debug chrome");},300);
    
    var recentHash = "";
    setInterval(function() {
         var curl = window.location.hash;
         var surl = curl.toString();
         // last link
         var srecentHash = recentHash.toString();
         //console.log("[COMMON] > Waiting for a clic ....");
         // if the current page has different href, and anchor given, (not #- > real anchor)
         if(surl.substr(-6, 6) != srecentHash.substr(-6, 6) && surl != "" && surl.indexOf("#-") == -1){
             //console.log('[COMMON] : Detect page update ',surl,srecentHash, surl.indexOf("#-"), srecentHash.substr(-6, 6), surl.substr(-6, 6));
             srecentHash = surl;
             var nreg = new RegExp("(#)", "g");
             var mgo = srecentHash.replace(nreg,"");
             //load new page
             $(this).diva_asyLoad(mgo);
             // set new recentHash after reload
             recentHash = surl;
             //console.log(surl, mgo);
             // check if new page is SHOP && content is loaded
             if(surl == "#/softwares"){
                //console.log("[COMMON] > detect soft page");
                var catalog_state = setInterval(function() {
                    //console.log("[COMMON] > wait for catalog to load");
                    if($("#content-inside").data("state") == "ready"){
                        shop.LoadApps();
                        clearInterval(catalog_state);
                        //console.log("[COMMON] > delete interval, catalog ready");
                    }
                },300);
              }
        }

     }, 350);
    
    
    var pathname = window.location.pathname;
    var purl = pathname.toString();
    if(purl == "/softwares"){
        console.log("[COMMON] > Launch catalogue (not asy)");
        shop.LoadApps();
    }
    
    
     /*
     *  Shop Init (cart)
     */
    console.log("[COMMON] > Shop Init (load cart event)");
    shop.Init();
    
    
    // konami
    console.log("[COMMON] > Konami launched");
    if ( window.addEventListener ) {
        var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
        window.addEventListener("keydown", function(e){
                kkeys.push( e.keyCode );
                if ( kkeys.toString().indexOf( konami ) >= 0 ){
                    window.location = "http://konamicodesites.com";
		}
        }, true);
    }
    
    /*
     * Start Diva Maintenance page JS
     */
    ////console.log("[COMMON] > Mainenance page (init)");
    //$.diva_maintenance_page();
    
    /*
     * Reload events
     */
    console.log("[COMMON] > Reload JS events (init)");
    $.diva_reload_event();
    
    /*
     * Tips  
     *   ex : nw | n | ne | w | e | sw | s | se / tipsy({title: function() { return this.getAttribute('original-title').toUpperCase(); } }) / tipsy({live: true,title: 'href',fade: true,gravity: $.fn.tipsy.autoNS})
     */
    console.log("[COMMON] > Tipsy live init");
    $('.qm, .q, a.more, #content-inside a,.side_image img').tipsy({delayIn: 100,live: true,title: 'title',opacity: 0.92,gravity: $.fn.tipsy.autoNS});
    //$('.side_image img').tipsy({trigger:'manual',delayIn: 100,live: true,title: 'title',opacity: 0.92,gravity: $.fn.tipsy.autoNS});
    $('.q-right').tipsy({delayIn: 300,delayOut: 200,live: true,title: 'title',opacity: 0.92,gravity: 'w'});
    $('#sec-menu a').tipsy({delayIn: 200,live: true,title: 'title',opacity: 0.92,gravity: 'n'});
    $('.menu a, .tips').tipsy({delayIn: 200,fade: true,live: true,title: 'title',opacity: 0.92,gravity: 's'});
    $('.feedback').tipsy({live: true,delayIn: 200,title:function() {return '<img src="/sites/all/themes/divatheme/images/contact.png" /><br />\n\<div style="text-align:center;width:200px;font-size:13px;">\n\Un commentaire ? Un message à nous faire passer ? N\'hésitez pas à nous contacter !</div>'; },html:true,opacity: 0.92,gravity: 'w',fade: true});
    $('.encart > .content-info > img').tipsy({live: true,delayIn: 200,title:function() { return $('.tip',$(this).parents(".encart")).html(); },html:true,opacity: 0.92,gravity: $.fn.tipsy.autoNS,fade: true});

    /*
     * Labelify init
     */
    console.log("[COMMON] > Labelify init");
    $("input:text, textarea").not(".admin-se input, .admin-se textarea").labelify({ text: "label" });
    
    /*
     * Asynchronous nav init
     */
    //console.log("[COMMON] > Asylink : create asy live event - Just once (those menus do not reload)");
    //$("#site-name a").diva_asyLinks();
    
    
    /*
     * Lightbox
     */
    //console.log("[COMMON] > lightbox");
    //$('#header-inside-left a').lightBox({fixedNavigation:true});
    
    
    
    
    
    /* edito manager */
    //$("#node-22 .field-item > p > img").hide();
    /*var i=0;
    $("#node-22 .field-item > p > img").each(function(){
        if(i>0){
            $(this).after("<div class='ex'><div class='ex-title'><b>"+$(this).attr("alt")+"</b></div><img width=22 height=22 src='/sites/all/themes/divatheme/images/find.png' /></div>");
            $(this).fadeTo('slow', 0.2);
            $(this).hover(function(){
                $(this).stop().fadeTo('slow', 1);
                $(this).siblings(".ex").stop().fadeTo('slow', 0.2);
            },
            function(){
                $(this).stop().fadeTo('slow', 0.2);
                $(this).siblings(".ex").stop().fadeTo('slow', 1);
            }
            );
        }
        i++;
    });*/
    
    
    

//};

}
}
