function checkStageHasProduct($item){
  if($item.parent().attr('id')=='td1'){
    return true;
  }
  return false;
}

function addMsgBox(msg){
  $("#td2").append("<div class='msg'>"+msg+"</div>");
}

function addSpacer(height){
  $("#td2").append("<div style='height: "+height+"px;clear:both'></div>");
}
/*
function addBrandSelect(options){
    var sel;
    sel = "<select name='brand' id='brand'  onchange='getCategories()'>";
    sel+="<option value=''>- Seleziona -</option>";
    for(i=0; i<options.length; i++){
        sel+="<option value='"+options[i]['id']+"'>"+options[i]['name']+"</option>";
    }
    sel+="</select>";

    $("#td2").append(sel);
}

function addCategorySelect(options){
    var sel;
    sel = "<select name='category' id='category'  onchange='getProducts()'>";
    sel+="<option value=''>- Tutte le categorie -</option>";
    for(i=0; i<options.length; i++){
        sel+="<option value='"+options[i]['id']+"'>"+options[i]['name']+"</option>";
    }
    sel+="</select>";

    $("#td2").append(sel);
}*/

function setBrandBoxNo(no){
  document.brandboxes = no;
}

function getBrandBoxNo(){
  return document.brandboxes;
}

function setProductBoxNo(no){
  document.boxes = no;
}

function getProductBoxNo(){
  return document.boxes;
}


function addProductToStage($origitem) {
  log("addProductToStage"+$origitem.attr("id"));
  //the product is already on the stage
  if(checkStageHasProduct($origitem)){
    return;
  }

  var $item=$origitem.clone();
  $origitem.remove();

  //add prod to stage
  $item.fadeOut(function() {
    
    //find prod id
    var prodid = $item.find('.prodid').attr('innerHTML');
    //get and load big image
    $.ajax({
      type: "POST",
      url: "actions.php",
      dataType: "json",
      data: "action_type=MM_GETPRODIMAGE&img=img1&id="+prodid,
      cache: false,
      success: function(response){
        if(!response['error']){
          var $img=$item.find('img');
          $img.attr('src',response['img']);
          $img.attr('width',response['sx']);
          $img.attr('height',response['sy']);
        }
      }
    });
    //calcola top
    var top="-"+$(".staged").length*255+"px";
    //change div id so it doesn't get removed together with the products on the right
    var new_name="stager"+prodid;
    $item.attr("id",new_name)
    .attr("name",new_name)
    .css({
      "top":top,
      "left":0
    })
    .addClass('staged')
    .click(function(){
      stagerClicked($item)
    })
    .dblclick(function(){
      stagerUnselect($(this))
    })
    .resizable({
      aspectRatio: true,
      alsoResize: $item.find(".prodimg"),
      maxWidth: 300,
      maxHeight: 300,
      minWidth: 100,
      minHeight: 100,
      handles :"se"
    })
    .draggable({//make draggable
      containment: '#td1',
      revert: false
    })
    .appendTo("#td1")
    .fadeIn('slow')
    .find(".ui-resizable-se").css("display","none");

     
    
    
  //add element to container
  /* $("#td1")
    .append($item)
    .fadeIn('slow');*/

   

   
  });
}

function addProductToStage_alt($item) {
  //the product is already on the stage
  if(checkStageHasProduct($item)){
    return;
  }

  
  var prodid = $item.find('.prodid').attr('innerHTML');
  
  //get and load big image
  $.ajax({
    type: "POST",
    url: "actions.php",
    dataType: "json",
    data: "action_type=MM_GETPRODIMAGE&img=img1&id="+prodid,
    cache: false,
    success: function(response){
      if(!response['error']){
        var image_src=response['img'];
        var image_width=response['sx'];
        var image_height=response['sy'];
        
        $item.remove();
  
        var $stager = $("<div id='stager1' class='loading'></div>");
        loadProductImage("stager1", image_src);

        $stager.resizable({
          aspectRatio: true,
          //alsoResize: $item.find(".prodimg"),
          maxWidth: 300,
          maxHeight: 300,
          minWidth: 100,
          minHeight: 100,
          handles :"se"
        });
        $stager.draggable({
          containment: '#td1',
          revert: false
        });

        $("#td1").append($stager);
      }
    }
  });
  
}


function removeProductBoxes(){
  for(i=0;i<getProductBoxNo();i++){
    $("#prod"+i).remove();
  }
}

function removeBrandBoxes(){
  $(".brand-box").remove();
  $(".brand-spacer").remove();
}


function loadProductImage(box, src) {
  var img = new Image();
  $(img).attr('src', src+"#"+Math.random());
  //log("loading: "+src)
  $(img).load( function () {
    //log("  +++ loaded "+src)
    $('#'+box).append(this);
    $('#'+box).removeClass("loading");
    $(this).addClass("prodimg");
  }).error(function () {
    //log("ERROR LOADING: "+src)
    });
}

function getBrandBoxName(brand){
  return "bn_"+brand;
}

function addBrandBoxes(options){
  var cur_brand='';
  var bb_name='';
  setBrandBoxNo(options.length);

  for(var i=0; i<options.length; i++){
    if(cur_brand!=options[i]['brand_name']){
      cur_brand=options[i]['brand_name'];
      bb_name=getBrandBoxName(options[i]['brand_id']);
      $("#products","#td2").append("<div id='"+bb_name+"' class='brand-box'><div class='brand-name'><img src='upload_area/mmbrands/0/"+options[i]['brand_logo']+"'></div></div><div class='brand-spacer'></div>");
    }
  }

}

function addProductBoxes(options){
  var name;
  var brand_box;

  setProductBoxNo(options.length);

  for(i=0;i<options.length;i++){
    name="prod"+i;
    brand_box=getBrandBoxName(options[i]['brand_id']);
    $("#"+brand_box).append("<div id='"+name+"' class='draggable ui-widget-content loading'><div class='prodid'>"+options[i]['id']+"</div></div>");
    $("#"+name).draggable({
      containment: '#containment-wrapper',
      scroll: false,
      revert: 'invalid',
      cursor: 'move'
    });
  }
}

function addProductSelect(options){
  var no=options.length;
  var box, src;

  //remove help text
  $("#helper3").hide();

  //clear old product boxes
  removeProductBoxes();

  //clear old brand boxes
  removeBrandBoxes();

  //create brands boxes
  addBrandBoxes(options);

  //add prods boxes
  addProductBoxes(options);

  //load product images
  for(i=0;i<no;i++){
    box="prod"+i;
    src="/preview/upload_area/mmproducts/0/"+options[i]['img0'];
    loadProductImage(box, src);
  }

  //make pane scroll
  $("#products").jScrollPane({
    showArrows:true
  });
}

//caricamento dei prod  su uno stage salvato*/
function loadProductsOnStage(products){
  var no=products.length, $item, box;

  for(i=0;i<no;i++){
    box = "stager"+i;
    $("#td1").append("<div id='"+box+"' name='"+box+"'><div class='prodid'>"+products[i]['product_id']+"</div></div>");
    $item=$("#"+box);

    //load prod img
    var img = new Image();
    $(img).attr("src", products[i]['img1']);
    $(img).attr("width", products[i]['width']);
    $(img).attr("height", products[i]['height']);
    $item.append(img);

    //postion prod on stage
    $item.css("position","absolute");
    $item.css("left",products[i]['left']+"px");
    $item.css("top",products[i]['top']+"px");
    $item.css("z-index",products[i]['zindex']);

  }
}



function getBrands(){
  var collection = $("#collection").val();
  if(collection==''){
    return false;
  }

  $.ajax({
    type: "POST",
    url: "actions.php",
    dataType: "json",
    data: "action_type=MM_GETBRANDS&collection="+collection,
    cache: false,
    success: function(response){
      if(response['error']){
        $("#error").attr('innerHTML',response['error_msg']);
        $("#error").show("slow");
      }else{
        $("#error").hide();
        if(response.length>0){
          addMsgBox('Seleziona il brand');
          addBrandSelect(response);
        }

      }
    }
  }) ;
}

function getCategories(){
  var brand = $("#brand").val();
  var collection = $("#collection").val();
  if(brand=='' || collection==''){
    return false;
  }

  $.ajax({
    type: "POST",
    url: "actions.php",
    dataType: "json",
    data: "action_type=MM_GETCATEGORIES&brand="+brand+"&collection="+collection,
    cache: false,
    success: function(response){
      if(response['error']){
        $("#error").attr('innerHTML',response['error_msg']);
        $("#error").show("slow");
      }else{
        $("#error").hide();
        if(response.length>0){
          addMsgBox('Seleziona la categoria');
          addCategorySelect(response);
        }

      }
    }
  }) ;
}

function showCategoryDirectSelect(){
  $("#jScrollPaneContainer").hide();
  $("#directselect").show();
  $("#helper3").show();
}

function selectCategory(id){
  $("#category").val(id);
  $("#directselect").hide();
  $("#jScrollPaneContainer").show();

  getProducts();
}

function getProducts(){
  var category = $("#category").val();
  $("#directselect").hide();
  $("#jScrollPaneContainer").show();

  if(category==0){
    return false;
  }
  if(category==-1){
    showCategoryDirectSelect();
    return true;
  }

  $.ajax({
    type: "POST",
    url: "actions.php",
    dataType: "json",
    data: "action_type=MM_GETPRODUCTS&category="+category,
    cache: false,
    success: function(response){
      if(response['error']){
        $("#error").attr('innerHTML',response['error_msg']);
        $("#error").show("slow");
      }else{
        $("#error").hide();
        if(response.length>0){
          addProductSelect(response);
        }
      }
    }
  }) ;
}

function log(txt){
//$("#logger").append(txt+"<BR>");
}

function stagerRemove(id){
  $("#"+id).remove();
}

function stagerBringToFront(id){
  $(".staged-selected").removeClass("zindex1");
  $(".staged").removeClass("zindex1");
  $("#"+id).addClass("zindex1");
}

function stagerDeselectAll(){
  log("stagerDeselectAll");
  $(".staged-selected").each(function(){
    stagerUnselect($(this))
  })
}

function stagerSelect($item){
  var id =$item.attr("id");
  log("stagerSelect"+$item.attr("id"));
  $item.addClass("staged-selected");
  $item.find(".ui-resizable-se").css("display","block");

  var $buttons=$("<div class='staged-buttons' id='staged-buttons'></div>");
  $item.append($buttons);

  var $deselect_link=$("<a href='javascript:void(0)' title='Deseleziona' id='deselect'><img src='images/maya2/stage_remove.png' align='absmiddle' border='0'></a>");
  $deselect_link.click(function(){
    stagerDeselectAll();
  });
  var $delete_link=$("<a href='javascript:void(0)' title='Rimuovi' id='remove'><img src='images/maya2/stage_remove.png' align='absmiddle' border='0'></a>");
  $delete_link.click(function(){
    stagerRemove(id);
  });
  var $front_link=$("<a href='javascript:void(0)' title='Porta in primo piano' id='bringfront'><img src='images/maya2/stage_pp.png' align='absmiddle' border='0' ></a>");
  $front_link.click(function(){
    stagerBringToFront(id);
  });
  
 
  //$buttons.append($deselect_link);
  $buttons.append($delete_link);
  $buttons.append($front_link);
  
  
}

function stagerUnselect($item){
  log("stagerUnselect"+$item.attr("id"));
  $item.removeClass("staged-selected");
  $item.find("#staged-buttons").remove();
  $item.find(".ui-resizable-se").css("display","none");
}



function stagerClicked($item){
  log("stager clicked");
  /*var show = $item.hasClass("staged-selected");
  if(show){//hide
    stagerUnselect($item);
  }else{//show
    stagerDeselectAll();
    stagerSelect($item);
  }*/

  stagerDeselectAll();
  stagerSelect($item);
}

function td1RelativePos($item){
  var $td1= $("#td1")
    

  return ({
    left: ($item.offset().left-$td1.offset().left),
    top: ($item.offset().top-$td1.offset().top)
  });

}

function saveStage(){
  var blob='',
  i=0,
  id,
  left,
  top,
  width,
  zindex,
  pos;

  $("#td1").find(".staged").each(function(){
    pos = td1RelativePos($(this));
    id=$(this).find('.prodid').text();
    left=pos.left;
    top=pos.top;
    width=$(this).find(".prodimg").attr("width");
    height=$(this).find(".prodimg").attr("height");
    zindex=$(this).css("z-index");
    blob+="&id["+i+"]="+id+"&left["+i+"]="+left+"&top["+i+"]="+top+"&width["+i+"]="+width+"&height["+i+"]="+height+"&zindex["+i+"]="+zindex;
    i++;
  });
  //log(blob);
  $.ajax({
    type: "POST",
    url: "actions.php",
    dataType: "json",
    data: "action_type=MM_SAVESTAGE"+blob,
    cache: false,
    success: function(response){
      $("#error-msg2").hide();
      if(response['error']){
        if(response['error_msg']=='NOTLOGGEDIN'){
          $("#boxlogin").show('slow');
        }
        if(response['error_msg']=='NOPRODONSTAGE'){
          $("#error-msg2").text('ERRORE: nessun prodotto sullo stage!');
          $("#error-msg2").show('slow');
        }
        if(response['error_msg']=='SAVEERROR'){
          $("#error-msg2").text('ERRORE: errore database!');
          $("#error-msg2").show('slow');
        }
      }else{
        $("#boxlogin").hide();
        $("#ok-msg2").text('Il tuo set è stato salvato correttamente!');
        $("#ok-msg2").show('slow');
      }
    }
  });
}

//after login operations
var handler=true;
var handler_function="saveStage()";