// Use $('#myDiv').shop({varone: '333'});
//$(function(){
Drupal.behaviors.DiVAShopBehavior = {
    attach: function (context, settings) {
    
/*___________________________________________________________________________ VARS & INIT
    */
   
   $.AppliancesData = [];
   $.AppliancesCartData = [];
   $.AppliancesCartObfuscatedData = [];
   $.Appliances = [];
   $.Appliances.Cart = [];
   $.PriceData = {month:{cpu:0.0, memory:0.0, disk:0.0},burst:{cpu:0.0, memory:0.0, disk:0.0}};
   $.PriceMonthData = 0.0;
   $.PriceMonthHourData = 0.0;
   $.PriceHourData = 0.0;
   $.Price = [];


$.shop = function(options) {
    
  var defaults = {
    varone: '321',
    vartwo: '322'
  };
  var opts = $.extend(defaults, options);
  
  
  
   
   /*
    * Events on cart, update price, init sliders
    */
   
   this.Init = function() {

      // Is there a configuration already ?
      if ($._GET("cpu")){
          $("#shopping-div", $(this)).LoadingImage();
          var names = $._GET("app").split(',');
          var name;
          $('body').data('appliances', []);
          for (name in names){
              $('body').data('appliances').push(names[name]);
          }
          $.each(["cpu", "memory", "disk"],
               function(key, val){
                   $('body').data('cart'+val, $._GET(val));
               });
        //$('body').data('carttraffic', $._GET('traffic'));
          $('body').data('cartburst', $._GET("burst"));
          $('body').data('cartduration', $._GET("duration"));
        $.MyPost({
          url : "index.php",
          data:{
            act: "userForm"
          },
          success: $.ShowUserLogin
        });
      }
      else{
        
        //console.log("DIVA > SHOP INIT (cart, sliders, prices)");
        
        function changeInput( event ) {
          if (!$.isUnsignedInteger($(this).val()))
            $(this).val($($(this).attr('name')).slider("option", "min"));
          else if ($(this).val() > $($(this).attr('name')).slider("option", "max"))
            $(this).val($($(this).attr('name')).slider("option", "max"));
          else if ($(this).val() < $($(this).attr('name')).slider("option", "min"))
            $(this).val($($(this).attr('name')).slider("option", "min"));
          $($(this).attr('name')).slider("value", $(this).val());
          if ($("#price").length >0){
              $.Price.update();
              if ($(".shopping-div-service").length == 0 && $(".shopping-div-cloud").length == 0)
                  $.Appliances.Cart.checkRequirements();
              else if ($(".shopping-div-cloud").length > 0)
                  $.Appliances.Cart.checkRequirementsForCloud();
          }
        }

        var options = {
          range: "min",
          value: 500,
          min: 0,
          max: 20000,
          slide: function(event, ui) {
            $("#"+$(this).attr('id')+"-data").val(ui.value);
            $("#"+$(this).attr('id')+"-data").change();
          }
        };

        $("#slider-cpu").slider($.extend(options,{min: 500}));
        $("#slider-cpu-data")
          .val($("#slider-cpu").slider("value"))
          .attr('name', "#slider-cpu")
          .change(changeInput);

        $("#slider-memory").slider($.extend(options,{value: 256, max: 16384, min: 256}));
        $("#slider-memory-data")
          .val($("#slider-memory").slider("value"))
          .attr('name', "#slider-memory")
          .change(changeInput);

        $("#slider-disk").slider($.extend(options,{value: 2, max: 1000, min: 2}));
        $("#slider-disk-data")
          .val($("#slider-disk").slider("value"))
          .attr('name', "#slider-disk")
          .change(changeInput);

            if ($("#price").length >0){
                $("#subscribe-cloud-per-hour").change($.Price.update);
                $("#subscribe-cloud-per-month").change($.Price.update);
                $("#subscribe-month").change($.Price.update);
                $("#subscribe-hour").change($.Price.update);
            }

        // Check radio on click <TR>
        function onClickTR(event){
          if (event.target.type !== 'radio') {
            $(":radio", this).click();
            $(":radio", this).change();
          }
        }
        $("#subscribe-month-tr").click(onClickTR);
        $("#subscribe-hour-tr").click(onClickTR);

        // Buy & Deploy (add buttons and call price webservice)
        $("#confirm-cart-button").button().click(
          function(){

            //console.log("DIVA > Deploy");

            $(this).LoadingImage();

            $('body').data('appliances', []);
            $("#shopping-cart-content ul.gallery > span > div > h2").each(
              function(index) {
                var item = $.Appliances.find($(this).attr('class'));
                // if it's a standard app
                if( typeof(item.apps) == 'undefined' ){
                    $('body').data('appliances').push($(this).attr('class'));
                }
                // if it's a package, add each apps
                else{
                    $.each(item.apps,
                       function(){
                           $('body').data('appliances').push(this);
                       }
                    );
                }
                
                
              });
            $.each(["cpu", "memory", "disk"],
                   function(key, val){
                     $('body').data('cart'+val,
                                    $("#slider-"+val+"-data").val());
                   });
            $('body').data('cartburst', $("#subscribe-hour").attr("checked")?true:false);
            $('body').data('cartduration',
                           ($("#subscribe-hour").attr("checked")?
                            $("#subscribe-cloud-per-hour").val():
                            $("#subscribe-cloud-per-month").val()));
            $.ValidateCart();

        });


        // Retreive Price infos
        //if ($("#price").length >0){
        
            //console.log("DIVA > Retreive PRICES");
        
            var url = "/query.php";
            $.MyPost({url:url, data:{act:"price"},
                        dataType: "json",
                        success: function(data) {
                            $.PriceData = data;
                            $.each(["cpu", "memory", "disk"],
                               function(key, val){
                                   if ($("#slider-"+val+"-data").attr('origin'))
                                       $("#slider-"+val+"-data").val($("#slider-"+val+"-data").attr('origin')).change();
                               });
                            $.Price.update();
                    }
                });
        //}


        $.ValidateCart = function() {
          $(location).attr('href', 'https://shop.diva-cloud.com/?cpu='+$('body').data('cartcpu')+"&memory="+$('body').data('cartmemory')+"&disk="+ $('body').data('cartdisk')+"&burst="+$('body').data('cartburst')+"&duration="+$('body').data('cartduration')+/*"&traffic="+$('body').data('carttraffic')+*/"&app="+$('body').data('appliances'));
        };

        // Events on cart items (live : reloaded)
        $(".shop_item a, .gallery span a").live("click",
            function( event ) {

            var $item = $(this);
            var $target = $(event.target);

            if ($target.is("a.ui-icon-circle-plus")) {
              $.AddItem( $item );
              $("#cart_popup").slideDown("fast");
            } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
              //console.log("DIVA > Zoom item");
              $.ViewItem( $target );
            } else if ( $target.is( "a.ui-icon-circle-close" ) ) {
              //console.log("DIVA > Remove item");
              $.RemoveItem( $item );
            }else{
              //console.log("DIVA > Other click");
            }
            return false;
            });

        }

   }
   
   this.LoadApps = function() {
       
      // retreive appliances array on document ready (isotope catalogue)
      $.MyPost({url: "/query.php",
              data:{act:"list"},
              dataType: "json",
                error: function(data) {
                  //console.log("DIVA > Appliances failed retreived (query)");
                },
                success: function(data) {

                    var i;
                    var reg = new RegExp("([/.* &;{}\\[\\]])", "g");
                    
                    if(!data) console.log("[DIVA SHOP] BUG loadApps, AppliancesData : ",data);
                    
                    $.AppliancesData = data;

                    $.each(data, function(key, val) {
                        if (val.obfuscated == 0 && $.Appliances.Cart.inArray(val.name) === false) {
                           var	typeId = val.type.replace(reg, "_");
                           var	nameId = val.name.replace(reg, "_");

                           //Create the Wizard
                           $("#td-wizard-"+val.name).Wizard();
                        }
                    });

                    //$("body").data("state","ready");
                    //console.log("DIVA > LOAD APPS");
                }
        });  
   }
   
   
   /*___________________________________________________________________________ Appliance find & inArray & addObfuscated
    */


     // Search for an appliance object
     $.Appliances.find = function(toFind) {
         
         
         
         
         //console.trace();
         //console.log("    Trying to find",toFind,"in",$.AppliancesData);
         
         //if(typeof(toFind) == "undefined") alert("an app is undefined");
         
         
         
       var result = $.grep($.AppliancesData,
	 function(value) {
	   return value.intname == toFind;
	 });
       if (result.length > 0)
	 return result[0];
       return false;
     };
     
     // Find an appliance in current cart
     $.Appliances.Cart.inArray = function(toFind){
	var l = $.AppliancesCartData.length;
	for(var i = 0; i < l; i++) {
	    if($.AppliancesCartData[i] == toFind) {
		return true;
	    }
	}
	return false;
     };
     
     // Add an obfuscated appliance to the cart
     $.Appliances.Cart.addObfuscated = function(toAdd){
       var	app;


       // if is an app, and has dependencies
       if (toAdd.hasOwnProperty("depends")) {
	 $.each(toAdd.depends,
		function(key, val){
                  //console.log("DIVA > APP DETECTED");
                  // Test if already in cart
		  if ($.inArray(val, $.AppliancesCartObfuscatedData) == -1) {
		    app = $.Appliances.find(val);
                    
		    $.AppliancesCartObfuscatedData.push(val);
		    $.each(["cpu", "memory", "disk"/*, "traffic"*/],
			   function(key, val){
			     $("#slider-"+val+"-data")
			       .val(parseInt($("#slider-"+val+"-data").val())
				    + parseInt(app[val]));
			     $("#slider-"+val+"-data").change();
			   });
		  }
		});
       }
     };
     
     // Check minimum requirements
     $.Appliances.Cart.checkRequirements = function(){
         //console.log("DIVA > Shop > CHECK requirement");
	 var values = {cpu:0,memory:0,disk:0};
	 $.each($.AppliancesCartData,
		function(key,val){
		    $.each(["cpu", "memory", "disk"/*, "traffic"*/],
			   function(k, v){
			       var app = $.Appliances.find(val);

			       values[v] += parseInt(app[v]);
			       //Add wizard answer
			       if (app.questions)
				   $.each(app.questions,
				      function(key,val){
					  $.each(val.answers,
						 function(key,val){
						     if (val.check === true)
							 values[v] += parseInt(val[v]);
						 });
				      });
			   });
		});
	 $.each($.AppliancesCartObfuscatedData,
		function(key,val){
		    $.each(["cpu", "memory", "disk"/*, "traffic"*/],
			   function(k, v){
			       values[v] += parseInt($.Appliances.find(val)[v]);
			   });
		});
	 $.each(["cpu", "memory", "disk"/*, "traffic"*/],
		function(key,val){
		    if ($("#slider-"+val+"-data").val() < values[val])
			$("#slider-"+val+" .ui-slider-range").css('background', '#C42424');
		    else
			$("#slider-"+val+" .ui-slider-range").css('background', '#13B313');
		});
	 return values;
     },
     
     
     // Add an appliance to the cart
     $.Appliances.Cart.add = function(toAdd){
       if(toAdd.hasOwnProperty("depends")){  
           //console.log("DIVA > add App",toAdd);
           $.AppliancesCartData.push(toAdd.intname);
           if ($(".shopping-div-service").length == 0){
               $.Appliances.Cart.addObfuscated(toAdd);
           }
           if ($(".shopping-div-service").length == 0){
           //Adjust sliders
             $.each(["cpu", "memory", "disk"/*, "traffic"*/],
                  function(key, val){
                    $("#slider-"+val+"-data")
                      .val(parseInt($("#slider-"+val+"-data").val())
                           + parseInt(toAdd[val]));
                    $("#slider-"+val+"-data").change();
                  });
           }
       }
       // if it's a pack
       else if (toAdd.hasOwnProperty("apps")) {
         //console.log("DIVA > add pack",toAdd);
         $.each(toAdd.apps,
                function(key, val){
                   //console.log("DIVA > PACK DETECTED > ",val,$.Appliances.find(val));
                   $.Appliances.Cart.add($.Appliances.find(val));
                });
       }

     },
     
     // Remove an appliance from the cart
     $.Appliances.Cart.remove = function(toRemove){
       //console.log("DIVA > removeAppliance",toRemove);
       var	app;

       if ($(".shopping-div-service").length == 0){
       //Remove appliance
       $.each(["cpu", "memory", "disk"/*, "traffic"*/],
	      function(key, val){
		$("#slider-"+val+"-data")
		  .val(parseInt($("#slider-"+val+"-data").val())
		       - parseInt(toRemove[val]));
		$("#slider-"+val+"-data").change();
	     });
       }
       $.AppliancesCartData = $.ArrayRemove($.AppliancesCartData, toRemove.intname);
       if ($(".shopping-div-service").length == 0){
       //Remove old dependencies
       $.each($.AppliancesCartObfuscatedData,
         function(key, val){
		  app = $.Appliances.find(val);
		  $.each(["cpu", "memory", "disk"/*, "traffic"*/],
			 function(key, val){
			   $("#slider-"+val+"-data")
			     .val(parseInt($("#slider-"+val+"-data").val())
				  - parseInt(app[val]));
			   $("#slider-"+val+"-data").change();
			 });
	 });
       $.AppliancesCartObfuscatedData = [];
       //Recreate dependencies
       $.each($.AppliancesCartData,
         function(key, val){
	   $.Appliances.Cart.addObfuscated($.Appliances.find(val));
	 });
       }
     };
  
  
  
      /*___________________________________________________________________________ ASY FUNCTION
    */
   
     $.MyPost = function(options) {
         jQuery.ajax($.extend(
                     {
                       url: "/query.php",
                       type: "POST",
                       dataType: (jQuery.isEmptyObject(options.dataType) ? "html" : options.dataType),
                       error:function(xhr, textStatus, thrownError){
                           if (xhr.responseText.indexOf('<meta http-equiv="refresh" content="1; url=index.php" />') != -1)
                             window.location.href = "index.php";
                           if (this.data.indexOf("act=bug_report") == -1)
                             $.MyPost({
                               data:{
                                 act: "bug_report",
                                 data: this.data,
                                 url: this.url,
                                 type: this.type,
                                 textStatus: textStatus,
                                 thrownError: thrownError,
                                 status: xhr.status,
                                 response: xhr.responseText
                               }
                             });
                         }
                       }, options));
       };
   
   /*___________________________________________________________________________ Plugin functions
    */
   
    //Add an appliance on cart
    $.AddItem = function($item) {
        
          // show deploy button
          $("#confirm-cart-button").show();
          $('html, body').animate({ scrollTop: 0 }, 'slow');
          
          //var currentApp = $.Appliances.find($item.text());
          var currentApp = $.Appliances.find($("h2",$item.siblings(".cart_info1")).attr("class"));
          
          if(!currentApp){
              ////console.log($("h2",$item.siblings(".cart_info1")).attr("class"));
              console.log("/! DIVA > no app found in json reference");
          }
          
        
	  var $list = $("ul", $("#shopping-cart-content")).length ?
			$("ul", $("#shopping-cart-content")) :
			$("<ul class='gallery ui-helper-reset'/>")
			  .appendTo($("#shopping-cart-content"));

	  //Change icon 'delete'
	  //$($item).append("<a href='#' title='Remove this item' class='ui-icon ui-icon-circle-close'>Remove</a>");
          
          //Add to cart list (html)
	  $list.append($item.parent().parent().html());
          
          if (currentApp.hasOwnProperty("questions"))
              $.each(currentApp.questions,
                     function(key, val){
                         if (val.hasOwnProperty("answers"))
                             $("#"+currentApp.name+key+"0").click();
                     });
                     
          //Remove empty message & resize div (scroll)
          $("#shopping-cart-content span.empty").remove();
          $("#shopping-cart-content").css("height","258px");
          
          //Add appliance to cart (if it's not a pack)
          $.Appliances.Cart.add(currentApp);
          
          //Update Price
          if ($("#price").length >0 && $(".shopping-div-service").length == 0){
              $.Price.update();
          }


    };
    
   // Remove item from shopping cart
    $.RemoveItem = function($item) {

      //var currentApp = $.Appliances.find($item.attr('name'));
      var currentApp = $.Appliances.find($("h2",$item.siblings(".cart_info1")).attr("class"));
      //console.log("DIVA > removeItem",currentApp);
      
      if(!currentApp){
          //alert("BUG ! no app founded !");
      }
      
      // remove from cart (html)
      $item.parent("span").remove();
            
      //Remove appliance to cart
      $.Appliances.Cart.remove(currentApp);
      
      //Update price
      if ($("#price").length >0 && $(".shopping-div-service").length == 0){
          $.Price.update();
      }
          
    };
    
   /*___________________________________________________________________________ PRICES update
    */
    
    $.Price.update = function() {
        
      var durationHour = parseInt($("#subscribe-cloud-per-hour").val());
      var durationMonth = parseInt($("#subscribe-cloud-per-month").val());
      var duration = 0;

      if ($("#subscribe-month").attr("checked")) {
	duration = 30*24*durationMonth;
      } else {
	duration = durationHour;
      }

      //Show price per hour for a monthly subscription
      $.PriceMonthHourData =
	($("#slider-cpu-data").val()*$.PriceData.month.cpu/1000/30/24*100
	     +$("#slider-memory-data").val()*$.PriceData.month.memory/1024/30/24*100
	     +$("#slider-disk-data").val()*$.PriceData.month.disk/30/24*100
	 /*+$("#slider-traffic-data").val()*$.PriceData.month.traffic/30/24*100*/)/100;


      //Get price per month for a monthly subscription
      $.PriceMonthData =
	($("#slider-cpu-data").val()*$.PriceData.month.cpu/1000*100
	     +$("#slider-memory-data").val()*$.PriceData.month.memory/1024*100
	     +$("#slider-disk-data").val()*$.PriceData.month.disk*100
	 /*+$("#slider-traffic-data").val()*$.PriceData.month.traffic*100*/)/100;

      //Show price per hour for an hourly subscription
      $.PriceHourData = ($("#slider-cpu-data").val()*$.PriceData.burst.cpu/1000*100
	    +$("#slider-memory-data").val()*$.PriceData.burst.memory/1024*100
	    +$("#slider-disk-data").val()*$.PriceData.burst.disk*100
			 /*+$("#slider-traffic-data").val()*$.PriceData.burst.traffic/duration*100*/)/100;
      if ($.PriceHourData < 0.04)
	 $.PriceHourData = 0.04;

      var total = 0.0;  
      
      if ($("#subscribe-month").attr("checked")) {
	  $("#table-td-gb_month .gb_month").show();
	  $("#table-td-gb_month .gb").hide();
	  $("#subscribe-month-tr").addClass("selected");
	  $("#subscribe-hour-tr").removeClass("selected");
	  $.PriceMonthData =
	      ($("#slider-cpu-data").val()*$.PriceData.month.cpu/1000*durationMonth*100
	       +$("#slider-memory-data").val()*$.PriceData.month.memory/1024*durationMonth*100
	       +$("#slider-disk-data").val()*$.PriceData.month.disk*durationMonth*100
	       /*+$("#slider-traffic-data").val()*$.PriceData.month.traffic*durationMonth*100*/)/100;
	  total += parseInt($.PriceMonthData);

	  //Add prices services * duration
	  $.each($.AppliancesCartData,
		 function(key, val) {
		     total += parseInt($.Appliances.find(val).price) * durationMonth;
		 });
	  //Add prices services obfuscated * duration
	  $.each($.AppliancesCartObfuscatedData,
		 function(key, val) {
		     total += parseInt($.Appliances.find(val).price) * durationMonth;
		 });  

	  $("#price-cloud-per-hour").html((total*2/durationMonth/30/24).toFixed(2));
	  $("#price-cloud-per-month-per-hour").html((total/durationMonth/30/24).toFixed(2));

	  $("#price-total-burst").parent().hide();
	  $("#price-total").html(total.toFixed(2));
	  $("#price-total").parent().show();
          
      }
      else {

	  $("#table-td-gb_month .gb_month").hide();
	  $("#table-td-gb_month .gb").show();
	  $("#subscribe-month-tr").removeClass("selected");
	  $("#subscribe-hour-tr").addClass("selected");
	  $.PriceMonthData = 0.0;


	  //Show price per hour for an hourly subscription
	  $.PriceHourData = ($("#slider-cpu-data").val()*$.PriceData.burst.cpu/1000 * durationHour*100
			     +$("#slider-memory-data").val()*$.PriceData.burst.memory/1024 * durationHour*100
			     +$("#slider-disk-data").val()*$.PriceData.burst.disk * durationHour*100
			     /*+$("#slider-traffic-data").val()*$.PriceData.burst.traffic*100*/)/100;
	  if ($.PriceHourData < 0.04)
	      $.PriceHourData = 0.04;


          //console.log("    DIVASHOP > updatePrice HOURS : ",$.PriceHourData,$("#slider-cpu-data").val(),$.PriceData.burst.cpu);
          

	  total += $.PriceHourData;

	  //Add prices services * duration
	  $.each($.AppliancesCartData,
		 function(key, val) {
		     total += parseInt($.Appliances.find(val).priceBurst) * durationHour;
		     $.PriceMonthHourData += $.Appliances.find(val).price/30/24;
		 });
	  //Add prices services obfuscated * duration
	  $.each($.AppliancesCartObfuscatedData,
		 function(key, val) {
		     total += parseInt($.Appliances.find(val).priceBurst) * durationHour;
		     $.PriceMonthHourData += $.Appliances.find(val).price/30/24;
		 });
	  $("#price-total").parent().hide();
	  $("#price-cloud-per-hour").html((total/durationHour).toFixed(2));
	  $("#price-cloud-per-month-per-hour").html($.PriceMonthHourData.toFixed(2));

	  $("#price-total-burst").html(total.toFixed(2));
	  $("#price-total-burst").parent().show();
      }
      
      //console.log($("#subscribe-month").attr("checked")?"month":"hour",$.PriceHourData,$.PriceMonthData,$.PriceData.month.cpu,total);
   };
    
    
    
   /*___________________________________________________________________________ MY
    */ 
    
    
   $.fn.LoadingImage = function(options) {
     //$(this).html("<center><img src=\"https://data.diva-cloud.com/common/img/loading.gif\" /></center>");
     //console.log("DIVASHOP > loading....");
   };
   
   $._GET = function(name) {
     name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
     var regexS = "[\\?&]"+name+"=([^&#]*)";
     var regex = new RegExp(regexS);
     var results = regex.exec(window.location.href);
     if (results == null)
       return "";
     else
       return results[1];
   };
     
     
   /*___________________________________________________________________________ SERVSTORE
    */    
     
     
   $.isUnsignedInteger = function(s) {
     return (s.toString().search(/^[0-9]+$/) == 0);
   };
  
   $.ArrayRemove = function(arr, toRemove){
      for(var i = 0; i < arr.length; i++){
           if(arr[i] == toRemove){
               arr.splice(i, 1);
               break;
           }
       }
       return arr;
       
   };
  
  


  
};


}}
//});
