function loadAction(dest) {
	try 
	{
   		 xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
	}catch(e){
	}
   document.getElementById("app_message").innerHTML = "<img src='/images/waiting.gif' />Processing...";
	xmlhttp.onreadystatechange = triggeredAction;
	xmlhttp.open("GET", dest);
	xmlhttp.send(null);
}

function triggeredAction() {
// if the readyState code is 4 (Completed)
// and http status is 200 (OK) we go ahead and get the responseText
// other readyState codes:
// 0=Uninitialised 1=Loading 2=Loaded 3=Interactive

if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
    // xmlhttp.responseText object contains the response.
	 document.getElementById("app_message").innerHTML = xmlhttp.responseText;
	 setTimeout("hideMessage()", 3000);
    }
}

function checkSignUpForm()
{
	var theForm = document.forms.user_form;

	if (!theForm.email.value)
	{
		alert("Please, enter your e-mail.");
		theForm.user_email.focus();
		return false;
	}

	if( !checkEmailAddress(theForm.email.value) )
	{
		alert("Please, enter valid email address.");
		theForm.email.focus();
		return false;
	}

	if (!theForm.password.value)
	{
		alert("Please, enter your password.");
		theForm.password.focus();
		return false;
	}

	if (theForm.password.value.length < 4 || theForm.password.value.length > 12)
	{
		alert("Your password must be 4 to 12 characters long with no spaces.");
		theForm.password.focus();
		return false;
	}

	if (theForm.password.value != theForm.password2.value)
	{
		alert("Please verify your password - the password you entered in both fields does not match.");
		theForm.password2.focus();
		return false;
	}

	if ($('#user_code').length && !theForm.code.value)
	{
		alert("Please, enter confirmation code.");
		theForm.code.focus();
		return false;
	}

	return true;
}

function validateFormCertificate()
{


	if (document.getElementById('amount').value == "")
	{
	  alert("Please, enter amount.");
	  document.getElementById('amount').focus();
	  return (false);
	}

	if (isNaN(document.getElementById('amount').value) || parseFloat(document.getElementById('amount').value) <= 0)
	{
	  alert("The number you entered is invalid, check the number and try again.");
	  document.getElementById('amount').focus();
	  return (false);
	}


	if (document.getElementById('email').value == "")
	{
	  alert("Please, enter email.");
	  document.getElementById('email').focus();
	  return (false);
	}
	
	var re_check_email = new RegExp("[A-Za-z0-9_]+([-+.][A-Za-z0-9_]+)*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\\.[A-Za-z0-9_]{2,}([-.][A-Za-z0-9_]+)*");
	var ares = re_check_email.exec(document.getElementById('email').value);
	if( ares == null )
	{
	  alert("Please, enter valid email address.");
	  document.getElementById('email').focus();
	  return (false);
	}

	return true;

}

function updateCertificateAjax(){
    $.ajax({
        type: "POST",
        url: "/checkout/first/",
        data: 'ajax=1&action=certificate_update&'+$('#certificate_form').serialize(),
        dataType: "html",
        beforeSend: function()
        {
            blockStandart('#modalContent');
        },
        complete: function()
        {
        },
        success: function(response) {
            var data = $.evalJSON(response);

            if (data.output) {
                $('#listing').html(data.output);
            }
            $('#modalContent').dialog('close');
        }
    });
}

function SendShippingState()
{
    if (!$("#shipping_state").length) return true;
    
	if ($('#spirits_in_cart').length)
	{
        if ( 'N/A' == $('#shipto_state').val() && !$('#delivery_type_in_store').is(':checked'))
        {
            alert('Please select your Ship To state to calculate your shipping price!');
            $('#shipto_state').focus();
            return false;
        }

        if ( 'NY' != $('#shipto_state').val() && $('#spirits_in_cart').val())
        {
            alert('We can only ship spirits to the state of New York!');
            $('#shipto_state').val('NY');
            $('#shipto_state').focus();
            return false;
        }
	}

    if ($('input[name=ages_radio]').length && $('input[name=ages_radio]:checked').val()!=1 )
    {
        alert('Sorry, you are younger than 21, so can not buy alcohol.');
        return false;
    }

    var id = $("#shipping_state input[name=id]").val();
    var quantity = $("#shipping_state input[name=quantity]").val();

	$.ajax({
		type: "POST",
		url: "/index.php?q=1",
		data: $("#shipping_state").serialize(),
		dataType: "html",
		complete: function(){},
		success: function(response) {
            if (response.substr(0, 13) == 'add_favorites') {
                favoritesAddAll(response.substr(14));
                return false;
            }
            processRecalculateResponse(response, id, quantity);
		}
	});
	return true;
}

// Dialog window	
function ShowDialog(url, width, title, buttons_view, callback)
{
    var urlData = url.split('?');
	$('#modalContent').html("");
    $('#modalWindow').show();
	$.ajax({
			type: "POST",
			url: urlData[0] + '?q=1',
            data: urlData[1],
			dataType: "html",
			async: false,
			complete: function(){if(callback) callback();return true},
			success: function(data){ 
				$('#modalContent').html(data);
				
				var dlgParams = {
					autoOpen: false,
					bgiframe: true,
					draggable: false,
					title: title,
					modal: true,
					resizable: false,
					width: width
				};
				$('#modalContent').dialog(dlgParams);
				
				var dlgButtons = {};

				$('#modalContent').dialog('option', 'buttons', dlgButtons);
				$('#modalContent').dialog('open');
                $('.ui-dialog').show();
                $('.ui-widget-overlay').show();
			},
			error: function()
			{
				//alert('Export operation failed!');
			}
	});
}

function ShowDialogText(str, title, width) {
	$('#modalContent').html("");
    $('#modalWindow').show();
    $('#modalContent').html(str);

    var dlgParams = {
        autoOpen: false,
        bgiframe: true,
        draggable: false,
        title: title,
        modal: true,
        resizable: false,
        width: width
    };
    $('#modalContent').dialog(dlgParams);
    $('.ui-dialog').show();
    $('.ui-widget-overlay').show();

    var dlgButtons = {};
        dlgButtons = {
            "Close" : function() { $(this).dialog("close"); }
        };

    $('#modalContent').dialog('option', 'buttons', dlgButtons);
    $('#modalContent').dialog('open');
}


function closePopup()
{
    $('#modalContent').html("");
    $('#modalContent').dialog("close");
    $('#modalWindow').hide();
    $('#body').unblock();
}

function hidePopup()
{
    $('#modalWindow').hide();
    $('.ui-dialog').hide();
    $('.ui-widget-overlay').hide();
}

function postComment()
{
    var error = '';
    if (!trim($("#comment_name").val())) error += strings['enter_your_name'];
    if (!trim($("#comment_post").val())) error += strings['enter_comment'];
    if (error) {alert(error);return false;}

    var lang_path = $('#lang_path').val();

   $.ajax({
      type: "POST",
      dataType: "html",
      error: function(response){},
      url: "/blog/comment/add/",
      data: $("#post_comment").serialize(),
      beforeSend: function()
      {
         blockStandart('comments_div');
      },
      complete: function()
      {
         $('#comments_div').unblock();
      },
      success: function(response)
      {
         $("#comments_div").html(response);
      }
   });

   return false;
}
				
function setExpiredDates()
{
    if (!$('#bill_expyear').length || !$('#bill_expmonth').length) return false;

    var sel_year = $('#bill_expyear').val();
    var sel_month = $('#bill_expmonth').val();
    if (parseInt(sel_month[0]) == 0) sel_month = parseInt(sel_month.split('0').join(''));
    else sel_month = parseInt(sel_month);

    var d = new Date();
    var curr_year = d.getFullYear();
    var curr_month = d.getMonth() + 1;
    var curr_month_text = curr_month<10?'0'+curr_month:curr_month;

    if (sel_year <= curr_year)
    {
        if (sel_month < curr_month) $('#bill_expmonth').val(curr_month_text);
        var i_text = '';
        for (i=1; i < curr_month; i++)
        {
            if (i < 10) i_text = '0'+i;
            else i_text = i_text;
            $('#bill_expmonth option[value="'+i_text+'"]').attr('disabled', 'disabled');
        }
    } else {
        $('#bill_expmonth option').attr('disabled',false);
    }
}

function checkLoginForm()
{
    if ($('#is_anonym').val() > 0) return true; //do not check anonym submit


	if (!$('#login_email').val())
	{
		alert("Please, enter your login e-mail.");
		$('#login_email').focus();
		return false;
	}

	if(!checkEmailAddress($('#login_email').val()))
	{
		alert("Please, enter valid email address.");
		$('#login_email').focus();
		return false;
	}

	if (!$('#login_password').val())
	{
		alert("Please, enter your password.");
		$('#login_password').focus();
		return false;
	}

	return true;
}

//CART
function cartReload(action)
{
        $.ajax({
            type: "POST",
            url: '/ajax_functions/',
            data: 'call=component&name=cart&action='+action+'&' + $('#cart_form').serialize(),
            dataType: "html",
            beforeSend: function()
            {
                blockStandart('#orange_panel');
            },
            complete: function()
            {
                 $('#orange_panel').unblock();
            },
            success: function(response){
                $('#cart_block_1').html(response);
            }
        });
}

function removeFromCart(id)
{
	if (confirm_delete())
	{
		$.ajax({
			type: "POST",
            url: '/ajax_functions/',
            data: 'call=component&name=cart&action=remove&id='+id,
			dataType: "html",
            beforeSend: function()
            {
                blockStandart('#orange_panel');
            },
            complete: function()
            {
                 $('#orange_panel').unblock();
            },
			success: function(response){
				$('#cart_block_1').html(response);
			}
		});
	}
}

function resetCart()
{
	if (confirm_delete())
	{
		$.ajax({
			type: "POST",
            url: '/ajax_functions/',
            data: 'call=component&name=cart&action=reset',
			dataType: "html",
            beforeSend: function()
            {
                blockStandart('#orange_panel');
            },
            complete: function()
            {
                 $('#orange_panel').unblock();
            },
			success: function(response){
				$('#cart_block_1').html(response);
			}
		});
	}
}


function addToCart(id, quantity, storage)
{
    if (null == storage || undefined == storage) storage = 0;
	var tmpCustom = (storage > 0)? ("_"+storage) : "";

    var dest = '.p_orange'
    if ($('#products_table').length) dest = '#products_table'

    $("#cartIcon_"+id+tmpCustom).effect('spectrum',
			{
                dest: $(dest), spCss: {'z-index':'999', 'border':'1px solid #333'}
            }, 1000, function(){
                addToCartActive(id, quantity);
			}
	);
}

function addToCartActive(id, quantity)
{
	$.ajax({
		type: "POST",
        url: '/ajax_functions/',
        data: 'call=component&name=cart&action=add&id='+id+"&quantity="+quantity,
		dataType: "html",
        beforeSend: function()
        {
            if ($('#products_table').length) blockStandart(('#products_table'));
            else blockStandart('#orange_panel');
        },
        complete: function()
        {
             $('#orange_panel').unblock();
        },
		success: function(response){
            processRecalculateResponse(response, id, quantity);
		},
		error: function()
		{
			//alert('Export operation failed!');
		}
	});
}

function recalculate(params)
{
   var step = '';
   var data ='';
   if ($('#billing_info_form').length) {
       step = 'second';
       data = $('#billing_info_form').serialize()
   } else {
       step = 'first';
       data = $('#save_first_step').serialize();
   }

   var paramsString = params?'&'+params:'';

   $.ajax({
      type: "POST",
      dataType: "html",
      url: "/checkout/"+step+"/",
      data: "ajax=1&action=update"+paramsString+"&" + data,
      beforeSend: function()
      {
         blockStandart('#products_table');
      },
      complete: function()
      {
         $('#products_table').unblock();
      },
      success: function(response)
      {
         if (trim(response))
         {
            var data = $.evalJSON(response);

            if (data.output) {
                $('#listing').html(data.output);
            }

            //promo error
            if (data.promo_error) {
                alert(data.promo_error);
            }

            //certificate error
            if (data.certificate_error) {
                alert(data.certificate_error);
            }

            //shipping error
            if (data.shipping_error) {
                alert(data.shipping_error);
                //ShowDialog("/index.php?a=2.19", 300, 'Ship To State', 'ship_to_state');
            }
         }
      }
   });
}

function reloadProductsTable()
{
   $.ajax({
      type: "POST",
      dataType: "html",
      url: "/checkout/second/",
      data: "ajax=1&action=update_products_table&" + $('#billing_info_form').serialize(),
      beforeSend: function()
      {
         blockStandart('#products_table');
      },
      complete: function()
      {
         $('#products_table').unblock();
      },
      success: function(response)
      {
         if (trim(response))
         {
            var data = $.evalJSON(response);

            if (data.output) {
                $('#products_table').html(data.products_table);
            }

            //promo error
            if (data.promo_error) {
                alert(data.promo_error);
            }

            //certificate error
            if (data.certificate_error) {
                alert(data.certificate_error);
            }

            //shipping error
            if (data.shipping_error) {
                $('#ship_state').val('NY');
                alert(data.shipping_error);
                //ShowDialog("/index.php?a=2.19", 300, 'Ship To State', 'ship_to_state');
            }
         }
      }
   });
}

function recalculate_certificates(id, amount)
{
   var step = 1;
   if (!$('#save_first_step').length) step = 2;

   $.ajax({
      type: "POST",
      dataType: "html",
      url: "/checkout/first/",
      data: "ajax=1&action=update&cert_id=" + id + "&cert_amount=" + amount + "&" + $('#save_first_step').serialize(),
      beforeSend: function()
      {
         blockStandart('#products_table');
      },
      complete: function()
      {
         $('#products_table').unblock();
      },
      success: function(response)
      {
         if (trim(response))
         {
            var data = $.evalJSON(response);

            if (data.output) {
                $('#listing').html(data.output);
            }

            //promo error
            if (data.promo_error) {
                alert(data.promo_error);
            }

            //certificate error
            if (data.certificate_error) {
                alert(data.certificate_error);
            }

            //shipping error
            if (data.shipping_error) {
                alert(data.shipping_error);
                //ShowDialog("/index.php?a=2.19", 300, 'Ship To State', 'ship_to_state');
            }
         }
      }
   });
}

function removeFromCheckout(id)
{
	if (confirm_delete())
	{
		$.ajax({
			type: "POST",
            url: "/checkout/first/",
            data: 'ajax=1&action=remove&id='+id,
			dataType: "html",
            beforeSend: function()
            {
                blockStandart('#products_table');
            },
            complete: function()
            {

            },
			success: function(response){
                  var data = $.evalJSON(response);

                    if (data.output) {
                        $('#listing').html(data.output);
                    }
			}
		});
	}
}

/*
 PROMO CODE
 */
function promoRemove()
{
	if (confirm_delete())
	{
        $.ajax({
            type: "POST",
            url: "/checkout/first/",
            data: 'ajax=1&action=promo_remove',
            dataType: "html",
            beforeSend: function()
            {
                blockStandart('#products_table');
            },
            complete: function()
            {
            },
            success: function(response) {
                var data = $.evalJSON(response);

                if (data.output) {
                    $('#listing').html(data.output);
                }

            }
        });
    }
}

function checkoutValidate(alerts)
{
    var error = '';
    var noteType = $(":radio[name=customer_note_type]").filter(":checked").val();
    if ( (noteType == 1 || noteType == 2) && !$('#customer_note').val())
    {
        error += 'Please, enter your customer note.\n';
        switchCheckoutButtons(0);
    }

    if (!$('#input_check').is(':checked'))
    {
        error += 'Please, agree with the disclaimer note.';
        switchCheckoutButtons(0);
    }

    if (alerts && error) alert(error);
    if (error) return false;

    switchCheckoutButtons(1);

    if (alerts) blockInvisible('#listing'); //checkout
    
    return true;
}

function onChangeShippingType()
{
    if ($('#shipping_type_in_store').is(':checked')) {
        $('#shipping_state').attr('disabled', true);
        $('#delivery_type').attr('disabled', true);
        $('#view_regardless_of_weather').hide();
    } else {
        $('#shipping_state').attr('disabled', false);
        $('#shipping_type').attr('disabled', false);
        $('#view_regardless_of_weather').show();
    }
}

function switchCheckoutButtons(param)
{
    if (param <= 0)
    {
        $('#checkout_btn').removeClass('b_green');
        $('#checkout_btn').addClass('button_disable');
    } else {
        $('#checkout_btn').removeClass('button_disable');
        $('#checkout_btn').addClass('b_green');
    }

    return true;
}

function customerNoteRadio(val)
{
    if (val == 0) {
        $('#customer_note').val('');
        $('#customer_note').attr('disabled', true);
        //$('#customer_note').hide();
    } else {
        $('#customer_note').attr('disabled', false);
        //$('#customer_note').show();
    }

    checkoutValidate(0);
}

function checkoutFirst()
{
   $.ajax({
      type: "POST",
      dataType: "html",
      url: "/checkout/second/",
      data: "ajax=1&" + $('#save_first_step').serialize(),
      beforeSend: function()
      {
         blockStandart('#products_table');
      },
      complete: function()
      {
         $('#products_table').unblock();
      },
        success: function(response) {
            var data = $.evalJSON(response);

            if (data.output) {
                $('#listing').html(data.output);
            }

        }
    });
}


function validateCheckoutForm()
{
   $.watermark.hideAll();
   var error = '';
   $('input').removeClass('error');
   $('select').removeClass('error');

   if (!trim($("#bill_firstname").val()))
   {
       error += 'Enter "First Name"\n';
       $("#bill_firstname").addClass('error');
   }

   if (!trim($("#bill_lastname").val()))
   {
       error += 'Enter "Last Name"\n';
       $("#bill_lastname").addClass('error');
   }

   if (!trim($("#bill_email").val()))
   {
        error += 'Enter "Email"\n';
        $("#bill_email").addClass('error');
   } else {
        if (!checkEmail($("#bill_email").val()))
        {
            error += 'Incorrect Email\n';
            $("#bill_email").addClass('error');
        }
   }
   if (!trim($("#bill_phone").val()))
   {
       error += 'Enter "Phone"\n';
       $("#bill_phone").addClass('error');
   }

   if (!trim($("#bill_address_line1").val()))
   {
       error += 'Enter "Address"\n';
       $("#bill_address_line1").addClass('error');
   }

   if (trim($("#bill_zip").val()).length != 5)
   {
       error += 'Enter correct "Zip" (5 digits)\n';
       $("#bill_zip").addClass('error');
   }

   if ($("#bill_state").val() == 0)
   {
       error += 'Select "State"\n';
       $("#bill_state").addClass('error');
   }

   if (!trim($("#bill_city").val()))
   {
       error += 'Enter "City"\n';
       $("#bill_city").addClass('error');
   }

   if ($('#save_bill_address').is(':checked'))
   {
        if (!trim($('#bill_record_name').val()))
        {
           error += 'Enter "Save As" for billing address\n';
           $("#bill_record_name").addClass('error');
        }
   }

   if ($('#save_ship_address').is(':checked'))
   {
       if (!trim($("#ship_firstname").val()))
       {
           error += 'Enter shipping "First Name"\n';
           $("#ship_firstname").addClass('error');
       }

       if (!trim($("#ship_lastname").val()))
       {
           error += 'Enter shipping "Last Name"\n';
           $("#ship_lastname").addClass('error');
       }
       
       if (!trim($("#ship_phone").val()))
       {
           error += 'Enter shipping "Phone"\n';
           $("#ship_phone").addClass('error');
       }

       if (!trim($("#ship_address_line1").val()))
       {
           error += 'Enter shipping "Address"\n';
           $("#ship_address_line1").addClass('error');
       }

       if (trim($("#ship_zip").val()))
       {
           var ship_zip = $("#ship_zip").val();
           if (String(ship_zip).length != 5)
           {
               error += 'Enter correct shipping "Zip" (5 digits)\n';
               $("#ship_zip").addClass('error');
           }
       }
       if (!trim($("#ship_city").val()))
       {
           error += 'Enter shipping "City"\n';
           $("#ship_city").addClass('error');
       }

        if (!trim($('#ship_record_name').val()))
        {
           error += 'Enter "Save As" for shipping address\n';
           $("#ship_record_name").addClass('error');
        }
   } else {
       if (trim($("#ship_zip").val()))
       {
           var ship_zip = $("#ship_zip").val();
           if (String(ship_zip).length != 5)
           {
               error += 'Enter correct shipping "Zip" (5 digits)\n';
               $("#ship_zip").addClass('error');
           }
       }
   }

   //CARD DATA
   if ($("#card_number").length)
   {
       if (!trim($("#card_number").val()))
       {
           error += 'Enter "Credit Card Number"\n';
           $("#card_number").addClass('error');
       }

       var card_type = $('input[name=card_type]:checked').val();
       if (card_type != 'A' && card_type != 'D' && card_type != 'V' && card_type != 'M')
       {
           error += 'Choose "Card Type"\n';
       }
/*
       var now = new Date();
       var month = now.getMonth() + 1;
       var selMonth = parseInt($('#bill_expmonth').val());
       if (parseInt($('#bill_expmonth').val()[0]) == 0) selMonth = parseInt($('#bill_expmonth').val().substr(1));
       if ( selMonth < month)
       {
           error += 'Your card is expired\n';
           $("#bill_expmonth").parent().addClass('error');
       } else {
           $("#bill_expmonth").parent().removeClass('error');
       }
*/
       if (!$("#card_code").val()) {
           error += 'Enter "Card Code"\n';
           $("#card_code").addClass('error');
       } else if ($("#card_code").val()) {
           if ( card_type == 'A')
           {
             if ( $("#card_code").val().length != 4 )
             {
                error += 'Please, enter 4 digits in the card security code.\n'
                $("#card_code").addClass('error');
             }
           } else {
             if ( $("#card_code").val().length != 3 )
             {
                error += 'Please, enter 3 digits in the card security code.\n'
                $("#card_code").addClass('error');
             }
           }
       }
   }

   if (error) {
        $.watermark.showAll();
        alert(error);
        return false;
   }

   blockInvisible('#billing_info_form');

   return true;
}


function checkout()
{
    if (validateCheckoutForm())
    {
        $.ajax({
             type: "POST",
             url: "/checkout/save/",
             data:  $('#billing_info_form').serialize(),
             dataType: "html",
             beforeSend: function()
             {
                blockStandart('#billing_info_form');
             },
             success: function(response){
                var data = $.evalJSON(response);
                if (data.error)
                {
                    $('#checkout_error_message').html(data.error);
                    $('#checkout_error_block').show();
                } else if (data.output) {
                    $('#listing').html(data.output);
                }
                $('#billing_info_form').unblock();
                //document.location.href='/checkout/complete';
             }
        });
    }
}

function processRecalculateResponse(response, id, quantity)
{
    if (response == "state_inactive")
    {
        alert('Product is out of stock');
        return false;
    }
    else if ('Select Shipping' == response)
    {
        var url_ship = "/index.php?a=2.17&id=" + id + "&quantity=" + quantity;
        ShowDialog(url_ship, 300, 'Ship To State', 'ship_to_state');
    }
    else if (response == "Need New York")
    {
        var url_ship = "/index.php?a=2.19";
        ShowDialog(url_ship, 300, 'Ship To State', 'ship_to_state');
    }
    else if (response == "Gift Sets")
    {
        var url_ship = "/index.php?a=2.20&id=" + id + "&quantity=" + quantity;
        ShowDialog(url_ship, 300, 'Ship To State', 'ship_to_state', function(){ cartReload('none'); });
    }
    else if (response == "Gift Sets no ship to")
    {
        var url_ship = "/index.php?a=2.17&id=" + id + "&quantity=" + quantity + "&is_first_gift_set=1";
        ShowDialog(url_ship, 550, 'Ship To State', 'ship_to_state', function(){ cartReload('none'); });
    }
    else
    {
        if ($('#products_table').length) recalculate();
        else if (trim(response)) $('#cart_block_1').html(response);
        else { cartReload(); }
    }
}

function selectZip(zip, type)
{
    if (zip.length != 5) return false;

    $.ajax({
         type: "POST",
         url: "/ajax_functions/select_zip/",
         data:  'zip='+zip,
         dataType: "html",
         success: function(response){
             var data = $.evalJSON(response);
             if (data.city) $('#'+type+'_city').val(data.city);
             if (data.state) $('#'+type+'_state').val(data.state);
         }
    });
}

function joinMailing()
{
    var email = document.forms['joinMail'].email_address.value;
    if( !checkEmailAddress(email) ) {
        alert('Please, enter valid e-mail address');
    } else {
        var psw = (document.forms['joinMail'].user_psw != null)? document.forms['joinMail'].user_psw.value: "";
        var zip = document.forms['joinMail'].user_zip.value;
        var dest = 'index.php?a=3.06&email_address='+email+'&user_psw='+psw+'&user_zip='+zip;
        $.ajax({
            type: "POST",
            url: dest,
            dataType: "html",
            complete: function(){},
            success: function(data){
                $('#view_psw').html(data);
            },
            error: function()
            {
            //alert('Export operation failed!');
            }
        });
    }
}


/* FILTERS */

function selectSpiritsBrand()
{
    $('#filter_type').val(2); //{/literal}{$smarty.const.PRODUCT_TYPE_SPIRIT}{literal}
    $('#filter_add_spirits_brand').attr('disabled', '');
    $('#filter_add_spirits_brand').val($('#filter_spirits_brand').val());
    $('#product_list_id').val(0);
    $('#tab_block_id').val(0);
    $('.filter_wine_category').remove();
    submitFilters();
}
function selectWineCountry()
{
    $('#filter_type').val(1);//{/literal}{$smarty.const.PRODUCT_TYPE_WINE}{literal}
    $('#filter_add_wine_country').attr('disabled', '');
    $('#filter_add_wine_country').val($('#filter_wine_country').val());
    $('#product_list_id').val(0);
    $('#tab_block_id').val(0);
    $('.filter_wine_category').remove();
    submitFilters();
}
function selectWineType()
{
    $('#filter_type').val(1); //'{/literal}{$smarty.const.PRODUCT_TYPE_WINE}{literal}'
    $('#filter_add_wine_type').attr('disabled', '');
    $('#filter_add_wine_type').val($('#filter_wine_type').val());
    $('#product_list_id').val(0);
    $('#tab_block_id').val(0);
    $('.filter_wine_category').remove();
    submitFilters();
}
function addPriceFilter(id)
{
    $('#sort_price_'+id).val(0);
    $('#product_list_id').val(0);
    $('.filter_wine_category').remove();
    $('#tab_block_id').val(0);
    submitFilters();
}
function removePriceFilter(id)
{
    $('#sort_price_'+id).val(1);
    $('#product_list_id').val(0);
    $('.filter_wine_category').remove();
    $('#tab_block_id').val(0);
    $('#sort_price_'+id).removeAttr('disabled');
    submitFilters();
}
function addSpiritsTypeFilter(id)
{
    $('#sort_spirits_type_'+id).val(0);
    $('.filter_wine_category').remove();
    $('#product_list_id').val(0);
    $('#tab_block_id').val(0);
    $('#spirits_type'+id).attr('disabled', 'disabled');
    $('#filter_type').val(2); //'{/literal}{$smarty.const.PRODUCT_TYPE_SPIRIT}{literal}'
    submitFilters();
}
function removeSpiritsTypeFilter(id)
{
    $('#sort_spirits_type_'+id).val(1);
    $('.filter_wine_category').remove();
    $('#product_list_id').val(0);
    $('#tab_block_id').val(0);
    $('#sort_spirits_type_'+id).attr('disabled', '');
    $('#filter_type').val(2); //'{/literal}{$smarty.const.PRODUCT_TYPE_SPIRIT}{literal}'
    submitFilters();
}
function addRatingFilter(id)
{
    $('#sort_rating_'+id).val(0);
    $('#product_list_id').val(0);
    $('.filter_wine_category').remove();
    $('#tab_block_id').val(0);
    $('#filter_type').val(1); //'{/literal}{$smarty.const.PRODUCT_TYPE_WINE}{literal}'
    $('#filter_page_n').val(1);
    $('#filter_sort_by').val('');
    submitFilters();
}
function removeRatingFilter(id)
{
    $('#sort_rating_'+id).val(1);
    $('#product_list_id').val(0);
    $('.filter_wine_category').remove();
    $('#tab_block_id').val(0);
    $('#sort_rating_'+id).attr('disabled', '');
    $('#filter_type').val(1); //'{/literal}{$smarty.const.PRODUCT_TYPE_WINE}{literal}'
    $('#filter_page_n').val(1);
    $('#filter_sort_by').val('');
    submitFilters();
}

function submitFilters(){
    $.ajax({
        type: "POST",
        url: "/catalog/",
        data: 'ajax=1&'+$('#sort_form').serialize(),
        dataType: "json",
        beforeSend: function()
        {
            blockStandart('#left .panel_shadow');
        },
        complete: function()
        {
            window.location.href = '/catalog/';
        },
        success: function(response) {
            //if (response.redirect) window.location.href = response.redirect;
            //else
          //  window.location.href = '/catalog/';
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#left .panel_shadow').unblock();
        }
    });
}

//function submitFilterBar(num){
//    $.ajax({
//        type: "POST",
//        url: "",
//        data: 'ajax=1&'+$('#filter_bar_form'+num).serialize(),
//        dataType: "json",
//        beforeSend: function()
//        {
//            //blockStandart('#left .panel_shadow');
//        },
//        complete: function()
//        {
//        },
//        success: function(response) {
//            //if (response.redirect) window.location.href = response.redirect;
//        },
//        error: function(xhr, textStatus, errorThrown) {
//            //$('#left .panel_shadow').unblock();
//        }
//    });
//}


$.fn.ceGalleryFillBlocks = function(minwidth){
		
	this.wrapAll('<div class="ce-gallery-list"></div>');
	this.wrap('<div class="ce-gallery-elem-wrapper"></div>');
	
	this.css({width:minwidth+'px'});
	
	var elem = this.closest('.ce-gallery-elem-wrapper');
	var elem_width = minwidth;
	var box = elem.closest('.ce-gallery-list');
	var box_width = box.width();
	
	function getBlocksQuantity (){
		var temp_len = Math.floor(box.width() / minwidth);
		return (temp_len > elem.length) ? elem.length : temp_len;
	}
	
	function getNewWidth(){
		elem_width = Math.floor(box_width / getBlocksQuantity ())-2;
		return elem_width;
	}
	

	elem.bind('refreshWidth',function (){
		elem_width = getNewWidth();
		elem.css({
			'width':elem_width+'px',
			'float':'left'
		});
	});

	$(window).resize(function (){
		if(box.width()!=box_width){
			box_width = box.width();
			elem.trigger('refreshWidth');
		}
	});

	elem.trigger('refreshWidth');
	return this.each(function (){});
};

$.fn.ceReceivesEqualMax = function(param){
	var maxParam = 0;
	this.each(function(){
		var f = parseFloat($(this).css(param));
		maxParam = (f > maxParam)? f : maxParam ;
	});
	
	return this.each(function (){
		$(this).css(param, maxParam);
	});
};


$.fn.ceReceivesEqualMaxHeight = function(){
	var maxParam = 0;
	this.each(function(){
		var f = parseFloat($(this).height());
		maxParam = (f > maxParam)? f : maxParam ;
	});
	return this.each(function (){
		$(this).css({'height' : maxParam});
	});
};

function FontDependentOnWidthScreenNow (){
	var future_width = $('#tab_box').width();
	var font_size = 10;
	if (future_width > 745) font_size = 16;
	else if (future_width > 725) font_size = 15;
	else if (future_width > 685) font_size = 14;
	else if (future_width > 645) font_size = 13;
	else if (future_width > 605) font_size = 12;
	else if (future_width > 575) font_size = 11;
	$('a.tab-n').css('font-size',  font_size + 'px');
}


function addToWishListPopup(prodId)
{
    ShowDialog('/wishlist/choice/?product_id='+prodId, '450', 'Wish Lists');
}

function showWishListForm(id, prodId)
{
    if (id > 0) var title = 'Edit';
    else var title = 'Add';
    ShowDialog('/wishlist/form/?id='+id+'&product_id='+prodId, '450', title+' Wish List');
}

function favoritesAddAll(id) {
    $.ajax({
         type: "POST",
         url: "/wishlist/add_to_cart/"+id+"/",
         data: "",
         dataType: "html",
         success: function(response){
             if (trim(response))
             {
                var data = $.evalJSON(response);
                if (data['select_shipping']) {
                    ShowDialog("/index.php?a=2.17&add_favorites="+id, 300, 'Ship To State', 'ship_to_state');
                } else if (data['no_products']) {
                    ShowDialogText('No Products', 'Error', 250);
                }

                 if (data['inactive']) {
                    var textMsg = '';
                    $.each(data['inactive'], function(k,v){
                        textMsg += v.name+"<span style='font-size:12px;font-style: italic;'> ("+v.reason+")</span><br>";
                    });
                    ShowDialogText(textMsg, "Unable to add folowing products:", 500);
                }

                if (data['reload_cart']) {
                    cartReload();
                }
             }
         }
    });
}

function addNewFavoritesList(prodId)
{
    var error = '';
    if (!trim($('#favorites_title').val())) {
        $('#favorites_title').addClass('error');
        $('#favorites_title').focus();
        return false;
    }
    if ($('#favorites_title').val().length < 5 || $('#favorites_title').val().length > 50)
    {
        $('#favorites_title').addClass('error');
        $('#favorites_title').focus();
        alert('Title should contain 5-50');
        return false;
    }

    $.ajax({
         type: "POST",
         url: "/wishlist/form/",
         data:  $('#favorites_add_list_form').serialize(),
         dataType: "html",
         beforeSend: function() {
            hidePopup();
         },
         success: function(response){
             if (trim(response))
             {
                 _gaq.push(['_trackEvent', 'Wish List', 'New Wish List from cart', '']);
                 var data = $.evalJSON(response);
                 ShowDialogText('Your cart was saved to wish list. You can manage it <a href="/profile/wishlist/'+data['wishlist_id']+'/">here</a>', 'Cart was saved', 300);
             } else {
                if (prodId > 0)
                {
                    _gaq.push(['_trackEvent', 'Wish List', 'New Wish List from product', '']);
                    closePopup();
                    addToWishListPopup(prodId);
                } else {
                    _gaq.push(['_trackEvent', 'Wish List', 'New Wish List from profile', '']);
                    window.location.reload();
                }
             }


         }
    });
}

function removeWishLists()
{
    if (!$('.wishlist_chk:checked').size())
    {
        alert('Check at least one item to remove');
        return false;
    }

    if (confirm_delete())
    {
        $.ajax({
             type: "POST",
             url: "/wishlist/remove/",
             data:  $('#wishlists_form').serialize(),
             dataType: "html",
             beforeSend: function() {
                $.each($('.wishlist_chk:checked'), function(){
                   $(this).parent().parent().remove();
                });
             },
             success: function(response){

             }
        });
    }
}

function removeWishListsProducts()
{
    if (!$('.wishlist_chk:checked').size())
    {
        alert('Check at least one item to remove');
        return false;
    }

    if (confirm_delete())
    {
        var dataStr = $('#wishlists_form').serialize();
        $.ajax({
             type: "POST",
             url: "/wishlist/remove_item/",
             data:  dataStr,
             dataType: "html",
             beforeSend: function() {
                $.each($('.wishlist_chk:checked'), function(){
                   $(this).parent().parent().remove();
                });
             },
             success: function(response){

             }
        });
    }
}

function addProductToFavorites()
{
    if ($('.dev_exists_fav:checked').length <= 0)
    {
        alert('Check at least one');
        return false;
    }

    $.ajax({
         type: "POST",
         url: "/wishlist/choice/",
         data:  $('#favorites_form').serialize(),
         dataType: "html",
         beforeSend: function() {
            hidePopup();
         },
         success: function(response){
            $('#fav_btn_'+$('#favorites_form [name=product_id]').val()).addClass('del-favorites');
 
            closePopup();
         }
    });
}

function sendWishListViaEmail()
{
    var error = '';
    $('input').removeClass('error');
    if (!trim($('#user_code').val()))
    {
        $('#user_code').addClass('error');
        $('#user_code').focus();
        error = 1;
    }
    if (!checkEmail($('#share_email_to').val()))
    {
        $('#share_email_to').addClass('error');
        $('#share_email_to').focus();
        error = 1;
    }
    if (error) { return false; }
    
    //GA track event
    if ($('#wishlist_id').val() > 0)
    {
        _gaq.push(['_trackEvent', 'Wish List', 'Share with friends', 'Wishlist via Email']);
    } else {
        _gaq.push(['_trackEvent', 'Wish List', 'Share with friends', 'Cart via Email']);
    }

    $.ajax({
         type: "POST",
         url: "/wishlist/share/",
         data:  $('#wishlist_email_form').serialize(),
         dataType: "html",
         beforeSend: function() {
            blockInvisible('.ui-dialog');
         },
         success: function(response){
            if (response == '_error_code')
            {
                $('#user_code').addClass('error');
                $('#user_code').focus();
                $('.ui-dialog').unblock();
            } else {
                hidePopup();

                alert('Products\' list was sent!');

                closePopup();
            }
         }
    });
}

function wishlistSaveCartPopup()
{
    $.ajax({
         type: "POST",
         url: "/wishlist/share/",
         data:  $('#wishlist_email_form').serialize(),
         dataType: "html",
         beforeSend: function() {
            //hidePopup();
         },
         success: function(response){
            //closePopup();
            //alert('Email was sent!');
         }
    });
}

//function showTRAIL IMG
var trailObj = {imgHeight:0,jqObj:$([])};
var trailMouseOffset = {left:50,top:0};

function showtrail(imagename,imgHeight,imagename2){
	trailObj.imgHeight = imgHeight;
	trailObj.jqObj = $('#trailimageid');
	str = '<img height="'+trailObj.imgHeight+'" src="' + imagename + '" border="0">';
	if(imagename2){
		str += '<span style="display:inline-block; width:10px; height:100%;">&nbsp;</span><img height="'+trailObj.imgHeight+'" src="' + imagename2 + '" border="0">';
	}
	trailObj.jqObj.html(str).stop(1).fadeTo(200,1);
	
	document.onmousemove=followmouse;
}

function hidetrail(){
	document.onmousemove="";
	trailObj.jqObj.stop(1).fadeTo(100,0,function(){$(this).css({left:"-1500px"});});
}

function getMousePosition(e){
	var position = {left:0,top:0};
	if(typeof e != "undefined"){
		position.left = e.pageX;
		position.top = e.pageY;
	}else if(typeof window.event != "undefined"){
		position.left = event.clientX;
		position.top = event.clientY;
	}
	return position;
}

function followmouse(e){
	var trailElemImg = $('img',trailObj.jqObj);
	var trailElemImgHeight = trailElemImg.height();
	if (!trailObj.imgHeight){
		trailObj.imgHeight = trailElemImg.height();
		trailElemImgHeight = trailObj.imgHeight;
	}
	var trailElemImgWidth  = trailElemImg.width();
	var trailCoord = {left:0,top:0};
	var mousePosition = getMousePosition(e);
	
	var docWidth = $(window).width();
	var docHeight = $(window).height();
	
	trailCoord.left = mousePosition.left + trailMouseOffset.left;
	
	var t_flag = docWidth - mousePosition.left < trailElemImgWidth + trailMouseOffset.left * 2 + 10;
	t_flag && (trailCoord.left = mousePosition.left - trailMouseOffset.left - trailElemImgWidth);
	
	trailCoord.top = (docHeight - trailElemImgHeight) / 2;
	
	var t = (docWidth < 1200) ? docWidth - 210 : docWidth / 2 + 390;
	if(mousePosition.left > t){ 
		trailCoord.left = t - trailMouseOffset.left - trailElemImgWidth;
		trailCoord.top = mousePosition.top;
	}
	
	trailObj.jqObj.css(trailCoord);
}
//END of function showTRAIL IMG

function addressBookDelete(id)
{
    if (confirm('Are you sure?'))
    {
       var url = '/profile/addresses/';
       var data = 'action=delete&id='+id;

       $.ajax({
          type: "POST",
          dataType: "html",
          url: url,
          data: data,
          beforeSend: function() { $('#address_row_'+id).remove(); }
       });
    }
}

function addressBookValidate()
{
    //validate
    var error = '';
    if (!$('#address_name').val()) error += 'Enter "Save As"\n';
    if (!$('#address_firstname').val()) error += 'Enter "First Name"\n';
    if (!$('#address_lastname').val()) error += 'Enter "Last Name"\n';
    if (!$('#address_address1').val()) error += 'Enter "Address"\n';
    if (!$('#address_city').val()) error += 'Enter "City"\n';
    if ($('#address_state').val() == 'N/A') error += 'Select "State"\n';
    if (!$('#address_zip').val()) error += 'Enter "ZIP"\n';
    //if (!$('#address_phone').val()) error += 'Enter "Phone"\n';
//        if (!checkEmailAddress($('#address_email').val())) error += 'Enter correct "Email Address"\n';
    if (error)
    {
        alert(error);
        return false;
    } else {
        return true;
    }
}

function addressBookSave()
{
    var url = '/profile/addresses/';
    var data = $('#address_form').serialize();

    $.ajax({
      type: "POST",
      dataType: "html",
      url: url,
      data: data,
      beforeSend: function() {
          blockStandart('.ui-dialog');
          blockStandart('#listing');
      },
      success: function(response) {
          if (response == '_error')
          {
            alert('Error data!');
          } else {
            $('#listing').html(response);
          }
      },
      complete: function() {
          $("#modalContent").dialog("destroy");
          $('#listing').unblock();
      }
    });
}

function addressBookLoad(value, typeText)
{
    if (value == -1)
    {
        useProfileData(0, typeText); //clean form
    } else if (value == 0) {
        useProfileData(1, typeText); //user profile data
    } else {

        blockStandart('#billing_data_block');
        var url = "/profile/addresses/?action=json&id="+value;
        $.getJSON(url,
            function(data){
              $.each(data, function(key,item){
                $('#'+typeText+key).val(item);
              });
            $('#billing_data_block').unblock();
            if (typeText == 'ship_') reloadProductsTable();
        });
    }
}

function productNotifyPopup(sys_id)
{
    ShowDialog('/product/notify/?sys_id='+sys_id, '368', 'Notification');
}


function addWatermarkOnPlaceholderAttr(){
	$('[placeholder]').each(function(){
		var placeholder = $(this).attr('placeholder');
		$(this).watermark(placeholder);
		!$(this).attr('title') && $(this).attr('title',placeholder);
	});
}$(function(){
	addWatermarkOnPlaceholderAttr();
	$('body').ajaxStop(function(){
		addWatermarkOnPlaceholderAttr();
	});
});
function submitAfterKeyPress(submitElem,keyNumber){submitElem.keypress(function(e){var self=$(this);if(e.which==keyNumber){self.closest('form').submit();console.log('submiting() ... -> well');}else{console.log('submiting() ... ->  ERROR');}});}

