/**
 * @author alltouch
 */

function Cash(){

	this . options = new Object();
	this . options . url = piro . options . path + 'cash.php';
	
	this . init = function(){
		piro . cash . load();
		
	}
	
	this . cacheData = null;
	
	this . items = [];	
	
	this . addTo = function (element){
		//piro . loading . hidePage('cash');

		var parent = $(element).parent();
		var obj = piro . catalog . cacheData . items [parent . find('.lineId').val()];
		piro . log(piro . chapters . cacheData . all[obj.category . id])
		if(!piro . chapters . cacheData . all[obj.category . id].orderTo){
			piro . alert . loadCustom('cannotOrderProduct')
			return false;
		}
		
		piro . ajax(
			piro . cash . options . url,
			{
				'type' : 'add',
				'count' : parent.children('.countItems').eq(0).val(),
				'productId' : parent.children('.productId').eq(0).val()
			},
			piro . cash . setTo
		)
		
	}
	
	this . setTo = function(obj){

		if(obj.currentId){
			var el = $('input.productId[value=' + obj . currentId + ']') . prev() . prev();
			if(el.length > 0){
				el.css('visibility', 'visible');
				setTimeout(function(){
					el.css('visibility', 'hidden');
				},2000);
			}
		}
		
		obj . opt = {
			'hideOverlay' : true
		};
		
		piro . cash . set(obj);
	}
	
	this . addToRecomended = function (productId){
		piro . loading . hidePage('cash');
		
		piro . ajax(
			piro . cash . options . url,
			{
				'type' : 'add',
				'count' : 1,
				'productId' : productId
			},
			piro . cash . setToRecomended
		)
		
	}
	
	this . setToRecomended = function(obj){

		if(obj.currentId){
			var el = $('#moreContent a.shop[productid=' + obj . currentId + ']');
			if(el.length > 0){
				el.addClass('SuccessAdd');
				setTimeout(function(){
					el.removeClass('SuccessAdd');
				},3000);
			}
		}
		
		obj . opt = {
			'hideOverlay' : true
		};
		
		piro . cash . set(obj);
	}
	
	this . load = function(){
		
		piro . loading . hidePage('cash');
		
		$.ajax({
			type : 'POST',
			async : false,
			url : piro . cash . options . url,
			data : 	{ data: $.toJSON({ 'type' : 'list' }) },
			dataType : 'json',
			success : piro . cash . set,
			error : piro . ajaxError
		});
		
	}
	
	this . set = function(obj){
		piro . cash . cacheData = obj;
		
		piro . cash . updateBlock(obj);
		
		if (obj . opt && obj . opt . hideOverlay) {
			
		} else {
			piro.loading.showPage('cash');
		}
		
	}
	
	this . updateBlock = function (obj){
		
		
		var element = $('#CashBlock'); 
		element.children('p,table').remove();
		
		var txt = '';
		var opt = piro . auth . mode();
		
		var summ = piro . cash . summ();
		

		if(opt . mode != 1){

			
			var l = obj . items . length;
			if(l>0){
				
				txt += '<table>\
							<thead>\
								<tr>\
									<td class="first">Наименование</td>\
									<td class="middle">Кол-во</td>\
									<td class="last">Сумма</td>\
								</tr>\
							</thead>\
							<tbody>';
			
				for(var i = 0; i<l-1 || (i == l-1 && obj . delivery == 50); i++){
					txt += '<tr>\
								<td class="first">\
									<a href="#"></a>\
									<input type="hidden" value="' + obj.items[i].id + '" />\
									' + obj.items[i].name + '\
								</td>\
								<td>' + obj.items[i].count + obj.items[i].unitName + '</td>\
								<td class="last">' + obj.items[i].summ + '</td>\
							</tr>';
				}
				
				if(obj . delivery == 50){
					txt += '<tr class="bottom">\
							<td class="first">\
								Доставка\
							</td>\
							<td class="middle">&nbsp;</td>\
							<td class="last">50</td>\
						</tr>\
					</tbody>\
					</table>';
				} else {
					txt += '<tr class="bottom">\
							<td class="first">\
								<a href="#"></a>\
								<input type="hidden" value="' + obj.items[l-1].id + '" />\
								' + obj.items[l-1].name + '\
							</td>\
							<td class="middle">' + obj.items[l-1].count + obj.items[l-1].unitName + '</td>\
							<td class="last">' + obj.items[l-1].summ + '</td>\
						</tr>\
					</tbody>\
					</table>';
				}
			}
			if(l > 20){
				txt = '';
			}
			txt += '<p>Товаров: <b>' + summ.count + '</b></p>';
			if(l > 0 && obj . delivery == 50){
				txt += '<p class="short">Доставка: <b> 50 грн.</b></p>';
			}
			txt +='<p>На сумму: <b>' + piro . formatPrice(summ.summ) + ' ' + obj.currency + '.</b></p>';
			
			
		} else {
			txt = '<p>Товаров: <b>' + summ.count + '</b></p><p>На сумму: <br/>';
			var l = obj.optTypes.length;
			for(var i=0; i<l; i++){
				txt += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + obj.optTypes[i].name + ': <b' + (summ.summ[i].active?' class="active"':'')  + '>' + piro . formatPrice(Math.round(summ.summ[i].value*100)/100) + '</b> ' + obj.currency + '<br/>'; 
			}
		}
		element.children('a.title').after(txt);
		
		
		
		piro.call('InitLongCashBlock');
		
		if(obj.items . length == 0){
			element.children('a.order').hide();
			element . removeClass('full')
			element.children('a.title').removeAttr('href');
		} else {
			element.children('a.order').show();
			element . addClass('full')
			element.children('a.title').attr('href','#order');
		}
		
		
		piro . call('NeedResize');
	}
	
	this.setTable = function(){
		var txt = '\
			<table class="cash">\
				<thead>\
					<tr class="top">\
						<td colspan="7">\
							<div></div>\
						</td>\
					</tr>\
					<tr>\
						<td class="first" colspan="2">Товар</td>\
						<td>Цена</td>\
						<td>Кол-во</td>\
						<td>Сумма</td>\
						<td class="last" colspan="2">Удалить</td>\
					</tr>\
				</thead>\
				<tbody>\
		';
		
		var top = piro . cash . cacheData;
		var data = top . items;		
		var l = data.length;
		for(var i = 0; i < l ; i++){
			var item = data[i];
			
			var clas='';
			if (i == 0) {
				clas = 'top';
			}
			else if (i == l - 1) {
				//clas = "bottom";
			}
			txt += '\
				<tr class="' + clas + '">\
					<td class="left">\
						<input type="hidden" class="productId" value="' + item.id + '" />\
						<input type="hidden" class="lineId" value="' + i + '" />\
					</td>\
					<td class="product first">\
						<img src="/data/products' + item.image + '.s1.jpg" />\
						<b>' + item.category.name + ': ' + item.name + ' (' + item.artikul + ')</b>\
					</td>\
					<td>' + piro . formatPrice(item.price) + ' ' + top.currency + '.</td>\
					<td><input value="' + item.count + '" class="countItemsInCash" /> ' + item . unitName + '</td>\
					<td>' + piro . formatPrice(item.price * item . count) + ' ' + top.currency + '.</td>\
					<td class="last"><a class="deleteLine"></a></td>\
					<td class="right"></td>\
				</tr>\
			';
			
		}

			txt += '\
				<tr class="bottom">\
					<td class="left"></td>\
					<td class="product first">\
						<span>Доставка по г.Киеву</span>\
					</td>\
					<td>50 ' + top.currency + '.</td>\
					<td>1</td>\
					<td>50 ' + top.currency + '.</td>\
					<td class="last"></td>\
					<td class="right"></td>\
				</tr>';

		
		var summ = piro . cash . summ();
		
		txt += '\
			</tbody>\
			<tfoot>\
				<tr class="ftop">\
					<td class="first" colspan="3"></td>\
					<td></td>\
					<td></td>\
					<td class="last" colspan="2"></td>\
				</tr>\
				<tr>\
					<td class="first" colspan="3">Итого:</td>\
					<td>' + summ.count + '</td>\
					<td>' + piro . formatPrice(summ.summ ) + ' ' + top.currency + '.</td>\
					<td class="last" colspan="2"><a class="deleteAllLines"></a></td>\
				</tr>\
				<tr class="fbottom">\
					<td class="first" colspan="3"></td>\
					<td></td>\
					<td></td>\
					<td class="last" colspan="2"></td>\
				</tr>\
				<tr class="bottom">\
					<td colspan="7">\
						<div></div>\
					</td>\
				</tr>\
			</tfoot>\
		</table>\
		';
		
		$('#body h1:first').after(txt);
		
	}
	
	this.setTable2 = function(){
		var txt = '\
			<table class="cash">\
				<thead>\
					<tr class="top">\
						<td colspan="8">\
							<div></div>\
						</td>\
					</tr>\
					<tr>\
						<td class="first" colspan="2">Товар</td>\
						<td>Кол-во</td>\
						<td>Прайс</td>\
						<td>Цена</td>\
						<td>Сумма</td>\
						<td class="last" colspan="2">Удалить</td>\
					</tr>\
				</thead>\
				<tbody>\
		';
		
		var top = piro . cash . cacheData;
		var data = top . items;
		
		piro . log(top);
		
		var rowspan = data[0].price . length;
				
		var l = data.length;
		for(var i = 0; i < l ; i++){
			var item = data[i];
			
			var clas='';
			if (i == 0) {
				clas = 'top';
			}
			else if (i == l - 1) {
				//clas = "bottom";
			}			
			
			txt += '\
				<tr class="' + clas + '">\
					<input type="hidden" class="productId" value="' + item.id + '" />\
					<input type="hidden" class="lineId" value="' + i + '" />\
					<td class="left" rowspan="' + rowspan + '"></td>\
					<td class="product first" rowspan="' + rowspan + '">\
						<img src="/data/products' + item.image + '.s1.jpg" />\
						<b>' + item.category.name + ': ' + item.name + ' (' + item.artikul + ')</b>\
					</td>\
					<td rowspan="' + rowspan + '"><input value="' + item.count + '" class="countItemsInCash" /> ' + item . unitName + '</td>\
					<td>' + item.price[0].name.substr(4) + '</td>\
					<td>' + piro . formatPrice(item.price[0].value) + ' ' + top.currency + '.' + '</td>\
					<td>' + piro . formatPrice(item.price[0].value * item . count) + ' ' + top.currency + '.' + '</td>\
					<td class="last" rowspan="' + rowspan + '"><a class="deleteLine"></a></td>\
					<td class="right" rowspan="' + rowspan + '"></td>\
				</tr>\
			';
			
			for(var j=1; j<rowspan; j++){
				txt += '<tr>\
					<td>' + item.price[j].name.substr(4) + '</td>\
					<td>' + piro . formatPrice(item.price[j].value) + ' ' + top.currency + '.' + '</td>\
					<td>' + piro . formatPrice(item.price[j].value * item . count) + ' ' + top.currency + '.' + '</td>\
				</tr>';
			}
			
			if (i != l - 1) {
				txt += '<tr>\
						<td class="left"></td>\
						<td colspan="6" class="empty"></td>\
						<td class="right"></td>\
						</tr>';
			}
			
		}
		
		var all = piro . cash . summ();
		piro . log(all)
		piro . log(typeof all)
		txt += '\
			</tbody>\
			<tfoot>\
				<tr class="ftop">\
					<td class="first" colspan="2"></td>\
					<td></td>\
					<td></td>\
					<td colspan="2"></td>\
					<td class="last" colspan="2"></td>\
				</tr>\
				<tr>\
					<td class="first" colspan="2" rowspan="' + rowspan + '">Итого:</td>\
					<td rowspan="' + rowspan + '">' + all.count + '</td>\
					<td>' + (all.summ[0].active? '<b>' : '') + top.optTypes[0].name.substr(4) + (all.summ[0].active? '</b>' : '') + '</td>\
					<td colspan="2">' + (all.summ[0].active? '<b>' : '') + piro . formatPrice(all.summ[0].value) + ' ' + top.currency + '.' + (all.summ[0].active? '</b>' : '') + '</td>\
					<td class="last" colspan="2" rowspan="' + rowspan + '"><a class="deleteAllLines"></a></td>\
				</tr>';
		for(j = 1; j<rowspan; j++){
			txt += '<tr class="moreLines">\
					<td>' + (all.summ[j].active? '<b>' : '') + top.optTypes[j].name.substr(4) + (all.summ[j].active? '</b>' : '') + '</td>\
					<td colspan="2">' + (all.summ[j].active? '<b>' : '') +  piro . formatPrice(all.summ[j].value) + ' ' + top.currency + '.' + (all.summ[j].active? '</b>' : '') + '</td>\
				</tr>';
		}
		txt +=  '\
				<tr class="fbottom">\
					<td class="first" colspan="2"></td>\
					<td></td>\
					<td></td>\
					<td colspan="2"></td>\
					<td class="last" colspan="2"></td>\
				</tr>\
				<tr class="bottom">\
					<td colspan="8">\
						<div></div>\
					</td>\
				</tr>\
			</tfoot>\
		</table>\
		';
		
		$('#body h1:first').after(txt);
	}
	
	this . setTableAll = function(){
		
		$('#body table').remove();
		
		if(piro . cash . cacheData . items . length == 0){
			$('#body p.cash-empty').show();
			$('#body div.cash-empty').hide();
			return ;
		}
		
		$('#body p.cash-empty').hide();
		$('#body div.cash-empty').show();
		
		var _aError = new aError();
		
		var mode = piro . auth . mode();
		if (mode . type > 0 && mode . type < 6) {
			var userinfo = piro.auth.cache.userinfo;
			var i;
			for (i in userinfo) {
				var t = $('#formOrder [name=' + i + ']');
				if (t.length > 0) {
					if (t.is('input,textarea')) {
						t.val(userinfo[i]);
					}
					else 
						if (t.is('select')) {
							t.find('option[value=' + userinfo[i] + ']').attr('selected', 'selected');
						}
				}
			}
			
			if(mode . type == 1 || mode . mode == 2) {
				$('#formOrder .uhide').remove();
				
				_aError . loadCustomOpt('formOrderUser');
			
			} else {
				$('#formOrder .phide').remove();
				$('#formOrder div.deliveryType1,#formOrder div.deliveryType2,#formOrder div.deliveryType3').hide();
				
				_aError . loadCustomOpt('formOrderPartner');
			}
			
		} else {
			if ((mode . type == 7 || mode . type == 9) && piro.auth.cache.userinfo.pricesType == 1)
			{
				$('#formOrder .phide').remove();
					
				_aError . loadCustomOpt('formOrderPartner');
			}
			else
			{
				$('#formOrder .nhide').remove();
							
				_aError . loadCustomOpt('formOrderNone');
			}
		}
		
		_aError . addListeners();
		_aError . addSubmitEvent('SubmitOrder','f_order_submit');
		$('#formOrder')[0].aError = _aError;
		
		
		if(piro.auth.cache && piro.auth.cache.userinfo && piro.auth.cache.userinfo.userType > 1 && piro.auth.cache.userinfo.pricesType && piro.auth.cache.userinfo.pricesType == 1){
			piro.cash.setTable2();
		} else {
			piro.cash.setTable();
		}
		
		piro . call('InitOrderTable');
		
		piro . cash . summ();
	}
	
	this . deleteLine = function(el){
		
		var parent = $(el).parent().parent();
		
		var line = parseInt(parent . find('input.lineId').val());
		
		piro . ajax(
			piro . cash . options .url,
			{
				'type' : 'delete',
				'productId' : parent.find('.productId').val() 
			},
			function(answer){
				//piro . cash . set(answer);
				//piro.cash.setTableAll();
			}
		);
		piro . cash . cacheData . items . splice(line,1);
		piro.cash.setTableAll();
		piro . cash . updateBlock(piro . cash . cacheData);
	}
	
	this . deleteLineLongCash = function(el){
		
		piro . ajax(
			piro . cash . options .url,
			{
				'type' : 'delete',
				'productId' : el.val() 
			},
			function(answer){
				piro . cash . cacheData = answer;
				piro . cash . updateBlock(piro . cash . cacheData);
			}
		);		
	}
	
	this . clear = function(){
		
		piro . ajax(
			piro . cash . options . url,
			{
				'type' : 'clear'
			},
			function(answer){
				//piro . cash . set(answer);
				//piro.cash.setTableAll();
			}
		);
		
		piro . cash . cacheData . items = [];
		piro.cash.setTableAll();
		piro . cash . updateBlock(piro . cash . cacheData);
	}
	
	this . change = function(obj){
		
		piro . ajax(
			piro . cash . options . url,
			{
				'type' : 'change',
				'products' : obj
			},
			function(answer){
				//piro . cash . set(answer);
				//piro.cash.setTableAll();
			}
		);
	}
	
	this . summ = function(){
		var items = piro . cash . cacheData . items;
		var l = items . length;
		var result = {
			'count' : 0,
			'summ' : 0
		};
		
		var user = piro . auth . mode();
		
		if(user . mode == 1){
			result . summ = [0,0,0,0,0,0,0,0,0,0,0];
			for(var i = 0; i<l; i++){
				result . count += items[i].count;
				var l2 = items[i].price . length;
				for(var z = 0 ; z < l2 ; z++){
					result . summ[z] += items[i].count * items[i].price[z].value; 
				}
			}
			
			
				var l2 = piro . cash . cacheData. optTypes .length;
				for (var z = 0; z < l2; z++) {
					var obj = {};
					obj.value = result.summ[z];
					obj.active = (obj.value > parseInt(piro . cash . cacheData. optTypes[z].name.substr(4)));
					result.summ[z] = obj;
				}
			//piro . log(result)
			
		} else {
			for(var i = 0; i<l; i++){
				result . count += items[i].count;
				result . summ += items[i].count * items[i].price;
			}
			
			if(result . summ >= 400){
				piro . cash . cacheData . delivery = 0;
				$('table.cash tbody tr.bottom').hide();
			} else {
				piro . cash . cacheData . delivery = 50;
				if(result. summ > 0)
					result . summ += 50;
				$('table.cash tbody tr.bottom').show();
			}
		}
		
	
		
		return result;
	}
	
	this . loadItem = function(id){
		piro . loading . hidePage('cash-item');
		
		$.ajax({
			type : 'POST',
			async : false,
			url : piro . catalog . options . url,
			data : 	{ data: $.toJSON({ 'type' : 'item', 'id' : id }) },
			dataType : 'json',
			success : function(obj){
				piro . log(obj);
				piro . loading . showPage('cash-item');
				
				var t = {
					'items' : [obj . item],
					'recomended' : obj.recomended
				};
				
				piro . catalog . cacheData = t;
				
				piro . dpopup . set(0);
				piro . dpopup . show();
				
				
			},
			error : piro . ajaxError
		});
	}
}

piro . cash = new Cash();

