// This function checks if the username field
var pagRows = 0;
var order_numCars = 0;
var goldMaxCars = 10;
var b_num=-1;
var t_orders = 0;
var bookedOrders=new Array();
var reg_cityValues=new Array();
for(i=35; i<=48; i++){
	reg_cityValues[i]='';
}

function fillArray() {
 	fieldsToValidate = document.getElementById('requiredFields').value.split(",");
}

function displayUsers2(type,rows,filter,status) {
	var filterQuery=' ';
	if(type=='Suspend'){
		filterQuery += ' AND u_status = 2 AND penalties > 2 ';
	}
	
	if(filter != null){
		var FData = filter.split('|');
		var status = FData[0];
		var bType = FData[1];
		var mType = FData[2];	
	}else{
		var status = '';
		var bType = '';
		var mType = '';
	}
	
	$.post("includes/users"+type+".php", {"queryString": filterQuery, "status":status, "bType":bType, "mType":mType}, function(data){
		$('#orders_data').html(data);
		paginate(rows);
	});
	
}
 

function displayOrders(type, btype, u_id,rows,status, mType) {
	var ext='';

	if(btype != ''){
		if(btype=='cardealer'){
			ext='_D';
		}else if(btype=='carbroker'){
			ext='_B';
		}
		else{
			ext='_H';
		}
	}
//		alert("orders"+type+ext+".php");
/*	if (u_id==280){
		alert("orders"+type+ext+".php");
	}*/
	$.post("includes/orders"+type+ext+".php", {queryString: " ",bType: btype, mType: mType, uID: u_id, status:status}, function(data){
		$('#orders_data').html(data);
		paginate(rows);
	});	
}

function displayOrders2(type, btype, u_id,rows,status, mType, filter) {
	var ext='';
	if(btype != ''){
		if(btype=='cardealer'){
			ext='_D';
		}else if(btype=='carbroker'){
			ext='_B';
		}
		else{
			ext='_H';
		}
	}	
	
//	alert("orders"+type+ext+".php");
/*	if (u_id==498){
		alert("orders"+type+ext+".php");
	}*/

	$.post("includes/orders"+type+ext+".php", {queryString: " ",bType: btype, mType: mType, uID: u_id, status:status, filter:filter}, function(data){

		$('#orders_data').html(data);
		paginate(rows);
	});	
}


function displayOrders_admin(type, u_id, rows, filter) {
	if(filter != null){
		var FData = filter.split('|');
		var status = FData[0];
		var user = FData[1];
		var hauler = FData[2];
	}else{
		var status = '';
		var user = '';
		var hauler = '';
	}

	$.post("includes/orders"+type+".php", {"queryString": '', "Status":status, "User":user, "Hauler":hauler}, function(data){
		$('#orders_data').html(data);
		paginate(rows);
	});
	
}

function displayListUsers()
{
	$.post("includes/addAdmin.php?opc=LoadUsers", {}, function(data){
		$('#ListUsers').html(data);
		//paginate(rows);
	});
}
function UserEdit(idUser)
{
	document.getElementById('newAdmin').style.display='none';
	document.getElementById('EditAdmin').style.display='block';
	$.post("includes/addAdmin.php?opc=EditUsers", {idUser: idUser}, function(data){
		$('#EditAdmin').html(data);
		//paginate(rows);
	});

}
//////



function filterAdvancedOrders(type, btype, u_id,status,date1,reg1,city1,date2,reg2,city2,pagRows, mType) {
	var filterQuery2=' ';
	$('#orders_data').html('');
	fdTableSort.initEvt();
	//use "-" to be replaced later with " ' " for the query
	if(date1!=''){
		filterQuery2 += ' AND pickup_date = -'+date1+'- ';
	}
	if(reg1!=''){
		filterQuery2 += ' AND regions1.region = -'+reg1+'- ';
	}
	if(city1!=''){
		filterQuery2 += ' AND city1.city LIKE -'+city1+'%- ';
	}
	
	if(date2!=''){
		filterQuery2 += ' AND delivery_date = -'+date2+'- ';
	}
	if(reg2!=''){
		filterQuery2 += ' AND regions2.region = -'+reg2+'- ';
	}
	if(city2!=''){
		filterQuery2 += ' AND city2.city LIKE -'+city2+'%- ';
	}
	
	if($('#o_id').val() != ''){
		filterQuery2 += ' AND order_id = -'+$('#o_id').val()+'-';
	}

	if($('#carhauler').val() != ''){
		filterQuery2 += ' AND c_name = -'+$('#carhauler').val()+'-';
	}
		
	if(filterQuery2 == ' '){
		document.getElementById('date_p').value = '';
		document.getElementById('reg_p').selectedIndex = 1;
		document.getElementById('reg_p').value = '';
		document.getElementById('city_p').value = '';
		document.getElementById('date_d').value = '';
		document.getElementById('reg_d').selectedIndex = 1;
		document.getElementById('reg_d').value = '';
		document.getElementById('city_d').value	= '';
		document.getElementById('o_id').value = '';
		document.getElementById('carhauler').value = '';
	}
	
	var ext='';
	if(btype != ''){
		if(btype=='cardealer'){
			ext='_D';
		}else{
			ext='_H';
		}
	}
	
	$('#orders_data').html('');
	$('#showTResults').html('');
	
	if(type=='Full' && ext=='_H' && mType==1){	
		document.getElementById('goldCart').style.display='none';
	}
	$.post("includes/orders"+type+ext+".php", {queryString: filterQuery2,bType: btype,uID: u_id, status:status, mType: mType}, function(data){
		$('#orders_data').html(data);
		paginate(pagRows);
		
	});
}



///////
function filterOrders(type, btype, u_id,status,date1,reg1,city1,date2,reg2,city2,pagRows, mType) {
	
	var filterQuery=' ';
	$('#orders_data').html('');
	fdTableSort.initEvt();
	//use "-" to be replaced later with " ' " for the query
	if(date1!=''){
		filterQuery += ' AND pickup_date = -'+date1+'- ';
	}
	if(reg1!=''){
		filterQuery += ' AND regions1.region = -'+reg1+'- ';
	}
	if(city1!=''){
		filterQuery += ' AND city1.city LIKE -'+city1+'%- ';
	}
	
	if(date2!=''){
		filterQuery += ' AND delivery_date = -'+date2+'- ';
	}
	if(reg2!=''){
		filterQuery += ' AND regions2.region = -'+reg2+'- ';
	}
	if(city2!=''){
		filterQuery += ' AND city2.city LIKE -'+city2+'%- ';
	}
	
	if(filterQuery == ' '){
		document.getElementById('date_p').value = '';
		document.getElementById('reg_p').selectedIndex = 1;
		document.getElementById('reg_p').value = '';
		document.getElementById('city_p').value = '';
		document.getElementById('date_d').value = '';
		document.getElementById('reg_d').selectedIndex = 1;
		document.getElementById('reg_d').value = '';
		document.getElementById('city_d').value	= '';
	}
	
	var ext='';
	if(btype != ''){
		if(btype=='cardealer'){
			ext='_D';
		}else{
			ext='_H';
		}
	}
	
	$('#orders_data').html('');
	$('#showTResults').html('');
	
	if(type=='Full' && ext=='_H' && mType==1){	
		document.getElementById('goldCart').style.display='none';
	}
	$.post("includes/orders"+type+ext+".php", {queryString: filterQuery,bType: btype,uID: u_id, status:status, mType: mType}, function(data){

		$('#orders_data').html(data);
		paginate(pagRows);
		
	});
	
}


///////
function filterOrdersDebug(type, btype, u_id,status,date1,reg1,city1,date2,reg2,city2,pagRows, mType) {
	var filterQuery=' ';
	$('#orders_data').html('');
	fdTableSort.initEvt();
	//use "-" to be replaced later with " ' " for the query
	if(date1!=''){
		filterQuery += ' AND pickup_date = -'+date1+'- ';
	}
	if(reg1!=''){
		filterQuery += ' AND regions1.region = -'+reg1+'- ';
	}
	if(city1!=''){
		filterQuery += ' AND city1.city LIKE -'+city1+'%- ';
	}
	
	if(date2!=''){
		filterQuery += ' AND delivery_date = -'+date2+'- ';
	}
	if(reg2!=''){
		filterQuery += ' AND regions2.region = -'+reg2+'- ';
	}
	if(city2!=''){
		filterQuery += ' AND city2.city LIKE -'+city2+'%- ';
	}
	if(filterQuery == ' '){
		document.getElementById('date_p').value = '';
		document.getElementById('reg_p').selectedIndex = 1;
		document.getElementById('reg_p').value = '';
		document.getElementById('city_p').value = '';
		document.getElementById('date_d').value = '';
		document.getElementById('reg_d').selectedIndex = 1;
		document.getElementById('reg_d').value = '';
		document.getElementById('city_d').value	= '';
	}
	var ext='';
	if(btype != ''){
		if(btype=='cardealer'){
			ext='_D';
		}else{
			ext='_H';
		}
	}
	$('#orders_data').html('');
	$('#showTResults').html('');
	if(type=='Full' && ext=='_H' && mType==1){	
		document.getElementById('goldCart').style.display='none';
	}
	$.post("includes/orders"+type+ext+".php", {queryString: filterQuery,bType: btype,uID: u_id, status:status, mType: mType}, function(data){
		$('#orders_data').html(data);
		paginate(pagRows);
	});	
}


function filterOrders_adm(type,order,vin,hauler,dealer,status,date1,reg1,city1,date2,reg2,city2,pagRows) {

	var VIN = false;	

	
	

var order = document.getElementById('order').value;
var vin =document.getElementById('vin').value;
var hauler=document.getElementById('hauler').value;
var dealer=document.getElementById('dealer').value;
var status=document.getElementById('status').value;
var date1=document.getElementById('date_p').value;
var reg1=document.getElementById('reg_p').value;
var city1=document.getElementById('city_p').value;
var date2=document.getElementById('date_d').value;
var reg2=document.getElementById('reg_d').value;
var city2=document.getElementById('city_d').value;
var pagRows=document.getElementById('paginationNum').value;



	
	var filterQuery=' ';
	$('#orders_data').html('');
	//fdTableSort.initEvt();
	
	//use "-" to be replaced later with " ' " for the query
	if(order!=''){
		filterQuery += ' AND order_id LIKE *'+order+'%* ';
	}
	if(vin!=''){
		filterQuery += ' AND car_vin = *'+vin+'* ';
		VIN = true;
	}
	if(hauler!=''){
		filterQuery += ' AND company2.c_name LIKE *'+hauler+'%* ';
	}
	if(dealer!=''){
		filterQuery += ' AND company1.c_name LIKE *'+dealer+'%* ';
	}
	if(status!=''){
		filterQuery += ' AND order_status = '+status+' ';
	}
	
	//Advanced search
	//if(date1 != '' && reg1!='' && city1!='' && date2!='' && reg2!='' && city2!=''){
		//if(document.getElementById('usrSearch-on').style.display=='inline-block'){
			
			if(date1!=''){
				filterQuery += ' AND pickup_date = -'+date1+'- ';
			}
			if(reg1!=''){
				filterQuery += ' AND regions1.region = -'+reg1+'- ';
			}
			if(city1!=''){
				filterQuery += ' AND city1.city LIKE -'+city1+'%- ';
			}
			
			if(date2!=''){
				filterQuery += ' AND delivery_date = -'+date2+'- ';
			}
			if(reg2!=''){
				filterQuery += ' AND regions2.region = -'+reg2+'- ';
			}
			if(city2!=''){
				filterQuery += ' AND city2.city LIKE -'+city2+'%- ';
			//}
		//}
	}
	

	
	if(filterQuery == ' '){
		document.getElementById('order').value = '';
		document.getElementById('hauler').value = '';
		document.getElementById('dealer').value = '';
		document.getElementById('status').selectedIndex = 1;
		document.getElementById('status').value = '';
		document.getElementById('vin').value = '';
		
		//advanced search
		if(document.getElementById('usrSearch-on').style.display=='inline-block'){
			document.getElementById('date_p').value = '';
			document.getElementById('reg_p').selectedIndex = 1;
			document.getElementById('reg_p').value = '';
			document.getElementById('city_p').value = '';
			document.getElementById('date_d').value = '';
			document.getElementById('reg_d').selectedIndex = 1;
			document.getElementById('reg_d').value = '';
			document.getElementById('city_d').value	= '';
		}
	}	
	
	$('#t1').html('');
	$('#orders_data').html('');
	$('#showTResults').html('');
	
	
	$.post("includes/orders"+type+".php", {queryString: filterQuery, vin: VIN}, function(data){

		$('#orders_data').html(data);
		paginate(pagRows);
		
	});
	
}

function mailUsers_adm(company,region,city,type, title, message,emailTest) {
	/*
	var filterQuery = ' ';
		
	if(company!=''){
		filterQuery += ' AND c_name LIKE  -'+company+'%- ';
	}
	if(region!=''){
		filterQuery += ' AND region = -'+region+'- ';
	}
	if(city!=''){
		filterQuery += ' AND city LIKE -'+city+'%- ';
	}
	if(type!=''){
		filterQuery += ' AND u_bType = -'+type+'- ';
	}
	
	if(filterQuery == ' '){
		document.getElementById('company').value = '';
		document.getElementById('city').value = '';
		document.getElementById('reg_p').value = '';
		document.getElementById('reg_p').selectedIndex = 0;
		document.getElementById('type').value = '';
		document.getElementById('type').selectedIndex = 0;
	}	
	*/
	$.post("../mailUsers.php", {"company":company ,"region":region ,"city":city ,"type":type, "mTitle":title, "mMessage":message , "emailTest":emailTest}, function(data){

	//	alert('The email was sent');
		if (parseInt(data) > 0){
			alert( '('+data+') e-mails was sent');
			//window.location.reload(true);
		}else{
			alert( '(0) e-mails was sent');
		}
		document.getElementById('mail_title').value='';
		document.getElementById('mail_msg').value='';
		document.getElementById('company').value = '';
		document.getElementById('city').value = '';
		document.getElementById('reg_p').value = '';
		document.getElementById('reg_p').selectedIndex = 0;
		document.getElementById('type').value = '';
		document.getElementById('type').selectedIndex = 0;
		
	});
	
}

function displayModifyRequest(type, rows) {
	// alert(type);
	//Order
	$.post("includes/modification"+type+".php", {type: type}, function(data){
		$('#modification_data').html(data);
		paginate(rows);
	});
	
}

function displayUsers(type,rows) {
	var filterQuery=' ';
	if(type=='Suspend'){
		filterQuery += ' AND u_status = 2 AND penalties > 2 ';
	}
	$.post("includes/users"+type+".php", {queryString: filterQuery}, function(data){
		$('#orders_data').html(data);
		paginate(rows);
	});
	
}

function displayUsersOnline(type,rows) {
	var filterQuery=' ';
	$.post("includes/users"+type+".php", {"queryString": filterQuery, "type":"brokers"}, function(data){
		$('#brokers_online').html(data);
		paginate(rows);
	});

	$.post("includes/users"+type+".php", {"queryString": filterQuery, "type":"dealers"}, function(data){
		$('#dealers_online').html(data);
		paginate(rows);
	});
	
	$.post("includes/users"+type+".php", {"queryString": filterQuery, "type":"haulers"}, function(data){
		$('#haulers_online').html(data);
		paginate(rows);
	});
	
	$.post("includes/users"+type+".php", {"queryString": filterQuery, "type":"admin"}, function(data){
		$('#admin_online').html(data);
		paginate(rows);
	});
	
}

function displayUsers_penalized(rows) {
	var filterQuery=' ';
	$.post("includes/usersActivate2.php", {queryString: filterQuery}, function(data){
		$('#penalized_data').html(data);
		paginate(rows);
	});
	
}



function filterUsers(type,company,reg,city,status,bType,mType,pagRows) {
	var filterQuery=' ';
	$('#orders_data').html('');
	
	fdTableSort.initEvt();
	var checkForSuspended='false';
	if(status==2){
		checkForSuspended='true';
	}
	//use "-" to be replaced later with " ' " for the query
	if(status!=''){
		if(status==1){
			filterQuery += ' AND (u_status =  :'+status+':  OR u_status =  2) ';
		}else if(status!=2) {
			filterQuery += ' AND u_status =  :'+status+': ';
		}else{
			filterQuery='  ';
		}
	}
	if(reg!=''){
		filterQuery += ' AND region = :'+reg+': ';
	}
	if(city!=''){
		filterQuery += ' AND city LIKE :'+city+'%: ';
	}
	if(bType!=''){
		filterQuery += ' AND u_bType = :'+bType+': ';
	}
	if(mType!=''){
		filterQuery += ' AND u_mType = :'+mType+': ';
	}
	if(company!=''){
		filterQuery += ' AND c_name LIKE :%'+company+'%: ';
	}
	if(type=='Suspend' && filterQuery==' '){
		//filterQuery += ' AND (u_status = 2 AND penalties >= 3) ';
	}
	
	if(filterQuery == ' '){
		document.getElementById('company').value = '';
		document.getElementById('reg_p').value = '';
		document.getElementById('city_p').value = '';
		document.getElementById('status').value = '';
		document.getElementById('status').selectedIndex =  0;
		document.getElementById('bType').value = '';
		document.getElementById('bType').selectedIndex = 0;
		document.getElementById('mType').value = '';
		document.getElementById('mType').selectedIndex = 0;
	}
	
	$('#orders_data').html('');
	$('#showTResults').html('');
	
	$.post("includes/users"+type+".php", {queryString: filterQuery, checkSuspended:checkForSuspended}, function(data){

		$('#orders_data').html(data);
		paginate(pagRows);
		
	});
	
}

function manageUsers(action,id, prevStatus,penalties, date, reason2) {
	//alert(action  + " " + id + " " + prevStatus);
	//return false;
	var valid=true;
	var msg='';
	var status='0';
	var days=0;
	var amount=0;
	var reason='';
	var pen=parseInt(penalties);
	
	switch(action){
		case 'Suspend': 
			status='3';
			msg='Are you sure you want to suspend this user?';
			days=document.getElementById('days'+id).value;
			reason=document.getElementById('reason'+id).value;
			if(days == '' || reason == ''){
				valid=false;
				alert('Please check that wrote the number of days and a reason to be suspended');
			}else{
				var alphaExp = /^[0-9]+$/;
				var text=days;
				if(!text.match(alphaExp)){
					valid=false;
					alert('There can only be numbers on the "# Days" field');
				}
			}
			break;
		case 'Activate':
			status='1';
			msg='Are you sure you want to activate this user?';
			break;
		case 'Autoactivate':
			status='1';
			break;
		case 'Accept':
			status='5';
			msg='Are you sure you want to accept this user?';
			break;
		case 'Reject':
			status='6';
			msg='Are you sure you want to reject this user?';
			break;
		case 'Delete':
			status='10';
			msg='Are you sure you want to Delete this user?';
			break;
		case 'Penalize':
			status='2';
			msg='Are you sure you want to penalize this user?';
			amount=document.getElementById('amount'+id).value;
			reason=document.getElementById('reason'+id).value;
			if(amount == '' || reason == ''){
				valid=false;
				alert('Please check that you wrote the amount and a reason to be penalized');
			}else{
				var alphaExp = /^[0-9$.]+$/;
				var text=amount;
				if(!text.match(alphaExp)){
					valid=false;
					alert('There can\'t be letters on the "Amount" field');
				}
			}
			break;
	}
	
	if(valid){
		if(action=='Autoactivate'){
			$.post("includes/manageUsers.php", {newstatus: status, uID:id, prevStatus:prevStatus, date:date, reason2:reason2}, function(data){
				if(data){
					document.getElementById('btn'+id).disabled=true;
				}
			});
		}else if(confirm(msg)){
			$.post("includes/manageUsers.php", {newstatus: status, uID:id, days:days, reason:reason, prevStatus:prevStatus, amount:amount, date:date, reason2:reason2}, function(data){
				
				if(data==true){
					if(action != 'Activate'){
						document.getElementById('btn'+id).disabled=true;
						if(action == 'Accept' || action == 'Reject' ){
							document.getElementById('btn2'+id).disabled=true;
							$.post("../accept_user.php", {uID:id}, function(data){}); //Send welcome mail
							
						}
						if(action == 'Penalize'){
							document.getElementById('amount'+id).readOnly=true;
							document.getElementById('reason'+id).readOnly=true;
							
							$.post("../notifyPenalty.php", {uID:id, reason:reason, amount:amount}, function(data){}); //Send notification of penalty mail
							
							if(pen >= 2){
								msg='This user has now '+(pen+1)+' penalties. \n Do you want to suspend it now?';
								if(confirm(msg)){
									window.location = 'manage.php?act=Suspend';
								}
							}
						}
						if(action == 'Suspend'){
							document.getElementById('days'+id).readOnly=true;
							document.getElementById('reason'+id).readOnly=true;
							$.post("../notifySuspension.php", {uID:id, days:days, reason:reason}, function(data){});
						}
					
					}else{
						window.location.reload();
					}
				}
			});
		}
	}
	
}

function cancelSomething(what,user,date,reason){
	if(what=='Penalty'){
		if(confirm('Are you sure you want to cancel this Penalty?')){
			$.post("includes/cancelPenalty.php", {user: user, date: date, reason: reason}, function(data){
				window.location.reload();
			});
		}
	}else{
		if(confirm('Are you sure you want to cancel this Suspension?')){
			$.post("includes/cancelSuspension.php", {user: user, date: date, reason: reason}, function(data){
			
				if(data=='true'){
					window.location.reload();
				}
			});
		}
	}
}

function paginate(rows,set){
	pagRows = rows;
	if(rows==0){
			try{
			document.getElementById('theTable').className = 'table_info paginate-900000000000000000 max-pages-5';
			}catch(e){
				}
		}else{
			try{
			document.getElementById('theTable').className = 'table_info paginate-'+rows+' max-pages-5';
			}catch(e){
				}
		}
	
	try{
	tablePaginater.init('theTable');
	}catch(e){
		
		}
	
	if(set==true){
		$.post("includes/setPagination.php", {pagination: document.getElementById('paginationNum').selectedIndex}, function(data){ });
	}
}

var upReqSent=false;
function onlyGold(user,req){
	
	if(confirm('This function is only available for GOLD members\n Do you want to upgrade now?')){
		//take the user to upgrade his membership
		if(upReqSent){
			alert('Your Membership Update Request is already being processed, we will contact you soon');
		}else{
			upReqSent=true;
			$.post("upgradeM.php", {user: user}, function(data){ });
			alert('Thanks!\nYour request has already been sent to us and we will contact you soon.');
			
		}
	}
	
}

function upgrade(user){
	if(confirm('You are about to upgrade your membership\nDo you want to continue?')){
		//take the user to upgrade his membership
		upReqSent=true;
		document.getElementById('upgradeBtn').style.display= 'none';
		$.post("upgradeM.php", {user: user}, function(data){ });
		alert('Thanks!\nYour request has already been sent to us and we will contact you soon.');
	}
	
}

function upgrade_adm(user, action){
	if(confirm('You are about to '+action+' this user\'s membership\nDo you want to continue?')){
		//take the user to upgrade his membership
		document.getElementById('up'+user).disabled=true;
		document.getElementById('re'+user).disabled=true;
		$.post("../confirmUpgrade.php", {user: user,action: action}, function(data){ });
	}
	
}

function upgrade_adm_srtCut(user, action){
	if(confirm('You are about to '+action+' this user\'s membership\nDo you want to continue?')){
		//take the user to upgrade his membership
		document.getElementById('upgrade').disabled=true;
		$.post("../confirmUpgrade.php", {user: user,action: action}, function(data){ });
	}
	
}

function downgrade_adm(user, action){
	if(confirm('You are about to '+action+' this user\'s membership\nDo you want to continue?')){
		//take the user to downgrade his membership
		$.post("../confirmDowngrade.php", {user: user,action: action}, function(data){ 
		try{
		document.getElementById('up'+user).disabled=true;
		document.getElementById('re'+user).disabled=true;
			}catch(e){
				
			}
		});
	}
	
}
function downgrade_adm_srtCut(user, action){
	if(confirm('You are about to '+action+' this user\'s membership\nDo you want to continue?')){
		//take the user to upgrade his membership
		document.getElementById('downgrade').disabled=true;
		$.post("../confirmDowngrade.php", {user: user,action: action}, function(data){ });
	}
	
}

function overMultiple(element,num){
	for(i=1; i<=num; i++){
		document.getElementById('r'+i+''+element).className = 'hover';
	}
}

function gotoDetails(order,hauler,dealer,m) {
	//if m is true means its is going to be a modification
	if(m==true){
		window.location = 'orders_details.php?order='+order+'&h='+hauler+'&d='+dealer+'&m=y';
	}else{
		window.location = 'orders_details.php?order='+order+'&h='+hauler+'&d='+dealer;
	}
}



function showDetails(order,h,d, bType,m,user) {
	$.post("includes/ordersDetails.php", {queryString: order, hauler: h, dealer: d, bType:bType, modif: m, user:user}, function(data){
		var table= data.toString();
		$('#ordersDetails').html(table);
	});
}

function showDetails2(order,h,d, bType,m,user) {
	$.post("includes/ordersDetails_driver.php", {queryString: order, hauler: h, dealer: d, bType:bType, modif: m, user:user}, function(data){
		var table= data.toString();
		$('#ordersDetails_driver').html(table);
	});
}


function showUserDetails(user,pwd) {
	$.post("includes/userDetails.php", {queryString: user, pass: pwd}, function(data){
		$('#userDetails').html(data);
	});
	//If password is null means is the admin view
	if(pwd==''){
		$.post("includes/userHistory.php", {queryString: user}, function(data){
			$('#userHistory').html(data);
		});
	}
}

function activateAccount(user) {
	$.post("includes/activateAccount.php", {queryString: user}, function(data){
		//alert(data);
		location.href = "/index.php";
		//$('#messageActive').html(data);
	});
}

function acceptUser(user,pwd) {
	
	$.post("includes/acceptUser.php", {queryString: user}, function(data){
		if(data){
			$.post("includes/notifyUser.php", {queryString: user, pass: pwd}, function(data2){
			if(data2){
				alert('Thanks, the user has been accepted and notified via email');
				window.location = 'http://php.danni2009.s156.eatj.com/ehaulers';
			}
			});
		}
	});
	
}

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

function outMultiple(element,num){
	for(i=1; i<=num; i++){
		document.getElementById('r'+i+''+element).className = '';
	}
}

function returnTP(num2,element,unitVals) {
	if(unitVals){
		indVals = unitVals.split("%");
		for(u=1; u<=indVals.length; u++){
			num = indVals[u-1];
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
			num = "0";
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			if(cents<10)
			cents = "0" + cents;
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
			var indVal = (((sign)?'':'-') + '$ ' + num + '.' + cents);
			$('#t'+u).html(indVal);
		}
	}
	num = num2.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	var value = (((sign)?'':'-') + '$ ' + num + '.' + cents);
	$('#'+element).html(value);
}

function makeCurrency(unitVals) {
	if(unitVals){
		indVals = unitVals.split("%");
		for(u=1; u<=indVals.length; u++){
			num = indVals[u-1];
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
			num = "0";
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			if(cents<10)
			cents = "0" + cents;
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
			var indVal = (((sign)?'':'-') + '$ ' + num + '.' + cents);
			$('#t'+u).html(indVal);
		}
	}
}

function makeCurrencyReports(unitVals,td) {
	if(unitVals){
		indVals = unitVals.split("%");
		for(u=1; u<=indVals.length; u++){
			num = indVals[u-1];
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
			num = "0";
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			if(cents<10)
			cents = "0" + cents;
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
			var indVal = (((sign)?'':'-') + '$ ' + num + '.' + cents);
			$('#'+td+u).html(indVal);
		}
	}
}

function goBack(){
	history.go(-1)
}

function printThis(order,hauler){
	$("#printArea").printArea({mode: "popup", popClose: false});
	//window.open('order_print.php?order='+order+'&h='+hauler);
	//print();
}

function displayHaulers(usr, mtype, req, rows) {
	$.post("includes/getHaulers.php", {"queryString": usr, "mT": mtype, "req": req, "action":"unblock"}, function(data){
		$('#haulers_info').html(data);
		paginate(rows);
	});
}
function displayBlockHaulers(usr, mtype, req, rows) {
	$.post("includes/getHaulers.php", {"queryString": usr, "mT": mtype, "req": req, "action":"block"}, function(data){
		$('#haulers_blocks').html(data);
		paginate(rows);
	});
}

function displayDealers(usr, mtype, req, rows) {
	$.post("includes/getDealers.php", {queryString: usr, mT: mtype, req: req}, function(data){
		$('#dealers_info').html(data);
		paginate(rows);
	});
	
	$.post("includes/get_blockDealers.php", {queryString: usr, mT: mtype, req: req}, function(data){
		$('#blockdealers_info').html(data);
		paginate(rows);
	});
}

function getBlockedUsers(usr,rows){
	$.post("includes/getBlockedUsers.php", {queryString: usr}, function(data){
		$('#blockedUsers_info').html(data);
		paginate(rows);
	});
}

function displayRating(usr, rows) {
	$.post("includes/getRating.php", {queryString: usr}, function(data){
		$('#rating_info').html(data);
		paginate(rows);
	});
}

function displayFeedback(usr, rows) {
	$.post("includes/getFeedback.php", {queryString: usr}, function(data){
		$('#feedback_info').html(data);
		paginate(rows);
	});
}

function displayPenalties(usr,rows) {
	$.post("includes/getPenalties.php", {queryString: usr}, function(data){
		$('#penalties_info').html(data);
		paginate(rows);
	});
}

function displayPayments(usr,rows) {
	$.post("includes/getPayments.php", {queryString: usr}, function(data){
		$('#payments_info').html(data);
		paginate(rows);
	});
}

function displayPayments2(usr,rows) {
	$.post("includes/getPayments2.php", {queryString: usr}, function(data){
		$('#payments_info').html(data);
		paginate(rows);
	});
}

function displayPenalties_historial(usr,rows) {
	$.post("includes/getPenalties_historial.php", {queryString: usr}, function(data){
		$('#penalties_info').html(data);
		paginate(rows);
	});
}

function displaySuspensions_historial(usr,rows) {
	$.post("includes/getSuspensions_historial.php", {queryString: usr}, function(data){
		$('#suspensions_info').html(data);
		paginate(rows);
	});
}

function displayPenalties_adm(rows) {
	$.post("includes/getPenalties.php", {}, function(data){
		$('#penalties_info').html(data);

		paginate(rows);
	});
}

function displayPayments_adm(rows,filter) {
	$.post("includes/getPayments.php", {"filter":filter}, function(data){
		//alert(data);
		$('#payments_info').html(data);
		paginate(rows);
	});
}

function displayPayments_adm2(rows,filter) {
	$.post("includes/getPayments2.php", {"filter":filter}, function(data){
		//alert(data);
		$('#payments_info').html(data);
		paginate(rows);
	});
}

function makePayment(amount, debt, user) {
	var valid= true;
	if(amount == ''){
		valid=false;
		alert('Please write the amount of the payment');
	}else{
		var alphaExp = /^[0-9$.]+$/;
		var text=amount;
		if(!text.match(alphaExp)){
			valid=false;
			alert('The amount can\'t contain letters');
		}
	}
	
	if(parseFloat(amount)>parseFloat(debt)){
		valid=false;
		alert('The amount is bigger than the debt');
	}
	
	if(valid){
		if(confirm('Do you confirm a payment of $'+amount+' for this user?')){
			$.post("includes/makePayment.php", {amount:amount, user: user, debt: debt}, function(data){
				if(data!='false'){
					document.getElementById(user).value='';
					document.getElementById('dh'+user).value=parseFloat(debt-amount);
					$('#debt'+user).html(data);
				}
			});
		}
	}
}

function blocking(who, usr, msgBlock, msgUnblock, block, unblock, action){ 
	
	if(action.toLowerCase()=='unblock'){
		if(confirm(msgUnblock)){
			$.post("includes/blocking.php", {user: usr, B_user: who, action: "unblock"}, function(data){
				if(data){
					$('#h'+who).html(block);
					location.reload(true);
				}
			});
			
		}
	}else{
		if(confirm(msgBlock)){
			$.post("includes/blocking.php", {user: usr, B_user: who, action: "block"}, function(data){
				if(data){
					$('#h'+who).html(unblock);
					location.reload(true);
				}
			});
		}
	}
}
/*
function send2smr(id){
	if (confirm("Are you sure to send this order to shipmyride.com?")){
		$.post("send_ehaorder.php",{"order_id":id},function(data){
			if(data!=0){
				alert("Order successful in shipmyride.com");
			}else{
				alert("Call support area");
				}
			
		});
	}
}

*/
/*function takeOrderOld(who, order, msg, uStatus, dealer,swRunning){ 
	if (swRunning==1){
		alert('Please notice that this order have NON-RUNNER vehicle(s).')
	}
	
	if(uStatus == 3){
		alert('Sorry, you are currently suspended and it\'s not possible to take orders with this status');
	}else{
		
		if(confirm(msg)){
			$.post("includes/takeOrder.php", {orderID: order, hauler:who}, function(data){
				var arrayData = data.split('|');
				if(arrayData[0] == 'true'){
					//$.post("notifyTakenOrder.php", {orderID: order, hauler:who}, function(data){
						if (arrayData.length==2){
							alert("The order Has been sent to "+arrayData[1]);
							window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
						}
						else if(arrayData.length==3){
							alert("Call support area");
						}
						else{
							window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
						}
					//});
				}else{
					alert('Sorry, this order has already been taken or is in process');
				}
			});	
		}
	}
	
}*/

// TAKE ORDER WITH SHOWBOX FUNCTION

var button_style = ".newFeature{ width:80px;margin-right:40px;-webkit-border-radius: 7px;-moz-border-radius: 7px;border-radius: 7px; -webkit-box-shadow: 0px 0px 2px 1px #777;-moz-box-shadow:0px 0px 2px 1px #777;background: rgb(252,234,187); /* Old browsers */background: -moz-linear-gradient(top, rgba(252,234,187,1) 0%, rgba(252,205,77,1) 50%, rgba(248,181,0,1) 51%, rgba(251,223,147,1) 100%); /* FF3.6+ */background:-webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(252,234,187,1)), color-stop(50%,rgba(252,205,77,1)),color-stop(51%,rgba(248,181,0,1)), color-stop(100%,rgba(251,223,147,1))); /* Chrome,Safari4+ */background:-webkit-linear-gradient(top,  rgba(252,234,187,1) 0%,rgba(252,205,77,1) 50%,rgba(248,181,0,1) 51%,rgba(251,223,147,1) 100%); /*Chrome10+,Safari5.1+ */background: -o-linear-gradient(top,  rgba(252,234,187,1) 0%,rgba(252,205,77,1) 50%,rgba(248,181,0,1)51%,rgba(251,223,147,1) 100%); /* Opera 11.10+ */background: -ms-linear-gradient(top,  rgba(252,234,187,1)0%,rgba(252,205,77,1) 50%,rgba(248,181,0,1) 51%,rgba(251,223,147,1) 100%); /* IE10+ */background: linear-gradient(top, rgba(252,234,187,1) 0%,rgba(252,205,77,1) 50%,rgba(248,181,0,1) 51%,rgba(251,223,147,1) 100%); /* W3C */filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#fceabb', endColorstr='#fbdf93',GradientType=0 ); /* IE6-9 */font-family:Arial, Helvetica, sans-serif;font-size:20px;color:#0000000;cursor:pointer;padding:8px;font-weight:bolder;}";

var msg_ask_take_order = '<p style="font-weight:bold;color:#000000;letter-spacing:0pt;word-spacing:4pt;font-size:24px;text-align:center;font-family:trebuchet MS, sans-serif;line-height:1;">Are you sure you can fulfill this order on time?</p><p>&nbsp;</p>';

var msg_cant_take_order = '<p style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:4pt;font-size:20px;text-align:center;font-family:trebuchet MS, sans-serif;line-height:1;">Sorry, you are currently suspended and it\'s not <br />possible to take orders on this status.</p>';

var msg_non_runner_vehicle = '<p style="font-weight:normal;color:#F70000;letter-spacing:0pt;word-spacing:4pt;font-size:16px;text-align:center;font-family:trebuchet MS, sans-serif;line-height:1;">Please notice that this order has a NON-RUNNER vehicle(s).</p><p>&nbsp;</p>';

var msg_call_support = '<p style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:4pt;font-size:20px;text-align:center;font-family:trebuchet MS, sans-serif;line-height:1;">Call support area.</p><p>&nbsp;</p>';

var msg_order_taken = '<p style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:4pt;font-size:20px;text-align:center;font-family:trebuchet MS, sans-serif;line-height:1;">Sorry, this order has already been taken <br />or is being processed.</p><p>&nbsp;</p>';

var msg_blue_alert = '<div style="float:left; margin-left:40px;"><img width="128" height="128" src="images/yellow_alert.png"/></div>'

function takeOrder(who, order, msg, uStatus, dealer,swRunning){ 
	if(uStatus == 3){
		showBox(msg_blue_alert + '<style>' + button_style + '</style>' + '<p>&nbsp;</p>' + msg_cant_take_order + '<p>&nbsp;</p>' + '<button  class="newFeature" onclick="hideBox()">Ok</button>');
	}else{
		if (swRunning==1){
			showBox(msg_blue_alert + '<style>' + button_style + '</style>' + msg_ask_take_order  + msg_non_runner_vehicle + '<button class="newFeature" onclick="takeOrderPost(\'' + who + '\',\'' + order + '\',\'' + dealer + '\')">Yes</button> <button  class="newFeature" onclick="hideBox()">No</button> '); 
		} else {
			showBox(msg_blue_alert + '<style>' + button_style + '</style>' + '<p>&nbsp;</p>' + msg_ask_take_order + '<button class="newFeature" onclick="takeOrderPost(\'' + who + '\',\'' + order + '\',\'' + dealer + '\')">Yes</button> <button  class="newFeature" onclick="hideBox()">No</button> ' + '<p>&nbsp;</p>');
		}
	}	
}


 
function takeOrderPost(who, order, dealer){ 
	$.post("includes/takeOrder.php", {orderID: order, hauler:who}, function(data){
		var arrayData = data.split('|');
		if(arrayData[0] == 'true'){
			$.post("notifyTakenOrder.php", {orderID: order, hauler:who}, function(info){			
				if (arrayData.length==2){
					alert("The order Has been sent to "+arrayData[1]);
					window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
				}
				else if(arrayData.length==3){
					showBox(msg_blue_alert + '<style>' + button_style + '</style>' + '<p>&nbsp;</p>' + msg_call_support + '<p>&nbsp;</p>' + '<button  class="newFeature" onclick="hideBox()">Ok</button>');
				}
				else{
					window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
				}
			});
		}
		else{
			showBox(msg_blue_alert + '<style>' + button_style + '</style>' + '<p>&nbsp;</p>' + msg_order_taken + '<p>&nbsp;</p>' + '<button  class="newFeature" onclick="hideBox()">Ok</button>');
		}
	});	
}


function showComments(user_id){
	$.post('get_comments.php', {"user_id":user_id}, function(data) {
		var comments = JSON.parse(data);
		var msg = "<div style='height:150px;overflow:scroll;overflow-x:hidden;'><table width='600' class='msg'>";
		msg += "<tr><th>Feedback</th><th>Comment</th><th>Reply</th></tr>";
		for(var i in comments){
			var comment = comments[i].rate_comment;
			var reply = comments[i].rate_reply;
			var value = comments[i].rate_value;
			if(comment == ""){
				comment = "No comments";
			}
			var rating = "unknown";
			switch (value){
				case "1":
					rating = "bad";
				break;
				case "2":
					rating = "regular";
				break;
				case "3":
					rating = "great";
				break;
			}
			msg += "<tr><td>" + rating + "</td><td>" + comment + "</td><td>" + reply + "</td></tr>";
		}
		msg += "</table></div>";
		msg += "<br /><hr /><br />";
		msg += "<style>" + button_style + "</style>";
		msg += "<button  class='newFeature' onclick='hideBox()'>Ok</button>";
		showBox(msg);
	});
}

function showNotes(notes){
	var msg = "";
	msg += "<p style='font-size:18px;'>" + notes + "</p>";
	msg += "<br /><hr /><br />";
	msg += "<style>" + button_style + "</style>";
	msg += "<button  class='newFeature' onclick='hideBox()'>Ok</button>";
	showBox(msg);
}

/*
function takeOrder(who, order, msg, uStatus, dealer,swRunning){ 
	if (swRunning==1){
		alert('Please notice that this order have NON-RUNNER vehicle(s).')
	}
	
	if(uStatus == 3){
		alert('Sorry, you are currently suspended and it\'s not possible to take orders with this status');
	}else{
		
		if(confirm(msg)){
			$.post("includes/takeOrder.php", {orderID: order, hauler:who}, function(data){
				if(data == 'true'){
					
					$.post("notifyTakenOrder.php", {orderID: order, hauler:who}, function(data){
						//alert(data + " -- " + who + " -- " + order );
						if (who==280){//shipmyride
							$.post("../send_ehaorder.php",{"order_id":order},function(datasmr){
								//alert('ok');
								if(datasmr!=0){
									alert("The order Has been sent to Shipmyride");
									window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
								}else{
									alert("Call support area");
								}
							});
						}
						else{
							window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
						}
					});
					
				}else{
					alert('Sorry, this order has already been taken or is in process');
				}
			});	
		}
	}
	
}
*/


/*
function takeOrder(who, order, msg, uStatus, dealer,swRunning){ 
	if (who==280){
//		alert('280');
	//	return false;
	
	
	
	}
	if (swRunning==1){
		alert('Please notice that this order have NON-RUNNER vehicle(s).')
	}
	
	if(uStatus == 3){
		alert('Sorry, you are currently suspended and it\'s not possible to take orders with this status');
	}else{
		if(confirm(msg)){
			$.post("includes/takeOrder.php", {orderID: order, hauler:who}, function(data){
				if(data == 'true'){
					$.post("notifyTakenOrder.php", {orderID: order, hauler:who}, function(data){
						window.location = 'orders_details.php?order='+order+'&h='+who+'&d='+dealer;
					});
				}else{
					alert('Sorry, this order has already been taken or is in process');
				}
			});	
		}
	}
	
}
*/

function deliverOrder(bType, order, h, d, user, msg,u_id){ 
	var message=msg;
		if (u_id==user){
		conf = confirm("YOU ARE NOW CONFIRMING THAT THE ORDER WAS DELIVERED?");
		
		if (conf){
			$.post("includes/deliveryOrder.php", {orderID: order, bType:bType, uID:user}, function(data){
			if(data){
				document.getElementById('ratedUser').value = h;
				document.getElementById('ratedOrder').value = order;
				document.getElementById('rating').style.display = 'block';
				document.getElementById('deliverBtn').disabled = true;
			}
		});
			}
		return;
		}
	
	
	if(bType==2){
		message='Please ensure that the Vehicle(S) has been delivered in order to avoid penalties';
	}
	
	if(confirm(message)){
		$.post("includes/deliveryOrder.php", {orderID: order, bType:bType, uID:user}, function(data){
			
			if(data){
				if(bType == 1){
					//Dealer marked as delivered, let's rate the hauler now
					document.getElementById('ratedUser').value = h;
				}else{
					//The hauler marked as delivered, let's ask the dealer to see if its true
					document.getElementById('ratedUser').value = d;
					$.post("notifyDeliveryOrder.php", {orderID: order}, function(data){});
					alert('Thank you! \nAn email has been sent to the dealer to confirm this delivery');
				}
				document.getElementById('ratedOrder').value = order;
				document.getElementById('rating').style.display = 'block';
				document.getElementById('deliverBtn').disabled = true;
			}
		});
	}
	
}

function delayedOrder(order, h, d, msg){ 

	if(confirm(msg)){
		$.post("notifyDelayedOrder.php", {orderID: order}, function(data){
			
				alert('Thank you, we will gonna solve this situation and contact you as soon as possible.');
				document.getElementById('delayBtn').disabled = true;
	
		});
	}
	
}


function rateUser(uID,comment,order,ratingUsr,msgBlock, msgUnblock, block, unblock, type, action, busines){ 
	
	//uID is the rated user can be the dealer or hauler, depending who is rating.
	
	var rate=0;
	if(document.getElementById('rate1').checked){
		rate=document.getElementById('rate1').value;
	}else if(document.getElementById('rate2').checked){
		rate=document.getElementById('rate2').value;
	}else if(document.getElementById('rate3').checked){
		rate=document.getElementById('rate3').value;
	}
	if(rate==0){
		alert('Please give a rate');
	}else if(confirm('Is this correct?')){
		if(rate==1&&comment==''){
			alert('Please write what was wrong');
		}else{
			$.post("includes/rateUser.php", {uID: uID, rate:rate, comment:comment, order: order, ratingUsr:ratingUsr}, function(data){
				
				if(data=='true'){		
					alert('Thank you!');
					document.getElementById('rating').style.display = 'none';
					//					if( (rate==1) && type==1 && ratingUsr!=uID && busines == 2){
					if( (rate==1) &&  ratingUsr!=uID){
						if(confirm('Do you want to block this user?')){
							
							if (type==1){
							//blocking(user to be bloqued, user, msgBlock, msgUnblock, block, unblock, action)
							blocking(uID, ratingUsr, msgBlock, msgUnblock, block, unblock, action);
							}else{
								var x=confirm("Just gold members can block users, do you want upgrade your account?");
								if (x){
									$.post("upgradeM.php", {user: uID}, function(data){ });
									alert('Thanks!\nYour request has already been sent to us and we will contact you soon.');
									}
								}
							
							
							
						}
					}
				}
			});
		}
	}
}

function replyRate(uID,reply,order){ 
	
	if(reply==''){
		alert('Please wirte your Reply');
	}else{
		$.post("includes/rateUser.php", {uID: uID, reply:reply, order: order}, function(data){
			if(data=='true'){		
				document.getElementById('reply'+order).readOnly=true;
				document.getElementById('replyBtn'+order).disabled=true;
			}
		});
	}
}

function advSearch(show) {
	if(show){
		document.getElementById('usrSearch-off').style.display = 'none';
		document.getElementById('usrSearch-on').style.display = 'inline-block';
	}else{
		document.getElementById('usrSearch-on').style.display = 'none';
		document.getElementById('usrSearch-off').style.display = 'inline-block';
	}
}

function deleteOrder(msg,order){
	$.msgbox(msg,{
		  type: "confirm",
		  buttons : [
			{type: "submit", value: "Yes"},
			{type: "submit", value: "No"},
			{type: "cancel", value: "Cancel"}
		  ]
},function(result){
	if(result=="yes"){
		$.post("includes/deleteOrder.php", {order: order}, function(data){
			if(data=='true'){
				//reload the page to refresh the table
				window.location.reload();
				$.post("notifyDeletedOrder_dealer.php", {order: order}, function(data){});
				//$.post("notifyDeletedOrder.php", {order: order}, function(data){});
			}
		});
	}
	
	
});
	
}

function deleteOrder_admn(msg,order){
	var n_user = document.getElementById('MgUserID').value;
	var Comments = document.getElementById('CommentsConfirm').value

	if(confirm(msg)){
		$.post("includes/deleteOrder.php", {order: order, comment: Comments, N_user: n_user}, function(data){
			if(data=='true'){
				//reload the page to refresh the table
				$.post("../notifyDeletedOrder.php", {order: order, comment: Comments, N_user: n_user}, function(data){});
				window.location.reload();				
			}
		});
	}
	
}

function contacted(val, pMail, type){
	var contacted=0;
	if(val){
		contacted=1;
	}
	$.post("includes/contact_dealer.php", {pMail: pMail,type: type,contacted:contacted}, function(data){
		
	});
}


function goldAddCar(units, order, usr){
	if(usr==''){
		// I use this function in case the user has left some booked orders before
		b_num++;
		order_numCars += units;
		bookedOrders[b_num] = order;
	}else{
		if(document.getElementById(order).checked){
			if((order_numCars + units) <= goldMaxCars){
				//book the order
				var action = 1; // 1 = true (book)
				$.post("includes/bookOrder.php", {order: order,usr: usr,action:action}, function(data){
					if(data == true){
						b_num++;
						order_numCars += units;
						bookedOrders[b_num] = order;
					}else{
						alert('Sorry, this orders has just been taken');
						document.getElementById(order).checked = false;
					}
				});
			}else{
				alert('You can select '+goldMaxCars+' units maximum each time.');
				document.getElementById(order).checked = false;
			}
			
		}else{
			order_numCars -= units;
			for(i=0; i<=bookedOrders.length; i++){
				if(bookedOrders[i] == order){
					bookedOrders[i] = 'x';
				}
			}
			var action = 0; // 0 = false (dont book)
			$.post("includes/bookOrder.php", {order: order,usr: usr,action:action}, function(data){
				if(data == true){
					
				}else{
					alert('Sorry, your booking time expired and this orders has just been taken');
				}
			});
		}
	}
}

function goldTakeCars(who,msg){
	if(order_numCars==0){
		alert('You haven\'t select any orders yet');
	}else{
		if(confirm(msg)){
			n=0;
			for(i=0; i< bookedOrders.length ; i++){
				if(bookedOrders[i] != 'x'){
					n++;
					$.post("includes/takeOrder.php", {orderID: bookedOrders[i], hauler:who}, function(data){
						if(data == 'true'){
							t_orders++;
							
						}else{
							n--;
							alert('There was a problem with an order that could not been taken');
							
						}
						if(t_orders==n){
								alert(t_orders+' Orders were taken!');
								window.location = 'orders_taken.php';
							}
					});	
				}
			}	
		}
	}
}

function approveOrder(order,status,btnID,msg){
	if(confirm(msg)){
		$.post("includes/manageOrders.php", {orderID: order, newstatus:status}, function(data){
			if(data == 'true'){					
				document.getElementById(btnID).disabled = true;
				$.post("../accept_order.php", {order:order}, function(data){}); //Send mail to Gold haulers
			}else{
							
			}
		});	
	}
}

function confirmOrderModification(order,approved,msg){
	if(confirm(msg)){
		document.getElementById('b_a'+order).disabled = true;
		document.getElementById('b_r'+order).disabled = true;
		$.post("../confirmOrderModification.php", {orderID: order, status:approved}, function(data){
			if(data == 'true'){					
				document.getElementById('b_a'+order).disabled = true;
				document.getElementById('b_r'+order).disabled = true;
				alert("Data updated!");
			}else{
				alert("Issue with the network provider.");
				document.getElementById('b_a'+order).disabled = true;
				document.getElementById('b_r'+order).disabled = true;
				}
		});	
	}
}

function confirmCompanyModification(company,approved,msg){
	if(confirm(msg)){
		document.getElementById('b_a'+company).disabled = true;
		document.getElementById('b_r'+company).disabled = true;
		$.post("../confirmCompanyModification.php", {company: company, status:approved}, function(data){
			if(data == 'true'){					
				document.getElementById('b_a'+company).disabled = true;
				document.getElementById('b_r'+company).disabled = true;
			}
		});	
	}
}

function trashDelete(what,id,action,msg){
	if(confirm(msg)){
		$.post("includes/trash.php", {what:what, id:id, action:action}, function(data){
			if(data == 'true'){	
				if(document.getElementById('b_det'+id)){
					document.getElementById('b_det'+id).disabled = true;
				}
				if(document.getElementById('b_a'+id)){
					document.getElementById('b_a'+id).disabled = true;
				}
				if(document.getElementById('b_r'+id)){
					document.getElementById('b_r'+id).disabled = true;
				}
				if(document.getElementById('b_p'+id)){
					document.getElementById('b_p'+id).disabled = true;
				}
				if(action=='Restore'){
					$.post("../notifyRestore.php", {id:id}, function(data){});
				}else if(action=='Repost'){
					$.post("../notifyRepost.php", {id:id}, function(data){});
				}
			}
		});	
	}
}

function makeReport(type,date1,date2,valExtra){
	//alert(".");
	var extra=valExtra;
	var dat1=document.getElementById(date1).value;
	var dat2=document.getElementById(date2).value;
	if(validDates(date1,date2) || (dat1!='' && dat2=='')){
		// Make Report
		
		document.getElementById('chart2div').style.display= 'none';
		document.getElementById('reportOrders').style.display= 'none';
		document.getElementById('reportDealers').style.display= 'none';
		document.getElementById('reportHaulers').style.display= 'none';
		document.getElementById('reportPenalties').style.display= 'none';
		document.getElementById('reportUsersLog').style.display= 'none';
	
		document.getElementById('report'+type).style.display= 'block';
		switch(type){
			case 'Orders': 		loading='<td colspan="4">';
								if(valExtra!=''){
									extra = ' AND order_status =  -'+valExtra+'- ';
								}
								break;
			case 'Dealers': 	loading='<td colspan="6">';
								if(valExtra!=''){
									extra = ' AND c_name LIKE  -'+valExtra+'%- ';
								}
								break;
			case 'Haulers': 	loading='<td colspan="6">';
								if(valExtra!=''){
									extra = ' AND c_name LIKE  -'+valExtra+'%- ';
								}
								break;
			case 'Penalties': 	loading='<td colspan="5">';
								if(valExtra!=''){
									extra = ' AND penalty_status =  -'+valExtra+'- ';
								}
								break;
								
			case 'UsersLog':	loading='<td colspan="5">';
								if(valExtra!=''){
									extra = ' AND penalty_status =  -'+valExtra+'- ';
								}
								break;
		}
		
		$('#report_'+type).html('<tr>'+loading+'<img src="../images/ajax-loader.gif" /> Generating Report... </td></tr>');
		$.post("includes/makeReport.php", {type:type, date1:dat1, date2:dat2, extra:extra}, function(data){
//			alert(data);
			if(data){
				if(type=='Orders'){
					document.getElementById('ord_panel').style.display='block';
				}else{
					document.getElementById('ord_panel').style.display='none';
					document.getElementById('status').selectedIndex=0;
				}
				
				if(type=='Penalties'){
					document.getElementById('pen_panel').style.display='block';
				}else{
					document.getElementById('pen_panel').style.display='none';
					document.getElementById('status2').selectedIndex=0;
				}
				
				if(type=='Dealers' || type=='Haulers'){
					document.getElementById('usr_panel').style.display='block';
					document.getElementById('cname').value='';
					
					if(type=='Dealers'){
						document.getElementById('btn_dealers').style.display='inline';
						document.getElementById('btn_haulers').style.display='none';
					}else{
						document.getElementById('btn_dealers').style.display='none';
						document.getElementById('btn_haulers').style.display='inline';
					}
				}else{
					document.getElementById('usr_panel').style.display='none';
				}
				$('#report_'+type).html(data);
			}
		});	
	}else{
		alert('Please check that the dates are correct, start date must be before the current date.\n\n -> If you want to make a single day report leave the end date field empty.');
	}
}

function displayCityLevel(region){
	if(document.getElementById('sm'+region).style.display=='none'){
		document.getElementById('sm'+region).style.display='table-row';
		document.getElementById('i'+region).style.display='none';
	}else{
		document.getElementById('sm'+region).style.display='none';
		document.getElementById('i'+region).style.display='inline';
	}
}

function makeSubReport(parent,date1,date2){
	
	try{
	var city = document.getElementById("city_p").value;
	}catch(e){
		
		}
	
	var valExtra = document.getElementById('status').value;
	var extra = '';
	if(valExtra!=''){
		extra =' AND order_status =  -'+valExtra+'- ';
	}
	
	if(document.getElementById('i'+parent).style.display=='none'){
		reg_cityValues[parent]=$('#sR'+parent).html();
		$('#sR'+parent).html('');
		//document.getElementById('sR'+parent).style.display= 'none';
		document.getElementById('i'+parent).style.display= 'inline-block';
	}else if(reg_cityValues[parent]==''){
		$.post("includes/makeReport.php", {type:parent, date1:date1, date2:date2, extra:extra, city:city}, function(data){																					
			if(data){
				//document.getElementById('sR'+parent).style.display= 'table-row';
				//document.getElementById('sR'+parent).style.lineHeight='100px';
				document.getElementById('i'+parent).style.display= 'none';
				$('#sR'+parent).html(data);
			}
		});	
	}else{
		$('#sR'+parent).html(reg_cityValues[parent]);
		//document.getElementById('sR'+parent).style.display= 'table-row';
		//document.getElementById('sR'+parent).style.lineHeight=100;
		document.getElementById('i'+parent).style.display= 'none';
	}
	/*
	if(document.getElementById('i'+parent).style.display=='none'){
		reg_cityValues[parent]=$('#sR'+parent).html();
		//document.getElementById('sR'+parent).style.display= 'none';
		document.getElementById('i'+parent).style.display= 'inline-block';
	}else if($('#sR'+parent).html()==''){
		$.post("includes/makeReport.php", {type:parent, date1:date1, date2:date2}, function(data){																					
			if(data){
				//document.getElementById('sR'+parent).style.display= 'table-row';
				//document.getElementById('sR'+parent).style.lineHeight='100px';
				document.getElementById('i'+parent).style.display= 'none';
				$('#sR'+parent).html(data);
			}
		});	
	}else{
		//document.getElementById('sR'+parent).style.display= 'table-row';
		//document.getElementById('sR'+parent).style.lineHeight=100;
		document.getElementById('i'+parent).style.display= 'none';
	}
	*/
}

function sendPass(){
	var p1=document.getElementById('password').value;
	var p2=document.getElementById('password2').value;
	if(p1=='' || p2==''){
		alert('No empty fields please');
	}else if(p1!=p2){
		alert('Please type the same password in both fields');
	}else{
		document.getElementById('chPass').submit();
	}
}

function displayEmailSettings(element){
	if(document.getElementById(element).style.display=='none'){
		document.getElementById(element).style.display='block';
	}else{
		document.getElementById(element).style.display='none';
	}
}

  function allowBST(u_id,cheked){
	$.post("includes/sbt_allowBST.php", {u_id:u_id,cheked:cheked}, function(data){																					
	});	
  }


function changeEmailSettings(user, mail, val){
	
	var active=0;
	if(val){
		active=1;
	}
	
	$.post("includes/change_emailSettings.php", {user: user,mail: mail, active: active}, function(data){});
}

function getMessages(user,rows,order){
	$.post("includes/getMessagesOrders.php", {user:user,ord:order}, function(data){																					
		if(data){
			$('#messages_data').html(data);
			paginate(rows);
		}
	});	
}

function getMails(user,rows){
	$.post("includes/getNotifications.php", {user:user}, function(data){																					
		if(data){
			$('#notifications_data').html(data);
			paginate(rows);
		}
	});	
}

var LastStyle="";

function displayMail(id,viewed){

        var trid = $("#"+id).closest('tr').attr('id');	
		$("#"+trid).css({"color":"black","background":"white"});
		$("#"+id).css({"color":"black","background":"white"});
		
		if(document.getElementById(id).style.display=="none"){
			document.getElementById(id).style.display="block";
			$("#"+id).hide();
			
		}
		$("#"+id).slideToggle(1300,function(){
		});
		   
		
	if(viewed==0){
		$.post("includes/updateNotifications.php", {id:id}, function(data){});	
	}
	
}

function displayInfoMB(message){
	   $.msgbox(message,{
		  type: "info",
		  buttons : [
			{type: "submit", value: "ok"}
		  ]
});
	}
function deleteMail(id){
		
	$.msgbox("Are you sure want to delete this email?",{
		  type: "confirm",
		  buttons : [
			{type: "submit", value: "Yes"},
			{type: "submit", value: "No"},
			{type: "cancel", value: "Cancel"}
		  ]
},function(result){

	if(result=='Yes'){
	
		$.post("includes/deleteNotifications.php", {id:id}, function(data){
			if(data=="deleted"){
				$.msgbox("Notification Deleted", {type: "info"});

					document.getElementById('row-'+id).style.display='none';
				
				}															 
			
		});	
		
		
	}
	});
	
	
	
	
}



function clicklookup3(text,where){
	document.getElementById("city"+where).value=text;
	document.getElementById("autoSuggestionsList"+where).style.display="none";
	}




function displayMessages(user,order,status, user2, h, d){
	var trid = $("#row-"+order).closest('tr').attr('id');	

	$("#row-"+order+" td:nth-child(3)").attr("id",order);
	if(document.getElementById(order).style.overflow==''){
	var content=$('#'+order).html();
	$.post("includes/getMessagesDisplay.php", {user:user, user2:user2, order:order, status:status, haul:h, deal:d}, function(data){																					
		if(data){

					document.getElementById(order).style.overflow='auto';
					$("#"+trid).css({"color":"black","background":"#FFF"});
					$('#'+order).html(content+data);
						
				
			
		}
	});	
	}else{
			
		$('#'+order).html('<i style="color:#999; float:left">Messages from <b>'+document.getElementById('restore'+order).value+'</b></i>');
		document.getElementById(order).style.overflow='';
	}
		$("#"+trid).removeAttr("style");
$("#"+trid).addClass("tableContent")
}
function deleteMessage(user,messageID)
{
	var opc='Deleted';
	$.post("includes/getMessagesDisplay.php", {user:user, opc:opc, messageID:messageID}, function(data){																					
		alert(data)
		window.location='messages.php';
	});
}

function sendMessage(user, message, order, user2, h, d){
	$.post("includes/sendMessage.php", {user:user, user2:user2, message:message, order:order}, function(data){																					
		displayMessages(user,order,'8', user2, h, d);
	});	
}

function showPwdBox(element){
	if(document.getElementById(element).style.display=='none'){
		document.getElementById(element).style.display='block';
	}else{
		document.getElementById(element).style.display='none';
	}
}

function changePwd_admin(user,p1,p2,p3,element){
	if(p1!='' && p2!='' && p3!=''){
		if(p2==p3){
			$.post("includes/changePwd_admin.php", {user:user, pwd1:p1, pwd2:p2}, function(data){																					
				if(data=='true'){
					document.getElementById(element).style.display='none';
					alert('Your password was changed');
				}else{
					alert('There was an error, please verify you enter the correct password');
				}
			});	
		}else{
			alert('Passwords are not the same');
		}
	}else{
		alert('Can\'t be empty fields');
	}
}
