function block_on(i) {
	$('#block_'+i).hide();
	$('#block-txt_'+i).show();
}

function block_off(i) {
	$('#block_'+i).show();
	$('#block-txt_'+i).hide();
}

function addBuketToCart(id){
	var val=1;
	if(isNaN(val))val = 0;
	if(val<0)val=1;
	if(val>0){
		$.post('/catalogue/cart',{
			'id' : id,
			'do' : 'add_buket',
			'count' : val
		}, function(data){
			if(data=='success'){
				document.location = CURRENT_PAGE;//'/catalogue/cart';
			}else{
				alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
			}
		});
	}
}
	
function addFlower(id,_v, val_container)
{
	var val=parseInt(val_container.val());
	if(isNaN(val))val = 0;
	if(val<0)val=0;
	var def=val+_v;
	if(def<0)def=0;
	val_container.val(def);
	countFlowers();
}
function addFlowerToCart(id, val_container){
	var val=parseInt(val_container.val());
	if(isNaN(val))val = 0;
	if(val<0)val=0;
	if(val>0){
		$.post('/catalogue/cart',{
			'id' : id,
			'do' : 'add_flower',
			'count' : val
		}, function(data){
			if(data=='success'){
				document.location = CURRENT_PAGE;//'/catalogue/cart';
			}else{
				alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
			}
		});
	}
}
function countFlowers(){
    x = document.getElementsByName("flowers_count[]");
    n = 0;
    for (i = 0; i < x.length; i ++)
	n += Number(x[i].value);
    document.getElementById('flowerCount').innerHTML = flowers_in_cart + n;
}

function buyManyFlowers(){
    x=document.getElementsByName("flowers_count[]");
    ids = '';
    vals = '';
    for (i = 0; i < x.length; i ++){
	if(isNaN(x[i].value))t = 0; else t = x[i].value;
	if (t > 0){
	    ids += x[i].id.substring(6) + ',';
	    vals +=  t + ',';
	}
    }
    ids = ids.substring(0, ids.length - 1);
    vals = vals.substring(0, vals.length - 1);

    //alert(vals)
    //addFlowerToCart(ids, vals);
    //addFlowerToCart(x[i].id.substring(6), x[i].value);
    if (ids.length > 0)
    {
	    $.post('/catalogue/cart',{
		    'id' : ids,
		    'do' : 'add_flower',
		    'count' : vals
	    }, function(data){
		//alert(data)
		    if(data=='success'){
			    document.location = CURRENT_PAGE;//'/catalogue/cart';
		    }else{
			    alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
		    }
	    });
    }
}

$(document).ready(function(){

	$('.flower_count').change(function(){
	    countFlowers();
	});
	$('.flowers-to-cart',$(this)).click(function(){
	    buyManyFlowers();
	});

	//----

	$('.cart_buket').each(function(i){
		var id = $(this).attr('id');
		$('.to-cart',$(this)).click(function(){
			addBuketToCart(id);
		});
	});

	$('.cart_flower').each(function(i){
		var id = $(this).attr('id');
		var val_container = $('.flower_count',$(this));
		$('.to-cart',$(this)).click(function(){
			addFlowerToCart(id, val_container);
		});
		$('.plus',$(this)).click(function(){
			addFlower(id, 1,val_container);
		});
		$('.minus',$(this)).click(function(){
			addFlower(id, -1, val_container);
		});
	});
	$('td.del-btn a.cart_flower').click(function(){
		var id = $(this).attr('id');
		if(confirm('Вы действительно хотите удалить этот элемент из корзины?')){
			$.post('/catalogue/cart',{
				'id' : id,
				'do' : 'delete_flower'
			}, function(data){
				if(data=='success'){
					document.location = '/catalogue/cart';
				}else{
					alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
				}
			});
		}
	});
	$('td.del-btn a.cart_buket').click(function(){
		var id = $(this).attr('id');
		if(confirm('Вы действительно хотите удалить этот элемент из корзины?')){
			$.post('/catalogue/cart',{
				'id' : id,
				'do' : 'delete_buket'
			}, function(data){
				if(data=='success'){
					document.location = '/catalogue/cart';
				}else{
					alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
				}
			});
		}
	});
	$('td.del-btn a.clear_cart').click(function(){
		var id = $(this).attr('id');
		if(confirm('Вы действительно хотите очистить корзину?')){
			$.post('/catalogue/cart',{
				'do' : 'delete_cart'
			}, function(data){
				if(data=='success'){
					document.location = '/catalogue/cart';
				}else{
					alert('Произошла внутреняя ошибка. Попробуйте повторить заказ через некоторое время.');
				}
			});
		}
	});

});
jQuery.validator.addMethod("validphone",  function(value, element, param) {
            $c = 0;
            $value = value;
            for ($i = 0; $i < $value.length; $i ++)
                if (parseInt($value[$i]) >= 0 && parseInt($value[$i]) < 10)
                    $c ++;
            if ($c >= 9 && $c <= 11) return true;
            else return false;
	}, 'Please enter valid phone number!');
jQuery.validator.addMethod("validnickname",  function(value, element, param) {
		if(trim(value)=='' && this.optional(element)==false)return true;
		var reg = /^[a-z0-9_-]+$/i
		return reg.test(value) || reg.test(value);
	}, 'Please enter valid nickname!');
jQuery.validator.addMethod("validpassword", function(value, element, param) {
		if(trim(value)=='' && this.optional(element)!=false)return true;
		var reg = /^[a-z0-9_\$\@\*\%\^\?\(\)+=-]+$/i
		return reg.test(value) || reg.test(value);
	}, 'Please enter valid password!');
jQuery.validator.addMethod("validemail", function(value, element, param) {
		if(trim(value)=='' && this.optional(element)==false)return true;
		var reg = /^[0-9a-z_\.-]+@[0-9a-z_^\.-]+\.[a-z]{2,6}$/i
		return this.optional(element) || (reg.test(value) || reg.test(value));
},'Please enter valid email');
jQuery.validator.addMethod("secretkey",  function(value, element, param) {
		if(trim(value)=='' && this.optional(element)==false)return true;
		var reg = /^[a-z0-9_-]+$/i
		return reg.test(value) || reg.test(value);
	}, 'Please enter valid secretkey!');


function processXml(responseXML, form_id, callback_function) {
	var form = $('#'+form_id);
	$('[id^=error_]',form).hide();
	var count_errors = 0;
	$('e', responseXML).each(function(i){
		count_errors++;
		var container	= $('c',$(this)).text();
		var message		= $('m',$(this)).text();
		if(container==form_id+'_secretkey'){
			var s=explode('Form',container);
			refreshSecretkey(form_id+'_secretkey_img',s[0]);
		}
		$('#error_'+container).html(message).show();
	});
	if(count_errors==0 && typeof(callback_function)=='function'){
		callback_function(form_id);
	}
}


function trim( str, charlist ) {
	charlist = !charlist ? ' \s\xA0' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
	var re = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
	return str.replace(re, '');
}

/***********************************************************************************/

function str_replace(search, replace, subject) {
	var s = subject;
	var f = [].concat(search);
	var r = [].concat(replace);
	var l = (f.length>r.length) ? r.length : f.length;
	var i = 0;

	for (i=0; i<l; ++i)
	{
		s = s.split(f[i]).join(r[i]);
	}

	return s;
}
function explode( delimiter, string ) {    // Split a string by string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: kenneth
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

    var emptyArray = { 0: '' };

    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}

function number_format( number, decimals, dec_point, thousands_sep ) {    // Format a number with grouped thousands
    //
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)

    var i, j, kw, kd, km;

    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ",";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ".";
    }

    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }

    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


    return km + kw + kd;
}

