function prepareProfileForm(){
  var card_val = $('#NewObject[17][discount_card]').val();
  var p = $('#NewObject[17][discount_card]').parent();
  p.css('text-align', 'left');
  $('#NewObject[17][discount_card]').remove();
  p.text(card_val);

  var num = '';
  for(var i = 1; i < 4 ; i++){
    num = i == 1
        ? ''
        : '_'+i;
    var phone_div = $('#NewObject[17][phone'+num+']_ebox');
    if(!phone_div.get(0)){
      continue;
    }
    phone_div.hide();
    var phone = phone_div.find('input:text');
    var phone_val = phone.val();
    var phone = phone_val.replace(/\D/g, '')
    $('#phone'+i+'_p1').attr('value', phone.substr(-10,3));
    $('#phone'+i+'_p2').attr('value', phone.substr(-7));
  }
}

function prepareProfileFormData(){
  for(var i = 1; i < 4 ; i++){
    num = i == 1
        ? ''
        : '_'+i;
    var phone_div = $('#NewObject[17][phone'+num+']_ebox');
    if(!phone_div.get(0)){
      continue;
    }
    phone_div.hide();
    var phone = phone_div.find('input:text');

    var val1 = $('#phone'+i+'_p1').attr('value');
    var val2 = $('#phone'+i+'_p2').attr('value');
    if(val1.length && val2.length){
      phone.attr('value', val1+''+val2);
    }else{
      phone.attr('value', '');
    }
  }
  return accountSubmit('#aeform_17', ['NewObject[17][name]', 'NewObject[17][surname]', 'NewObject[17][address]']);
}

function addColorboxToImage(selector){
	$(selector).colorbox({
		inline:true,
		scrolling:false,
		href:".smallFormCont.Pic",
		iframe:false,
		onClosed:function() {
			$("body").css('overflow','auto');
		},
    onOpen:function(){
      if(document.body.clientHeight < 650){
        $('.smallFormCont.Pic').css('margin-top', '-70px');
      }else{
        $('.smallFormCont.Pic').css('margin-top', '0px');
      }
			$.colorbox.hideDefaultDesign();
      $('#cboxContent').css('background', 'none');
      var link = $(this);
      $('.smallFormCont.Pic .important').html(link.attr('data-alt'));
      $('.smallFormCont.Pic img.largeProductImage').attr('src', link.attr('href'));
      $('#cboxTitle').hide();
      $('#cboxTitle').attr('id', '');
      $("body").css({
      	overflow: document.body.clientHeight < 570 ? 'auto' : 'hidden'
			});
		}
  });
}

function addColorboxToYoutube(selector){
  $(selector).colorbox({
    inline:true,
    scrolling:false,
    href:".popup-window.Yt",
    iframe:false,

    onClosed:function() {
      $("body").css('overflow','auto');
    },
    onComplete:function(){
      $.colorbox.hideDefaultDesign();
      $('#cboxContent').css({'background':'none', 'overflow':'visible'});
      $('#cboxLoadedContent').css({'overflow':'visible'});
      $('#cboxWrapper').css({'overflow':'visible'});
      $('#colorbox').css({'overflow':'visible'});
      var link = $(this).find('textarea');
      if(!link.length){
        return false;
      }
      $('.popup-window.Yt .popup-title').html(link.attr('data-alt'));
      var code = link.html();
      code = htmlspecialchars_decode(code);
      $('.popup-window.Yt .popup-content').html(code);
      $('#cboxTitle').hide();
      $('#cboxTitle').attr('id', '');
      $("body").css({
        overflow: document.body.clientHeight < 570 ? 'auto' : 'hidden'
      });
    }
  });
}

function colorboxSacura(e, ucfg){
  e = $(e);
  var container = $('#popup-window-sacura .popup-content');
  if(!e.length || !container.length){
    return false;
  }
  container.html(e);
  var cfg = {
    inline:true,
    scrolling:false,
    href: '#popup-window-sacura',
    iframe:false,

    onClosed:function() {
      $("body").css('overflow','auto');
      container.empty();
    },
    onComplete:function(){
      $.colorbox.hideDefaultDesign();
      $('#cboxContent').css({'background':'none', 'overflow':'visible'});
      $('#cboxLoadedContent').css({'overflow':'visible'});
      $('#cboxWrapper').css({'overflow':'visible'});
      $('#colorbox').css({'overflow':'visible'});
      $('#cboxTitle').hide();
      $('#cboxTitle').attr('id', '');
      $("body").css({
        overflow: document.body.clientHeight < 570 ? 'auto' : 'hidden'
      });
    }
  };
  if(ucfg && !$.isEmptyObject(ucfg)){
    $.extend(cfg, ucfg, true);
  }
  $.colorbox(cfg);
}

function on_product_over(productId, productName, product_thumb, product_thumb_large){
  var bpb = $('#bigPicBlock');
  if (!bpb.length) return;
	var cid = bpb.get(0).currentProductId;
  var cimg = bpb.children('img.bigPic');

  if(cimg.length && cimg.attr('src') ==  product_thumb){
    return;
  }

  bpb.empty();
  bpb.get(0).currentProductId = productId;

	var a = $('<a/>', {'href': product_thumb_large, 'alt': productName});
	addColorboxToImage(a);
	var img = $('<img>', {'class':'bigPic', 'src': product_thumb, 'alt': productName});
  bpb.append(a.append(img));
}

var imagePath = '/images/';
var currDay, currMonth, currYear;

function xlog(mess)
{
  if (window.console && window.console.log)
  {
    window.console.log(mess);
  }
  else
  {
    //$('#rolldebug').append(mess + '<br />');
  }
}

function trim(str)
{
  var str = str || '';
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function siteXMLHttpRequest()
{
   var request = null;
   if(window.XMLHttpRequest)
   {   //moz, safari1.2+, opera8
      try
      {
         request = new XMLHttpRequest();
         request.overrideMimeType('text/xml');
      }
      catch(e)
      {
         request = null;
      }
   }
   else if(window.ActiveXObject)
   {   //ie5.5+
      try
      {
         request = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e)
      {
         try
         {
         request = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(e)
         {
            request = null;
         }
      }
   }
   return request;
}

/**
* Toggles the check state of a group of boxes
*
* Checkboxes must have an id attribute in the form cb0, cb1...
* @param The number of box to 'check'
* @param An alternative field name
*/
function checkAll( n, fldName )
{
  if (!fldName)
  {
     fldName = 'id';
  }
  for (var j = 1; j <= n; j++)
  {
    box = eval(document.getElementById(fldName + j));
    toggle = eval(document.getElementById('toggle'));
    if (toggle.checked)
    {
      box.checked = true;
      document.adminForm.boxchecked.value++;
    }
    else
    {
      box.checked = false;
      document.adminForm.boxchecked.value--;
    }
  }
}

function checkAllCart()
{
  $("input[@id*=id]").attr({checked:true});
}

function uncheckAllCart()
{
  $("input[@id*=id]").attr({checked:false});
}

function isChecked(isitchecked)
{
	if (isitchecked == true){
		document.adminForm.boxchecked.value++;
	}
	else {
		document.adminForm.boxchecked.value--;
	}
}

function isCheckedSite(isitchecked)
{
	if (isitchecked == true){
		document.siteForm.boxchecked.value++;
	}
	else {
		document.siteForm.boxchecked.value--;
	}
}



/**
* Default function.  Usually would be overriden by the component
*/
function submitbutton(pressbutton)
{
  if (document.adminForm && pressbutton == 'cancel')
  {
    document.adminForm.hidemainmenu.value = 0;
  }
	submitform(pressbutton);
}

/**
* Submit the admin form
*/
function submitform(pressbutton){
	document.adminForm.task.value=pressbutton;
	try
	{
		document.adminForm.onsubmit();
	}
	catch(e)
	{

	}
	document.adminForm.submit();

}


/**
* Default function.  Usually would be overriden by the component
*/
function submitbuttonsite(pressbutton)
{
	submitform1(pressbutton);
}

/**
* Submit the admin form
*/
function submitform1(pressbutton){
	document.siteForm.task.value=pressbutton;
	try
	{
		document.siteForm.onsubmit();
	}
	catch(e)
	{

	}
	document.siteForm.submit();

}



function hideMainMenu()
{
	document.adminForm.hidemainmenu.value=1;
}

function confirmSubmit()
{
  var agree=confirm("Are you sure you wish to continue?");
  if (agree)
    return true ;
  else
    return false ;
}

function saveorder( n )
{
	checkAll_button( n );
}

//needed by saveorder function
function checkAll_button( n )
{
	for ( var j = 1; j <= n; j++ )
	{
		box = eval( "document.adminForm.id" + j );
		if ( box )
		{
			if ( box.checked == false )
			{
				box.checked = true;
			}
		}
		else
		{
			alert("You cannot change the order of items, as an item in the list is `Checked Out`");
			return;
		}
	}
	submitform('saveorder');
}

function listOrderTask( id, task )
{
  var f = document.adminForm;
  cb = eval( 'f.' + id );
  if (cb)
  {
    for (i = 0; true; i++)
    {
      cbx = eval('f.id'+i);
      if (!cbx) break;
      cbx.checked = false;
    }
    cb.checked = true;
    f.boxchecked.value = 1;
    submitbutton(task);
  }
  return false;
}

function listTask( id, task )
{
  var f = document.adminForm;
  cb = eval( 'f.' + id );
  if (cb)
  {
    for (i = 0; true; i++)
    {
      cbx = eval('f.id'+i);
      if (!cbx) break;
      cbx.checked = false;
    }
    cb.checked = true;
    f.boxchecked.value = 1;
    submitbutton(task);
  }
  return false;
}

function parseFormErrors( data )
{
  var errors = new Array();
  var item;
  $("span[@id*=error_]").html("");

   try {errors = eval( data );} catch(err){}
   for (i = 0; i < (errors.length); i++ )
   {
  	  item = errors[i];
  	  if ( document.getElementById('error_' +item['name']) != null )
    	  document.getElementById('error_' +item['name']).innerHTML = '<br/>'+item['value'];
  	  else
  	   document.getElementById('TD_' +item['name']+ '_element').innerHTML += '<span id="error_' +item['name']+ '" class="error"><br/>' + item['value']+ '</span>';
   }

}


function parseFormErrors1( data, divId )
{
  var errors = new Array();
  var item, errMsg;
  errMsg = '';

  $("span[@id*=error_]").html("");

   try {errors = eval( data );} catch(err){}
   for (i = 0; i < (errors.length); i++ )
   {
  	  item = errors[i];
  	  caption = $('#TD_'+item['name']+'_caption').html();
  	  caption = caption.replace('&nbsp;*', '');
  	  errMsg += caption+' '+item['value']+'<br/>';
  	  document.getElementById('TD_'+item['name']+'_caption').className = 'errorRed';
   }
   document.getElementById(divId).innerHTML = 'ERROR IN THE FOLLOW FIELD:<br/>' +errMsg;
   $('#'+divId).show();

}

function createCustomUpload()
{
  var W3CDOM = (document.createElement && document.getElementsByTagName);

  if (!W3CDOM) return;
  var fakeFileUpload = document.getElementById('fakefile');
  var x = document.getElementsByTagName('input');
  for (var i=0;i<x.length;i++)
  {
  	if (x[i].type != 'file') continue;
  	if (x[i].parentNode.className != 'fileinputs' && x[i].parentNode.className != 'fileinputs1' ) continue;
  	x[i].className = 'file hidden';
  	var clone = fakeFileUpload.cloneNode(true);
  	x[i].parentNode.appendChild(clone);
  	x[i].relatedElement = clone.getElementsByTagName('input')[0];
  	x[i].relatedElement.id = 'new_element';
  	document.getElementById('new_element').style.width = '100px';

  	x[i].onchange = x[i].onkeyup = x[i].onmouseout = function () {
  		this.relatedElement.value = this.value;
  		document.getElementById("fileInputCustom").value = this.value;
  	}
  }
}


function changeOrder( orderBy, desc )
{
	$('#orderBy').val( orderBy );
	$('#desc').val( desc );
	document.adminForm.submit();
}



/*                  ===========================  CART FUNCTION ==========================*/

function plus( id, fieldName )
{
	var currVal = $("#" +fieldName+ "_"+id).val();
	currVal++;
	$("#" +fieldName+ "_"+id).val(currVal);
}
function minus( id, fieldName )
{
	var currVal = $("#" +fieldName+ "_"+id).val();
	if ( currVal != 1 ) currVal--;
	$("#" +fieldName+ "_"+id).val(currVal);
}
function plus1( id, fieldName )
{
	var currVal = parseFloat($("#" +fieldName+ "_"+id).val());
	var currOld = parseFloat($("#" +fieldName+ "_"+id+'1').val());
	var cartVal = parseFloat($("#" +fieldName+ "_"+id).val());
//	var item;

	if (isNaN(currVal))
	{
	  currVal = 0;
	  currOld = 0;
	  //$("#" +fieldName+ "_"+id).val();
	}

	if ( currVal == currOld )
	{
		currVal++;
		$("#" +fieldName+ "_"+id).val(currVal);
	}

  var currWeight = parseFloat($('#weight_'+id).html());
  var currPrice = parseFloat($('#price_'+id).html());

	$('#totalw_'+id).html(currWeight*currVal);
	$('#totalp_'+id).html(number_format(currPrice*currVal,  2, '.', ' '));
	$('#quantityw_'+id).html(currVal);
	$('#quantityp_'+id).html(currVal);

  $.post(urlSite+"modules/mod_jquery.php",{ productId: id, quantity: currVal, nodisplay: 1,  task:'addToCart', section:'com_cart' },
    function(data)
    {
      var item, cartInfo;
		  try {cartInfo = eval( data );} catch(err){}
		  if (cartInfo.length != undefined)
		  {
  		  for (var i in cartInfo)
  		  {
  		  	item = cartInfo[i];
  		  	if ( item['name'] == 'totalsSumm' )
  		  	  $('#cartp_total').html(item['value']);
  		  	else if ( item['name'] == 'totalsWeight' )
  		  	  $('#cartw_total').html(item['value']);
  		  	else if ( item['name'] == 'discountSumm' )
  		  	  $('#cartd_total').html(item['value']);
  		  	else if ( item['name'] == 'paymentSumm' )
  		  	  $('#cart_total').html(item['value']);
  		  }
		  }
    }
  );
  $("#" +fieldName+ "_"+id+'1').val( $("#" +fieldName+ "_"+id).val() );
}

function minus1( id, fieldName )
{
  var item;
	var currVal = parseFloat($("#" +fieldName+ "_"+id).val());
	var currOld = parseFloat($("#" +fieldName+ "_"+id+'1').val());
	var cartVal = parseFloat($("#" +fieldName+ "_"+id).val());

	if (isNaN(currVal))
	{
	  currVal = 0;
	  currOld = 0;
	  //$("#" +fieldName+ "_"+id).val();
	}

	if ( currVal == currOld )
	{
		currVal--;
		if ( currVal <= 0 ) currVal = 1;
		$("#" +fieldName+ "_"+id).val(currVal);
	}

  var currWeight = parseFloat($('#weight_'+id).html());
  var currPrice = parseFloat($('#price_'+id).html());

	$('#totalw_'+id).html(currWeight*currVal);
	$('#totalp_'+id).html(number_format(currPrice*currVal,  2, '.', ' '));

	//$('#totalp_'+id).html(currPrice*currVal);
	$('#quantityw_'+id).html(currVal);
	$('#quantityp_'+id).html(currVal);

  $.post(urlSite+"modules/mod_jquery.php",{ productId: id, quantity: currVal, nodisplay: 1,  task:'addToCart', section:'com_cart' },
    function(data)
    {
      var item;
		  try {cartInfo = eval( data );} catch(err){}
		  for (var i = 0; i < (cartInfo.length); i++ )
		  {
		  	item = cartInfo[i];
		  	if ( item['name'] == 'totalsSumm' )
		  	  $('#cartp_total').html(item['value']);
		  	else if ( item['name'] == 'totalsWeight' )
		  	  $('#cartw_total').html(item['value']);
		  	else if ( item['name'] == 'discountSumm' )
		  	  $('#cartd_total').html(item['value']);
		  	else if ( item['name'] == 'paymentSumm' )
		  	  $('#cart_total').html(item['value']);
		  }

    }
  );
  $("#" +fieldName+ "_"+id+'1').val( $("#" +fieldName+ "_"+id).val() );
}

function cart_recheck(id, fieldName)
{
  var currVal = $("#" +fieldName+ "_"+id).val();
  if (isNaN(currVal)||(currVal<=0)||(currVal==''))
  {
    currVal = 1;
    $("#" +fieldName+ "_"+id).val(currVal);
    $("#" +fieldName+ "_"+id+'1').val( $("#" +fieldName+ "_"+id).val() );
  }
}

function cart_set(id, fieldName, val)
{
  var val = (val*1) || 1;
	var currVal = parseFloat(val);
	var currOld = parseFloat($("#" +fieldName+ "_"+id+'1').val());

  if ( currVal <= 0 ) currVal = 1;

	//$("#" +fieldName+ "_"+id).val(currVal);

  var currWeight = parseFloat($('#weight_'+id).html());
  var currPrice = parseFloat($('#price_'+id).html());

	$('#totalw_'+id).html(currWeight*currVal);
	$('#totalp_'+id).html(number_format(currPrice*currVal,  2, '.', ' '));

	//$('#totalp_'+id).html(currPrice*currVal);
	$('#quantityw_'+id).html(currVal);
	$('#quantityp_'+id).html(currVal);

  $.post(urlSite+"modules/mod_jquery.php",{ productId: id, quantity: currVal, nodisplay: 1,  task:'addToCart', section:'com_cart' },
    function(data)
    {
		  try {cartInfo = eval( data );} catch(err){}
		  for (i = 0; i < (cartInfo.length); i++ )
		  {
		  	item = cartInfo[i];
		  	if ( item['name'] == 'totalsSumm' )
		  	  $('#cartp_total').html(item['value']);
		  	else if ( item['name'] == 'totalsWeight' )
		  	  $('#cartw_total').html(item['value']);
		  	else if ( item['name'] == 'discountSumm' )
		  	  $('#cartd_total').html(item['value']);
		  	else if ( item['name'] == 'paymentSumm' )
		  	  $('#cart_total').html(item['value']);
		  }

    }
  );
  $("#" +fieldName+ "_"+id+'1').val( $("#" +fieldName+ "_"+id).val() );
}

function cart_movedown(){
  if ( $('#last_id').val() < $('#max_id').val() )
  {
  	var lId = parseFloat($('#last_id').val());
  	lId = lId + 1;

    $('#last_id').val(lId);

    $('#prod'+$('#last_id').val()).show();

    $('#prod'+$('#first_id').val()).hide();

    lId = parseFloat($('#first_id').val());
    lId = lId + 1;
    $('#first_id').val(lId);
  }
  return false;
}

function cart_moveup()
{
  if ($('#first_id').val()>0)
  {
  	var lId = parseFloat($('#first_id').val());
  	lId = lId - 1;

    $('#first_id').val(lId);
    $('#prod'+$('#first_id').val()).show();

    $('#prod'+$('#last_id').val()).hide();

  	var lId = parseFloat($('#last_id').val());
  	lId = lId - 1;
    $('#last_id').val(lId);
  }
    return false;
}

function lastorder_movedown(){
  if ( $('#lo_last_id').val() < $('#lo_max_id').val() )
  {
  	var lId = parseFloat($('#lo_last_id').val());
  	lId = lId + 1;

    $('#lo_last_id').val(lId);

    $('#lo_prod'+$('#lo_last_id').val()).show();

    $('#lo_prod'+$('#lo_first_id').val()).hide();

    lId = parseFloat($('#lo_first_id').val());
    lId = lId + 1;
    $('#lo_first_id').val(lId);
  }
  return false;
}

function lastorder_moveup()
{
  if ($('#lo_first_id').val()>0)
  {
  	var lId = parseFloat($('#lo_first_id').val());
  	lId = lId - 1;

    $('#lo_first_id').val(lId);
    $('#lo_prod'+$('#lo_first_id').val()).show();

    $('#lo_prod'+$('#lo_last_id').val()).hide();

  	var lId = parseFloat($('#lo_last_id').val());
  	lId = lId - 1;
    $('#lo_last_id').val(lId);
  }
    return false;
}


function addToCart( productId, quantity)
{
  var quantity = quantity || $('#quantity_'+productId).val();
  var name = name || $('#prodName_'+productId).html();
  $('#loading').show();
  $.post(urlSite+"modules/mod_jquery.php",{ productId: productId, quantity: quantity, price:price, priceSpecial: priceSpecial, name:name, weight:weight, task:'addToCart', section:'com_cart', psection: psection },
    function(data)
    {
  	  $('#cartBlock').html(data);
      $('#loading').hide();
    }
  );
  var lastId = $("#last_id").val();
  $("#last_id").val( lastId++ );
}


function updateCart( productId, price, priceSpecial, type )
{
	var currVal = parseFloat($("#quantityCart_"+productId).val());
	var currOld = parseFloat($("#quantityCart_"+productId+'_1').val());
	//$('#loading').show();
	if ( currVal <= 0 || isNaN(currVal)) currVal = 1;

	if ( currVal == currOld && type == 'plus' )
	{
		currVal++;
		$("#quantityCart_" +productId).val(currVal);
	}
	else if ( currVal == currOld && type == 'minus' )
	{
		currVal--;
		if ( currVal <= 0 ) currVal = 1;
		$("#quantityCart_" +productId).val(currVal);
	}

	if (currVal != currOld)
	{
    var quantity = 1;
    $.post(urlSite+"modules/mod_jquery.php",{ productId: productId, price:price, priceSpecial: priceSpecial, quantity: currVal, task:'addToCart', section:'com_cart' },
      function(data)
      {
    	  $('#cartBlock').html(data);
    	$('#loading').hide();
      }
    );
	}
  $("#quantityCart_"+productId+'_1').val(currVal);
}


function deleteFromCart( productId )
{
	$('#loading').show();
  $.post(urlSite+"modules/mod_jquery.php",{ productId: productId, task:'deleteOneItem', section:'com_cart' },
    function(data)
    {
  	  $('#cartBlock').html(data);
  	$('#loading').hide();
    }
  );
}

function deleteFromCart1( productId )
{
  $.post(urlSite+"modules/mod_jquery.php",{ productId: productId, task:'deleteOneItem', section:'com_cart' },
    function(data)
    {
  	  window.location = urlSite+'order/';
    }
  );
}


function clearCart(){
  $.post(urlSite+"modules/mod_jquery.php",{ task:'emptyCart', section:'com_cart' },
    function(data)
    {
  	  $('#cartBlock').html(data);
    }
  );
}

function validatePhone(phone)
{
  // 8-ddd-ddd-dd-dd
	var format1 = new RegExp("^8-[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}$","g");
	// +38(ddd)-ddddddd
	// 8(ddd)-ddddddd
	// +38ddd-ddddddd
	// 8ddd-ddddddd
	// ddd-ddddddd
	// dddddddddd
	var format2 = new RegExp("^([+]3)?(8?)(([0-9]{3}[-/ ]?)|(\([0-9]{3}\)[-/ ]?))[0-9]{7}$","g");

	// any of characters "+-" "()" "0123456789" " "
	//var format3 = new RegExp("^[ \()0-9+\-]{10}$","g");

	//var exp = new RegExp("^([0-9]{3}[/ ])[0-9]{7}$","g");
	return format1.test(phone) || format2.test(phone);
}

function validateEmail(mail)
{
	var exp = new RegExp("^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3}))$","g");
	return exp.test(mail);
}

function validateLogin(login){
	var exp = new RegExp("^[\._a-z0-9\-@]+$","ig");
	return exp.test(login);
}

// used with UNregistered members
function checkCartData()
{
	var error = {};
	var authorized = CartInstance.customer.user_id > 0;
  $("span[id*='_tip']").attr({className:"tip"});
	if(!authorized){
		if (((trim($('#guestFirstName').val()) == '') || ($('#guestFirstName').val() == $('#guestFirstName').attr('placeholder'))))
		{
			error.guestFirstName = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
		}

		var code = trim($('#guestPhone_p1').val());
		var number = trim($('#guestPhone_p2').val());
		if ( (code == '') || (code == $('#guestPhone_p1').attr('placeholder')))
		{
			error.guestPhone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
		}
		else if (!RegExp("^0", "g").test(code))
		{
			error.guestPhone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_CODEFORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
		}
		else if (!RegExp("^0[0-9]{2}$", "g").test(code))
		{
			error.guestPhone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_CODE_FORMATCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
		}
		if ( (number == '') || (number == $('#guestPhone_p2').attr('placeholder')))
		{
			error.guestPhone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
		}
		else if (!RegExp("^[0-9]{7}$", "g").test(number))
		{
			error.guestPhone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_FORMATCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
		}

		if (!(error.guestPhone_p1 || error.guestPhone_p2))
		{
			var phone = code+number;
			if (!validatePhone(phone))
			{
				error.guestPhone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
			}
		}

		if ( (trim($('#guestDiscountCart').val()) == '') || ($('#guestDiscountCart').val() == $('#guestDiscountCart').attr('placeholder')))
		{
		}
		else if (!RegExp("^[0-9]*$", "g").test(trim($('#guestDiscountCart').val())))
		{
			error.guestDiscountCart = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_DCART_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
		}

		if ( (trim($('#guestAddress').val()) == '') || ($('#guestAddress').val() == $('#guestAddress').attr('placeholder')))
		{
			error.guestAddress = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
		}
	}
	if ( !($('#guestPersonCount').val() > 0) )
	{
	  error.guestPersonCount = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_EMPTY_PERSONCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
	}

	if ( !$.isEmptyObject(error)){
	  for (var i in error)
	  {
	    if (i != 'empty')
	    {
      	$('#' + i + '_tipx').html( error[i] );
      	$('#' + i + '_tipx').attr({className:"tip-visible"});
	    }
	  }
	  return false;
	}
	var placeholders = ['guestFirstName', 'guestPhone_p1', 'guestPhone_p2', 'guestAddress', 'guestDiscountCart'];
	for (var i in placeholders)
	{
		var phsel = '#' + placeholders[i];
		if ($(phsel).val() == $(phsel).attr('placeholder'))
		{
			$(phsel).val('');
		}
	}
	return true;
}

function report_error(err_txt, script_err_txt, goto_url)
{
  var goto_url = goto_url || '';
  $.post(urlSite+"support.php",{ err:err_txt, script_err_txt:script_err_txt, task:'submitError'},function()
  {
    if (goto_url != '')
    {
//      window.console.log('window.location = goto_url;');
//      window.console.log('goto_url:' + goto_url + ';');
      window.location = goto_url;
    }
  }
  );
}


// used with registered members
function checkoutSubmit()
{
  var error = 0;
  $("#personCount_tipx").attr({className:"tip"});
	if ( !($('#personCount').val() > 0) )
	{
  	$('#personCount_tipx').html( "<span class=\"tip-left\">&nbsp;</span>" +ERR_EMPTY_PERSONCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>" );
  	$('#personCount_tipx').attr({className:"tip-visible"});
		error = 1;
	}

	if ( error == 1 ) return false;
	else
	{
	  var str = $("form").serialize();
	  $.post(urlSite+"modules/mod_jquery.php",{ str:str, task:'submitOrder', section:'com_cart' },
	    function(data)
	    {
	      if (trim(data)=='ok')
	      {
	  	    window.location = urlSite+'content/sendorder/';
	      }
	      else
	      {
	        report_error(data, 'error in checkCartData() on order submit.', urlSite+'content/ordererror/');
	        //window.location = urlSite+'content/ordererror/';
	      }
	    }
	  );
	}
	return false;
}

/*
function checkOrder()
{
	var totalCart = parseFloat($('#cartTotal').html());
	var minCart = parseFloat($('#min_order').val());
	if ( totalCart < minCart )
	{
	  alert( msgCartAlert + ' '+minCart );
	}
	else
	{
		document.location.href = urlSite+'order/';
	}
	return false;
}*/




/*                  ===========================  REGISTRATION FUNCTION ==========================*/
function logout()
{
  $.post(urlSite+"modules/mod_jquery.php",{ task:'logout', section:'com_registration' },
    function(data)
    {
    	if ( task == 'changeaccount' )
    	  window.location = urlSite+'/';
    	else if ( section == 'com_cart' )
    	  window.location =  urlSite+'order/';
    	else
    	  $('#regBlock').html(data);
    }
  );
}


function loginSubmit()
{
	$("span[id*='_tip']").attr({className:"tip"});

	var str = $("form").serialize();
	var errors = new Array();
	var item;
  $.post(urlSite+"modules/mod_jquery.php",{ str: str, task:'loginSubmit', section:'com_registration' },
    function(data)
    {
      var pos = data.lastIndexOf('success');
      if ( pos < 0 )
      {
				  try {errors = eval( data );} catch(err){}
				  for (i = 0; i < (errors.length); i++ )
				  {
				  	item = errors[i];
				  	$('#'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
				  	$('#'+item['name']+'_tip').attr({className:"tip-visible"});
				  }
      }
      else
      {
      	if ( section == 'com_cart' )
      	  window.location = urlSite+'order/';
      	else
      	  $('#regBlock').html(data.replace('success',''));
      }

    }
  );
}

function accountSubmit(formId, reqFields){
  if(typeof(formId) == 'undefined'){
    formId = '#regSiteForm';
  }
  if(typeof(reqFields) == 'undefined'){
    reqFields = ['firstName', 'lastName', 'address'];
  }
  $(formId+" span[id*='_tip']").attr({className:"tip"}).show();
	var errors = new Array();
	var item;


	var fieldName;
	var field;
	for (var i in reqFields){
	  fieldName = '#'+reqFields[i];
	  field = $(fieldName);
    if(trim(field.val()) == ''){
      errors.push({name: fieldName, value: Lang.rollhouse.errors.emptyValue});
    }
	}

	field = $('#regSiteForm #password1');
	if (field.get(0) && field.val() && trim(field.val()) != ''){
	  if ($('#regSiteForm #password1').val() != $('#regSiteForm #vpassword').val()){
      errors.push({name: '#password1', value: Lang.rollhouse.errors.ERROR_PASSWORD1});
	  }
	}
	var codeVal, phoneVal, codeEId, phoneEId;
	for (var i=1; i<=3; i++){
		codeEId = '#phone' + i + '_p1';
		phoneEId = '#phone' + i + '_p2';
  	codeVal = trim($(codeEId).val());
  	phoneVal = trim($(phoneEId).val());

  	if(codeVal != ''){
  		if(!RegExp("^0[0-9]{2}$", "g").test(codeVal)){
				errors.push({name: codeEId, value: Lang.rollhouse.errors.ERR_CODE_FORMATCOUNT});
  		}
  	}else if(i == 1){
  	  errors.push({name: codeEId, value: Lang.rollhouse.errors.emptyValue});
  	}

  	if(phoneVal != ''){
  		if(!RegExp("^[0-9]{7,7}$", "g").test(phoneVal)){
    		errors.push({name: phoneEId, value: Lang.rollhouse.errors.ERR_PHONE_FORMATCOUNT});
			}
  	}else if(i == 1){
  	  errors.push({name: phoneEId, value: Lang.rollhouse.errors.emptyValue});
  	}
	}

  $('.tip-visible2').hide();
	if(errors.length > 0){
    for (var i = 0; i < errors.length; i++ ){
    	item = errors[i];
    	var itemTip = $(item['name']+'_tip');
      itemTip.show();
      itemTip.html( '<span class="tip-left">&nbsp;</span>' +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
    	itemTip.attr({className:"tip-visible2"});
    }
    return false;
	}
	return true;
}




function accountSave()
{
  $("span[id*='_tip']").attr({className:"tip"});
	var str = $("form").serialize();
	var error = {};
	error.empty = true;

	for (var i=1; i<=3; i++)
	{

  	if ((trim($('#phone' + i + '_p1').val()) == ''))
  	{
  	  if (i==1)
  	  {
    	  error['phone' + i + '_p1'] = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
    	  error.empty = false;
  	  }
  	}
  	else if (!RegExp("^0[0-9]{2}$", "g").test(trim($('#phone' + i + '_p1').val())))
  	{
  	  error['phone' + i + '_p1'] = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_CODEFORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
  	  error.empty = false;
  	}
  	if ( (trim($('#phone' + i + '_p2').val()) == '') || ($('#phone' + i + '_p2').val() == $('#phone' + i + '_p2').attr('placeholder')))
  	{
  	  if (i==1)
  	  {
    	  error['phone' + i + '_p2'] = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
    	  error.empty = false;
  	  }
  	}
  	else if (!RegExp("^[0-9]*$", "g").test(trim($('#phone' + i + '_p2').val())))
  	{
  	  error['phone' + i + '_p1'] = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
  	  error.empty = false;
  	}

  	if (error.empty)
  	{
      var phone = trim($('#phone' + i + '_p1').val())+trim($('#phone' + i + '_p2').val());
    	if (trim(phone)!='' && !validatePhone(phone))
    	{
    	  error['phone' + i + '_p2'] = "<span class=\"tip-left\">&nbsp;</span>" +Lang.rollhouse.errors.ERR_PHONE_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
    	  error.empty = false;
    	}
  	}
	}

	xlog(error);

	if ( error.empty == false )
	{
	  for (var i in error)
	  {
	    if (i != 'empty')
	    {
      	$('#' + i + '_tip').html( error[i] );
      	$('#' + i + '_tip').attr({className:"tip-visible"});
	    }
	  }
	  return false;
	}
	else
	{
  	var item;
    $.post(urlSite+"modules/mod_jquery.php",{ str: str, task:'accountSave', section:'com_registration' },
      function(data)
      {
        var errors = [];
        var pos = data.lastIndexOf('success');
        var pos1 = data.lastIndexOf('ok');
        if ( pos<0 && pos1<0  )
        {
  			  try {errors = eval( data );} catch(err){}
  			  for (i = 0; i < (errors.length); i++ )
  			  {
  			  	item = errors[i];
  			  	$('#'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
  			  	$('#'+item['name']+'_tip').attr({className:"tip-visible"});
  			  }
        }
        else
        {
        	//$('#messSave').show();
        	$('#messSave').fadeIn();
        	window.setTimeout("$('#messSave').fadeOut();", 5000);
        }
      }
    );
	}
}

function restoreSubmit()
{
  $("span[id*='_tip']").attr({className:"tip"});
	var str = $("form").serialize();
	var errors = new Array();
	var item;
  $.post(urlSite+"modules/mod_jquery.php",{ str: str, task:'restoreSubmit', section:'com_registration' },
    function(data)
    {
      var pos = data.lastIndexOf('success');
      var pos1 = data.lastIndexOf('ok');
      if ( pos<0 && pos1<0  )
      {
			  try {errors = eval( data );} catch(err){}
			  for (i = 0; i < (errors.length); i++ )
			  {
			  	item = errors[i];
			  	$('#'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
			  	$('#'+item['name']+'_tip').attr({className:"tip-visible"});
			  }
      }
      else
      {
    	  window.location = urlSite+'content/restoresuccess/';
      }
    }
  );
}



function sendContact()
{
	$("span[id*='_tip']").attr({className:"tip"});

	var str = $("form").serialize();
	var errors = new Array();
	var item;
  $.post(urlSite+"modules/mod_jquery.php",{ str: str, task:'postSubmit', section:'com_content' },
    function(data)
    {
      var pos = data.lastIndexOf('success');
      if ( pos < 0 )
      {
				  try {errors = eval( data );} catch(err){}
				  for (i = 0; i < (errors.length); i++ )
				  {
				  	item = errors[i];
				  	$('#'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
				  	$('#'+item['name']+'_tip').attr({className:"tip-visible"});
				  }
      }
      else
      {
     	  window.location = urlSite+'content/sendrequest/';
      }

    }
  );

}


function changeContent( id )
{
	$("div[id*='contentMainPage_']").hide();
	$("#contentMainPage_" +id).show();
}


function showBigPhoto(url){
$.nyroModalManual({'url':url})
}




function plus_person()
{
  var fieldName = 'personCount';
	var currVal = parseFloat($("#" +fieldName).val());
	var currOld = parseFloat($("#" +fieldName+'1').val());
	var cartVal = parseFloat($("#" +fieldName).val());

	if ( currVal == currOld )
	{
		currVal++;
		if ( currVal > 10 ) currVal = 10;
		$("#" +fieldName).val(currVal);
	}

  $("#" +fieldName+'1').val( $("#" +fieldName).val() );
}

function minus_person()
{
  var fieldName = 'personCount';
	var currVal = parseFloat($("#" +fieldName).val());
	var currOld = parseFloat($("#" +fieldName+'1').val());
	var cartVal = parseFloat($("#" +fieldName).val());

	if ( currVal == currOld )
	{
		currVal--;
		if ( currVal < 0 ) currVal = 0;
		$("#" +fieldName).val(currVal);
	}

  $("#" +fieldName+'1').val( $("#" +fieldName).val() );
}

function core_getEventElement(e)
{
  if (!e) e = window.event;
  if (e.originalTarget)
  {
    return e.originalTarget;
  }
  else
  {
    if (e.srcElement)
    {
      return e.srcElement;
    }
  }
}

function dynplaceholder_init(elid, placeholder_text)
{
  var elSID = '#' + elid;
  $(elSID).attr('userchanged', 0);
  $(elSID).attr('placeholder', placeholder_text);
  if (($(elSID).val() == '') || ($(elSID).val() == placeholder_text))
  {
    $(elSID).val(placeholder_text);
    $(elSID).focus(dynplaceholder_onenter_e);
    $(elSID).blur(dynplaceholder_onleave_e);
    $(elSID).change(dynplaceholder_onchange_e);
    //$(elSID).css({color: '#777777'});
    $(elSID).addClass('placeholder_active');
    $(elSID).attr('ph_set',1);
  }
}

function dynplaceholder_masked_init(elid, placeholder_text, mask)
{
  var elSID = '#' + elid;
  $(elSID).attr('masked', 1);
  $(elSID).attr('mask_val', mask);
  dynplaceholder_init(elid, placeholder_text);
}

var dp_regex_queue = [];

function dynplaceholder_regex_init(elid, placeholder_text, mask)
{
  // works not right... keypress gives scan code instead of keycode...
  var elSID = '#' + elid;
  var regexp = new RegExp(mask,"g");
  $(elSID).attr('regexp', 1);
  $(elSID)[0].regexp_val = mask;

  $(elSID)[0].onkeydown = dynplaceholder_regex_onkeydown;

  dynplaceholder_init(elid, placeholder_text);
}

function dynplaceholder_regex_onkeydown(e)
{
  var e = e || window.event();
  var resvalue = this.value + String.fromCharCode(e.keyCode); //e.keyCode;

//  window.console.log(this);
//  window.console.log(e);
//  window.console.log(resvalue);

  var regexp = new RegExp(this.regexp_val,"g");
  var t = regexp.test(resvalue);
//  window.console.log(t);
  return t;
}

function dynplaceholder_onenter_e()
{
  if ($(this).attr('ph_set') == 1)
  {
//    if ($(this).attr('userchanged') != 1)
//    {
      $(this).attr('ph_set',0);
      $(this).val('');
      if ($(this).attr('masked'))
      {
        $(this).mask($(this).attr('mask_val'), {hide_incomplete:false});
        $(this).focus();
      }
      //$(this).css({color: '#000000'});
      $(this).removeClass('placeholder_active');
//    }
  }
}

function dynplaceholder_onleave_e()
{
  if ($(this).val() == '')
  {
//    if ($(this).attr('userchanged') != 1)
//    {
      if ($(this).attr('masked'))
      {
        $(this).unmask();
      }
      $(this).val($(this).attr('placeholder'));
      //$(this).css({color: '#777777'});
      $(this).addClass('placeholder_active');
      $(this).attr('ph_set',1);
//    }
  }
}

function dynplaceholder_onchange_e()
{
  $(this).attr('userchanged', 1);
}
