/**/
function trim(string)
{
  return string.replace(/(^\s+)|(\s+$)/g, "");
}

var updateBackgroundImage = function() {};

$(document).ready(function () {
    initBanner();
    initTextItems();

});

function initBanner() {
  $("#tcMain").tabs( {
    select: function(event, ui)
    {
      if(ui.index != 3)
      {
        itemOnTop(0);
      }
     
      if(ui.index == 4)
      {
        $('#gotonexttabbtn').css('display', 'none');
      }
      else
      {
        $('#gotonexttabbtn').css('display', 'block');
      }

      if(ui.index == 0)
      {
        $('#gotoprevtabbtn').css('display', 'none');
      }
      else
      {
        $('#gotoprevtabbtn').css('display', 'block');
      }

    }


  } );

  $('#width').keyup(function (e) {sizeChanged();});
  $('#height').keyup(function (e) {sizeChanged();});

  $('#btnSizeDialog').click(showSizeDialog);
  $('#btnApplySize').click(applySize);
  $('#btnRevertSize').click(revertSize);

  applySize();
  $("#mainBackground").tabs( {show: function(event, ui) {updateBackgroundImage();}} );

  $('#bkgSolidColorPicker').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false, onChangeHex:
      function(color) {
        $('#bkgSolidColor').attr('value', '#' + color);
        updateBackgroundImage();
			}
  });
  
  $('#bkgGradientFromColorPicker').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false, onChangeHex: 
      function(color) {
        $('#bkgGradientFromColor').attr('value', '#' + color);
        updateBackgroundImage();
			}
  });

  $('#bkgGradientToColorPicker').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false, onChangeHex: 
      function(color) {
        $('#bkgGradientToColor').attr('value', '#' + color);
        updateBackgroundImage();
			}
  });

  $("#bkgGradientTypeS").children().click(function() {
    if($(this).hasClass("ui-selected"))
    {
      return;
    }
    $(this).toggleClass("ui-selected").siblings().removeClass("ui-selected");
    var alt_var = $(this).children().attr('alt').toLowerCase();
    setBkgGradientType(alt_var);
  });
  $("#bkgGradientTypeS li:first-child").click();

  new AjaxUpload('#btnBkgImgUpload', {
    action: './banner/UploadTmpImage',
    name: 'TmpFile',
    autoSubmit: true,
    onComplete: uploadImage,
    hoverClass: 'btnBkgImgUpload_hovered_hack'
    });

  $('#bkgImageActionBlock').css('display', 'none');
  
  $('#btnBkgImageResize').click(function() {
    setBannerSize($('#bkgImageW').attr('value'),
      $('#bkgImageH').attr('value'));
    $('#bkgDisplayType').attr('value', 'stretch');
    updateBackgroundImage();
  });

  $('#btnBkgImageStretch').click(function() {$('#bkgDisplayType').attr('value', 'stretch');updateBackgroundImage();});
  $('#btnBkgImageRepeat').click(function()  {$('#bkgDisplayType').attr('value', 'repeat');updateBackgroundImage();});
  $('#btnBkgImagePart').click(function() {getImagePart();});

  $('#outerBrdWidth').slider({
			min: 0,
			max: 100,
			change: function(event, ui) {
        $('#bkgBOWidth').attr('value', ui.value);
        updateBackgroundImage();
			} 
    });
    
  $('#outerBrdOffset').slider({
			min: 0,
			max: 100,
			change: function(event, ui) {
        $('#bkgBOOffset').attr('value', ui.value);
        updateBackgroundImage();
			}
    });
    
  $('#outerBrdOpacity').slider({
			min: 0,
			max: 127,
			change: function(event, ui) {
        $('#bkgBOOpacity').attr('value', ui.value);
        updateBackgroundImage();
			}
    });

  $('#innerBrdWidth').slider({
			min: 0,
			max: 100,
			change: function(event, ui) {
        $('#bkgBIWidth').attr('value', ui.value);
        updateBackgroundImage();
			}
    });
    
  $('#innerBrdOffset').slider({
			min: 0,
			max: 100,
			change: function(event, ui) {
        $('#bkgBIOffset').attr('value', ui.value);
        updateBackgroundImage();
			}
    });
    
  $('#innerBrdOpacity').slider({
			min: 0,
			max: 127,
			change: function(event, ui) {
        $('#bkgBIOpacity').attr('value', ui.value);
        updateBackgroundImage();
			}
    });

  $('#outerBrdColor').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false, onChangeHex:  
      function(color) {
        $('#bkgBOColor').attr('value', '#' + color);
        updateBackgroundImage();
			}
  });
  
  $('#innerBrdColor').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false, onChangeHex:
      function(color) {
        $('#bkgBIColor').attr('value', '#' + color);
        updateBackgroundImage();
			}
  });

  $('#btnAddImageItem').css('display', 'none');

  /* Items */
  initBannerItems();

  $('#btnSavePng').click(function() {saveAs('png');});
  $('#btnSaveGif').click(function() {saveAs('gif');});
  $('#btnSaveJpeg').click(function() {saveAs('jpeg');});
  $('#btnSaveCode').click(function() {getCodeUrl();});

  /* ctbText */
  $('#ctbText').change(function() {markAsChanged();});
  $('#ctbText').keydown(function() {markAsChanged();});
  
  // $('#ctbTextSize > a').click(function() { markAsChanged(); });
  // $('#ctbTextAngle > a').click(function() { markAsChanged(); });
  // $('#ctbTextOpacacity > a').click(function() { markAsChanged(); });
  // $('#ctbTextShadowOffset > a').click(function() { markAsChanged(); });
  // $('#ctbTextOutlineOffset > a').click(function() { markAsChanged(); });
  // $('#ctbTextShadowPos').click(function() { markAsChanged(); });

  updateBackgroundImage = updateBackgroundImageEx;
  updateBackgroundImage();
  markAsUnChanged();
}
/*Dialogs*/
var activeDialog = 0;
var dialogsCache = new Object();

function showSimpleDialog(type) {
  if(dialogsCache[type] == undefined)
  {
    $.get("./banner/GetDialog", {id: type},
      function(data){
        var dlg = $(data);
        activeDialog = dlg;
        dialogsCache[type] = activeDialog;
        activeDialog.dialog({zIndex: 100000, bgiframe: true, modal: true, width: 978, height: 600, draggable: false, resizable: false});
        });
  }
  else
  {
    activeDialog = dialogsCache[type];
    activeDialog.dialog('open');
  }
}

function showCropDialog(_params) {
	$.get("banner/GetDialog", {id: 'cropimagedialog', params: $.toJSON(_params)},
  function(data){
  	activeDialog = $(data);
  	activeDialog.dialog({zIndex: 100000, bgiframe: true, modal: true, width: 978, height: 600, draggable: false, resizable: false, close: function(event, ui) {destroyActiveDialog();}});
  	});
	}
  
function destroyActiveDialog() {
	if(activeDialog !== 0)
  {
    activeDialog.dialog('destroy');
    activeDialog.remove();
    activeDialog = 0;
  }
}

function closeActiveDialog() {
	if(activeDialog !== 0)
  {
    activeDialog.dialog('close');
    activeDialog = 0;
  }
}

/* SIZE FUNCTIONS */
function setBannerSize(w, h) {
  $('#width').attr('value', w);
  $('#height').attr('value', h);
  applySize();
}

function showSizeDialog() {
  showSimpleDialog("sizedialog");
}

function getRealWidth() {
  return parseInt($('#bannerBlock').css('width'));
}

function getRealHeight() {
  return parseInt($('#bannerBlock').css('height'));
}

function sizeChanged() {
  var new_w = parseInt($('#width').attr('value'));
  var new_h = parseInt($('#height').attr('value'));

  var w = getRealWidth();
  var h = getRealHeight();
  
  if(isNaN(new_w))
  {
    new_w = w;
    $('#width').attr('value', new_w);
  }
  if(isNaN(new_h))
  {
    new_h = h;
    $('#height').attr('value', new_h);
  }

  if(new_w == w && new_h == h)
  {
    $('#sizeControlButtons').css('display', 'none');
  }
  else
  {
    $('#sizeControlButtons').css('display', 'inline');
  }
}

function applySize() {
  var new_w = parseInt($('#width').attr('value'));
  var new_h = parseInt($('#height').attr('value'));

  $('#bannerBlock').width(Number(new_w));
  $('#bannerBlock').height(Number(new_h));
  sizeChanged();
  
  updateBackgroundImage();
}

function revertSize() {
  var w = getRealWidth();
  var h = getRealHeight();

  $('#width').attr('value', w);
  $('#height').attr('value', h);

  sizeChanged();
}

/**********************************************************************************/
/*Background color*/
/**********************************************************************************/
function setBkgGradientType(type_name) {
  $('#bkgGradientImage').attr('alt', type_name);
  $('#bkgGradientType').attr('value', type_name);
  $('#bkgGradientImage').attr('src', './images/gradient/' + type_name + '.gif');
  updateBackgroundImage();
}

function setBkgImage(file, dsp_type) {
  $('#bkgImagePreview').attr('src', './banner/GetTmpImage?file=' + file + '&w=90&h=90');
  $('#bkgImageFile').attr('value', file);
  $('#bkgDisplayType').attr('value', dsp_type);
}

function uploadImage(file, response) {
  var val = $.evalJSON(response);
  if(val.file)
  {
    $('#bkgImageActionBlock').css('display', 'block');
    
    setBkgImage(val.file, 'stretch');

    $('#bkgImageW').attr('value', val.w);
    $('#bkgImageH').attr('value', val.h);

    $('#bkgImagePartX').attr('value', '');
    $('#bkgImagePartY').attr('value', '');
    $('#bkgImagePartW').attr('value', '');
    $('#bkgImagePartH').attr('value', '');



    updateBackgroundImage();
  }
  else if(val.error) {alert(val.error);}
  else {alert('Error');}
}

function acceptImagePart(file, x, y, w ,h) {
  setBkgImage(file, 'part');
  $('#bkgImagePartX').attr('value', x);
  $('#bkgImagePartY').attr('value', y);
  $('#bkgImagePartW').attr('value', w);
  $('#bkgImagePartH').attr('value', h);

  destroyActiveDialog();
  updateBackgroundImage();
}

function getImagePart() {
  var image_src = $('#bkgImageFile').attr('value');
  getImagePartByImage(image_src);
}

function getImagePartByImage(image_src) {
  if (!image_src.length)
  {
    return;
  }
  
  var w = getRealWidth();
  var h = getRealHeight();

  var p_x = parseInt($('#bkgImagePartX').attr('value'));
  var p_y = parseInt($('#bkgImagePartY').attr('value'));
  var p_w = parseInt($('#bkgImagePartW').attr('value'));
  var p_h = parseInt($('#bkgImagePartH').attr('value'));

  if(isNaN(p_x) || isNaN(p_y) || isNaN(p_w) || isNaN(p_h))
  {
    showCropDialog({image: image_src, bw: w, bh: h});
  }
  else
  {
    showCropDialog({image: image_src, bw: w, bh: h, px: p_x, py: p_y, pw: p_w, ph: p_h});
  }
}

/**********************************************************************************/
/* Items */
/**********************************************************************************/
 var Items = new Array();
 var ActiveItem = 'undefined';
 var MaxItemIndex = -1;

 /*CONTROL*/
  var ItemText = 0;
  var ItemTextSize = 0;
  var ItemTextColor = 0;
  var ItemTextAngle = 0;
  var ItemTextOpacacity = 0;

  var ItemTextShadow = new Object();

  var ItemTextShadowOffset = 0;
  var ItemTextShadowColor = 0;
  var ItemTextOutlineOffset = 0;
  var ItemTextOutlineColor = 0;

  var zTop = 10000;
  var zBottom = zTop;


  function initBannerItems()
  {
    $('#btnAddTextItem').click(function() {addNewTextItem();});
    $('#btnAddImageItem').click(function() {addNewImageItem();});

    $('#btnDeleteItem').click(function() {deleteActiveItem();});
    $('#btnItemOnTop').click(function() {upActiveItem();});
    $('#btnItemOnBottom').click(function() {downActiveItem();});

    $('#ctbTextFont').click(function() {showSimpleDialog('TextItemFontDialog');});

    $('#btnApplyItemChanges').click(function() {setActiveItem();});
    $('#bannerBkgImg').click(function() {itemOnTop(0);});

    $('#ctbImageCrop').click(function() {cropActiveImageItem();});
    ItemText = $('#ctbText');

    ItemTextSize = $('#ctbTextSize').slider({
			min: 8,
			max: 60,
      step: 2,
      value: 8,
			change: function(event, ui) {
        $(this).attr('value', ui.value + 'px');
        markAsChanged();
			}
    }
    );
      
    ItemTextAngle = $('#ctbTextAngle').slider({
			min: 0,
			max: 360,
      step: 1,
      value: 0,
			change: function(event, ui) {
        $(this).attr('value', ui.value + '');
        markAsChanged();
			}
    }
    );

    ItemTextOpacacity = $('#ctbTextOpacacity').slider({
			min: 0,
			max: 127,
      step: 1,
      value: 0,
			change: function(event, ui) {
        $(this).attr('value', ui.value + '');
        markAsChanged();
			}
    }
    );

    $('#ctbTextShadowPos').click(function() {showSimpleDialog('TextItemShadowDialog');});

    ItemTextShadowOffset = $("#ctbTextShadowOffset").slider({
			min: 0,
			max: 8,
      step: 1,
      value: 0,
			change: function(event, ui) {
        $(this).attr('value', ui.value + '');
        markAsChanged();
			}
    }
    );
    
    ItemTextShadowColor = $("#ctbTextShadowColor").ColorPicker({flat: true, color: '#000',
      livePreview: false,
      onChangeHex: function(color) {
        markAsChanged();
      }
    });
    
    ItemTextOutlineOffset = $("#ctbTextOutlineOffset").slider({
			min: 0,
			max: 8,
      step: 1,
      value: 0,
			change: function(event, ui) {
        $(this).attr('value', ui.value + '');
        markAsChanged();
			}
    }
    );

    ItemTextOutlineColor = $("#ctbTextOutlineColor").ColorPicker({flat: true, color: '#000',
      livePreview: false,
      onChangeHex: function(color) {
        markAsChanged();
      }
    });

    ItemTextColor = $('#ctbTextColor').ColorPicker({flat: true, color: '#32fa32',
    livePreview: false,
      onChangeHex: function(color) {
        markAsChanged();
      }
    });

    new AjaxUpload('#ctbImageUpload', {
      action: './banner/UploadTmpImage',
      name: 'TmpFile',
      autoSubmit: true,
      onComplete: uploadItemImage
    });
    
    itemOnTop(0);
  }
  
function cropActiveImageItem()
{
  if(ActiveItem != 0 && ActiveItem['Type'] == 'Image')
  {
    if(ActiveItem['Src'] != '')
    {
      var w = getRealWidth();
      var h = getRealHeight();

      var p_x = ActiveItem['PX'];
      var p_y = ActiveItem['PY'];
      var p_w = ActiveItem['PW'];
      var p_h = ActiveItem['PH'];
      var image_src = ActiveItem['Src'];

      if(p_x == '' || p_y == '' || p_w == '' || p_h  == '')
      {
        showCropDialog({image: image_src, bw: w, bh: h, maxW: w, maxH: h});
      }
      else
      {
        showCropDialog({image: image_src, bw: w, bh: h, px: p_x, py: p_y, pw: p_w, ph: p_h, maxW: w, maxH: h});
      }
    }
  }
}
function updateImageActiveItemAttr() {
  if(ActiveItem != 0 && ActiveItem['Type'] == 'Image')
  {
    if(ActiveItem['Src'] != '')
    {
      $('#ctbImagePreview').attr('src', './banner/GetTmpImage?file=' + ActiveItem['Src'] + '&w=90&h=90');
    }
    else
    {
      var item = $("#" + ActiveItem['id']);
      $('#ctbImagePreview').attr('src', item.attr('src'));
    }
  }
}

function uploadItemImage(file, response) {
  if(ActiveItem != 0 && ActiveItem['Type'] == 'Image')
  {
    var item = $("#" + ActiveItem['id']);
    var val = $.evalJSON(response);
    if(val.file)
    {
      ActiveItem['Src'] = val.file;
      ActiveItem['PX'] = '';
      ActiveItem['PY'] = '';
      ActiveItem['PW'] = '';
      ActiveItem['PH'] = '';
      updateImageActiveItemAttr();
      updateActiveItem();
      return;
    }
  }

  if(val.error)
  {
    alert(val.error);
  }
  else
  {
    alert('Error');
  }
}

  function getNewItemTemplate(type)
  {
    MaxItemIndex = MaxItemIndex + 1;
    var NewActiveItem = new Object();

    NewActiveItem['Type'] = type;
    NewActiveItem['idx'] = MaxItemIndex;
    NewActiveItem['id'] = "BannerItem" + MaxItemIndex;
    
    return NewActiveItem;
  }

  function addNewItemTemplate(NewActiveItem)
  {
   var img = "<img id='" + NewActiveItem['id'] + "' style='position: absolute; z-index: auto; left: " +
     $("#bannerBkgImg").position().left + "px; top: " + $("#bannerBkgImg").position().top + "px;' />";

   $('#bannerBlock').append(img);
   var item = $("#" + NewActiveItem['id']);


   /**
    *  ЕСЛИ ТЕБЕ НАДО УЗНАТЬ ПОЗЦИЮ АЙТЕМА _ РАССКОМЕННТИРУЙ И 2 РАЗА КЛАЦНИ ! :)
    **/
   /*item.dblclick(function() {
     var t = "x: " + ActiveItem['X'] + " y: " + ActiveItem['Y'];
     alert(t);
   });*/

   item.mousedown(function() {
     
     var id = parseInt(this.id.substr(10));
     var item = Items[id];

     $("#tcMain").tabs("select" , 3);
     
     itemOnTop(item);
   });
   item.draggable({containment: 'parent', zIndex: zTop, snap: '#ItemsBlock',
    drag: function(event, ui)
    {
      var id = parseInt(this.id.substr(10));
      var item = Items[id];
      var pos_x = $("#" + this.id).position( ).left - $("#bannerBkgImg").position( ).left;
      var pos_y = $("#" + this.id).position( ).top - $("#bannerBkgImg").position( ).top;
      item['X'] = pos_x;
      item['Y'] = pos_y;
    }
   }
   );
   
   NewActiveItem['X'] = item.position( ).left - $("#bannerBkgImg").position( ).left;
   NewActiveItem['Y'] = item.position( ).top - $("#bannerBkgImg").position( ).top;

   Items[MaxItemIndex] = NewActiveItem;

   itemOnTop(NewActiveItem);
   updateActiveItem();
   upActiveItem();
  }

  function addNewImageItem()
  {
    var NewActiveItem = getNewItemTemplate('Image');

    NewActiveItem['Src'] = '';
    
    addNewItemTemplate(NewActiveItem);
  }

  function setActiveItemPos(x, y)
  {
    var aid = '#' + ActiveItem['id'];
    $(aid).css("left", $("#bannerBkgImg").position().left + x);
    $(aid).css("top", $("#bannerBkgImg").position().top + y);

    ActiveItem['X'] = x;
    ActiveItem['Y'] = y;
  }

  function initTextItems()
  {
    addNewTextItem();
    ActiveItem['Text'] = 'Click here and edit text in the field below!';
    ActiveItem['TextSize'] = 16;
    ActiveItem['TextFont'] = 'main/Baroque Script.ttf';
    ActiveItem['TextColor'] = '#345559';
    ActiveItem['TextOutlineOffset'] = 0;
    setActiveItemPos(65, 20);
    Items[ActiveItem['idx']] = ActiveItem;
    updateActiveItem();
  
    markAsUnChanged();
    itemOnTop(0);
 }
  
 function addNewTextItem()
 {
   var NewActiveItem = getNewItemTemplate('Text');
   
   NewActiveItem['Text'] = 'New text item';
   NewActiveItem['TextSize'] = 23;
   NewActiveItem['TextColor'] = '#00AAFF';
   NewActiveItem['TextFont'] = 'main/arial.ttf';
   NewActiveItem['TextAngle'] = 0;
   NewActiveItem['TextOpacacity'] = 0;

   NewActiveItem['TextShadow'] = new Object();
   NewActiveItem['TextShadow']['Type'] = 'NN';
   NewActiveItem['TextShadow']['Name'] = 'No shadow';

   NewActiveItem['TextShadowOffset'] = 2;
   NewActiveItem['TextShadowColor'] = '#999999';
   NewActiveItem['TextOutlineOffset'] = 0;
   NewActiveItem['TextOutlineColor'] = '#DDDDDD';

   addNewItemTemplate(NewActiveItem);
   markAsUnChanged();
 }

 function deleteActiveItem()
 {
   if(ActiveItem != 0)
   {
     var item = $("#" + ActiveItem['id']);
     Items[ActiveItem['idx']] = 0;
     itemOnTop(0);
     item.remove();
   }
 }

 function upActiveItem()
 {
   if(ActiveItem != 0)
   {
     zTop = zTop + 1;
     var item = $("#" + ActiveItem['id']);
     item.css('z-index', zTop);
   }
 }

 function downActiveItem()
 {
   if(ActiveItem != 0)
   {
     zBottom = zBottom - 1;
     var item = $("#" + ActiveItem['id']);
     item.css('z-index', zBottom);
   }
 }

 function setTextItemFont(text)
 {
   $('#ctbTextFont').attr('alt', text);
   $('#ctbTextFont').attr('src', './banner/GetFontImage?res=' + text);
   markAsChanged();
   closeActiveDialog();
 }

 function setShadow(type, name)
 {
   $('#ctbTextShadowPos').attr('alt', name);
   $('#ctbTextShadowPos').attr('src', './img/shadow/' + type + '.png');
   ItemTextShadow['Type'] = type;
   ItemTextShadow['Name'] = name;

   if(type != "NN")
   {
     
   }
 }

 function setTextItemShadow(type, name)
 {
   setShadow(type, name);
   markAsChanged();
   closeActiveDialog();
 }

 function makeItemJSON(item)
 {
   var json
   if(item['Type'] == 'Text')
   {
     json = {
       X : item['X'],
       Y : item['Y'],
       Type : item['Type'],
       Text : item['Text'],
       TextSize : item['TextSize'],
       TextColor : item['TextColor'],
       TextFont : item['TextFont'],
       TextAngle : item['TextAngle'],
       TextOpacacity : item['TextOpacacity'],
       TextShadow : item['TextShadow']['Type'],
       TextShadowOffset : item['TextShadowOffset'],
       TextShadowColor : item['TextShadowColor'],
       TextOutlineOffset : item['TextOutlineOffset'],
       TextOutlineColor : item['TextOutlineColor']
     }
     return json;
   }
   else if(item['Type'] == 'Image')
   {
     json = {
       Type : item['Type'],
       Src : item['Src'],
       ImageX : item['PX'],
       ImageY : item['PY'],
       ImageW : item['PW'],
       ImageH : item['PH'],
       BannerW: getRealWidth(),
       BannerH: getRealHeight()
     }
     return json;
   }

   return 0;
 }

 function setActiveItem()
 {
   if(ActiveItem != 0)
   {
     if(ActiveItem['Type'] == 'Text')
     {
         /** COPY **/
       ActiveItem['Text'] = trim($('#ctbText').attr('value'));
       ActiveItem['TextSize'] = ItemTextSize.slider('value');

       ActiveItem['TextColor'] = $(ItemTextColor).ColorPickerGetColor();
       ActiveItem['TextFont'] = $('#ctbTextFont').attr('alt');
       ActiveItem['TextAngle'] = ItemTextAngle.slider('value');
       ActiveItem['TextOpacacity'] = ItemTextOpacacity.slider('value');
       ActiveItem['TextShadow'] = ItemTextShadow;

       ActiveItem['TextShadowOffset'] = ItemTextShadowOffset.slider('value');
       ActiveItem['TextShadowColor'] = ItemTextShadowColor.ColorPickerGetColor();
       ActiveItem['TextOutlineOffset'] = ItemTextOutlineOffset.slider('value');
       ActiveItem['TextOutlineColor'] = ItemTextOutlineColor.ColorPickerGetColor();
     }
     else if(item['Type'] == 'Image')
     {

     }
     
     Items[ActiveItem['idx']] = ActiveItem;
     updateActiveItem();

     markAsUnChanged();

     //$('#btnApplyItemChanges').css('color', '#F60');
     //$('#btnApplyItemChanges').css('border', '1px solid #F60');
   }
 }
 
 function updateActiveItem()
 {
   if(ActiveItem != 0)
   {
     var json = makeItemJSON(ActiveItem);
     if(json != 0)
     {
       var item = $("#" + ActiveItem['id']);
       item.attr('src', 'banner/GetItem?p=' + $.URLEncode($.toJSON(json)));
     }
   }
 }

 function itemOnTop(item)
 {
   if(ActiveItem == item)
     return;

   if(item != ActiveItem && ActiveItem != 0)
   {
     var i = $("#" + ActiveItem['id']);
     i.css('border', '1px solid transparent');
   }

   ActiveItem = item;
   if(ActiveItem == 0)
   {
     $('#ControlImageBlock').hide();
     $('#ControlTextBlock').hide();
     $('#ControlInfoBlock').show();

     $("#btnApplyItemChanges").hide();
     $("#btnDeleteItem").hide();
     $("#btnItemOnTop").hide();
     $("#btnItemOnBottom").hide();
   }
   else if(ActiveItem['Type'] == 'Text')
   {
     //var changed_state = ActiveItem['changed'];
     
     var item = $('#' + ActiveItem['id']);
     item.css('border', '1px dashed red');
       
     $('#ControlImageBlock').hide();
     $('#ControlInfoBlock').hide();
     $('#ControlTextBlock').show();

     $("#btnApplyItemChanges").show();
     $("#btnDeleteItem").show();
     $("#btnItemOnTop").show();
     $("#btnItemOnBottom").show();
     /** COPY **/
     ItemText.attr('value', ActiveItem['Text']);
     ItemTextSize.slider('value', ActiveItem['TextSize']);
     
     $(ItemTextColor).ColorPickerSetColor(ActiveItem['TextColor'].substr(1));
     setTextItemFont(ActiveItem['TextFont']);
     ItemTextAngle.slider('value', ActiveItem['TextAngle']);
     ItemTextOpacacity.slider('value', ActiveItem['TextOpacacity']);

     setShadow(ActiveItem['TextShadow']['Type'], ActiveItem['TextShadow']['Name']);

     ItemTextShadowOffset.slider('value', ActiveItem['TextShadowOffset']);
     ItemTextShadowColor.ColorPickerSetColor(ActiveItem['TextShadowColor'].substr(1));
     ItemTextOutlineOffset.slider('value', ActiveItem['TextOutlineOffset']);
     ItemTextOutlineColor.ColorPickerSetColor(ActiveItem['TextOutlineColor'].substr(1));

/*     if(changed_state == true)
     {
        markAsChanged();
     }
     else
     {
       markAsUnChanged();
     }*/

   }
   else if(ActiveItem['Type'] == 'Image')
   {
     $('#ControlTextBlock').hide();
     $('#ControlInfoBlock').hide();
     $('#ControlImageBlock').show();

     $("#btnApplyItemChanges").hide();
     $("#btnDeleteItem").show();
     $("#btnItemOnTop").show();
     $("#btnItemOnBottom").show();
     
     updateImageActiveItemAttr();
   }
   markAsUnChanged();
 }

/**********************************************************************************/
/* SAVE*/
/**********************************************************************************/
function getBkgParams()
{
   /* Вот это я наворотил :))  блин точно Димыч, черт ногу сломит */
  var selected = $('#mainBackground').tabs('option', 'selected'); // => 0

  var bkg = {};
  if(selected == 0)
  {
    bkg = {
      type: "solid",
      color: $("#bkgSolidColor").attr('value')
    }
  }
  else if(selected == 1)
  {
    bkg = {
      type: "gradient",
      from: $("#bkgGradientFromColor").attr('value'),
      to: $("#bkgGradientToColor").attr('value'),
      grad: $("#bkgGradientType").attr('value')
    }
  }
  else if(selected == 2)
  {
    bkg = {
      type: "image",
      file: $('#bkgImageFile').attr('value'),
      dsp: $('#bkgDisplayType').attr('value')
    }
    if($('#bkgDisplayType').attr('value') == "part")
    {
      bkg.bkgImagePartX = $('#bkgImagePartX').attr('value');
      bkg.bkgImagePartY = $('#bkgImagePartY').attr('value');
      bkg.bkgImagePartW = $('#bkgImagePartW').attr('value');
      bkg.bkgImagePartH = $('#bkgImagePartH').attr('value');
    }
  }

  var bi = {
    w: $('#bkgBIWidth').attr('value'),
    offset: $('#bkgBIOffset').attr('value'),
    opac: $('#bkgBIOpacity').attr('value'),
    color: $('#bkgBIColor').attr('value')
  }

  var bo = {
    w: $('#bkgBOWidth').attr('value'),
    offset: $('#bkgBOOffset').attr('value'),
    opac: $('#bkgBOOpacity').attr('value'),
    color: $('#bkgBOColor').attr('value')
  }

  var _items = new Array();
  for (i = 0; i < Items.length; i++)
  {
    if(Items[i] != 0)
      _items.push(Items[i]);
  }

  var banner = {
    w: getRealWidth(),
    h: getRealHeight(),
    bkg: bkg,
    bi: bi,
    bo: bo
  }

  return banner;
}

function tmp_items_sort_func_(i1, i2)
{
  var item1 = $("#" + i1['id']);
  var z_index1 = item1.css('z-index');

  var item2 = $("#" + i2['id']);
  var z_index2 = item2.css('z-index');

  if(parseInt(z_index1) > parseInt(z_index2))
    return 1;
  else if(parseInt(z_index1) < parseInt(z_index2))
    return -1;
  else
    return 0;
}

function makeBannerParams()
{
  /* Вот это я наворотил :)) */
  var banner = getBkgParams();

  var _items = new Array();
  for(var i = 0; i < Items.length; i++)
  {
    var item_data = Items[i];
    if(item_data != 0 || item_data != 'null' || item_data != 'undefined')
    {
      _items.push(item_data);
    }
  }

  _items.sort(tmp_items_sort_func_);

  banner.items = new Array();

  for(var i2 = 0; i2 < _items.length; i2++)
  {
    var item_json = makeItemJSON(_items[i2]);
    banner.items.push(item_json);
  }

  return banner;
}

function getCodeUrl()
{
  var banner = makeBannerParams();
  banner.type = 'png';

  $.get("banner/GetCodeDialog", {value: $.toJSON(banner)}, 
  function(data) {
  	activeDialog = $(data);
  	activeDialog.dialog({zIndex: 100000, bgiframe: true, modal: true, width: 978,
      height: 600, draggable: false, resizable: false,
      close: function(event, ui) {destroyActiveDialog();}});
  	});
}

function saveAs(type)
{
  var banner = makeBannerParams();

  banner.type = type;
  
  top.location.href='banner/GetBanner?p=' + $.URLEncode($.toJSON(banner));
}
/**********************************************************************************/
/* Image update*/
/**********************************************************************************/
function updateBackgroundImageEx() {
  var banner = getBkgParams();
  $('#bannerBkgImg').attr('src', 'banner/BackgroundImage?p=' + $.URLEncode($.toJSON(banner)));
}

/***/
function tmp_copy_content(val)
{
   val.select();
   var text = val.value();
   text.execCommand("copy");
   text.execCommand("RemoveFormat");
}

function markAsChanged()
{
  if(ActiveItem != 0)
  {
    // $("#applyHelpMessBlock").css('display', 'block');
    
    ActiveItem['changed'] = true;
    $('#btnApplyItemChanges').css('color', '#F60');
    $('#btnApplyItemChanges').css('border', '1px solid #F60');
  }
  
}

function markAsUnChanged()
{
  if(ActiveItem != 0)
  {
    ActiveItem['changed'] = false;
  }

  // $("#applyHelpMessBlock").css('display', 'none');
  $('#btnApplyItemChanges').css('color', '#EEE');
  $('#btnApplyItemChanges').css('border', '1px solid #777');
}



function gotonexttab()
{
  var selected = $("#tcMain").tabs("option", "selected");
  selected = selected + 1;
  $("#tcMain").tabs("select" , selected);    
}

function gotoprevtab()
{
  var selected = $("#tcMain").tabs("option", "selected");
  $("#tcMain").tabs("select" , selected - 1);
}


