var imagePath = './templates/client_admin/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, price, priceSpecial, weight, name, quantity, psection)
{
  var quantity = quantity || $('#quantity_'+productId).val();
  var name = name || $('#prodName_'+productId).html();
  var psection = psection || 'product';
  $('#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);
    }
  );
}

var productoverid = -1;

function on_product_over(productId, productName, psection)
{
  var bpb = document.getElementById('bigPicBlock');
  if (!bpb) return;
  
  var psection = psection || 'product';
  var product_thumb = urlSite + 'images/';
  
  if (psection == 'sam')
  {
    product_thumb += 'sdelaysam/thumb376X281.jpg';
  }
  else
  {
    product_thumb += 'products/thumb376X281_' + productId + '.jpg';
  }
  
  
  if ((typeof(productoverid) != "undefined") && (productoverid == productId))
  {
    if (bpb.src == product_thumb)
    {
      //xlog('skip over');
      return;
    }
  }
  
  productoverid = productId;
  
  //xlog('onover - set:' + product_thumb);
  
  bpb.productId = productId;
  bpb.psection = psection;
  bpb.alt = productName;
  bpb.src = product_thumb;
}

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);
}

// used with UNregistered members
function checkCartData()
{
	var error = {empty: true};
  $("span[id*='_tip']").attr({className:"tip"});
	if ( (trim($('#firstName').val()) == '') || ($('#firstName').val() == $('#firstName').attr('placeholder')))
	{
	  error.firstName = "<span class=\"tip-left\">&nbsp;</span>" +emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
  
	
	var code = trim($('#phone_p1').val());
	var number = trim($('#phone_p2').val());
	if ( (code == '') || (code == $('#phone_p1').attr('placeholder')))
	{
	  error.phone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	else if (!RegExp("^0", "g").test(code))
	{
	  error.phone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +ERR_PHONE_CODEFORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	else if (!RegExp("^0[0-9]{2}$", "g").test(code))
	{
	  error.phone_p1 = "<span class=\"tip-left\">&nbsp;</span>" +ERR_CODE_FORMATCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	if ( (number == '') || (number == $('#phone_p2').attr('placeholder')))
	{
	  error.phone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	else if (!RegExp("^[0-9]{7}$", "g").test(number))
	{
	  error.phone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +ERR_PHONE_FORMATCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	
	if (!(error.phone_p1 || error.phone_p2))
	{
    var phone = code+number;
  	if (!validatePhone(phone))
  	{
  	  error.phone_p2 = "<span class=\"tip-left\">&nbsp;</span>" +ERR_PHONE_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
  	  error.empty = false;
  	}
	}
  
	if ( (trim($('#discountCart').val()) == '') || ($('#discountCart').val() == $('#discountCart').attr('placeholder')))
	{
	}
	else if (!RegExp("^[0-9]*$", "g").test(trim($('#discountCart').val())))
	{
	  error.discountCart = "<span class=\"tip-left\">&nbsp;</span>" +ERR_DCART_FORMAT+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	
	if ( (trim($('#address').val()) == '') || ($('#address').val() == $('#address').attr('placeholder')))
	{
	  error.address = "<span class=\"tip-left\">&nbsp;</span>" +emptyValue+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	if ( !($('#personCount').val() > 0) )
	{
	  error.personCount = "<span class=\"tip-left\">&nbsp;</span>" +ERR_EMPTY_PERSONCOUNT+ "!<span class=\"tip-right\">&nbsp;</span>";
	  error.empty = false;
	}
	
	if ( error.empty == false )
	{
	  for (var i in error)
	  {
	    if (i != 'empty')
	    {
      	$('#' + i + '_tipx').html( error[i] );
      	$('#' + i + '_tipx').attr({className:"tip-visible"});
	    }
	  }
	  return false;
	}
	else
	{
	  var placeholders = ['firstName', 'phone_p1', 'phone_p2', 'address', 'discountCart'];
	  for (var i in placeholders)
	  {
	    var phsel = '#' + placeholders[i];
	    if ($(phsel).val() == $(phsel).attr('placeholder'))
	    {
	      $(phsel).val('');
	    }
	  }
	  var str = $("form").serialize();
	  $.post(urlSite+"modules/mod_jquery.php",{ str:str, task:'submitOrder', section:'com_cart' },
	    function(data)
	    {
	  	  //window.location = urlSite+'content/sendorder/';
	  	  if (typeof(roll_debug)!="undefined" && roll_debug==1)
	  	  {
	  	    xlog(data);
	  	  }
	  	  else
	  	  {
//	  	    xlog(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/';
  	      }
	  	  }
	    }
	  );
	  
	}
}

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()
{
  $("#regSiteForm span[id*='_tip']").attr({className:"tip"}).show();
	var errors = new Array();
	var error = false;
	var item;
	
	var reqFields = ['firstName', 'lastName', 'email', 'password1', 'address'];
	var fieldName;
	var field;
	for (var i in reqFields)
	{
	  fieldName = reqFields[i];
	  field = $('#regSiteForm #' + fieldName);
    if (field.val() == undefined || trim(field.val()) == '')
    {
      errors.push({name: fieldName, value: ERROR_EMPTYFIELD});
      error = true;
    }
	}
	
//  var phone = $('#regSiteForm #phone1_p1').val() + $('#regSiteForm #phone1_p2').val();
//  if (phone == undefined || trim(phone) == '')
//  {
//    errors.push({name: 'phone1', value: ERROR_EMPTYFIELD});
//    error = true;
//  }
	
	
	field = $('#regSiteForm #password1');
	if (field && field.val() && trim(field.val()) != '')
	{
	  if ($('#regSiteForm #password1').val() != $('#regSiteForm #vpassword').val())
	  {
      errors.push({name: 'password1', value: ERROR_PASSWORD1});
      error = true;
	  }
	}
  
	for (var i=1; i<=3; i++)
	{
	  xlog('checking #phone' + i + '');
	  
  	if ((trim($('#phone' + i + '_p1').val()) == '') || ($('#phone' + i + '_p1').val() == $('#phone' + i + '_p1').attr('placeholder')))
  	{
  	  if (i==1)
  	  {
    	  errors.push({name: 'phone' + i + '_p1', value: emptyValue});
    	  error = true;
  	  }
  	}
  	else if (!RegExp("^0[0-9]{2}$", "g").test(trim($('#phone' + i + '_p1').val())))
  	{
  	  errors.push({name: 'phone' + i + '_p1', value: ERR_PHONE_CODEFORMAT});
  	  error = true;
  	}
  	if ((trim($('#phone' + i + '_p2').val()) == '') || ($('#phone' + i + '_p2').val() == $('#phone' + i + '_p2').attr('placeholder')))
  	{
  	  if (i==1)
  	  {
    	  errors.push({name: 'phone' + i + '_p2', value: emptyValue});
    	  error = true;
  	  }
  	}
  	else if (!RegExp("^[0-9]*$", "g").test(trim($('#phone' + i + '_p2').val())))
  	{
  	  errors.push({name: 'phone' + i + '_p1', value: ERR_PHONE_FORMAT});
  	  error = true;
  	}
    
  	if (!error)
  	{
      var phone = trim($('#phone' + i + '_p1').val())+trim($('#phone' + i + '_p2').val());
    	if (trim(phone)!='' && !validatePhone(phone))
    	{
    	  errors.push({name: 'phone' + i + '_p2', value: ERR_PHONE_FORMAT});
    	  error = true;
    	}
  	}
	}
	
	//xlog(errors);
	
	field = $('#regSiteForm #email');
	if (field && field.val() && trim(field.val()) != '' && !validateEmail(field.val()))
	{
    errors.push({name: 'email', value: ERROR_EMAIL});
    error = true;
	}
	
	
	if (error)
	{
	  var lasti=-1;
    for (var i = 0; i < (errors.length); i++ )
    {
      lasti = i;
    	item = errors[i];
    	
    	//xlog('error[' + i + '](' + errors.length + '):name="' + item.name + '"');
    	$('#regSiteForm #'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
    	$('#regSiteForm #'+item['name']+'_tip').attr({className:"tip-visible2"});
    	window.setTimeout("$('#regSiteForm #"+item['name']+"_tip').fadeOut();", 5000);
//    	var xxx = document.getElementById(item['name'] + '_tip');
//    	$(xxx).html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
//    	$(xxx).attr({className:"tip-visible"});
    	//alert(item['name'] + ':' + $('#regSiteForm #'+item['name']+'_tip').attr('className'));
    	
    }
	}
	
	if (!error)
	{
	  var str = $("#regSiteForm").serialize();
	  
    $.post(urlSite+"modules/mod_jquery.php",{ str: str, task:'accountSubmit', 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];
  			  	//window.console.log('error[' + i + '](' + errors.length + '):name="' + item.name + '"');
  			  	$('#regSiteForm #'+item['name']+'_tip').html( "<span class=\"tip-left\">&nbsp;</span>" +item['value']+ "!<span class=\"tip-right\">&nbsp;</span>" );
  			  	$('#regSiteForm #'+item['name']+'_tip').attr({className:"tip-visible"});
  			  }
        }
        else
        {
        	$.nyroModalRemove();
        	if ( data == 'success' ) window.location = urlSite;
        	else
        	{
  	      	if ( section == 'com_cart' )
  	      	  window.location = urlSite+'order/';
  	      	else  
        		  $('#regBlock').html(data.replace('ok',''));
        	}
        }
      }
    );
	}
}




function accountSave()
{
  $("span[id*='_tip']").attr({className:"tip"});
	var str = $("form").serialize();
	var error = {};
	error.empty = true;
	
	for (var i=1; i<=3; i++)
	{
	  xlog('checking #phone' + i + '');
	  
  	if ((trim($('#phone' + i + '_p1').val()) == ''))
  	{
  	  if (i==1)
  	  {
    	  error['phone' + i + '_p1'] = "<span class=\"tip-left\">&nbsp;</span>" +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>" +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>" +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>" +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>" +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()
{
//alert($('#bigPicBlock').attr("src"));	
//var image = $('#bigPicBlock').attr("src");
//var image1 = image.replace(urlSite+'images/products/thumb376X281_','');
//var imageId = image1.replace('.jpg', '' );
var imageId = $('#bigPicBlock').attr("productId");
var section = $('#bigPicBlock').attr("psection");

//window.console.log(imageId);
//window.console.log(section);
if (section == 'sam') imageId = 'sam_' + imageId;

$.nyroModalManual({url:urlSite+'imagesview/'+imageId+'/'})	
}




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);
}
