function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
  var x = Math.round(num * Math.pow(10,dec));
  if (x >= 0) n1=n2='';

  var y = (''+Math.abs(x)).split('');
  var z = y.length - dec;

  if (z<0) z--;

  for(var i = z; i < 0; i++)
    y.unshift('0');

  y.splice(z, 0, pnt);
  if(y[0] == pnt) y.unshift('0');

  while (z > 3)
  {
    z-=3;
    y.splice(z,0,thou);
  }

  var r = curr1+n1+y.join('')+n2+curr2;
  return r;
}


function changeWall(img,id) {
  $("photo_background_"+id).style.backgroundImage="url("+img+")";
  return false;
}

function changeDimensions(id) {
  createDimensions(thumbNailWidth[id], thumbNailHeight[id], id);
}

function changeFrame(id) {
  createRama(thumbNailWidth[id], thumbNailHeight[id], id);
}

function changePassepartout(id) {
  createPP(thumbNailWidth[id], thumbNailHeight[id], id);
}

function createPoster(thumbnailData,id) {
  ($("photo_background_"+id).getWidth() != 0) ? bgWidth = $("photo_background_"+id).getWidth() : bgWidth = 297;
  ($("photo_background_"+id).getHeight() != 0) ? bgHeight = $("photo_background_"+id).getHeight() : bgHeight = 204;
  var params = thumbnailData.split(",");
  tbWidth = parseInt(params[1]);
  tbHeight = parseInt(params[2]);
  resoWidth = parseInt(params[3]);
  resoHeigh = parseInt(params[4]);
  thumbNailHeight[id] = tbHeight;
  thumbNailWidth[id] = tbWidth;
  $("thumb_photo_"+id).style.backgroundImage="url("+params[0]+")";
  $("thumb_photo_"+id).style.width= tbWidth+"px";
  $("thumb_photo_"+id).style.height= tbHeight+"px";
  $("thumb_photo_"+id).style.position= "absolute";
  $("thumb_photo_"+id).style.top = ((bgHeight - tbHeight)/2) + "px";
  $("thumb_photo_"+id).style.left = ((bgWidth - tbWidth)/2) + "px";
  $("file_"+id).value = params[0];
  $("file_x_"+id).value = tbWidth;
  $("file_y_"+id).value = tbHeight;
  $("reso_x_"+id).value = resoWidth;
  $("reso_y_"+id).value = resoHeigh;

  createPP(tbWidth, tbHeight, id);
	
  createRama(tbWidth, tbHeight, id);
	
  createDimensions(tbWidth, tbHeight, id);
	
  updatePrice(id);
}


function createDimensions(tbWidth, tbHeight, id) {
  var support_id = $("support_"+id).value;
  
  factor = tbWidth / tbHeight;
  var selectList = $("dimensiune_"+id);
	
  var value = selectList.value;
  var w, h;
  selectList.options.length = 0;
  for(i = 0; i < tipHeights[support_id].size(); i++) {
    if (selectList != null && selectList.options != null)
    {
      w = Math.round(tipHeights[support_id][i]*factor);
      h = tipHeights[support_id][i];

      if (Math.max(w, h) <= swf_options.limits['whmax'])
        selectList.options[selectList.options.length] =
        new Option(w+"x"+h+' cm',w+"x"+h, false, false);
    }
  }
  if (!value) value = selectList.options[0].value;
  $("dimensiune_"+id).value = value;
}

function createPP(tbWidth, tbHeight, id) {
  var bgWidth = ($("photo_background_" + id).getWidth() != 0) ? $("photo_background_" + id).getWidth() : 297;
  var bgHeight = ($("photo_background_" + id).getHeight() != 0) ? $("photo_background_" + id).getHeight() : 204;

  if ($("tip_rama_"+id).value != 0 && $("tip_pp_"+id).value != 0) {
    var pp = tipPassepartout[$("tip_pp_"+id).value];
    var ppWidth = tbWidth + pp['px_w_size']*2;
    var ppHeight = tbHeight + pp['px_h_size']*2;
    $("passepartout_"+id).style.width= ppWidth + "px";
    $("passepartout_"+id).style.height= ppHeight + "px";
    $("passepartout_"+id).style.display = "block";
    $("passepartout_"+id).style.position= "absolute";
    $("passepartout_"+id).style.top = ((bgHeight - ppHeight)/2) + "px";
    $("passepartout_"+id).style.left = ((bgWidth - ppWidth)/2) + "px";
		
    $("pp_top_"+id).style.backgroundImage = "url(/images/"+pp['path']+"/2.png)";
    $("pp_top_"+id).style.width = ppWidth+"px";
    $("pp_top_"+id).style.height = pp['px_h_size']+"px";
    $("pp_tl_"+id).style.backgroundImage="url(/images/"+pp['path']+"/1.png)";
    $("pp_tl_"+id).style.width = pp['px_w_size']+"px";
    $("pp_tl_"+id).style.height = pp['px_h_size']+"px";
    $("pp_tr_"+id).style.backgroundImage="url(/images/"+pp['path']+"/3.png)";
    $("pp_tr_"+id).style.width = pp['px_w_size']+"px";
    $("pp_tr_"+id).style.height = pp['px_h_size']+"px";

    $("pp_bottom_"+id).style.backgroundImage = "url(/images/"+pp['path']+"/6.png)";
    $("pp_bottom_"+id).style.width = ppWidth+"px";
    $("pp_bottom_"+id).style.height = pp['px_h_size']+"px";
    $("pp_bottom_"+id).style.top = (ppHeight-pp['px_h_size']) + "px";
    $("pp_bl_"+id).style.backgroundImage="url(/images/"+pp['path']+"/7.png)";
    $("pp_bl_"+id).style.width = pp['px_w_size']+"px";
    $("pp_bl_"+id).style.height = pp['px_h_size']+"px";
    $("pp_br_"+id).style.backgroundImage="url(/images/"+pp['path']+"/5.png)";
    $("pp_br_"+id).style.width = pp['px_w_size']+"px";
    $("pp_br_"+id).style.height = pp['px_h_size']+"px";

    $("pp_middle_"+id).style.backgroundImage = "url(/images/"+pp['path']+"/8.png)";
    $("pp_middle_"+id).style.width = ppWidth+"px";
    $("pp_middle_"+id).style.height = (ppHeight-pp['px_h_size']*2)+"px";
    $("pp_middle_"+id).style.top = pp['px_h_size'] + "px";
    $("pp_mr_"+id).style.backgroundImage="url(/images/"+pp['path']+"/4.png)";
    $("pp_mr_"+id).style.width = pp['px_w_size']+"px";
    $("pp_mr_"+id).style.height = (ppHeight-pp['px_w_size']*2)+"px";
  } else if ($("tip_rama_"+id).value != 0 && $("tip_pp_"+id).value == 0) {
    $("passepartout_"+id).style.display = "none";
  }

  if ($('tip_pp_'+id).getAttribute('disabled')) $("passepartout_"+id).style.display = "none";
}

function createRama(tbWidth, tbHeight, id) {
  var bgWidth = ($("photo_background_" + id).getWidth() != 0) ? $("photo_background_" + id).getWidth() : 297;
  var bgHeight = ($("photo_background_" + id).getHeight() != 0) ? $("photo_background_" + id).getHeight() : 204;
  
  var pp = tipPassepartout[$("tip_pp_"+id).value];
  var ppWidth = tbWidth;
  var ppHeight = tbHeight;
  var rama = tipRame[$("tip_rama_"+id).value];
  if ($("tip_pp_"+id).value != 0 && !$('tip_pp_'+id).getAttribute('disabled')) {
    ppWidth  += pp['px_w_size']*2;
    ppHeight += pp['px_h_size']*2;
  }
  var bname = navigator.appName;
  var version = navigator.appVersion;

  ramaWidth = ppWidth+rama['px_w_size']*2;
  ramaHeight = ppHeight+rama['px_h_size']*2;
  $("rama_"+id).style.width= ramaWidth+"px";
  $("rama_"+id).style.height= ramaHeight+"px";
  $("rama_"+id).style.display = "block";
  $("rama_"+id).style.position= "absolute";
  $("rama_"+id).style.top = ((bgHeight - ramaHeight)/2) + "px";
  $("rama_"+id).style.left = ((bgWidth - ramaWidth)/2) + "px";
  $("rama_top_"+id).style.width = ramaWidth+"px";
  $("rama_top_"+id).style.height = rama['px_h_size']+"px";
  $("rama_tl_"+id).style.backgroundImage="url(/images/"+rama['path']+"/1.png)";
  $("rama_tl_"+id).style.width = rama['px_w_size']+"px";
  $("rama_tl_"+id).style.height = rama['px_h_size']+"px";
  $("rama_tm_"+id).style.backgroundImage = "url(/images/"+rama['path']+"/2.png)";
  $("rama_tm_"+id).style.width = (ramaWidth-rama['px_w_size']*2)+"px";
  $("rama_tm_"+id).style.height = rama['px_h_size']+"px";
  $("rama_tr_"+id).style.backgroundImage="url(/images/"+rama['path']+"/3.png)";
  $("rama_tr_"+id).style.width = rama['px_w_size']+"px";
  $("rama_tr_"+id).style.height = rama['px_h_size']+"px";
  $("rama_bottom_"+id).style.width = ramaWidth+"px";
  $("rama_bottom_"+id).style.height = rama['px_h_size']+"px";
  $("rama_bottom_"+id).style.top = (ramaHeight-rama['px_h_size']) + "px";
  $("rama_bl_"+id).style.backgroundImage="url(/images/"+rama['path']+"/7.png)";
  $("rama_bl_"+id).style.width = rama['px_w_size']+"px";
  $("rama_bl_"+id).style.height = rama['px_h_size']+"px";
  $("rama_bm_"+id).style.backgroundImage = "url(/images/"+rama['path']+"/6.png)";
  $("rama_bm_"+id).style.width = (ramaWidth-rama['px_w_size']*2)+"px";
  $("rama_bm_"+id).style.height = rama['px_h_size']+"px";
  $("rama_br_"+id).style.backgroundImage="url(/images/"+rama['path']+"/5.png)";
  $("rama_br_"+id).style.width = rama['px_w_size']+"px";
  $("rama_br_"+id).style.height = rama['px_h_size']+"px";
  $("rama_middle_"+id).style.width = ramaWidth+"px";
  $("rama_middle_"+id).style.height = (ramaHeight-rama['px_h_size']*2)+"px";
  $("rama_middle_"+id).style.top = rama['px_h_size'] + "px";
  $("rama_mr_"+id).style.backgroundImage="url(/images/"+rama['path']+"/4.png)";
  $("rama_mr_"+id).style.width = rama['px_w_size']+"px";
  $("rama_mr_"+id).style.height = (ramaHeight-rama['px_h_size']*2)+"px";
  $("rama_ml_"+id).style.backgroundImage="url(/images/"+rama['path']+"/8.png)";
  $("rama_ml_"+id).style.width = rama['px_w_size']+"px";
  $("rama_ml_"+id).style.height = (ramaHeight-rama['px_h_size']*2)+"px";
}

function increaseQuantity(id) {
  var tokens = $("cantitate_"+id).value.split(" ");
  cantitate = parseInt(tokens[0]);
  // Limitare cantitate (quantity limit).
  if (cantitate < 50) {
    cantitate++;
    $("cantitate_"+id).value = cantitate + " buc.";
  }
  updatePrice(id);
}

function decreaseQuantity(id) {
  var tokens = $("cantitate_"+id).value.split(" ");
  cantitate = parseInt(tokens[0]);
  if (cantitate > 1) {
    cantitate--;
    $("cantitate_"+id).value = cantitate + " buc.";
  }
  updatePrice(id);
}

function updatePrice(id) {
  var url = swf_options.url_ajax_price;
  updateOptions(id);
  changePassepartout(id);
  changeFrame(id);
  changeDimensions(id);
  // var date = new Date();
  $('poster').value = id;
  showLoader(0.85);
  enableProductFields(id);
  new Ajax.Request(url, {
    parameters: Form.serialize($('poster_form')),
    onSuccess: function(transport) {
      var up = transport.responseText;
      var tokens = $("cantitate_"+id).value.split(" ");
      cantitate = parseInt(tokens[0]);
      $("unit_price_"+id).innerHTML = formatNumber(up, 2, '.',',','','','-','') + "" + swf_options.currency_sign;
      $("total_price_"+id).innerHTML = formatNumber(up*cantitate, 2, '.',',','','','-','') + "" + swf_options.currency_sign;
      updateInfo(id);
      disableProductFields(id);
      hideLoader(0.85);
    }
  });
}

/**
 * Resetam toate campurile daca a fost schimbat suportul.
 */
function updateSupport(id) {
  $('dimensiune_' + id).options.length = 0;
  changeDimensions(id);
  
  var support_id = $("support_" + id).value;
  var selectList = $("tip_rama_" + id);
  
  selectList.options.length = 0;
  
  tipSuportRame[support_id].each(function(s, index) {
    if (selectList != null && selectList.options != null) {
      selectList.options[selectList.options.length] = new Option(tipRame[s]['nume'], s, false, false);
      if (tipRame[s]['id'] == 1000) {
        selectList.options[selectList.options.length - 1].disabled = true;
      }
    }
  });
  
  var value = selectList.options[0].value;
  $("tip_rama_" + id).value = value;
}

/**
 * In functie de limitari, activeaza sau nu anumite campuri din formular.
 */
function updateOptions(id) {
  var rama = tipRame[$("tip_rama_" + id).value];
  var pp = tipPassepartout[$("tip_pp_" + id).value];
  
//  console.log(rama['can_joint']);
  var is_joint = rama['can_joint'];
  var is_pp = rama['can_pass'];
  
  var dimm = $('dimensiune_' + id).value.split("x");
  var x = parseInt(dimm[0]);
  var y = parseInt(dimm[1]);

  if (x + parseInt(pp['dimensiune']) * 2 > swf_options.limits['pwmax'] || y + parseInt(pp['dimensiune']) + parseInt(pp['dimensiune']) * 2 > swf_options.limits['phmax']) {
    is_pp = false;
  }

  if (is_pp) x = parseInt(dimm[0]) + parseInt(pp['dimensiune']) * 2;
  if (is_pp) y = parseInt(dimm[1]) + parseInt(pp['dimensiune']) * 2;
  
  // Limita de rama.
  if (x + y > swf_options.limits['joint'] || Math.min(x, y) < swf_options.limits['min']) {
    is_joint = false;
  }

  // Activam sau dezactivam itemurile.
  $('balama_'+id).writeAttribute('disabled', !is_joint);
  $('tip_pp_'+id).writeAttribute('disabled', !is_pp);
}

function showLoader(opacity, callRequest) {
  //daca n-a mai pornit nimeni efectul de loader, il activam noi
  if (curtain == 0)
  {
    curtain++;

    if (!opacity) opacity = 1;
    if ($('ajax_loader'))
    {
      mimicDimensions();
      $('ajax_loader').setOpacity(0);

      $('ajax_loader').show();
      if (opacity == 1) hideSelects();
      new Effect.Fade('ajax_loader', {
        from: 0,
        to: opacity,
        duration: 0.3,
        afterFinish: callRequest
      });
    }
  }
  else curtain++;
}

function hideLoader(opacity) {
  if (!opacity) opacity = 1;

  if (curtain > 1) curtain--;
  {
    mimicDimensions();
    if ($('ajax_loader'))
      new Effect.Fade('ajax_loader', {
        from: opacity,
        to: 0,
        duration: 0.3,
        queue: 'end',
        afterFinish: function() {
          curtain = 0;
          showSelects();
        }
      });
}
}

//Ascunde selectboxurile pentru IE6
function hideSelects() {
  var browser=navigator.appName;
  var b_version=navigator.appVersion;
  var version=parseFloat(b_version);

  if (browser == 'Microsoft Internet Explorer' && version == 4)
  {
    $$('#content select').each(function(e){
      e.setStyle({
        'visibility': 'hidden'
      });
    });
  }
}

/*
 * Imi duplica dimensiunile contentului pentru ajax_loader
 */
function mimicDimensions() {
  var element = $('content').getDimensions();
  $('ajax_loader').setStyle({
    'width': element.width + 'px',
    'height': element.height + 'px'
  });
}

//afisam selectboxurile pentru IE6
function showSelects() {
  $$('#content select').each(function(e){
    e.setStyle({
      'visibility': 'visible'
    });
  });
}

function validateEmail(email) { 
  var re=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
  return email.match(re)

}

//imi schimba valoarea in campul frame
//imi updateaza formularul si-mi inchide lyteboxul
function changeFrameClose(id, value) {
  $('tip_rama_' + id).value = value;
  updatePrice(id);
  myLytebox.end();
}

function showQuestion(value) {
  window.location= value;
}

function updateInfo(id) {
  var url = swf_options.url_ajax_info;
  new Ajax.Updater('info_' + id, url, {
    parameters: {
      id: id
    }
  });
}

/**
 * Activeaza campurile Support si Dimensiune pentru Foto stoc.
 */
function enableProductFields(id) {
  var element = document.getElementById('product_type_' + id);
  if (element) {
    var product_type = $('product_type_' + id).value;
    if (product_type == 2) {
      $('support_'+id).writeAttribute('disabled', false);
      $('dimensiune_'+id).writeAttribute('disabled', false);
    }
  }
}

/**
 * Dezactiveaza campurile Support si Dimensiune pentru Foto stoc.
 */
function disableProductFields(id) {
  var element = document.getElementById('product_type_' + id);
  if (element) {
    var product_type = $('product_type_' + id).value;
    if (product_type == 2) {
      $('support_'+id).writeAttribute('disabled');
      $('dimensiune_'+id).writeAttribute('disabled');
    }
  }
}

/**
 * Create a poster in Room View.
 * 
 * @see createPoster()
 */
function createRoomViewPoster(thumbnailData,id) {
  bgWidth = $("photo_background_"+id).getWidth();
  bgHeight = $("photo_background_"+id).getHeight();
  var params = thumbnailData.split(",");
  tbWidth = parseInt(params[1]);
  tbHeight = parseInt(params[2]);
  resoWidth = parseInt(params[3]);
  resoHeigh = parseInt(params[4]);
  $("thumb_photo_"+id).style.backgroundImage="url("+params[0]+")";
  $("thumb_photo_"+id).style.width= tbWidth+"px";
  $("thumb_photo_"+id).style.height= tbHeight+"px";
  $("thumb_photo_"+id).style.position= "absolute";
  $("thumb_photo_"+id).style.top = ((bgHeight - tbHeight)/2) + "px";
  $("thumb_photo_"+id).style.left = ((bgWidth - tbWidth)/2) + "px";

  createPP(tbWidth, tbHeight, id);
	
  createRama(tbWidth, tbHeight, id);
}

