$.blockUI.defaults.message = '<h1 class="bp-blockui">' + bp.lang.please_wait + '</h1>';
var crop = null;

$(function(){
  
  
  // init qtip
  
  $('ul#bp-actions li a[title], ul.rating li a[title]').qtip({
      content: {
         text: false
      },
      style: {
        'font-size': '12px',
        'padding': '5px',
        'text-align': 'center',
        width: { max: 500, min: 200 },
        border: {
          width: 2
        },
        name: 'cream', // Inherit from preset style
        tip: { 
          size: { x: 6, y: 6 },
          corner: 'bottomRight'
        }
      },
      position: {
        corner: {
          target: 'bottomMiddle',
          tooltip: 'bottomRight'
        },
        adjust: { y: -45, x: 0 } 
      },
   });
  
  // bigger preview
  $('div#bp-image-preview').click(function(){
    $.blockUI({
      message: $('#bp-image-big'),
      css: {
        height: '90%',
        width: '90%',
        left: '5%',
        top: '5%'
      },
      centerX: true,
      centerY: true
    });
    return false;
  });
  // add to cart 
  $('a#button_cart').click(function(){
    $.blockUI({
      message: $('#bp-frame-cart'),
      css: {
        width: '45%',
        height: '450px',
        left: '25%',
        top: '5%'
      },
      centerX: true,
      centerY: true
    });
    return false;
  });
  
  // close blockui
  $('a.close').click(function(){
    $.unblockUI();
    return false;
  });
  // frame selection
  $('div#bp-frame-select').click(function(){
    $.blockUI({
      message: $('#bp-frame-list'),
      css: {
        width: '80%',
        height: '400px',
        left: '10%',
        top: '10%'
      },
      centerX: true, 
      centerY: true
    });
    return false;
  });
  
  $('div#bp-frame-list ul li').click(function(){
    var fid = parseInt($(this).attr('id').replace('frame_', ''));
    
    $.ajax({
        type: "POST",
        url: bp.url.frame,
        data: 'frame_id=' + fid,
        cache: false,
        dataType: 'json',
        beforeSend: function()
        {
          $.blockUI();
        },
        success: function(response)
        { 
          location.reload();
          //$.unblockUI();
        }
      });
    
    return false;
  });
  
  $('a#app_rotate_left').click(function(){
      var formValues = $('form#builder').serialize();
      $.ajax({
        type: "POST",
        url: bp.url.build,
        data: 'act=rotate&direction=ccw&' + formValues,
        cache: false,
        dataType: 'json',
        beforeSend: function()
        {
          $.blockUI();
        },
        success: function(response)
        { 
          location.reload();
          //$.unblockUI();
        }
      });
    return false;
  });
  $('a#app_rotate_right').click(function(){
      var formValues = $('form#builder').serialize();
      $.ajax({
        type: "POST",
        url: bp.url.build,
        data: 'act=rotate&direction=cc&' + formValues,
        cache: false,
        dataType: 'json',
        beforeSend: function()
        {
          $.blockUI();
        },
        success: function(response)
        { 
          location.reload();
          //$.unblockUI();
        }
      });
    return false;
  });
  // make landscape selection
  $('a#app_landscape').click(function(){
    
    width  = parseInt($('input#id_width').val());
    height = parseInt($('input#id_height').val());
    min_width    = parseInt($('input#id_min_width').val());
    min_height   = parseInt($('input#id_min_height').val());
    
    $('input#id_width').val(Math.max(width, height));
    $('input#id_height').val(Math.min(width, height));
    $('input#id_min_width').val(Math.max(min_width, min_height));
    $('input#id_min_height').val(Math.min(min_width, min_height));
    
    updateCanvas();
    return false;
  });
  
  // make portrait selection
  $('a#app_portrait').click(function(){
    
    width  = parseInt($('input#id_width').val());
    height = parseInt($('input#id_height').val());
    min_width    = parseInt($('input#id_min_width').val());
    min_height   = parseInt($('input#id_min_height').val());
    
    $('input#id_width').val(Math.min(width, height));
    $('input#id_height').val(Math.max(width, height));
    $('input#id_min_width').val(Math.min(min_width, min_height));
    $('input#id_min_height').val(Math.max(min_width, min_height));
   
    updateCanvas();
    return false;
  });
  
  // preview button
  $('a#button_preview').click(function(){
      var formValues = $('form#builder').serialize();
      $.ajax({
        type: "POST",
        url: bp.url.build,
        data: 'act=generate&' + formValues,
        cache: false,
        dataType: 'json',
        beforeSend: function()
        {
          $.blockUI();
        },
        success: function(response)
        { 
          if (response.update == true)
          {
            updatePreview();
            
          }
          $.unblockUI();
          $('#button_cart').show();
        }
      });
    return false;
  });
});

function saveMessage()
{
  var msg = $('textarea#form_message').val();
  $.ajax({
    type: "POST",
    url: bp.url.settings,
    data: "message=" + encodeURIComponent(msg),
    cache: false,
    dataType: 'json',
    beforeSend: function()
    {
      $.unblockUI();
      $.blockUI();
    },
    success: function(response)
    {
      location.replace(bp.url.cart+'?product_add=true');
    }
  });
  return false;
}

function confirmDiscountCode()
{
  var code = $('input#order_discount_code').val();
  if (code.length > 0)
  {
    $.ajax({
      type: "POST",
      url: bp.url.settings,
      data: "discount_code=" + encodeURIComponent(code),
      cache: false,
      dataType: 'json',
      beforeSend: function()
      {
        $.unblockUI();
        $.blockUI();
      },
      success: function(response)
      {
        location.replace(bp.url.cart+'?discount_update=true');
      }
    });
  }
  return false;
}

function saveCoords(c)
{
  //c.x, c.y, c.x2, c.y2, c.w, c.h
  $('input#id_x').val(c.x);
  $('input#id_y').val(c.y);
  $('input#id_width').val(c.w);
  $('input#id_height').val(c.h);
  updateQuality();
  $('#button_cart').hide();
}

function updateCanvas()
{
  try {
    crop.destroy();
  } catch (e) {};
  
  width  = parseInt($('input#id_width').val());
  height = parseInt($('input#id_height').val());
  
  min_width    = parseInt($('input#id_min_width').val());
  min_height   = parseInt($('input#id_min_height').val());
  
  if (min_width > image_width) {
    min_width = image_width;
  }
  if (min_height > image_height) {
    min_height = image_height;
  }
  selectCoords = [20, 20, 20+width, 20+height];
  cropOptions = {
    onSelect:    saveCoords,
    setSelect:   selectCoords,
    aspectRatio: min_width/min_height,
    trueSize:    [image_width, image_height],
    maxSize:     [image_width, image_height],
    minSize:     [min_width, min_height]
  };

  crop = $.Jcrop($('#cropbox'), cropOptions);
  crop.setSelect(selectCoords);
  updateQuality();
}

function updatePreview()
{
  var prevImg = $('img#bp-preview');
  var oldsrc = prevImg.attr('src').split('?')[0];
  prevImg.attr('src', oldsrc + '?' + (new Date()).getTime());
  
  var prevImg = $('img#bp-preview-big');
  var oldsrc = prevImg.attr('src').split('?')[0];
  prevImg.attr('src', oldsrc + '?' + (new Date()).getTime());
}

function updateThumb()
{
  var prevImg = $('img#cropbox');
  var oldsrc = prevImg.attr('src').split('?')[0];
  prevImg.attr('src', oldsrc + '?' + (new Date()).getTime());
}

function setSize(size_id, e)
{  
  $.ajax({
    type: "POST",
    url: bp.url.size,
    data: "size_id=" + size_id,
    cache: false,
    dataType: 'json',
    beforeSend: function()
    {
      $.blockUI();
    },
    success: function(response)
    {
      $('li.size').removeClass('active');
      $(e).addClass('active');
      $('span#note').html(response.note).show();
      $('#uploadDiv').show();
      
      $.unblockUI();
    }
  });
}

function beginUpload()
{
  $.blockUI({message: $('#uploader')});
  $('#uploader').show();
  
   var i = setInterval(function()
   {
      $.ajax({
        url: bp.url.progress,
        dataType: 'json',
        cache: false,
        data: "progress_key=" + $('#progress_key').val(),
        success: function(rsp)
        {
          if (rsp == null) {
            clearInterval(i);
            location.reload(true);
            return;
          }
         var percentage = Math.floor(100 * parseInt(rsp.current) / parseInt(rsp.total));
         $("#progressbar").reportprogress(percentage);
        }
      });
   }, 750);
}

function updateQuality() 
{			
	var width = parseInt($('input#id_width').val()) || 0;
	var real_width = parseInt($('input#id_image_width').val()) || 0;
	
	var points = [[100, 1], [150, 2], [250, 3]];
	var resolution = width/(real_width/300);

	var quality = 1;
	for (var i = 0; i < points.length; i++) {
		var point = points[i];
		if (point[0] <= resolution) {
			quality = point[1];
		} else {
			break;
		}
	}
	var rating = $('ul.rating');
	rating.removeClass();
	rating.addClass('rating star_' + quality);
}

function quantity(key, action)
{
  $.ajax({
    type: "POST",
    url: bp.url.cart,
    data: "do="+action+"&key=" + key,
    cache: false,
    dataType: 'json',
    beforeSend: function()
    {
      $.blockUI();
    },
    success: function(response)
    {
      location.replace(bp.url.cart);
    }
  });
}

