var preview_url = '/shop/text.img'; 
var product_url = '/shop/product.html';
var images_url = '/shop/tee-images/';var menu_first_id = 'menu-first-page';
var menu_second_id = 'menu-second-page';
var preview_timeout;
var product_status_timeout;
var emptyString = /^s*$/;
var ie=document.all;
var nn6=document.getElementById&&!document.all;

//var waitImg = new Image();
//waitImg.src = images_url + 'ProductWait.gif';

function trim(str)
{
  return str.replace(/^s+|s+$/g, '');
}

function timestamp()
{
  var now = new Date();
  var time_stamp =   now.getFullYear().toString() + now.getMonth().toString() + now.getDay().toString() + 
  now.getHours().toString() + now.getMinutes().toString() + now.getSeconds().toString();
  return (time_stamp);
} 

function UpdatePreviewDelayed(doc)
{
  if('undefined' == typeof doc)
  {
    doc = document;
  }

  clearTimeout(preview_timeout);
  Update = function () {UpdatePreview(doc);}
 
  preview_timeout = setTimeout('Update()', 500);
}

function UpdatePreview(doc)
{
  var font_size;
  var all_text;
  var font;
  var fill;
  
  if('undefined' == typeof doc)
  {
    doc = document;
  }

  all_text = doc.getElementById('custom-text').value;

  var font_sizeRE = /^[0-9]{1,3}$/;
  if(doc.getElementById('id-font-size'))
  {
    font_size = trim(doc.getElementById('id-font-size').value);
    if (emptyString.test(font_size) || !font_sizeRE.test(font_size) || font_size < 40)
    {
      return;
    }
  }

  if (doc.getElementById('id-font-family'))
  {
    font = doc.getElementById('id-font-family').value;
  }

  if(doc.getElementById('fill-id'))
  {
    fill = doc.getElementById('fill-id').value;
  }

  var url = preview_url + 
  '?image-id=' + doc.curr_image_id +
  '&text=' + escape(all_text) + 
  '&font=' + escape(font) + 
  '&size=' + escape(font_size) + 
  '&fill=' + escape(fill) + 
  '&timestamp=' + timestamp();

  doc.TextCtrlObj.newUrl(url);
}

function UpdatePreviewIfTextValid()
{
  ajax_validate_text_callback(
      function(res)
      {
          if(res == 'pass') 
          {
             UpdatePreviewDelayed();
          }
          else
          {
            document.getElementById('custom-text').value = '';
            alert('Please, use latin letters!');
          }
      }
      , document.getElementById('custom-text').value);
}

function ChangeMerch()
{
  var merch;

  if(document.getElementById('id-merch'))
  {
    merch = document.getElementById('id-merch').value;
  }

  if (document.getElementById('txt-selected-merch') && document.getElementById('id-merch'))
  {
    document.getElementById('txt-selected-merch').innerHTML = document.getElementById('id-merch').value;
  }
  ajax_set_current_merch_callback(function(res)
  {
      var merch_prop = res.split(';');
      var image_src = merch_prop[0];
      var price = merch_prop[1];
      var colors = merch_prop[2];
      var sizes = merch_prop[3];
      document.getElementById('merch-preview-img').src = image_src;
      document.getElementById('merch-preview-price').innerHTML = '$' + price;
      if(colors)
      {
          document.getElementById('merch-preview-colors').style.display = 'block';
          document.getElementById('merch-preview-colors-hint').onmouseover = function onmouseover(event)
          {
              showhint(colors, this, event, '150px');
          }
      }
      else
      {
          document.getElementById('merch-preview-colors').style.display = 'none';
      }
      if(sizes)
      {
          document.getElementById('merch-preview-sizes').style.display = 'block';
          document.getElementById('merch-preview-sizes-hint').onmouseover = function onmouseover(event)
          {
              showhint(sizes, this, event, '150px');
          }
      }
      else
      {
          document.getElementById('merch-preview-sizes').style.display = 'none';
      }

  }, merch);
}

function SetFontValue (elem_id)
{
  window.opener.document.getElementById('id-font-family').value = document.getElementsByName('fontsel')[elem_id].value;
  UpdatePreview(window.opener.document);
}

function HandleFontImgClk(elem_id)
{
  document.getElementsByName('fontsel')[elem_id].checked=true;
  SetFontValue(elem_id);
}

function FontWndClose()
{
  for (var i = 0; i < document.getElementsByName('fontsel').length; i++)
  {
     if(document.getElementsByName('fontsel')[i].checked)
     {
       SetFontValue(i);
     }
  }
  window.close();
}

function ChangeFont(font_page, width, height)
{
  window.open (font_page.href, null, 
	'menubar=no, location=no, toolbar=no, resizable=1,left=10,top=250, width=' + width + ',height=' + height);
  return false;
}

function UploadImage(link)
{
  window.open (link.href , null, 'menubar=no, location=no, toolbar=no, resizable=1,left=10,top=250, width=350,height=130');
  return false;
}

function ShowMerchDetail(DetailPage)
{
  window.open (DetailPage, null, 
	'menubar=no, location=no, toolbar=no, resizable=1,left=10,top=10,width=650,height=600');
}

function PickColor()
{
  cp.select(document.forms[0].fill, 'ColorPickerId', UpdatePreview);
  return false;
}

function DecFontSize()
{
  var Val =  parseInt(document.getElementById('id-font-size').value);
  var NewVal = Val - 10;
  if(NewVal <= 30)
  {
    return;
  }
  document.getElementById('id-font-size').value = NewVal;
  UpdatePreviewDelayed();
}

function IncFontSize()
{
  var Val =  parseInt(document.getElementById('id-font-size').value);
  var NewVal = Val + 10;
  if(NewVal >= 1000)
  {
    return;
  }
  document.getElementById('id-font-size').value = NewVal;
  UpdatePreviewDelayed();
}

function UpdateProductProgress()
{
  ajax_update_html_element_set_element('prod_progress_' + document.curr_image_id, 'update-progress'); 
  clearTimeout(product_status_timeout);
  product_status_timeout = setTimeout('UpdateProductProgress()', 1000);
}

function CreateProduct()
{
  //window.location.href = product_url;
  document.getElementById('btnCreateProd').style.cursor='wait';
  document.getElementById('btnCreateProd').value= ' Please wait... ';
  document.getElementById('btnCreateProd').disabled = true;
  document.getElementById('product-status-' + document.curr_image_id).style.display = 'block';
  if(document.curr_text_img)
  {
    document.curr_text_img.style.display = 'none';
  }
  document.curr_bg_img.src = images_url + 'ProductWait2.gif';
  clearTimeout(product_status_timeout);
  product_status_timeout = setTimeout('UpdateProductProgress()', 1000);
  ajax_create_product_callback(function(res){window.location.href = res;}, '');
}

function ShowHideSides(menu_num)
{
  document.getElementById(menu_first_id).className = '';
  document.getElementById(menu_second_id).className = '';

  if(menu_num == 1)
  {
    document.getElementById(menu_first_id).className = 'current';
    document.getElementById('main-' + front_image_id.toString()).style.display = '';
    document.getElementById('main-' + back_image_id.toString()).style.display = 'none';
    document.getElementById('hidden-current-image-id').value = front_image_id;
    document.curr_image_id = front_image_id;
  }
  else
  {
    document.getElementById(menu_second_id).className = 'current';
    document.getElementById('main-' + back_image_id.toString()).style.display = '';
    document.getElementById('main-' + front_image_id.toString()).style.display = 'none';
    document.getElementById('hidden-current-image-id').value = back_image_id;
    document.curr_image_id = back_image_id;
  }
  document.getElementById('divImgLayoutCtrl-' + document.curr_image_id).style.visibility = 'visible';
  document.curr_text_img = document.getElementById('text-image-' + document.curr_image_id);
  document.curr_bg_img = document.getElementById('design-preview-' + document.curr_image_id);
}

function updatePhoto (doc)
{
  //todo: update style of the image to get-shrunk-photo-style-str
  document.PhotoCtrlObj.setWaitCursor();
  document.PhotoCtrlObj.newUrl('/shop/uploaded.img?timestamp=' + timestamp());
}

function OnDesignLoad(curr_img_id)
{
  document.updatePhoto = updatePhoto;
  document.getElementById('hidden-current-image-id').value = curr_img_id;
  document.getElementById('divImgLayoutCtrl-' + curr_img_id).style.visibility = 'visible';

  document.curr_image_id = curr_img_id;
  document.curr_text_img = document.getElementById('text-image-' + curr_img_id);
  document.curr_bg_img = document.getElementById('design-preview-' + curr_img_id);
  
  ajax_set_current_image_id_callback(function(res){}, curr_img_id);

  if(document.getElementById(menu_first_id))
  {
    if (first_customizable_image_id == front_image_id)
    {
      document.getElementById(menu_first_id).className = 'current';
    }
    else
    {
      document.getElementById(menu_second_id).className = 'current';
    }
  }

  if(document.curr_text_img)
  {
    document.TextCtrlObj = new Mover(document.curr_text_img, document.curr_text_img,
    new Rect(0, 0, document.curr_text_img.width, document.curr_text_img.height), 
    new Rect(0, 0, document.curr_bg_img.width, document.curr_bg_img.height));
    document.TextCtrlObj.serverUpdateTextPosFn = ajax_update_design_text_pos_callback;
    document.TextCtrlObj.enableDragging();
  }

  var clickImg = document.getElementById('clickZoneImg');
  if(clickImg)
  {
    var photoImg = document.getElementById('photo-image-' + curr_img_id);
    var apertRect = new Rect(0, 0, clickImg.width, clickImg.height); // We position photoImg relative to aperture
    var photoRect = _getRect(photoImg);
    document.PhotoCtrlObj = new Mover(photoImg, clickImg, photoRect, null);
    document.PhotoCtrlObj.apertRect = apertRect;
    document.PhotoCtrlObj.zoomFactor = 1.1;
    document.PhotoCtrlObj.serverUpdatePosAndZoomFn = ajax_update_photo_pos_callback;
    document.PhotoCtrlObj.onLoadStyleUpdate = ajax_get_photo_style_callback;
    document.PhotoCtrlObj.enableDragging();
  }
}

function Rect(x, y, w, h)
{
   this.x = x;
   this.y = y;
   this.w = w;
   this.h = h;
   this.toString = function()
   {
	   return 'Rect{ x:'+this.x+', y:'+this.y+', w:'+this.w+', h:'+this.h +'}';
   };
}

function Point(x, y)
{
   this.x = x;
   this.y = y;
   this.toString = function()
   {
	   return 'Point{ x:' + this.x + ', y:' + this.y + '}';
   };
}

function _resize(obj, w, h) 
{
	w = Math.max(0, w);
	h = Math.max(0, h);
	obj.style.width = w + 'px';
	obj.style.height = h + 'px';
}

function _move(obj, x, y) 
{
	obj.style.top = '' + y + 'px';
	obj.style.left = '' + x + 'px';
}

function _getSize(obj)
{
  if(obj.style.width)
  {
    return new Point (parseInt(obj.style.width.replace('px','')), parseInt(obj.style.height.replace('px','')));
  }
  else
  {
    return new Point (obj.width, obj.height);
  }
}

function _getPos(obj)
{
  return new Point (parseInt(obj.style.left.replace('px','')), parseInt(obj.style.top.replace('px','')));
}

function _getRect(obj)
{
   var Pos =  _getPos(obj);
   var Size = _getSize(obj);
   return new Rect(Pos.x, Pos.y, Size.x, Size.y);
}

function _getCenter(obj)
{
  var Pos = _getPos(obj);
  var Size = _getSize(obj);
  return new Point(Pos.x + Size.x/2, Pos.y + Size.y/2);
}

function _getCenterRect(rect)
{
  return new Point(rect.x + rect.w/2, rect.y + rect.h/2);
}


function Mover(obj, mouseHandlerObj, dragRect, boundRect)
{
   this.drag_obj = obj;
   this.mouseHandlerObj = mouseHandlerObj;
   this.boundRect = boundRect;
   this.dragRect = dragRect;
   this.setOrigRect(dragRect);
   //if zoomFactor == 1.1 it adds +10% per zoom
   this.zoom = 1;
   this.oldCenter = _getCenter(this.drag_obj);
}

Mover.prototype.setOrigRect = function (rect)
{
   this.origDragRect = new Rect(0,0,0,0);
   for (i in rect) 
   {
      this.origDragRect[i] = rect[i];
   }
};


Mover.prototype.newUrl = function (url)
{
  this.drag_obj.src = url;
};

Mover.prototype.setWaitCursor = function ()
{
  document.body.style.cursor = 'wait';
};

Mover.prototype.calcBoundingRect = function (apertRect, dragRect)
{
    this.boundRect = new Rect(apertRect.x - (dragRect.w - apertRect.w), 
                              apertRect.y - (dragRect.h - apertRect.h), 
                              2 * (dragRect.w - apertRect.w) + apertRect.w,
                              2 * (dragRect.h - apertRect.h) + apertRect.h);
};

Mover.prototype.enableDragging = function ()
{
  var originalonmouseup = document.onmouseup;
  var originalonmousemove = null;
  var dragging = false;
  var obj = this; //for the inside handlers
  var click_pos_x, click_pos_y;
  var orig_obj_left, orig_obj_top;
  var drag_obj = this.drag_obj;
  var oldCenter = _getCenter(drag_obj);

  if(!this.boundRect && this.apertRect)
  {
    this.calcBoundingRect(this.apertRect, this.dragRect);
  }

  drag_obj.onload = function ()
  {
      if(obj.serverUpdateTextPosFn)
      {
         var newCenter = _getCenter(drag_obj);
         var offset_x = newCenter.x - oldCenter.x;
         var offset_y = newCenter.y - oldCenter.y;
     
         var newPos = new Point (parseInt(drag_obj.style.left+0) - offset_x, parseInt(drag_obj.style.top+0) - offset_y);
         obj.dragRect = _getRect(drag_obj); //get new rect as text changed
         obj.Move(newPos);

         obj.serverUpdateTextPosFn(function(res){}, drag_obj.style.left + ';' + drag_obj.style.top);
         oldCenter = _getCenter(drag_obj);
      }
      if(obj.onLoadStyleUpdate)
      {
          obj.onLoadStyleUpdate(
              function(res){
                  var arr = res.split(';'); 
                  drag_obj.style.left = arr[0];
                  drag_obj.style.top = arr[1];
                  drag_obj.style.width = arr[2];
                  drag_obj.style.height = arr[3];
                  obj.dragRect = _getRect(drag_obj);
                  obj.setOrigRect(obj.dragRect);
                  obj.calcBoundingRect(obj.apertRect, obj.dragRect);
              }, '');
      }
      document.body.style.cursor = 'auto';
  };

  this.limitMove = function (pt)
  {
     if(obj.boundRect)
     {
       pt.x = Math.min(pt.x, (obj.boundRect.x + obj.boundRect.w) - obj.dragRect.w);
       pt.x = Math.max(obj.boundRect.x, pt.x);
       pt.y =  Math.min(pt.y, (obj.boundRect.y + obj.boundRect.h) - obj.dragRect.h);
       pt.y =  Math.max(obj.boundRect.y, pt.y);
       obj.dragRect.x = pt.x;
       obj.dragRect.y = pt.y;
     }
  };

  this.Move = function (pt)
  {
     obj.limitMove(pt);
     _move(drag_obj, pt.x, pt.y);
  };

  this.Zoom = function (delta)
  {  
     var Factor = (delta > 0) ? obj.zoomFactor:(1 / obj.zoomFactor);
     var newW = obj.zoom * Factor * obj.origDragRect.w;
     var newH = obj.zoom * Factor * obj.origDragRect.h;
     if( Math.min(newW, newH) <= Math.min(obj.origDragRect.w, obj.origDragRect.h))
       return;

     var CenterPos = _getCenter(drag_obj);
     obj.zoom *= Factor;     
     obj.dragRect = new Rect(CenterPos.x - newW/2, CenterPos.y - newH/2, newW, newH);
     var newPos = new Point(obj.dragRect.x, obj.dragRect.y);
     this.calcBoundingRect(obj.apertRect, obj.dragRect);
     obj.limitMove(newPos);

     _move(drag_obj, obj.dragRect.x, obj.dragRect.y);
     _resize(drag_obj, obj.dragRect.w, obj.dragRect.h);

     if(obj.serverUpdatePosAndZoomFn)
     {
        var origCenter = _getCenterRect(obj.origDragRect);
        var newCenter = _getCenterRect(obj.dragRect);
        var x_offset = newCenter.x - origCenter.x;
        var y_offset = newCenter.y - origCenter.y;
        obj.serverUpdatePosAndZoomFn(function(res){}, x_offset + ';' + y_offset + ';' + obj.zoom);
     }

     //Calc new bounding box
  };

  this.Wheel = function (event)
  {
     var delta = 0;
     if (!event) /* For IE. */
        event = window.event;
     if (event.wheelDelta) { /* IE/Opera. */
        delta = event.wheelDelta/120;
        if (window.opera)
           delta = -delta;
     }else if (event.detail) { /** Mozilla case. */
        delta = -event.detail/3;
     }
     if (delta)
     {
        obj.Zoom(delta);
     }
     if (event.preventDefault)
        event.preventDefault();
     event.returnValue = false;
  };

  if(this.zoomFactor)
  {
     //For Mozilla
     if (this.mouseHandlerObj.addEventListener)
        this.mouseHandlerObj.addEventListener('DOMMouseScroll', this.Wheel, false);
     
     //For IE/Opera
     this.mouseHandlerObj.onmousewheel= this.Wheel;
  }

  this.mouseHandlerObj.onmousedown = function (e) 
  {
      originalonmousemove = document.onmousemove;
      dragging = true;


      orig_obj_left = parseInt(drag_obj.style.left+0);
      orig_obj_top = parseInt(drag_obj.style.top+0);
      click_pos_x = nn6 ? e.clientX : event.clientX;
      click_pos_y = nn6 ? e.clientY : event.clientY;
      obj.mouseHandlerObj.style.cursor = 'move';

      document.onmousemove = function(e) 
      {
          if (!dragging) 
          {
              document.onmousemove = originalonmousemove;
              return false;
          }
          var new_left = nn6 ? orig_obj_left + e.clientX - click_pos_x : orig_obj_left + event.clientX - click_pos_x;
          var new_top  = nn6 ? orig_obj_top + e.clientY - click_pos_y : orig_obj_top + event.clientY - click_pos_y;
          obj.Move(new Point (new_left, new_top));
          return false;
      };
      document.onmouseup = function(e) 
      {
          dragging = false;
          obj.mouseHandlerObj.style.cursor = 'pointer';
          document.onmousemove = originalonmousemove;
          obj.dragRect = _getRect(drag_obj); //get new rect as position has changed
          oldCenter = _getCenter(drag_obj); //for text image to keep it centered
          if(obj.serverUpdateTextPosFn)
          {
            obj.serverUpdateTextPosFn(function(res){}, drag_obj.style.left + ';' + drag_obj.style.top);
          }
          if(obj.serverUpdatePosAndZoomFn)
          {
             var origCenter = _getCenterRect(obj.origDragRect);
             var newCenter = _getCenterRect(obj.dragRect);
             var x_offset = origCenter.x - newCenter.x;
             var y_offset = origCenter.y - newCenter.y;
             obj.serverUpdatePosAndZoomFn(function(res){}, x_offset + ';' + y_offset + ';' + obj.zoom);
          }
      };
      return false;
  };
};


function borderit(which, color)
{
   if (document.all||document.getElementById)
      which.style.borderColor = color;
}
