/******************************* Custom function to easy control **************************/
function _blockUI(message) {
  //return; //hide couse Nancy don't like it
  if (!message) 
    message = "Updating your lab...";
  if (typeof($.blockUI) == 'function') {
    $.blockUI({ css: {
      border: 'none',
      padding: '15px',
      backgroundColor: '#fff',
      '-webkit-border-radius': '10px',
      '-moz-border-radius': '10px',
      opacity: .5,
      color: '#0F6079'
    }
    , message: "<div class='lab_title'>" + message + " <br/>Please be patient...</div>"
    }); 
    //Updating your lab... Please be patient.
    $('.blockOverlay').click(function(event) {
      _unblockUI();
    });

  }
}

function _unblockUI() {
  //return;
  if (typeof($.unblockUI) == 'function') {
    $.unblockUI();
  }
}


function showside(id) {
    if($('#haveside'+id).attr('checked')) {
        $('#customside'+id).attr('class', 'sidedisplay');
    }
    else {
        $('#customside'+id).attr('class', 'sidehided');
    }
}

function showside(id, attr) {
    if($('#haveside'+id+'_'+attr).attr('checked')) {
        $('#customside'+id+'_'+attr).attr('class', 'sidedisplay');
    }
    else {
        $('#customside'+id+'_'+attr).attr('class', 'sidehided');
    }
}


function savecustom() {
	div = $('#imprintarea_image1');
	div_of = div.offset();

    $('#imprint_top_1').val(div.css("top"));
	$('#imprint_left_1').val(div.css("left"));
	$('#imprint_width_1').val(div.css("width"));
	$('#imprint_height_1').val(div.css("height")); 

    if($('#haveside2').attr('checked')) {
        div = $('#imprintarea_image2');
        $('#imprint_top_2').val(div.css("top"));
        $('#imprint_left_2').val(div.css("left"));
        $('#imprint_width_2').val(div.css("width"));
        $('#imprint_height_2').val(div.css("height")); 
    }

    $('#customization_name').submit();
}


function savecustom_fromedit(imprintarray) {
    for(i=0; i<imprintarray.length; i++) {
        imp = imprintarray[i];
        div = $('#imprintarea_image1_' + imp);
        div_of = div.offset();

        $('#imprint_top_1_' + imp).val(div.css("top"));
        $('#imprint_left_1_' + imp).val(div.css("left"));
        $('#imprint_width_1_' + imp).val(div.css("width"));
        $('#imprint_height_1_' + imp).val(div.css("height")); 

        if($('#haveside2' + imp).attr('checked')) {
            div = $('#imprintarea_image2_' + imp);
            $('#imprint_top_2_' + imp).val(div.css("top"));
            $('#imprint_left_2_' + imp).val(div.css("left"));
            $('#imprint_width_2_' + imp).val(div.css("width"));
            $('#imprint_height_2_' + imp).val(div.css("height")); 
        }
    }
    $('#new_option_value_custom').submit();
}

function loadside(filename, side, imagewidth, imageheight) {
    $('#table_part_image_' + side).css('display', '');
    $('#side_image_' + side).css('background-image', 'url('+ filename +'?rand='+Math.random()+')');
    $('#side_image_' + side).css('width', imagewidth+'px');
    $('#side_image_' + side).css('height', imageheight+'px');
    $('#image_width_' + side).val(imagewidth);
    $('#image_height_' + side).val(imageheight);
    $('#imprint_filename_' + side).val(filename);
    $('#imprintarea_image' + side).resizable({ 
        handles: 'all',
        autoHide: true, 
        //aspectRatio: 'preserve',
        minHeight: 10, 
        minWidth: 10,
        containment: $('#side_image_' + side)
    });
    $("#imprintarea_image" + side).draggable({containment: '#side_image_' + side});
}

function loadside(filename, side, attr, imagewidth, imageheight) {
    $('#table_part_image_' + side + '_' + attr).css('display', '');
    $('#side_image_' + side + '_' + attr).css('background-image', 'url('+ filename +'?rand='+Math.random()+')');
    $('#side_image_' + side + '_' + attr).css('width', imagewidth+'px');
    $('#side_image_' + side + '_' + attr).css('height', imageheight+'px');
    $('#image_width_' + side + '_' + attr).val(imagewidth);
    $('#image_height_' + side + '_' + attr).val(imageheight);
    $('#imprint_filename_' + side + '_' + attr).val(filename);
    $('#imprintarea_image' + side + '_' + attr).resizable({ 
        handles: 'all',
        autoHide: true,
        //aspectRatio: 'preserve',
        minHeight: 10, 
        minWidth: 10,
        containment: $('#side_image_' + side + '_' + attr)
    });
    $("#imprintarea_image" + side + '_' + attr).draggable({containment: '#side_image_' + side + '_' + attr});
}

function loadside_edit2(filename, side, attr, left, top, width, height, imagewidth, imageheight) {
    $(window).attr('parent').$('#table_part_image_' + side+ '_' + attr).css('display', '');
    $('#side_image_' + side+ '_' + attr).css('background-image', 'url('+ filename +'?rand='+Math.random()+')');
    $('#side_image_' + side+ '_' + attr).css('width', imagewidth+'px');
    $('#side_image_' + side+ '_' + attr).css('height', imageheight+'px');
    //$('#imprint_filename_' + side).val(filename);

    $('#imprintarea_image' + side+ '_' + attr).resizable({ 
        handles: 'all',
        autoHide: true, 
        //aspectRatio: 'preserve',
        aspectRatio: false,
        minHeight: 10, 
        minWidth: 10,
        containment: $(window).attr('parent').$('#side_image_' + side+ '_' + attr)
    });
    $("#imprintarea_image" + side+ '_' + attr).draggable({containment: '#side_image_' + side+ '_' + attr});
    $('#imprintarea_image' + side+ '_' + attr).css('left',left+'px');
    $('#imprintarea_image' + side+ '_' + attr).css('top',top+'px');
    $('#imprintarea_image' + side+ '_' + attr).css('width',width+'px');
    $('#imprintarea_image' + side+ '_' + attr).css('height',height+'px');
}

function loadside_edit(filename, side, left, top, width, height, imagewidth, imageheight) {
    $(window).attr('parent').$('#table_part_image_' + side).css('display', '');
    $('#side_image_' + side).css('background-image', 'url('+ filename +')');
    $('#side_image_' + side).css('width', imagewidth+'px');
    $('#side_image_' + side).css('height', imageheight+'px');
    //$('#imprint_filename_' + side).val(filename);

    $('#imprintarea_image' + side).resizable({ 
        handles: 'all',
        autoHide: true, 
        minHeight: 10, 
        minWidth: 10,
        containment: $(window).attr('parent').$('#side_image_' + side)
    });
    $("#imprintarea_image" + side).draggable({containment: '#side_image_' + side});
    $('#imprintarea_image' + side).css('left',left+'px');
    $('#imprintarea_image' + side).css('top',top+'px');
    $('#imprintarea_image' + side).css('width',width+'px');
    $('#imprintarea_image' + side).css('height',height+'px');
}


function AddArt(params) {
      fid = params.fid;
      filename = params.filename;
      path = params.path;
      width = params.width;
      height = params.height;
      colors = params.colors;
      rotate = params.rotate;
      transparent_color = params.transparent_color;
      side = $('#sideidvalue').val();
      $("#"+side+"_imprintarea").append("<div id='"+ fid +"' style=\"margin: 0; top: 0px; height:"+height+"px; width: "+width+"px; position:absolute; background: none;\"><img src='"+ path + "result_" + filename + "' width='100%' height='100%'></div>");

    $('#' + fid).resizable({ 
        autoHide: true,
  		  minHeight: 10, 
        minWidth: 10,
        aspectRatio: 'preserve',
        containment: $('#'+side+'_imprintarea')
		});

    $('#' + fid).draggable({containment: '#'+side+'_imprintarea'});
    $('#' + fid).click(function () { ShowEditPanel($(this).attr('id')); });
    AddToCustom(fid, {  fid:fid,
                        width: width+'px', 
                        height: height+'px', 
                        top:'0px',
                        left:'0px', 
                        rotate:rotate, 
                        colors:colors,
                        transparent_color:transparent_color,
                        side:side,
                        filename:filename, 
                        type:'art'});
}

function CustomAddArt(params) { //internal?
    side = params.side;
    height = params.height;
    width = params.width;
    top_ = params.top;
    left_ = params.left;      
    fid = params.fid;
    filename = params.filename;
    transparent_color=params.transparent_color;
    colors=params.colors;
    
    $("#"+side+"_imprintarea").append("<div id='"+ fid +"' style=\"margin: 0; top: "+top_+"; left: "+left_+"; height:"+height+"; width: "+width+"; position:absolute; background: none;\"><img src='"+ currentsessiontempdir_ws + "result_" + filename + "' width='100%' height='100%'></div>");

    $('#' + fid).resizable({ 
        autoHide: true,
  		minHeight: 10, 
        minWidth: 10,
        aspectRatio: 'preserve',
        containment: $('#'+side+'_imprintarea')
		});

    $('#' + fid).draggable({containment: '#'+side+'_imprintarea'});
    $('#' + fid).click(function () { ShowEditPanel($(this).attr('id')); });
    AddToCustom(fid, {  fid:fid,
                        width: width, 
                        height: height, 
                        top:top_,
                        left:left_, 
                        rotate: params.rotate, 
                        side:side,
                        filename:filename, 
                        transparent_color: params.transparent_color,
                        colors: params.colors,
                        type:'art'});
   
    selectUsedColors('color_id_');
    selectUsedColors('new_clipart_id_');
    selectUsedColors('clipart_id_');
    updatePrice();
}

function AddToShoppingCart() {
    if(shoppingcart!="") {
        showMessage(true);
        return false;
    }

    if(checkCountOfUsedColors()) {
        //ajax asynch
        saveCustomizationPost('Shopping_cart_' + session_id, 0, 0, 1);
        if(fids_params.length>0) {
            CustomizationSaved = true;
            updateParams();
            
            for(i in fids_params) {
               if(fids_params[i].fid!="") {
                    AddHidenFields(fids_params[i].type, fids_params[i].fid, fids_params[i]);
               }
            }            
            //side_option_id = $('#bagSidesOptionId').val();
            //side = $('#id_'+side_option_id).val();
            //content = '<input type=hidden name="id['+side_option_id+']" value="'+side+'" />';
            
            color_option_id = $('#bagColorOptionId').val();
            color_value_option_id = $('#selectedBagColor').val();
            content = content + '<input type=hidden name="id['+color_option_id+']" value="'+color_value_option_id+'" />';
            $('#addtocart').after(content);
            $('#addproduct').submit();
            return true;
        }
        else {
            alert('Custom tool is empty');
            return false;
        }
    }
}

function AddToCustom(id, params) { //internal
    CustomizationSaved = false;
    if(params.color) {
        updateUsedColors(params.color);
    }
    addborder(params.fid);
    fids_params[fids_params.length] = params;
    //fids_count++;
}

function UpdateCustom(id, params) { //internal
    CustomizationSaved = false;
    if(params.color) {
        updateUsedColors(params.color);
    }
    for(i in fids_params) {
       if(fids_params[i].fid==id) {
           for(attr in params) {
            fids_params[i][attr] = params[attr];
           }
       }
    }
    $('#'+id).click();
}

function AddHidenFields(type, id, params) {
    content = '';
    for(ind in params) {
        content = content + '<input type=hidden name="art['+id+']['+ ind +']" value="'+ params[ind] +'" />';
    }
    $('#addtocart').after(content);
}

function RemoveItem(id) {
    if (!id) {
      id = $('#selectedvalue').val();
    }
    CustomizationSaved = false;
    unselectUsedColors('color_id_');
    unselectUsedColors('new_clipart_id_');
    //$('#'+id).empty();
    $('#'+id).replaceWith('');
    $('#previewart').html('');
    
    obj = loaditem(id);
    for(i in fids_params) {
        if(fids_params[i] == id) {
            fids_params[i]="";
        }
    }
    
    new_fids_params = new Array();
    for(fids in fids_params) {
        if(fids_params[fids].fid != id) {
            new_fids_params[new_fids_params.length] = fids_params[fids];
        }
    }
    
    fids_params = new_fids_params;
      
    $('#editform').html('');
    selectUsedColors('color_id_');
    selectUsedColors('new_clipart_id_');
    updatePrice();
}

function loaditem(id) {
    finded = false;
    for(i in fids_params) {
        if(id==fids_params[i].fid) {
            return fids_params[i];
        }
    }
}

function ChooseSides(sides, no_update) {
  sides_1 = sides.substring(0,1);
  sides_2 = sides.substring(2,3);

  if(sides_2!=1 && sides_2!=2) {
    sides_2=1;
  }
  if(sides_2>1) {
    $('#side_2').css('display', 'block');
  }
  else {
    //clean up back side
    if (fids_params.length > 0) {
      var back_side_fids = new Array();
      for(i=0; i<fids_params.length; i++) {
          if(fids_params[i].side != 'side1') {
            back_side_fids[back_side_fids.length] = fids_params[i].fid;
          }
      }
      
      if (back_side_fids.length > 0) {
        if (confirm("Your custom art on the second side will be lost.\nAre you sure you want to continue?")) {
        
            CustomizationSaved = false;
            unselectUsedColors('color_id_');
            unselectUsedColors('new_clipart_id_');
            
            //$('#previewart').html(''); //???
  
            var new_fids_params = new Array();
            var fid_delete;
            var to_delete = false;
            
            for(fids in fids_params) {
              to_delete = false;
              for(i_back in back_side_fids) {
                fid_delete = back_side_fids[i_back];
                
                $('#'+fid_delete).replaceWith('');
                if(fids_params[fids].fid == fid_delete) {
                  to_delete = true;
                }
              }
              
              if(!to_delete) {
                new_fids_params[new_fids_params.length] = fids_params[fids];
              }
            }
            fids_params = new_fids_params;
            
            selectUsedColors('color_id_');
            selectUsedColors('new_clipart_id_');
        //    updatePrice();
        } else {
          return false;
        }
      }
      
    
      /*     
        for(i=0; i<fids_params.length; i++) {
            if(fids_params[i].side != 'side1') {
                $('#'+fids_params[i].fid).replaceWith('');
                fids_params[i] = new Array();
            }
        }
      */
    }
    $('#side_2').css('display', 'none');
    $('#side1_').click();  
    
  }
  
  $('#sides_hidden').val(sides);  
  $('#selectedBagSidesOption').val(sides);
  if (!no_update) {
    updatePrice();
  }
}

function ChooseHandles(handles, no_update) {
  if (handles) {
    $('#baghandles').css('display', 'block');
  } else {
    $('#baghandles').css('display', 'none');
  } 
  $('#handles_hidden').val(handles); 
  $('#selectedBagHandlesOption').val(handles)
  if (!no_update) {
    updatePrice();
  }
}
//function ChooseSides(sides) {
//  $('#sides_hidden').val(sides);  
//  updatePrice();
//}

function LoadSideImage(products_id, color_id) {
  $.get(customizationHref, {product_id: products_id,
                            color_id: color_id,
                            action: 'loadside'},
      function(xml){
        image = $('file:first', xml).text();
        image_width = $('image_width:first', xml).text();
        image_height = $('image_height:first', xml).text();
        image_width = $('image_width:first', xml).text();
        height = $('height:first', xml).text();
        width = $('width:first', xml).text();
        top_ = $('top:first', xml).text();
        left_ = $('left:first', xml).text();
        side_id = $('side_id:first', xml).text();
        LoadCutomSide(image, side_id, left_, top_, width, height, image_width, image_height);
      });
}

function SelectColor(products_id, id, replace, without_loadside) {
  id_ex = $('#selectedBagColor').val();
  if (id_ex != id || replace) {
    
    if (!without_loadside) {
      LoadSideImage(products_id, id);
    }

    $('#bagcolors TD.color_box').html('&nbsp;');
    
    $('#bag_color_id_'+id).html('<img src="images/bulet.gif">');
    
    $('#selectedBagColor').val(id);
  }
}

function ChangeCategory(parent_category_id, category_id) { //didn't find
    $.get(customizationHref, {category_id: parent_category_id,
                              action: 'getsizes'},function(data){ 
        obj = $('#prod_size');
        obj.html(data)
        obj.val(category_id);
        obj = $('#prod_size');
        ChangeSizes(obj);
    });    
}

function ChangeSizes(oo) { // Dasha, select->option behaviour
  var val, cat;
  var callback = function() {
    //debugger;
    cat = $('#category_id').val();
    val = $('#prod_size option:selected').val();
    
    $.get(customizationHref, {category_id: cat,
                              prod_size: val,
                              action: 'getquantities'},function(data){//old getsizes
        obj = $('#prod_qty');
        obj.html(data)
        obj = $('#prod_qty option:selected');
        if (!obj.val()) {
          obj = $('#prod_qty option:first');
        }
        var product_id = obj.val();
        
        UpdateProductTab(product_id);
        
    });
  };
  saveInSessionTmp(false, callback);
}

function ChangeQuantity(oo) {
        //o = $(oo);
  var callback = function() {
    o = $('option:selected', oo);

    UpdateProductTab(o.val());
        
  }
  saveInSessionTmp(false, callback);
}

function LoadCutomSide(filename, side, left, top, width, height, imagewidth, imageheight) {
    $('#side_image_' + side).css('background-image', 'url('+ filename +'?'+Math.random()+')');
    $('#side_image_' + side).css('width', imagewidth+'px');
    $('#side_image_' + side).css('height', imageheight+'px');
    $("#side" + side + "_imprintarea").css('left',left+'px');
    $("#side" + side + "_imprintarea").css('top',top+'px');
    $("#side" + side + "_imprintarea").css('width',width+'px');
    $("#side" + side + "_imprintarea").css('height',height+'px');
    
    $('#side_image_2').css('background-image', 'url('+ filename +'?'+Math.random()+')');
    $('#side_image_2').css('width', imagewidth+'px');
    $('#side_image_2').css('height', imageheight+'px');
    $("#side2_imprintarea").css('left',left+'px');
    $("#side2_imprintarea").css('top',top+'px');
    $("#side2_imprintarea").css('width',width+'px');
    $("#side2_imprintarea").css('height',height+'px');    
}

function SelectFontColor(id) {
    if($('#new_font_color').val() > 0) {
      id_ex=$('#new_font_color').val();
      $('#color_id_'+id_ex).html('');
    }
    $('#color_id_'+id).html('<img src="images/bulet.gif">');
    $('#new_font_color').val(id);
}

function EditFontColor(id) {
    if($('#new_font_color').val() > 0) {
      id_ex=$('#new_font_color').val();
      $('#edit_id_'+id_ex).html('&nbsp;');
    }    
    if($('#edit_font_color').val() > 0) {
      id_ex = $('#edit_font_color').val();
      $('#edit_id_'+id_ex).html('&nbsp;');
    }
    $('#edit_id_'+id).html('<img src="images/bulet.gif">');
    $('#edit_font_color').val(id);
}

function SelectClipartColor(id) {
    if($('#clipart_color').val() >= 0) {
      id_ex = $('#clipart_color').val();
       $('#clipart_id_'+id_ex).html('');
    }
    $('#clipart_id_'+id).html('<img src="images/bulet.gif">');
    $('#clipart_color').val(id);
}

function SelectNewClipartColor(id) {
    if($('#new_clipart_color').val() >= 0) {
      id_ex = $('#new_clipart_color').val();
      $('#new_clipart_id_'+id_ex).html('');
    }
    $('#new_clipart_id_'+id).html('<img src="images/bulet.gif">');
    $('#new_clipart_color').val(id);
}


function selectUsedColors(id) {
  for(ind in fids_params) {
    if($("#" + id + fids_params[ind].color)) {
        $("#" + id + fids_params[ind].color).html('&nbsp;');
        //$("#" + id + fids_params[ind].color).css("border", "2px solid black");
        $("#" + id + fids_params[ind].color).css("background-image", "url('images/bullet_small.gif')");
        $("#" + id + fids_params[ind].color).css("background-repeat", "no-repeat");
    }
  }
}

function unselectUsedColors(id) {
  $("." + id + '-class').html('');
  $("." + id + '-class').css("background-image", "");
    
  /*for(ind in used_colors) {
    $("#" + id + used_colors[ind]).html('');
    $("#" + id + used_colors[ind]).css("background-image", "");
    //$("#" + id + fids_params[ind].color).css("border", "0px solid black");
  }*/
}

function useThisCustomization(id) {
    if(useDefaultTemplate>0) {
        $('#use_' + id).val(true);
    }
    useDefaultTemplate = $('#use_' + id).val();
    
}


function updatePrice(no_message) {
  //debugger;
    str = "";
    updateParams();
    for(i in fids_params) {
        for(el in fids_params[i]) {
          if (fids_params[i][el]) {
            str = str + "'" + el + "_" + i + "':'" + fids_params[i][el].replace(/\'/g,'&quote;') + "',";
          }
        }
    }
    products_id = $('#prod_qty').val();
    //sides_hidden = $('#bagSidesOptionId').val();
    sides_hidden = $('#sides_hidden').val();
    handles_hidden = $('#handles_hidden').val();
    bio_id = $('#bagFilmOptionId').val();
    if($('[id=id_'+bio_id+']').attr('checked')) {
        bio = 1;
    }
    else {
        bio = 0;
    }                
                
    $.post(customizationHref, {
      sides: sides_hidden, 
      handle: handles_hidden, 
      film: bio, 
      param: str, 
      products_id:products_id, 
      no_message: no_message ? 1 : 0,
      action: 'updateprice'},
      function(xml){
        var product_price = "";
        var plate_charge = "";
        var total_price = "";
        var per_bag_price = "";
        var message = "";

        shoppingcart = "";
        per_bag_price = $('per_bag_price:first', xml).text();
        product_price = $('product_price:first', xml).text();
        plate_charge = $('plate_charge:first', xml).text();
        total_price = $('total_price:first', xml).text();
        message = $('message:first', xml).text();
        shoppingcart = $('shoppingcart:first', xml).text();
        
        $('#price_per_bag').html(per_bag_price);
        $('#product_price').html(product_price);
        $('#plate_charge').html(plate_charge);
        $('#total_price').html(total_price);
        if(message!='' && fids_params.length>0) {
            addMessage(message);
        }
    });  
}

function updateParams() {
    for(i in fids_params) {
        fid = fids_params[i].fid;
        fids_params[i].height = $('#'+fid).css('height');
        fids_params[i].width = $('#'+fid).css('width');
        fids_params[i].top = $('#'+fid).css('top');
        fids_params[i].left = $('#'+fid).css('left');
    }
}

function countUsedColors() {
    ar = new Array();
    colors = 0;
    
    for(i in fids_params) {
        if(fids_params[i].type=='art') {
            colors = colors + fids_params[i].colors;
        }
        else {
            if(fids_params[i].color) {
                ar[fids_params[i].color] = fids_params[i].color;
                /*if(!in_array(fids_params[i].color, ar)) {
                    ar[ar.length] = fids_params[i].color;
                }*/
            }
        }
    }
    ar.sort();
    
    j=0;
    arr = new Array();
    while(ar[j]>0) {
        arr[arr.length] = ar[j];
        j++;
    }
 
    colors = colors + arr.length;
    
    return colors;
}

function countUsedColors(color) {
    ar = new Array();
    ar[color] = color;
    colors = 0;
    
    for(i in fids_params) {
        if(fids_params[i].type=='art') {
            colors = colors + fids_params[i].colors;
        }
        else {
            if(fids_params[i].color) {
                ar[fids_params[i].color] = fids_params[i].color;
                /*if(!in_array(fids_params[i].color, ar)) {
                    ar[ar.length] = fids_params[i].color;
                }*/
            }
        }
    }
    ar.sort();
    
    j=0;
    arr = new Array();
    while(ar[j]>0) {
        arr[arr.length] = ar[j];
        j++;
    }
 
    colors = colors + arr.length;
    
    return colors;
}

//Check when we try add new object
function checkUsedColors(color) {
    colors = countUsedColors(color);
    if((colors > MaxColorsUsed)) {
        msg = 'This product can only have '+MaxColorsUsed+' colors';
        addMessage(msg);
        showMessage(true);
        return false;
    }
    return true;
}

//Just chek count of used colors
function checkCountOfUsedColors() {
    ar = new Array();
    colors = 0;
    for(i in fids_params) {
        if(fids_params[i].type=='art') {
            colors = colors + fids_params[i].colors;
        }
        else {
        /*
            if(!in_array(fids_params[i].color, ar)) {
                ar[ar.length] = fids_params[i].color;
            }*/
            ar[fids_params[i].color] = fids_params[i].color;
        }
    }

    ar.sort();
    
    j=0;
    arr = new Array();
    while(ar[j]>0) {
        arr[arr.length] = ar[j];
        j++;
    }
    
    colors = colors + arr.length;
    if((colors > MaxColorsUsed)) {
        msg = 'This product can only have '+MaxColorsUsed+' colors';
        addMessage(msg);
        showMessage(true);
        return false;
    }
    return true;
}


function in_array(val, ar) {
    for(i in ar) {
        if(ar[i] == val) {
            return true;
            }
    }
    alert("Not Found");    
    return false;
}

function addMessage(msg) {
  if(msg=='') return false;
  //if(msg == $('#message_error_text').html()) return false;
/* dima's part. Commenting
    html = $('#Message').html();
    //html = html + '<br>' + msg;
    html = msg;
    $('#Message').html(html);
    $('#Message').css('display', 'block');
*/
  $('#message_error_text').html(msg);
  $('#Message').fadeIn('slow');
}

function MoveObject(obj) {
    $('#'+obj.fid).css('top',obj.top+'px');
    $('#'+obj.fid).css('left',obj.left+'px');
}

function showMessage(with_options) {
  if (!with_options) {
    $('#message_options').hide();
  }
  $('#Message').fadeIn('slow');
}

function getValue(id, xml) {
  if($(id+':first', xml)) {
   return $(id+':first', xml).text();
  }
  else {
    return null;
  }
}

function checkFileExt() {
  path = $('#image').val();
  if(path!='') {
    path = path.toLowerCase();
    restoredArray = path.split("\.");
    ext = restoredArray[restoredArray.length-1];
    if(in_array(ext, extensions)) {
      $('#progressbar').css('display','block');
      $('#imageupload').css('display','none');
      return true;
    }
    else {
      msg = "You couldn't' use this file type!";
      $(window).attr('parent').addMessage(msg);
      $(window).attr('parent').showMessage();
      return false;
    }
  }
  else {
    msg = "You should select file for upload first!";
    $(window).attr('parent').addMessage(msg);
    $(window).attr('parent').showMessage();
    return false;
  }
  return false;
}

function selectClipArt(fid, cc_id, ci_id, filename) {
    /*
    id_ex = $('#new_md5').val();
    if(id_ex!='') {
        $('#clipart_'+id_ex).css("border", "0px solid black");
    }
    $('#clipart_'+fid).css("border", "2px solid black");
    */
    $('#new_md5').val(fid);
    $('#new_cc_id').val(cc_id);
    $('#new_ci_id').val(ci_id);
    $('#new_filename').val(filename);
    AddClipArt();
}

function clearSelection() {
    if(selected_fid!='') {
        hideborder();
        selected_fid="";
        $('#editform').html('');
        if(lastused.tab) {
            $('#'+lastused.tab + "link").click();
            if(lastused.subtab) {
                $('#'+lastused.subtab + "link").click();
            }
        }
        else {
            $('#pickproductlink').click();
        }
    }
    $('#customizationtool > ul').tabs("disable", 3);
}

function selectFont(id) {
    id_ex = 0;
    id_ex = $('#new_font').val();
    if(id_ex>0) {
        unselectFont(id_ex);
    }
    $('#new_font').val(id);
    //$('#new_font_' + id).css('border', '1px solid black');
    $('#new_font_' + id).css('background-color', 'yellow');
    return false;
}

function unselectFont(id) {
    //$('#new_font_' + id).css('border', '0px solid black');
    $('#new_font_' + id).css('background-color', '');
}

function EditFont(id) {
    if($('#edit_font').val() > 0) {
      id_ex = $('#edit_font').val();
      //$('#edit_font_'+id_ex).css('border', '0px solid black');
      $('#edit_font_'+id_ex).css('background-color', '');
    }
    //$('#edit_font_'+id).css('border', '1px solid black');
    $('#edit_font_'+id).css('background-color', 'yellow');
    $('#edit_font').val(id);
    return false;
}

/******************************************* Saving before leave the page *******************************/

/* Dasha rewrite here to the 4 functions:
SaveBeforeLogin()
SaveOnPickDifProduct()
SavePermanently()
SaveInSession()
///

function confirmSaving(th) {
  saveinsession = true;
  if(th=='login') {
    afterloginredirect = true;
  }
  return true;
}

function SavingConfirmed() {
      if(fids_params.length>0 && !CustomizationSaved) {
        //if(confirm('Do you want use current customization on another bag?')) 
            {
                updateParams();
                str = fidsToStr();

                options_id = $('#bagSidesOptionId').val();
                handle_id = $('#bagHandlesOptionId').val();
                bio_id = $('#bagFilmOptionId').val();
                if($('[id=id_'+bio_id+']').attr('checked')) {
                    bio = 'TRUE';
                }
                else {
                    bio = 'FALSE';
                }                
                
                $.post(customizationHref, {
                                           param:str, 
                                           bio:bio,
                                           handles:$('[id=id_'+handle_id+']:checked').val(), 
                                           sides:$('[id=id_'+options_id+']:checked').val(), 
                                           bagcolor: $('#selectedBagColor').val(), 
                                           products_id:$('#prod_qty').val(), 
                                           size_id:$('#prod_size').val(),
                                           sessionidsaved:session_id,
                                           afterloginredirect: afterloginredirect,
                                           action: 'saveinsession'},function(xml){
                    return true;
                });                 
            }
       } 
    return true;
}
*/
function SaveBeforeLogin(from) {
  //saveinsession = true;
  afterloginredirect = true;
  saveInSessionTmp();
  SaveInSession(from);
  
  CustomizationSaved = true;
  //debugger;
  return true;
}

function SaveOnPickDifProduct() {
  //saveinsession = true;
  if(fids_params.length>0) {
    if (confirm("Do you want to apply current customization to a different product (keep it)?\nIf you click cancel all changes will be lost.")) {
      SaveInSession();
    }
  } 
}

function SaveBeforeLeave() {
  if (confirm('Do you want to save current customization for later use?')) {
    //open save tab
    saveCustomization();
    return false;
  }
  return true;
  /*
  if (customer_id) {
    if (confirm('Do you want use current customization for later use?')) {
      //open save tab
      saveCustomization();
      return false;
    }
  }
  */
}

function SaveInSession(from) {
  updateParams();
  str = fidsToStr();

/*
//move to SaveinSessionTmp()
  options_id = $('#bagSidesOptionId').val();
  handle_id = $('#bagHandlesOptionId').val();
  bio_id = $('#bagFilmOptionId').val();
  if($('[id=id_'+bio_id+']').attr('checked')) {
      bio = 'TRUE';
  }
  else {
      bio = 'FALSE';
  }                
 bio:bio,
 handles:$('[id=id_'+handle_id+']:checked').val(), 
 sides:$('[id=id_'+options_id+']:checked').val(), 
 bagcolor: $('#selectedBagColor').val(), 
 
 //products_id:$('#prod_qty').val(), 
*/

  $.ajaxSetup({
    async: false
  });
  $.post(customizationHref, {
                             param:str, 
                             sessionidsaved:session_id,
                             products_id:$('#products_id').val(), 
                             category_id: $('#category_id').val(),
                             afterloginredirect: afterloginredirect,
                             from: from,
                             action: 'saveinsession'},function(xml){
      $.ajaxSetup({
        async: true
      })
      return true;
  });                 
}

/*window.onbeforeunload = function() {
    setTimeout(userDidNotLeave,10);
    return "Are you sure you want to leave? changes will be lost";
}
 
function userDidNotLeave() {
    $("#content").css("background", "#df34ef");
}
*/
  
function ChooseFilm(cheked) {
  if (cheked) {
    $('[id=id_'+$('#bagFilmOptionId').val()+']').attr('checked', true);
  }
}

/*******************************customization.php******************************/
function CloseMessageBox() {
  $('#message_options').show();
  $('#Message').fadeOut('slow');
}

function CustomAddText() {
  if($('#new_text').val() == '') {
      alert('Text empty!');
      return false;
  }
  if($('#new_font').val() == '') {
      alert('Select font first!');
      return false;    
  }
  
  if(checkUsedColors($('#new_font_color').val())) { 
    CustomizationSaved = false;
      if($('#new_font_color').val()>0) {
          params = {
                      text: $('#new_text').val(), 
                      font: $('#new_font').val(), 
                      color: $('#new_font_color').val(), 
                      size: $('#new_size').val(), 
                      rotate: $('#new_rotate').val(), 
                      effect: $('#new_effect').val(), 
                      side: $('#sideidvalue').val(),
                      top: '0px',
                      left: '0px',
                      fid: ''
                  }
          AddText(params);
          $('#new_font_color').val('');
          //unselectFont($('#new_font').val(''));
          //$('#new_font').val('');
      }
      else {
          alert('Select font color!');
      }        
  }
}

function AddSavedObject(params) {
  if(params.type == 'text') {
      if(params.f_id>0) {
          params.font = params.f_id;
      }
      AddText(params, true);
  }
  if(params.type == 'clipart') {
      CustomAddClipArt(params);
  }
  if(params.type == 'art') {
      CustomAddArt(params);
  }    
}

function AddText(params) {
  $.post(customizationHref, {
                              fid: params.fid, 
                              width: params.width, 
                              height: params.height, 
                              top: params.top, 
                              left: params.left,
                              text: params.text, 
                              font: params.font, 
                              color: params.color, 
                              size: params.size, 
                              rotate: params.rotate, 
                              effect: params.effect, 
                              side: params.side,
                              action: 'gentext'},function(data){
      var xml = data;
      file = $('file:first', xml).text();
      fid = $('fid:first', xml).text();
      width = Math.abs($('width:first', xml).text());
      height = Math.abs($('height:first', xml).text());
      topp = $('top:first', xml).text();
      left = $('left:first', xml).text();
      side = $('side:first', xml).text();
      size = $('size:first', xml).text();
      font = $('font:first', xml).text();
      color = $('color:first', xml).text();
      effect = $('effect:first', xml).text();
      rotate = $('rotate:first', xml).text();
      text = $('text:first', xml).text();
      $("#"+side+"_imprintarea").append("<div id='"+ fid +"' style=\"margin: 0; height:"+height+"; width: "+width+"px; top: "+topp+"px; left: "+left+"px; position:absolute; background: none;\"><img src='"+ file +"' width='100%' height='100%' style='float:left;'></div>");

      $('#' + fid).css('top', topp+'px');
      $('#' + fid).css('left', left+'px');
      $('#' + fid).css('height', height+'px');
      $('#' + fid).css('width', width+'px');

      $('#' + fid).draggable({containment: '#'+side+'_imprintarea'});
      $('#' + fid).click(function () { ShowEditPanel($(this).attr('id'));});
      $('#new_text').val('');
    AddToCustom(fid, {  fid:fid,
                        width:width, 
                        height:height, 
                        top:topp+'px',
                        left:left+'px', 
                        rotate:rotate, 
                        side:side,
                        font:font, 
                        color:color, 
                        size:size,
                        effect:effect, 
                        text:text,
                        type:'text'});
      selectUsedColors('color_id_');
      selectUsedColors('new_clipart_id_');
      selectUsedColors('clipart_id_');
      updatePrice();
      lastused.color = color;
      $('#color_id_' + lastused.color).click();
      $('img[@src$=.png]').ifixpng();
  });
}

function checkBeforeUpdate(fid) {
  var colors;
  colors = 0;
  
  ar = new Array();
  for(i in fids_params) {
    if(fids_params[i].fid == fid) {
        if(fids_params[i].type == 'text') {
          color = $('#edit_font_color').val();
          ar[color] = color;
        }
        if(fids_params[i].type == 'clipart') {
          color = $('#clipart_color').val();
          ar[color] = color;
        }
    }
  }
  
  for(i in fids_params) {
      if(fids_params[i].type=='art') {
          colors = colors + fids_params[i].colors;
      }
      else {
          if(fids_params[i].fid!=fid) {
              if(fids_params[i].color) {
                  ar[fids_params[i].color] = fids_params[i].color;
              }
          }
      }
  }
  ar.sort();
  j=0;
  arr = new Array();
  while(ar[j]>0) {
      arr[arr.length] = ar[j];
      j++;
  }
  colors = colors + arr.length;
  
  var checked = false;
  //alert("(("+MaxColorsUsed+"<="+colors+") || ("+countUsedColors()+" < "+colors+"))");
  if((MaxColorsUsed>=colors) || (countUsedColors() > colors)) {
      checked = true;
  }
  
  return checked;
}

function CustomUpdateText(fid) {
  //if(checkUsedColors($('#edit_font_color').val())) {
  if(checkBeforeUpdate(fid)) {
      $.post(customizationHref, {text: $('#edit_text').val(), 
                                  font: $('#edit_font').val(), 
                                  color: $('#edit_font_color').val(), 
                                  size: $('#edit_size').val(), 
                                  rotate: $('#edit_rotate').val(), 
                                  effect: $('#edit_effect').val(), 
                                  side: $('#sideidvalue').val(),
                                  fid: fid,
                                  action: 'gentext'},function(data){
                                  
          xml = data;
          file = $('file:first', xml).text();
          fid = $('fid:first', xml).text();
          width = $('width:first', xml).text();
          height = $('height:first', xml).text();
          side = $('side:first', xml).text();
          size = $('size:first', xml).text();
          font = $('font:first', xml).text();
          color = $('color:first', xml).text();
          effect = $('effect:first', xml).text();
          rotate = $('rotate:first', xml).text();
          text = $('text:first', xml).text();
          $("#"+fid).html("<img src='"+ file +"?rand="+Math.random()+"' width='100%' 2 height='100%' style='float:left;'>");
          addborder(fid);
    //      $('#' + fid).draggable({containment: '#'+side+'_imprintarea'});
    //      $('#' + fid).css('top', '1px');
    //      $('#' + fid).css('left', '1px');
          $('#' + fid).css('width', width+'px');
          $('#' + fid).css('height', height+'px');

      //    $('#' + fid).click(function () { ShowEditPanel($(this).attr('id')); });
        $('#new_text').val('');
        unselectUsedColors('color_id_');
        unselectUsedColors('edit_id_');
        UpdateCustom(fid, { fid:fid,
                            width:width, 
                            height:height, 
                            //top:'0px',
                            //left:'0px', 
                            rotate:rotate, 
                            side:side,
                            font:font, 
                            color:color, 
                            size:size,
                            effect:effect, 
                            text:text});
          selectUsedColors('color_id_');
          selectUsedColors('edit_id_');
          $('#'+fid).click();
          updatePrice();
      });
  }
  else {
      msg = 'This product can only have '+MaxColorsUsed+' colors';
      addMessage(msg);
      showMessage(true);
      return false;
  }
}

function LoadClipArt(params) { //I didn't find
  params.action = 'loadcustomizationclipart';
  $.post(customizationHref, params,function(data){
  });
}

function CustomAddClipArt(params, no_update) { //internal
  
  $("#"+params.side+"_imprintarea").append("<div id='"+ params.fid +"' style=\"margin: 0; top: 1px; height:"+params.height+"; width: "+params.width+"; left: "+params.left+"; top: "+params.top+"; position:absolute; background: none;\"><img src='"+ currentsessiontempdir_ws +"result_"+ params.filename +"' width='100%' height='100%'></div>");
  
  $('#' + params.fid).resizable({ 
            zIndex:2000,
            autoHide: true,
            minHeight: 10, 
            minWidth: 10,
            aspectRatio: 'preserve',
            stop: function(e, ui) {
                  showborder(params.fid);
            },
            containment: $('#'+params.side+'_imprintarea')});
  $('#' + params.fid).draggable({containment: '#'+params.side+'_imprintarea'});
  $('#' + params.fid).click(function () { 
        ShowEditPanel($(this).attr('id')); 
        selected_fid = params.fid;          
  });
  AddToCustom(params.fid, {  fid:params.fid,
                                width:params.width + 'px', 
                                height:params.height + 'px', 
                                top:params.top + '0',
                                left:params.left + '0', 
                                rotate:params.rotate, 
                                color:params.color, 
                                side:params.side,
                                cc_id:params.cc_id, 
                                ci_id:params.ci_id,
                                filename:params.filename,
                                type:'clipart'});
  
  
  selectUsedColors('color_id_');
  selectUsedColors('new_clipart_id_');
  selectUsedColors('clipart_id_');
      
  if (!no_update) {
    updatePrice(); 
  };
  lastused.color = params.color;        
  //AddClipArt(fid, cc_id, ci_id, filename);
  return false;
}

function AddClipArtRequest(fid, cc_id, ci_id, filename) { //didn't find
  html = $('#clipartimageedit').html();
  $('#editform').html(html);
  showEditLink();
}

//function AddClipArt(fid, cc_id, ci_id, filename) {
function AddClipArt() {  
  fid = $('#new_md5').val();
  cc_id = $('#new_cc_id').val();
  ci_id = $('#new_ci_id').val();
  rotate = 0;//$('#new_clipart_rotate').val();
  filename = $('#new_filename').val();
  
  if(!($('#new_clipart_color').val()>0)) {
      alert('You should select ink color first!');
      return false;
  }
  if(checkUsedColors($('#new_clipart_color').val())) {
    if($('#new_clipart_color').val()) {
        $.post(customizationHref, {cc_id: cc_id, 
                                    ci_id: ci_id, 
//                                      size: $('#edit_size').val(), 
                                    color:$('#new_clipart_color').val(),
                                    rotate: rotate, 
                                    filename: filename, 
                                    side: $('#sideidvalue').val(),
                                    fid: fid,
                                    action: 'addclipartimage'},function(data){
          xml = data;
          fid = $('fid:first', xml).text();
          cc_id = $('cc_id:first', xml).text();
          ci_id = $('ci_id:first', xml).text();
          filename = $('filename:first', xml).text();
          file = $('file:first', xml).text();
          filews = $('filews:first', xml).text();
          side = $('#sideidvalue').val();
          rotate = $('rotate:first', xml).text();
          color = $('color:first', xml).text();
          height= $('height:first', xml).text();
          width = $('width:first', xml).text();

          CustomAddClipArt({fid:fid, cc_id:cc_id, filename:filename, file:file, filews:filews, side:side, rotate:rotate, color:color, height:height+'px', width:width+'px'});
          selectUsedColors('new_clipart_id_');
          //$('#clipartimages').hide();
          
/*          $("#"+side+"_imprintarea").append("<div id='"+ fid +"' style=\"margin: 0; top: 1px; height:"+height+"; width: "+width+"px; position:relative; background: none;\"><img src='"+ filews +"' width='100%' height='100%'></div>");
          
          $('#' + fid).({ 
              zIndex:2000,
              autoHide: true,
              minHeight: 10, 
              minWidth: 10,
              aspectRatio: 'preserve',
              stop: function(e, ui) {
                    showborder(fid);
              },
              containment: $('#'+side+'_imprintarea')});
          $('#' + fid).draggable({containment: '#'+side+'_imprintarea'});
          $('#' + fid).click(function () { 
              ShowEditPanel($(this).attr('id')); 
              selected_fid = fid;          
          });
          AddToCustom(fid, {  fid:fid,
                              width:'0px', 
                              height:'0px', 
                              top:'0',
                              left:'0', 
                              rotate:'0px', 
                              color:0, 
                              side:side,
                              cc_id:cc_id, 
                              ci_id:ci_id,
                              filename:file,
                              type:'clipart'});
            updatePrice();*/
        });
    }
  }
}

function ShowEditPanel(id) { //internal
    /*if(id == $('#selectedvalue').val()) {
      hideborder();
      $('#selectedvalue').val('');
      $('#editform').html('');
      $('#pickproductlink').click();
      return false;
    }*/
    //selected_fid = id;
    
    //It's for make sure that we don't clear selected object on side click
    showeditpanel = true;
    showborder(id);
    
    obj = loaditem(id);
    showEditLink();
    $('#selectedvalue').val(id);

    if(obj.type == 'text') {
        html = $('#addtext').html();
        var srchText = /new_/g;
        var replacement = "edit_";
        html = html.replace(srchText, replacement);
        var srchText = /add_text/g;
        var replacement = "update_text";
        html = html.replace(srchText, replacement);
        var srchText = /CustomAddText\(\)\;/g;
        var replacement = "CustomUpdateText('"+id+"')";
        html = html.replace(srchText, replacement);
        var srchText = /Add text/g;
        var replacement = "Update text";
        html = html.replace(srchText, replacement);
        var srchText = /SelectFontColor/g;
        var replacement = "EditFontColor";
        html = html.replace(srchText, replacement);
        var srchText = /selectFont/g;
        var replacement = "EditFont";
        html = html.replace(srchText, replacement);          
        var srchText = /id=color_id_/g;
        var replacement = 'id=edit_id_';
        html = html.replace(srchText, replacement);
        var srchText = /id="color_id_/g;
        var replacement = 'id="edit_id_';          
        html = html.replace(srchText, replacement);

        var srchText = /fontslist/g;
        var replacement = 'editfontslist';          
        html = html.replace(srchText, replacement);          
        
        var srchText = /id\=\"fontcolors/g;
        var replacement = 'id="edit_fontcolors';
        html = html.replace(srchText, replacement);          

        $('#editform').html(html);
        
        $('#update_text').after($('#removeitem_button').html());
        used = 0;
        for(ind in fids_params) {
              if(fids_params[ind].color == obj.color) {
                used++;
              }
        }
        selectUsedColors('edit_id_');          
        $("#edit_id_" + $('#new_font_color').val()).html('<img src="images/bulet.gif">');
        $("#edit_id_" + obj.color).html('<img src="images/bulet.gif">');
        if(used==1) {
          //$("#edit_id_" + obj.color).css("border", "0px solid black");
          $("#edit_id_" + obj.color).css("background-image", "");
        }
        
        $('#editfontslist > div').css('background-color','');
        $('#edit_text:visible').val(obj.text);
        $('#edit_font_color').val(obj.color);
        EditFont(obj.font);
        EditFontColor(obj.color);
        $('#edit_size:visible').val(obj.size);
        $('#edit_rotate:visible').val(obj.rotate);
        $('#edit_effect:visible').val(obj.effect);
        $('#update_text').attr('onClick', 'CustomUpdateText("'+id+'");');

        setTimeout("editfont = $('#edit_font_' + obj.font); $('#editfontslist').scrollTop(editfont.attr('offsetTop'));", 1000);
        
    }
    if(obj.type == 'art') {
         html = $('#imageedit').html();
         var srchText = /ID/g;
         var replacement = id;
         html = html.replace(srchText, replacement);
        
         var srchText = /image_rotate/g;
         var replacement = "art_rotate";
         html = html.replace(srchText, replacement); 
        
         var srchText = /image_colors/g;
         var replacement = "art_colors";
         html = html.replace(srchText, replacement);
         
         var srchText = /new_transparent_color/g;
         var replacement = "art_transparent_color";
         html = html.replace(srchText, replacement);           
         
         $('#editform').html(html);
         $('#update_image').after($('#removeitem_button').html());           
         $('#art_rotate:visible').val(obj.rotate);
         $('#art_colors:visible').val(obj.colors);
         if(obj.transparent_color) {
              $('#art_transparent_color:visible').attr('checked','true');
         }
         else {
              //$('#art_transparent_color:visible').attr('checked','');
         }
    }
    if(obj.type == 'clipart') {
         html = $('#clipartimageedit').html();
         var srchText = /ID/g;
         var replacement = id;
         html = html.replace(srchText, replacement);
        
         var srchText = /image_rotate/g;
         var replacement = "clipart_rotate";
         html = html.replace(srchText, replacement);            
         
         $('#editform').html(html);
         $('#update_image').after($('#removeitem_button').html());
         
         $.get(customizationHref, {cc_id: obj.cc_id,
                                   color: obj.color,
                                   products_id:$('#prod_qty').val(),
                                   action: 'getClipartColors'},function(xml){
                  colors = $('colors:first', xml).text();
                  $('#clipartcolors').html(colors);
                  //SelectColor(obj.val(), color_id);
                  selectUsedColors('clipart_id_'); 

                  used = 0;
                  for(ind in fids_params) {
                        if(fids_params[ind].color == obj.color) {
                          used++;
                        }
                  }
                  
                  $("#clipart_id_" + obj.color).html('<img src="images/bulet.gif">');
                  if(used==1) {
                    //$("#clipart_id_" + obj.color).css("border", "0px solid black");
                    $("#clipart_id_" + obj.color).css("background-image", "");
                    
                  }
        
                  SelectClipartColor(obj.color);
              });           
         $('#clipart_rotate').val(obj.rotate);
    }     
 //   updatePrice();      
}

function updateFontList(font) {
  editfontslist = $('#editfontslist'); 
  editfont = $('#edit_font_' + font); 
  editfontslist.scrollTop(editfont.offset().top - 185);
}

function CustomUpdateImage(id) {
  obj = loaditem(id);
  updateParams();
  if($('#art_transparent_color').attr('checked') == true) {
      trans = $('#art_transparent_color').val();
  }
  else {
      trans = '';
  }
  $.post(customizationHref, {filename: obj.filename,
                              rotate: $('#art_rotate').val(), 
                              side: obj.side,
                              transparent_color:trans,
                              colors: $('#art_colors').val(),
                              width: obj.width,
                              height: obj.height,
                              fid: obj.fid,
                              action: 'imagerotate'},function(data){
      xml = data;
      fid = id;
      file = $('file:first', xml).text();
      filews = $('filews:first', xml).text();
      rotate = $('rotate:first', xml).text();
      colors = $('#art_colors').val();
      transparent_color = $('transparent_color:first', xml).text();
      height= $('height:first', xml).text();
      width = $('width:first', xml).text();        

      $("#"+fid).draggable("destroy");
      $("#"+obj.fid).resizable("destroy");
      
      $("#"+fid).html("<img src='"+ filews +"?rand="+Math.random()+"' width='100%' height='100%'>");
      $('#' + fid).resizable({ 
                zIndex:2000,
                autoHide: true,
                aspectRatio: 'preserve',
                minHeight: 10, 
                minWidth: 10,
                stop: function(e, ui) {
                      showborder(obj.fid);
                },
                containment: $('#'+obj.side+'_imprintarea')});
      $('#' + fid).draggable({containment: '#'+obj.side+'_imprintarea'});
      $('#' + fid).css('width', width+'px');
      $('#' + fid).css('height', height+'px');  
      addborder(fid);
      UpdateCustom(fid, {rotate:rotate, colors:colors, transparent_color:transparent_color});
      updatePrice();
  });
}

function ClipartUpdateImage(id) {
  //if(checkUsedColors($('#clipart_color').val())) {
  if(checkBeforeUpdate(id)) {
      updateParams();
      obj = loaditem(id);
      $.post(customizationHref, {filename: obj.filename,
                                  rotate: $('#clipart_rotate').val(), 
                                  color: $('#clipart_color').val(), 
                                  side: obj.side,
                                  fid: obj.fid,
                                  width: obj.width,
                                  height: obj.height,
                                  action: 'clipartupdate'},function(data){
                                  
          xml = data;
          fid = id;
          file = $('file:first', xml).text();
          filews = $('filews:first', xml).text();
          rotate = $('rotate:first', xml).text();
          color = $('color:first', xml).text();
          height= $('height:first', xml).text();
          width = $('width:first', xml).text();
          
          unselectUsedColors('color_id_');
          unselectUsedColors('clipart_id_');
          
          $("#"+fid).draggable("destroy");
          $("#"+obj.fid).resizable("destroy");
          
          //alert("#"+obj.fid);
          $("#"+fid).html("<img src='"+ filews +"?rand="+Math.random()+"' width='100%' height='100%'>");
          /*$('#' + fid).resizable({ 
                    zIndex:2000,
                    autoHide: true,
                    minHeight: 10, 
                    minWidth: 10,
                    aspectRatio: 'preserve',
                    stop: function(e, ui) {
                          showborder(params.fid);
                    },
                    containment: $('#'+obj.side+'_imprintarea')});*/

          $('#' + fid).resizable({ 
                    zIndex:2000,
                    autoHide: true,
                    aspectRatio: 'preserve',
                    minHeight: 10, 
                    minWidth: 10,
                    stop: function(e, ui) {
                          showborder(obj.fid);
                    },
                    containment: $('#'+obj.side+'_imprintarea')});
                    
          $('#' + fid).draggable({containment: '#'+obj.side+'_imprintarea'});
          
          $('#' + fid).css('width', width+'px');
          $('#' + fid).css('height', height+'px');
          
          addborder(fid);
          UpdateCustom(fid, {rotate:rotate, 
                             color:color});
          selectUsedColors('color_id_');
          selectUsedColors('clipart_id_');
          $('#' + fid).click();
          updatePrice();
      });  
  }
  else {
      msg = 'This product can only have '+MaxColorsUsed+' colors';
      addMessage(msg);
      showMessage(true);
      return false;
  }
}

function addborder(fid) {
    str = '';
    str = str + '<div id="selected_border_e" style="overflow: hidden; position: absolute; -moz-user-select: none; display: none; z-index:900;"></div>';
    str = str + '<div id="selected_border_s" style="overflow: hidden; position: absolute; -moz-user-select: none; display: none; z-index:900;"></div>';
    str = str + '<div id="selected_border_w" style="overflow: hidden; position: absolute; -moz-user-select: none; display: none; z-index: 900;"></div>';
    str = str + '<div id="selected_border_n" style="overflow: hidden; position: absolute; -moz-user-select: none; display: none; z-index: 900;"></div>';

    //str = '<div id="selected_border_e" class="ui-resizable-handle ui-resizable-e" onMouseOut="show(this);" onMouseOver="hide(this);" style="overflow: hidden; right: 0pt; height: 100%; position: absolute; -moz-user-select: none; display: none; z-index:900;"/> <div id="selected_border_s" class="ui-resizable-handle ui-resizable-s" style="overflow: hidden; bottom: 0pt; width: 100%; position: absolute; -moz-user-select: none; display: none;z-index:900;"/> <div id="selected_border_se" style="overflow: hidden; bottom: 0pt; right: 0px; position: absolute; z-index: 900; -moz-user-select: none; display: none;"/>';      
    $('#' + fid).append(str);
//      $('#' + fid + ' > #selected_border_e').css('display', 'none');
//      $('#' + fid + ' > #selected_border_s').css('display', 'none');
//      $('#' + fid + ' > #selected_border_se').css('display', 'none');
}

function hide(id) {
  if($(id).attr('id')==selected_fid) {
      $(id).css('display', 'none');
  }
}

/*  function show(id) {
  if($(id).attr('id')==selected_fid) {
      $(id).css('display', 'block');
  }
}  */

function hideborder() {
    $('#' + selected_fid + ' > #selected_border_e').css('display', 'none');
    $('#' + selected_fid + ' > #selected_border_s').css('display', 'none');
    $('#' + selected_fid + ' > #selected_border_w').css('display', 'none');
    $('#' + selected_fid + ' > #selected_border_n').css('display', 'none');
    selected_fid = '';
}

function showborder(fid) {
    hideborder();
    $('#' + fid + ' > #selected_border_e').css('display', 'block');
    $('#' + fid + ' > #selected_border_s').css('display', 'block');
    $('#' + fid + ' > #selected_border_w').css('display', 'block');
    $('#' + fid + ' > #selected_border_n').css('display', 'block');
    selected_fid = fid;
}

 
function loadCustomization() {
  showEditLink();
  html = $('#CustomizationLoadPanel').html();
  $('#editform').html(html);
  $.get(customizationHref, {action: 'getSavedCustomizations'},function(data){
      $('#editform').html(data);
  });
}

/*function loadSavedCustomization(id) {
  _blockUI();
  $.get(customizationHref, {products_id:$('#prod_qty').val(),
                            customization_saved_id: id,
                            action: 'getSavedCustomizationsId'},function(data){
      $('#side1_imprintarea').empty();
      $('#side2_imprintarea').empty();
      unselectUsedColors('color_id_');
      fids_params = new Array();
      fids_count = 0;        
      $('#CustomizationLoadPanel').html(data);
  });    
  _unblockUI();
}*/

function removeSavedCustomization(id, current) {
  if(confirm('Do you want delete saved customization?')) {
    _blockUI("Deleting...")
    $.get(customizationHref, {customization_saved_id: id,
                              action: 'removeSavedCustomizationsId'},function(data){
        if (id == current) {
          location.replace(customizationHref + '?category_id=' + $('#category_id').val());
        } else {
          loadCustomization();
          
        }
        _unblockUI();
    });
    //TODO: update list here 
  }
}

function saveCustomization() {
  showEditLink();
  html = $('#CustomizationSavePanel').html();
  $('#editform').html(html);
}
function fidsToStr() {
  for(i=0; i<fids_params.length; i++) {
      for(el in fids_params[i]) {
        if (fids_params[i][el]) {
          str = str + "'" + el + "_" + i + "':'" + fids_params[i][el].replace(/\'/g, "&quote;") + "',";
        }
      }
  }
  return str;
}

function saveCustomizationConfirm() {
  //var customization_id = $('#customization_id:checked').val();
  var customization_id = false;
  var customization_name = $('#customization_name').val();
  if (!customization_id) {
    $.post(customizationHref, {
                              action: 'savecustomization_checkname',
                              customization_name:customization_name},
    function(xml) {
       var status = $('status:first', xml).text();
       var customization_name = $('#customization_name').val();
       if(status == 'Allow') {
         saveCustomizationPost(customization_name)
       } else {
         if(confirm(status)) {
           saveCustomizationPost(customization_name, 1);
         }
       }
    });
  } else {
    saveCustomizationPost(customization_name, 1, customization_id);
  }
}

function saveCustomizationPost(customization_name, replace, customization_id, shopping_cart) {
  _blockUI("Saving...");
  updateParams();
  param = fidsToStr();
  //customization_name = $('#customization_name').val();
  options_id = $('#bagSidesOptionId').val();
  handle_id = $('#bagHandlesOptionId').val();
  bio_id = $('#bagFilmOptionId').val();
  if($('[id=id_'+bio_id+']').attr('checked')) {
      bio = 'TRUE';
  }
  else {
      bio = 'FALSE';
  }
  //
  if (shopping_cart) {
    $.ajaxSetup({
      async: false
    });
  }
  $.post(customizationHref, {bio:bio, 
                             handles:$('[id=id_'+handle_id+']:checked').val(), 
                             sides:$('[id=id_'+options_id+']:checked').val(), 
                             bagcolor: $('#selectedBagColor').val(), 
                             products_id: $('#prod_qty').val(), 
                                                              
                             category_id: $('#category_id').val(), 
                             product_id: $('#products_id').val(),
                             prod_size: $('#prod_size').val(),
                             product_qty: $('#prod_qty option:selected').html(),
                             bag_color: $('#selectedBagColor').val(),
                             bag_sides: $('#selectedBagSidesOption').val(), 
                             bag_handles: $('#selectedBagHandlesOption').val(),
                             bag_films: $('[id=id_'+$('#bagFilmOptionId').val()+']').attr('checked'),
                             replace: replace,
                             customization_id: customization_id,
                             shopping_cart: (shopping_cart) ? 1 : 0,
                             
                             customization_name:customization_name, 
                             param:param, 
                             action: 'savecustomization'},function(xml){
      var status_ = $('status:first', xml).text();
      var path = $('path:first', xml).text();
      var customization_id = $('customization_id:first', xml).text();
      $('#customization_id').val(customization_id);
      
      manually_select_sides = true;
      manually_select_handles = true;
      
      saveInSessionTmp(true);
      
      if (!shopping_cart) {
        if(status_ == 'Done') {
            //alert('Saved');
            CustomizationSaved = true;
            location.replace(path);
            //$('#customization_name').val('');
            //loadCustomization();
            //$('#customizationtool > ul').tabs({selected:0});
        }
        else {
            _unblockUI();
            alert(status_);
        }
      }
  });
}

function showEditLink() {
    $('#customizationtool > ul').tabs("enable", 3);
    $('#editlink').click();  
}

/*function loadCustomDebug() {
  $.get(customizationHref, {action: 'loadfromsession', products_id: $('#prod_qty').val()},function(data){
    saved = data;
    if(saved!="") {
    //        if(confirm('Load previous customization?')) {
    //                        eval(saved);
            $.post(customizationHref, {action: 'clearsavedcustomization'},function(xml){});        
        //}
        //else {
        //    $.post(customizationHref, {action: 'clearsavedcustomization'},function(xml){});
        //}
    }
  });    
}
*/
    
function loadclipart(id) {
  $.get(customizationHref, {cc_id: id, action: 'loadclipart', products_id: $('#prod_qty').val()},function(data){
      xml = data;
      $('#clipartimages').html(data);
      $('#clipartimages').show();
      $('#selectclipartcontent').hide();
      $('#reselectclipart_lst').show();
      selectUsedColors('new_clipart_id_');
  });
}

function updateUsedColors(color) {
    used_colors[used_colors.length] = color;
}

function saveInSessionTmp(clean, callback) {
  var qty, bag_color;
  /*
  qty = $('#prod_qty option:selected').html();
  if (!qty || qty == '') {
    qty = $('#prod_qty option:first').html();
  }
  */
  var product_info;
  var get_sides = true;
  var get_handles = true;
  //get_sides = manually_select_sides;
  //get_handles = manually_select_handles;
  get_sides = (fids_params.length > 0) ? true : false;
  
  if (clean == true) {
    product_info = {action: 'saveinsession_tmp'};
  } else {
    product_info = {
      action: 'saveinsession_tmp',
      category_id: $('#category_id').val(), 
      product_id: $('#products_id').val(),
      prod_size: $('#prod_size').val(),
      product_qty: $('#prod_qty option:selected').html(),
      bag_color: $('#selectedBagColor').val(),
      bag_sides: (get_sides) ? $('#selectedBagSidesOption').val() : 0, 
      bag_handles: (get_handles) ? $('#selectedBagHandlesOption').val() : 0,bag_films: $('[id=id_'+$('#bagFilmOptionId').val()+']').attr('checked'),
      customization_saved_id: $('#customization_saved_id').val()
    };
  };
  $.ajaxSetup({
    async: false
  });
  $.post(customizationHref, product_info, callback);
}

function UpdateProductTab(product_id) {
  
  action = "customization.php?product_id=" + product_id  + "&action=add_product";
  $('#addproduct').attr("action", action);
  $("#products_id").val(product_id);
  _blockUI("Update product parameters.");
  
  $.get(customizationHref, {product_id: product_id,
                            action: 'UpdateProductTab'},
    function(xml) {
      
      var data;
      
      //getcolors
      data = $('getcolors:first', xml).text();
      $('#bagcolors').html(data);
      SelectColor($('#products_id').val(), $('#selectedBagColor').val(), true, true);
      
      //getproductinfo
      productimage_ = $('productimage:first', xml).text();
      producttitle_ = $('producttitle:first', xml).text();
      $('#producttitle').html(producttitle_);
      $('#productimage').html(productimage_);
      
      //getAvaibleOptions
      data = $('getAvaibleOptions:first', xml).text();
      $('#message_options').html(data);
      
      //getsides
      data = $('getsides:first', xml).text();
      $('#bagsides').html(data);
      ChooseSides($('#selectedBagSidesOption').val(), true);
      
      //gethandles
      data = $('gethandles:first', xml).text();
      $('#baghandles').html(data);
      ChooseHandles($('#selectedBagHandlesOption').val(), true);
      
      //getfilms
      data = $('getfilms:first', xml).text();
      if(data!="") {
          $('#bagfilm').html(data);
          $('#bagfilmblock').css('display', 'block');
      }
      else {
          $('#bagfilmblock').css('display', 'none');
      }
      //getfontcolors
      data = $('getfontcolors:first', xml).text();
      $('#fontcolors').html(data);
      
      updatePrice();
      LoadSideImage($('#products_id').val(), $('#selectedBagColor').val());
      
      _unblockUI();
  });
  
  
}

function UpdateProductTabFromSessionTmp(prod_size) {
  $('#prod_size option').attr('selected', '');
  $('#prod_size [value=' +prod_size+ ']').attr('selected', 'selected');
  
  $.ajaxSetup({
    async: false
  });
  
  $.get(customizationHref, {category_id: $('#category_id').val(),
                              prod_size: prod_size,
                              action: 'getquantities'}, function(data){
        obj = $('#prod_qty');
        obj.html(data)
        obj = $('#prod_qty option:selected');
        if (!obj.val()) {
          obj = $('#prod_qty option:first');
        }
        var product_id = obj.val();
        UpdateProductTab(product_id);
  });
}

function updateFilm() {
  updatePrice();
}
