$(document).ready(function(){
    
    function bind_prices(s){
	    $("a[id*='"+s+"_price_']").click(function(){
		    var id = this.id.split('_');
		    var service_id = id[0];
		    var currency_id = id[2];
		    var email = $("input[name='email']").val();
		    var amount = $("input[id='"+ service_id +"_amount']").val();
		    var phone = $("input[id='" + service_id + "_phone']").val();
		    var account = $("input[id='" + service_id + "_account']").val();
		    var data = {service_id:service_id, currency_id:currency_id,
				        email:email, amount:amount, phone:phone, 
                        account:account};
		    $.ajax({
				url:'/JSON_service_order/',
				dataType:"json",
				type:"POST",
				data:data,
				success:function(data){
					//alert(data);
					if(data.result == 'corrections') {
						$('#order').html('');
						var params = {
							'email':$("#email_error"),
							'phone':$("#"+service_id+"_phone_error"),
							'account':$("#"+service_id+"_account_error"),
							'amount':$("#"+service_id+"_amount_error")
						}
						for(var param in params){
							if(typeof(data[param]) == 'undefined'){
								params[param].text('');
							} else {
								params[param].text(String(data[param]));
								// Scroll to e-mail error, if it exists
								if(param == 'email'){
									var isOpera = !!window.opera;
									if (isOpera) { var top = 'html'; } 
									else { var top = 'html, body'; }
									var offset = $('#email').offset().top - 10
									$(top).animate({scrollTop: offset}, 500);
								}
							}
						}
					} 
					else if(data.result == 'ok') {
                        $('ul.messages').remove();
						$('.error').text('');
						$.post('/order_show/', function(html){
							$('#order').html(html);
						});
						// Scroll to cart
						var isOpera = !!window.opera;
						if (isOpera) { var top = 'html'; } 
						else { var top = 'html, body'; }
						var offset = $('#order').offset().top - 10
						$(top).animate({scrollTop: offset}, 500);
					} 
				}
			})
		    return false;
	    });
    }

    function update_prices(){
        this.innerHTML = '<img src="/media/img/loading.gif">'
		var id = this.id.split('_');
		var service_id = id[0];
		var amount = $("input[id='"+ service_id +"_amount']").val();
		var data = {service_id:service_id, amount:amount};
		var tag = this;
        $.ajax({
			url:'/get_prices/',
			dataType:"html",
			type:"POST",
			data:data,
			success:function(data){
                //alert(data)
                tag.innerHTML = data;
                bind_prices(service_id);
            }
        });
    }
    
    //$('#order').load('/order_show/')

//    $("td[id*='_prices']").each(update_prices)
    $("td[id*='_prices']").each(function () {
        var id = this.id.split('_');
        var service_id = id[0];
        bind_prices(service_id);
    });

	
	$("input[id$='phone']").bind('keyup', function(){
		var reg=/^\d+$/;
		var value = $(this).val()
		if (!reg.test(value))
			$(this).val(value.substr(0,(value.length-1)));
	});

	$("input[id$='account']").bind('keyup', function(){
		var reg=/[-_@\w\d\.]+/;///[uUzZrReEbB]?[\d\.]*/
		var value = $(this).val();
        var res = reg.exec(value);
        try {
            $(this).val(res[0]);
        } catch (error) {
            $(this).val(null);
        }
	});
	
	$("input[id$='amount']").bind('keyup', function(){
		var id = this.id.split('_')[0];
		var value = this.value;
		value = parseInt(value,10);
		if (!value)
			value = 0;
		this.value = value;
		// $("a[id*='"+ id +"_price'] > label").each(function(i){
		// 	$(this).text(Math.ceil(100 * value * prices[id][this.id])/100);
		// });
        $("td[id='"+id+"_prices']").each(update_prices);
	});

    // Increment, decrement, deleting order items
    $(".inc, .dec, .del_item").live('click', incDecDel);

    // Changin order currency
    $('.cur_switch').live('click', changeOrderCurrency)
});

function incDecDel() {
    var action = $(this).attr('class');
    var service_id = $(this).attr('rel')
    var data = {service_id: service_id, action: action};
    $.ajax({
        url:'/item_inc_dec_del/',
        dataType:"json",
        type:"POST",
        data:data,
        success:function(data){
            $('ul.messages').remove();
            if(data.result == 'ok') {
                $('#order').html(data.order);
            }
            // Scroll to cart
            var isOpera = !!window.opera;
            if (isOpera) { var top = 'html'; }
            else { var top = 'html, body'; }
            var offset = $('#order').offset().top - 10
            $(top).animate({scrollTop: offset}, 500);
        }
    })
    return false;
}

function changeOrderCurrency() {
    var currency_id = $(this).attr('rel')
    var data = {currency_id: currency_id};
    $.ajax({
        url:'/change_order_currency/',
        dataType:"json",
        type:"POST",
        data:data,
        success:function(data){
            $('ul.messages').remove();
            if(data.result == 'ok') {
                $('#order').html(data.order);
           }
            // Scroll to cart
            var isOpera = !!window.opera;
            if (isOpera) { var top = 'html'; }
            else { var top = 'html, body'; }
            var offset = $('#order').offset().top - 10
            $(top).animate({scrollTop: offset}, 500);
        }
    })
    return false;
}
