/*
 *	Globals
 */
{
	//var baseURL = '192.168.1.34/conforama_multilingue_v2/';
	//var baseURL = 'www.pixel.pt/clientes/conforama2011/conforama_multilingue_v2/';
	//var baseURL = window.location.protocol+"//"+window.location.host+"/v2/";
	
	if( window.location.hostname.indexOf('pixel.pt') > 0 )
	{
		var baseURL = 'www.pixel.pt/clientes/conforama/v2/';
	}
	else if( window.location.hostname.indexOf('conforama.pt') > 0 )
	{
		var baseURL = window.location.host + '/v2/';
	}
	else
	{
		var baseURL = window.location.host + '/conforama/v2/';
	}	
	
	/*
	 *
	 */
	function updateProductsTableTotal()
	{
				var portes = parseFloat($('#portesRate').val());
				var total = parseFloat($('#orderTotalWithoutShipment').text());				
				var totalWithShipment = parseFloat(portes + total).toFixed(2);
				
				$('#orderDetailsTableTotal').text(totalWithShipment);
				$('#orderTotal').text(totalWithShipment);
	} //end updateProductsTableTotal
	
	
	/*
	 *
	 */
	function displayConfirmBtn()
	{

		if ( $('#checkProdAgreement:checkbox:checked').val() && $('#mensagem').val().length > 40 && $('#noShipment:checkbox:checked').val() == 'noShipment' )
		{
			$('#orDetNotify').css('display','block');
		}
		else
		{
			$('#orDetNotify').css('display','none');	
		}
	}  //end displayConfirmBtn

	
	/*
	 *
	 */
	function regexValidator(type,value)
	{
		switch(type)
		{
			case 'number':
				msg = 'São apenas aceites números decimais!';
				var regex = /^\d*[0-9](\,\d*[0-9])?$/;
			break;
			
			case 'price':
				msg = 'São apenas aceites números decimais!';
				var regex = /^\d*[0-9](\.\d*?)?$/;
			break;
			
			case 'alphanumeric':
				msg = 'São apenas aceites valores alfanumericos!';
				var regex = /[a-zA-Z0-9_]/;
			break;
			
			case 'email':
				msg = 'O endereço email é inválido!';
				var regex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i; 
			break;
			
		} //end switch type
		
		if( regex.test( value ) )
		{ 
			return true;
		}
		else
		{
			return false;
		}
		
	} //end regexValidator
}

/*
 * Confirm dialog for delete action
 */
$(function(){
	
	$('.iDelete').bind({
	
		click : function(e){
			
			if ( confirm( this.title ) )
			{
				window.location = this.href;    
			}
			
		return false;
		
		} //End click
	
	});
	
});

/*
 * Confirm dialog for delete action
 */
$(function(){

	$('.itmDel a').bind({
	
		click : function(e){
			
			if ( confirm( this.title ) )
			{
				window.location = this.href;    
			}
			
		return false;
		
		} //End click
	
	});
	
	$('#orDetCancel').bind({
	
		click : function(e){
			
			if ( confirm( this.title ) )
			{
				window.location = this.href;    
			}
			
		return false;
		
		} //End click
		
	});
	
	$('._topCornDel').bind({
	
		click : function(e){
			
			if ( confirm( this.title ) )
			{
				window.location = this.href;    
			}
			
		return false;
		
		} //End click
		
	});
	
});



$(function(){
	
	if ( $("#datepicker").length > 0 )
	{
		$("#datepicker").datepicker($.datepicker.regional['pt-BR']);
	}
});		

$(function(){
	$("#orderFormFilterSelectBox").bind({
		mouseover : function(){
			$("#orderFormFilterSelectBox li ul").fadeIn();
		}
	});
	$("#orderFormFilterSelectBox").bind({
		mouseleave : function(){
			$("#orderFormFilterSelectBox li ul").fadeOut();
		}
	});
});

/*
 * method for stock handling
*/
$(function(){
				
	$('#orDetColProducts .lineBottomRow .decStock').bind({
		click : function() {
			
			var index = $(this).parents('.lineBottomRow').index();
			index = index - 1; //offset

			var curVal = parseInt($('#orDetColProducts .lineBottomRow .existStock').eq(index).val());
			var maxVal = parseInt($('#orDetColProducts .lineBottomRow .wantedStock').eq(index).text());
			
			if ( curVal > 0 && curVal <= maxVal )
			{
				curVal = curVal - 1;
				$("#orDetColProducts ul li .eachStockWrapper .existStock").eq(index).val( curVal );
			}

			if ( curVal < 1 )
			{
				$('#orDetColProducts ul li  .itemOrStock').eq(index).text('vazio');
			}
			
		}
	});

	$('#orDetColProducts .lineBottomRow .incStock').bind({
		click : function() {
			
			var index = $(this).parents('.lineBottomRow').index();
			index = index - 1; //offset
			
			var curVal = parseInt($('#orDetColProducts .lineBottomRow .existStock').eq(index).val());
			var maxVal = parseInt($('#orDetColProducts .lineBottomRow .wantedStock').eq(index).text());
			
			if ( curVal >= 0 && curVal < maxVal )
			{
				$("#orDetColProducts ul li .eachStockWrapper .existStock").eq(index).val( curVal + 1 );
			}
			
			if ( curVal >= 0 )
			{
				$('#orDetColProducts ul li  .itemOrStock').eq(index).text('confirmado');
			}

		}
	});
});

/*
 * Used to validate shipment value
 */
$(function(){
	
	//Main params
	var msg;

	$('#portesRate').bind({
		keyup : function(){
			
			//Validate input data
			if ( regexValidator('price', this.value ) == false )
			{
				$('#portesRate').val( $('#portesRate').val().replace(this.value, '') );
			};
			
			$('#portes').val(this.value);
			
			if ( this.value.length != 0 && regexValidator('price',this.value) && this.value != 0  )
			{
				updateProductsTableTotal();
				$('#portesStateMsg').text('ok');
				$('#portesStateMsg').css('color','green');
				ci_csrf_token = $('#ci_csrf_token').val();
				
				if ( window.location.host !== 'www.conforama.pt' || window.location.host !== 'www.conforama.es')
				{
					var host = 'http://' + baseURL + 'index.php/adminic/backoffice/updateShipment';
				}
				else
				{
					//console.info("heythere");
					var host = 'http://' + baseURL + 'index.php/adminic/backoffice/updateShipment';
				} //end if localhost
				
				arrData = ({  "ci_csrf_token" : "" + ci_csrf_token + "",'portes' : [ $('#encomenda_id').text(), $(this).val()] });
				
				$.ajax({
				   type: "POST",
				   url: host,
				   dataType: "json",
				   data: arrData,
				   beforeSend : function(){
				   },
				   success: function(msg){
						setTimeout(function(){
							setMbReference();
						},1000);
				   }
				 });
				
			} 
			else if ( this.value.length == 0 )
			{
				updateProductsTableTotal();			
				$('#portesStateMsg').text( '(*) ' + (msg ? msg : 'Preencha devidamente!') );
				$('#portesStateMsg').css('color','#DE002A');
			}
			else if ( this.value == 0 )
			{
				updateProductsTableTotal();			
				$('#portesStateMsg').text( '(*) ' + (msg ? msg : 'Tem a certeza que pretende manter este valor?') );
				$('#portesStateMsg').css('color','#DE002A');
			}//end if not 0
		}
	});
	
	$('#mensagem.required').bind({
	
		click : function(){
			if ( $('.required').val() === 'Escreva a mensagem aqui...' )
			{
				$('.required').val('');
			}
		},
		mouseleave : function(){
			if ( $('.required').val().length < 1 )
			{
				$('#msgNotify').html('(*) Preenchimento obrigatório!');
				$('.required').val('Escreva a mensagem aqui...');
			} //end if
		},
		keyup : function(){
			$('.required').val(this.value);
			
			if ( $('.required').val().length < 40 )
			{
				if ( $('.required').val() === 'Escreva a mensagem aqui...' )
				{
					$('#msgNotify').html('(*) Preenchimento obrigatório!');
				}
				else
				{
					$('#msgNotify').html('(*) Preenchimento obrigatório! O texto aparenta ser demasiado curto ?');
				}
				
				displayConfirmBtn();
				showTicktMsgSbmt(false);
			}
			else
			{
				$('#msgNotify').html('<p class="green">Ok</p>');
				displayConfirmBtn();
				showTicktMsgSbmt(true);	
			}
		}
	});
	
});

/*
 * Ajax for order validation/update/save
 */
$(function(){
	
	function updateOrderTotal(total)
	{
		updateProductsTableTotal(total);
	} //end updateOrderTotal
	
	function validateOrderData()
	{
			var arrData = new Array();
			var intRef;
			var intQuantity;
			var c = 0;
			var eachRowTotal;
			var shipment = parseFloat($('#portesRate').val());
			var total = 0;
			var lineid = 0;
			
			arrData	=	$('#orDetColProducts .lineBottomRow').map(function(){
					
					intRef = $(this).find('._ref').text();
					intPrice = $(this).find('._price').val();
					//intQuantity = $(this).find('._quantity').text();
					intQuantity = $(this).find('.existStock').val();
					intAvailable = $(this).find('.existStock').val();
					intOrderId = $(this).find('._orderId').text();
					intId = $(this).find('._Id').text();
					lineid = $(this).find('._lineId').text();
					ci_csrf_token = $('#ci_csrf_token').val();

					//update substotal
					eachRowTotal = intPrice*intAvailable;
					eachRowTotal = eachRowTotal.toFixed(2);
					$(this).find('._subtotal').text(eachRowTotal);
					total = parseFloat(eachRowTotal) + total;
					//console.info(total);
						/*
						console.log('intRef: ' + intRef + 'intPrice: ' + intPrice + 'intQuantity: ' + intQuantity + 'intOrderId: ' + intOrderId + 'intId: ' + intId + 'ci_csrf_token: ' + ci_csrf_token + 'total: ' + total );
						Firebug's log limit has been reached. 0 entries not shown.		Preferences	 
						intRef: 289817intPrice: 39.99intQuantity: intOrderId: 20intId: 19ci_csrf_token: 8734b2aec5e8b0a44fb49a4dc9c9960ctotal: 0
						*/
					
						var tmp = {};
						if ( intRef && intQuantity ) {
								tmp = '{ "ci_csrf_token" : "' + ci_csrf_token  + '", "' + c + '" : [' + intRef + ', ' + intQuantity + ', ' + intPrice  + ', ' + intOrderId + ', '+lineid+', ' + intId + '] }';
						}
						c++;
						return tmp;
				
			});
			//console.info(arrData[0]);
			var txt = '';
			for ( var i=0; i <= arrData.length; i++ )
			{
				if ( typeof(arrData[i]) !== 'undefined' )
				{
					
						txt += arrData[i] + ( i < arrData.length - 1 ? ',' : '' );
				
				}
			}
			
			do
			{
				txt = txt.replace('},{', ',');
			} while ( txt.indexOf('},{') > 0 );
			
			arrData = eval('(' + txt + ')');
			
			var host = 'http://' + baseURL + 'index.php/adminic/backoffice/validateProductOrderData';
			
			//console.info(arrData);
			
			$.ajax({
			   type: "POST",
			   url: host,
			   dataType: "json",
			   data: arrData,
			   beforeSend : function(){
					$('#validateOrderedProducts p .msgAjax').text('A processar os dados de encomenda...');
					$('#validateOrderedProducts p .loading').css('display','inline-block');
					$('.lineBottomRowLast').css('background','#fff9dc');
			   },
			   success: function(msg){
					$('#validateOrderedProducts p .msgAjax').text('Os dados foram guardados com sucesso!');
					$('#validateOrderedProducts p .loading').css('display','none');
					$('.lineBottomRowLast').css('background','#dfffe2');
					
					total = parseFloat( total ).toFixed(2);
					//console.info(total);
					
					$('#orderTotalWithoutShipment').text(total);
					
					updateOrderTotal(total+shipment);
						
						setTimeout( function()
						{
							$('#validateOrderedProducts p .msgAjax').text('Total:');
							$('#validateOrderedProducts p .loading').css('display','none');
							$('.lineBottomRowLast').css('background','#FFF2F2');
						}, 4000);
					  
						setTimeout(function(){
							setMbReference();
						},1000);
					  
			   }
			 });
	};

	$('#validateOrderedProducts').bind({
	
		click : function(){
				validateOrderData();
		}
		
	});
	
	$('#orderDetailsWrapper ._price').bind({
	
			keyup : function(){
			
				/*
				//cleans unwanted values
				$(this).val($(this).val().replace(',','.'));
				*/
				
				//Validate input data
				if ( this.value != 0 && regexValidator('price', this.value ) == false )
				{
					$(this).val( $(this).val().replace(this.value, '') );
				};
		
				validateOrderData();
			}
	});
	
	$('.handlerStock').bind({
			
			click : function(){
				
				validateOrderData();
			}
	});
	
});

/*
 *	Checks state of shipment agreement
 */
$(function(){
	
	$('#noShipment').bind({
		click : function(){
			displayConfirmBtn();
		}
	});
	
	$('#checkProdAgreement').bind({
		click : function(){
			displayConfirmBtn();
		}
	});

});


/*
 *	Tip box when click important options
 */
$(function(){

	$('.importantTipA').bind({
		mouseover : function(){
			$('.notifyTipBox h3').text('Opção A:');
			$('.notifyTipBox p').text('Quando o pedido encontra-se tratado, ou seja, quando não há necessidade de comunicar com o cliente para que se proceda com a entrega! Assim, é lhe enviado o conteúdo em «mensagem para o cliente», a sua tabela com os produtos pedido, e o link com a refª multibanco para proceder com o pagamento.');
			$('.notifyTipBox').fadeIn('slow');
		},
		mouseleave : function(){
			$('.notifyTipBox').fadeOut('slow');
		}
	});
	
	$('.importantTipB').bind({
		mouseover : function(){
			$('.notifyTipBox h3').text('Opção B:');
			$('.notifyTipBox p').text('O cliente é apenas informado sobre o estado da encomenda, ou seja, o administrador comunica uma informação ao cliente, aguardando resposta para proceder com o processamento ou entrega! Como tal, é enviada apenas a mensagem, sem tabela ou referência multibanco.');
			$('.notifyTipBox').fadeIn('slow');
		},
		mouseleave : function(){
			$('.notifyTipBox').fadeOut('slow');
		}
	});
	
});



/*
 *	Change url form submit
 */
$(function(){

	var url = $('#orDetNotifyForm').attr('action');
	var orderId = $('input[name="encomendas_id"]').val() ? $('input[name="encomendas_id"]').val() : false;

	var url1 = 'backoffice/processOrder';
	var url2 = 'pt/confirma_encomenda/';

	$('.importantTipA').bind({
		click : function(){
			url = url.replace( url1, url2 + orderId );
			$('#orDetNotifyForm').attr('action', url);
		}
	});

	$('.importantTipB').bind({
		click : function(){
			url = url.replace( url2 + orderId , url1 );
			$('#orDetNotifyForm').attr('action', url);		
		}
	});
	
});


/*
 *
 */
$(function(){
	
	$('#orderAddFacNum .moveSubOk').bind({
	
		click : function(e) {
			e.preventDefault();
			validateNumFac();
		}
	
	});
	
	function validateNumFac()
	{
			
			if ( window.location.host !== 'www.conforama.pt' || window.location.host !== 'www.conforama.es' )
			{
				var host = 'http://' + baseURL + 'index.php/adminic/backoffice/validateNumFac';
			} 
			else
			{
				var host = 'http://' + baseURL + 'index.php/adminic/backoffice/validateNumFac';
			} //end if localhost

			$.ajax({
			   type: "POST",
			   url: host,
			   data: (
							{ 
								orderId :  parseInt($('#facNumOrderId').val()),
								num_fac :  parseInt($('#facNumInpDt').val()),
								'ci_csrf_token' :  $('#ci_csrf_token').val()								
							}
						),
			   beforeSend : function(){
					$('#facNumInpDt').css('background','#fff9dc');
			   },
			   success: function(msg){
					$('#facNumInpDt').css('background','#fff');
					$('#facStateMsg ').text('Actualizado!');
			   }
			 });
			 
	} //end validateNumFac
	
});


/*
 *
 */
$(function(){
	
	$('#orderAddTransfNum .moveSubOk').bind({
	
		click : function(e) {
			e.preventDefault();
			validateNumTransf();
		}
	
	});
	
	function validateNumTransf()
	{
			
			if ( window.location.host !== 'www.conforama.pt' || window.location.host !== 'www.conforama.es' )
			{
				var host = 'http://' + baseURL + 'index.php/adminic/backoffice/validateNumTransf';
			} 
			else
			{
				var host = 'http://' + baseURL + 'index.php/adminic/backoffice/validateNumTransf';
			} //end if localhost

			$.ajax({
			   type: "POST",
			   url: host,
			   data: (
							{ 
								orderId :  parseInt($('#transfNumOrderId').val()),
								num_transf :  parseInt($('#transfNumInpDt').val()),
								'ci_csrf_token' : $('#ci_csrf_token').val()
							}
						),
			   beforeSend : function(){
					$('#transfNumInpDt').css('background','#fff9dc');
			   },
			   success: function(msg){
			
					$('#transfNumInpDt').css('background','#fff');
					$('#transfStateMsg ').text('Actualizado!');
			   }
			 });
			 
	} //end validateNumFac
	
});
// unhidde submit btn for ticket msgs
var showTicktMsgSbmt = function(param){
	if ( param )
	{
		$('#userOrDetNotify').removeClass('hidden');
	}
	else
	{
		$('#userOrDetNotify').addClass('hidden');		
	}
};
var setMbReference = function(){
	var oid = parseInt($('#encomenda_id').text());
	var ott = parseInt($('#orderDetailsTableTotal').text());
	var host = "http://" + baseURL + "index.php/adminic/pt/getUpdatedMbRef/" + oid + "/" + ott;
	
	$.ajax({
	   type: "POST",
	   url: host,
	   beforeSend : function(){
			$('.setterRefMb').text('--- --- ---');
	   },
	   success: function(msg){
			var mb = msg.split(',');
			
			$('.setterRefMb.__ent').text(mb[0]);
			$('.setterRefMb.__ref').text(mb[1]);
			$('.setterRefMb.__val').text(mb[2]);			
		}
	 });
};
