/* basket */
var aElements = {};
function showError(error){
	alert(error);
}

function up_basket_top(BASKET_LIST){
	if(BASKET_LIST){
		$('#basket-status').html(BASKET_LIST);
	}
}

function up_el_price(iParent){
	var pizza_price = 0;
	if($('#pizza-element-price-'+iParent).length){
		pizza_price = $('#pizza-element-price-'+iParent).val();
	}else if(typeof(aElements[iParent]['SIZES']) !== undefined){
		pizza_price = parseInt(aElements[iParent]['SIZES'][$('#menu-size-id-'+iParent).val()]['PRICE']);
	}

	var toppings_price = 0;
	var count = $('#pizza-count-'+iParent).val()?$('#pizza-count-'+iParent).val():1;
	if(aElements[iParent] !== undefined && aElements[iParent]['TOPPINGS'] !== undefined){
		for(group in aElements[iParent]['TOPPINGS']){
			for(topping in aElements[iParent]['TOPPINGS'][group]){
				toppings_price += parseInt(aElements[iParent]['TOPPINGS'][group][topping]['PRICE'] * aElements[iParent]['TOPPINGS'][group][topping]['COUNT']);
			}
		}
	}

	$('#menu-el-price-'+iParent).html((toppings_price + pizza_price)*count);
	$('#pizza-prise-'+iParent).html(pizza_price);
	$('#pizza-sum-'+iParent).html((toppings_price + pizza_price)*count);

	
	if($('#pizza-type-'+iParent).val()){
		$('#basket-form-'+iParent).trigger('submit');
		
	}
	up_all_prices();
}

function up_all_prices(){
	price = 0;
	for(iParent in aElements){
		if($("#pizza-type-"+iParent).val()){
			var pizza_price = 0;
			if($('#pizza-element-price-'+iParent).length){
				pizza_price = $('#pizza-element-price-'+iParent).val();
			}else if(typeof(aElements[iParent]['SIZES']) !== undefined){
				pizza_price = parseInt(aElements[iParent]['SIZES'][$('#menu-size-id-'+iParent).val()]['PRICE']);
			}

			for(group in aElements[iParent]['TOPPINGS']){
				for(topping in aElements[iParent]['TOPPINGS'][group]){

					pizza_price += parseInt(aElements[iParent]['TOPPINGS'][group][topping]['PRICE'] * aElements[iParent]['TOPPINGS'][group][topping]['COUNT']);
				}
			}
			price += parseInt(pizza_price) * parseInt($('#pizza-count-'+iParent).val());
		}
	}
	$('#basket_total').html(price);
}
/* end add */

function up_element(){
	$('.pizza-up-list').each(function(){
		iParent = $(this).val();

		if(!aElements[iParent]){
			aElements[iParent] = {};
		}
		aElements[iParent]['SIZES'] = {};
		aElements[iParent]['TOPPINGS'] = {};

		if((el = $('#up-element-sizes-'+iParent)).length){

			aElements[iParent]['SIZES'] = eval("("+el.html()+")");

			$('#menu-size-'+iParent).click(function(){

				var iParent = $(this).attr('id').replace('menu-size-','');
				id_now  = $('#menu-size-id-' + iParent).val();
				var next = false;
				if(aElements[iParent]['SIZES']){
					for(el in aElements[iParent]['SIZES']){
						if(id_now == el){
							next = true;
							continue;
						}
						if(next){
							$('#menu-size-id-'+iParent).val(el);
							$('#menu-size-'+iParent+' .center').html(aElements[iParent]['SIZES'][el]['NAME']);
							next = false;
							break;
						}
					};
					if(next){
						for(el in aElements[iParent]['SIZES']){
							$('#menu-size-id-'+iParent).val(el);
							$('#menu-size-'+iParent+' .center').html(aElements[iParent]['SIZES'][el]['NAME']);
							break;
						};
					}
				}
				up_el_price(iParent);
				return false;
			});
		}
		if((el = $('#up-element-top-'+iParent)).length){
			aElements[iParent]['TOPPINGS'] = eval("("+el.html()+")");
			up_element_topping_list(iParent);
		}
	});
}

function up_element_topping_list(iParent){
	for(iToppingGroup in aElements[iParent]['TOPPINGS']){
		for(iTopping in aElements[iParent]['TOPPINGS'][iToppingGroup]){
			up_element_topping(iParent,iToppingGroup,iTopping);
		}	
	}
}

function up_element_topping(iParent,iToppingGroup,iTopping){
	if(parseInt(aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT'])){
		var topId = iParent +'_'+ iToppingGroup + '_' + iTopping;
		sTopping = '<a id="topping_'+ topId + '" class="topping-add-del button left green topping" href="#"><span class="right"><input name="ELEMENTS['+iParent+'][TOPPINGS]['+iToppingGroup+']['+iTopping+'][COUNT]" type="hidden" id="topping_count_'+ topId + '" value="' + aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT'] + '" /><span class="center">' + aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['NAME'] +  ' x' + aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT'] + ' = ' + (parseInt(aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT']) * parseInt(aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['PRICE']))+' руб. </span></span></a>';
		if((el = $('#topping_count_'+ topId)).length){
			$('#topping_'+ topId).replaceWith(sTopping);
		}else{
			$("#el_topping_list_" + iParent).append(sTopping);
		}
	}else{
		$('#topping_' + iParent + '_' + iToppingGroup + '_' + iTopping).remove();
	}
}

$(document).ready(function(){

	var options = { 
        success:       function(data){
	        if(data.ERROR){
				showError(data.ERROR);
			}else{
				$('.message.basket-item').hide();
				$('.message.basket-item.element-add.element-'+$(this.form).children('input[name=rand]').val()+' .inner-text').html('Товар добавлен!<br/>Перейти в <a href="/personal/cart/">корзину</a>');
				$('.message.basket-item.element-add.element-'+$(this.form).children('input[name=rand]').val()).show();
			}
			up_basket_top(data.BASKET_LIST);
		},
        url:       '/sourse/include/basket.add.php',
        dataType:  'json',
        type:      'get', 
        clearForm: false, 
        resetForm: false
        
    };

	$('.ajax-basket-add').ajaxForm(options);

	var options = { 
        success:       function(data){
	        if(data.ERROR){
				showError(data.ERROR);
			}
			up_basket_top(data.BASKET_LIST);
		},
        url:       '/sourse/include/basket.edit.php',
        dataType:  'json',
        type:      'get', 
        clearForm: false, 
        resetForm: false
    };

	$('.basket-form').ajaxForm(options);
	
    $('.topping-list-select-add').change(function(){
		el = $(this).children('option:selected');
		var tmp = el.val().split('_');
		var iToppingGroup = tmp[0];
		var iTopping = tmp[1];
		var iParent = $(this).attr('id').replace('el_toppings_','');

		aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT'] = parseInt(aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT']) + 1;

		up_element_topping(iParent,iToppingGroup,iTopping);
		up_el_price(iParent);
	});

	$('.el-topping-list.add .topping-add-del').live('click',function(){
		var tmp = ($(this).attr('id').replace('topping_','')).split('_');
		aElements[tmp[0]]['TOPPINGS'][tmp[1]][tmp[2]]['COUNT'] = 0;
		up_element_topping(tmp[0],tmp[1],tmp[2]);
		up_el_price(tmp[0]);
		return false;
	});



    $('.topping-list-select-edit').change(function(){
		el = $(this).children('option:selected');
		var tmp = el.val().split('_');
		var iToppingGroup = tmp[0];
		var iTopping = tmp[1];
		var iParent = $(this).attr('id').replace('el_toppings_','');

		aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT'] = parseInt(aElements[iParent]['TOPPINGS'][iToppingGroup][iTopping]['COUNT']) + 1;

		up_element_topping(iParent,iToppingGroup,iTopping);
		up_el_price(iParent);
	});

	$('.el-topping-list.edit .topping-add-del').live('click',function(){
		var tmp = ($(this).attr('id').replace('topping_','')).split('_');
		
		aElements[tmp[0]]['TOPPINGS'][tmp[1]][tmp[2]]['COUNT'] = 0;
		up_element_topping(tmp[0],tmp[1],tmp[2]);
		up_el_price(tmp[0]);
		return false;
	});

	$('.pizza-count').keyup(function(){
		iParent = $(this).attr('id').replace('pizza-count-','');
		if(val = parseInt($(this).val())){
			$(this).val(val);
		}else{
			$(this).val(1);
		}
		up_el_price(iParent);
	});

	$('.del-top').click(function(){
		iParent = $(this).attr('id').replace('pizza-del-','');
		$('#pizza-count-'+iParent).val(0);
		$('#pizza-body-'+iParent).hide();
		up_el_price(iParent);
		return false;
	});
});


/* end of basket */

check_main_add = function(text){
	$.post("/scripts/order.street.isset.php", {'STREET' : $('input[name=check-address]').val(),'CITY' : 'Москва'},function(data){
		if(data){
		   $('.message.main-page-checkaddr .inner-text').html(data);
			$('.message.main-page-checkaddr').show();
			return false;
		}
		return false;
	});
};

checkVal = function(field_name,handler){
	var $this = this;
	$this.handler = handler;
	$this.input = 'input[name='+ field_name +']'; 
	$this.select = '#' + field_name + ' .sub-select';
	$this.input_left = '#' + field_name + '  .input-text.left';
	$this.function_handler = {
		check_addr : function(){
			$.post("/scripts/order.street.isset.php", {'STREET' : text,'CITY' : $('select[name=UF_CITY] option:selected').text()},function(data){
				if(data){
					$('#street_sorry').hide();
				}else{
					$('#street_sorry').show();
				}
				return false;
			});
		},
		address : function(){
			$.post("/scripts/order.street.get.php", {'STREET' : $($this.input).val(),'CITY' : 'Москва'},function(data){
				if(data){
					$($this.select).html(data);
					$($this.select).show();
					$($this.input_left).addClass('selected');
				}else{
					$($this.select).hide();
					$($this.input_left).removeClass('selected');
					$($this.select).html('');
				}
				return false;
			});
		},
		metro : function(){
			$.post("/scripts/order.metro.get.php", {'METRO' : $($this.input).val()},function(data){
				if(data){
					$($this.select).html(data);
					$($this.select).show();
					$($this.input_left).addClass('selected');
				}else{
					$($this.select).hide();
					$($this.input_left).removeClass('selected');
					$($this.select).html('');
				}
				return false;
			});
		}
	};
	$($this.input).keyup(function(event){
		if(event.keyCode == 40){
			if($($this.select).html())
				$($this.select).focus();
		}else{
			$this.function_handler[$this.handler]();
		}
		if(event.keyCode == 13){
			check_main_add();
		}
	});

	$($this.select).keyup(function(event){
		if(event.keyCode == 13 || event.keyCode == 32){
			$($this.input).val($(this).val());
			$(this).html('');
			$(this).hide();
			$($this.input_left).removeClass('selected');
			$($this.input).focus();
			$('#street_sorry').hide();
		}
	});

	$($this.select).click(function(){
		$($this.input).val($(this).val());
		$(this).html('');
		$(this).hide();
		$($this.input_left).removeClass('selected');
		$('#street_sorry').hide();
		
	});

	$($this.select).focusout(function(event){
		$(this).hide();
		$($this.input_left).removeClass('selected');
		$(this).html('');
	});
	return $this;
};

$(document).ready(function(){
	$('input').customInput();
	$('#form_dropdown_SIMPLE_QUESTION_851').chosen();
	$('.topping-list-select-edit').chosen();
	$('.topping-list-select-add').chosen();
	$('#form_dropdown_SIMPLE_QUESTION_445').chosen();
	$('#message-control').click(function(){
		$('#message-control-form').show();
		return false;
	});
	if($('#message-control-form .errortext').html()){
		$('#message-control-form').show();
	}
	$('#corolev-city').click(function(){
		$('.message.main-page-checkaddr .inner-text').html('Доставка в Королев осуществляется по всем улицам.');
		$('.message.main-page-checkaddr').show();
		return false;
	});
	$('#moskow-city').click(function(){
		return false;
	});
	$('.message.main-page-checkaddr .close-but').click(function(){
		$('.message.main-page-checkaddr').hide();
		$('.message.main-page-checkaddr .inner-text').html('');
		return false;
	});
	
	$('.message.phone-me .close-but').click(function(){
		$('.message.phone-me').hide();
		return false;
	});
	$('.message  .close-but').click(function(){
		$($(this).attr('rel')).hide();
		return false;
	});
	$('#phone-me').click(function(){
		$('.message.phone-me').toggle();
		return false;
	});
	
	$('#check-addr').click(function(){
		check_main_add();
		return false;
	});

	address = new checkVal('form_text_66','address');
	reg_address = new checkVal('UF_STREET','address');
	reg_metro = new checkVal('UF_METRO','metro');
	metro = new checkVal('form_text_65','metro');
	check_addr = new checkVal('check-address','address');
	//main_UF_STREET = new checkVal('main_UF_STREET','address');
	
	$("#select-UF_CITY").chosen();
});



