function saveadminaction() {
  var data = ($('#adminactionform').formSerialize());
  $.post('offeraction.php', data, function(data) {
    setTimeout('document.location.reload()', 1000);
  });
}
function pleasewait(action) {
  tb_show('', 'pleasewait.php?height=350&width=400', null);
  setTimeout(action, 1000);
}
function sendref(id) {
  var data = {
    'data[Request][action]': 'sendref',
    'data[Request][id]': id
  };
  $.post('requestaction.php', data, function(data) {
    $('#sendref' + id).html('');
  });
}
function editpriceoffer(id, request_id) {
  if(isNaN($('#editpriceoffer').val())) {
    alert('Please, enter a valid number higher than the current offer.');
  } else {
    var data = {
      'data[Priceoffer][action]': 'edit',
      'data[Priceoffer][id]': id,
      'data[Priceoffer][request_id]': request_id,
      'data[Priceoffer][offer]': $('#editpriceoffer').val()
    };
    $.post('priceofferaction.php', data, function(res) {
      if(res.Errors) {
        $.each(res.Errors, function(index, item){
          alert(item);
        });
      } else {
        setTimeout('document.location.reload()', 1000);
      }
    }, 'json');
  }
}
function addreward(id, kind) {
  var data = {
    'data[Request][action]': 'reward',
    'data[Request][id]': id,
    'data[Request][kind]': kind
  };
  $.post('requestaction.php', data, function(data) {
    if(data == 1) {
      $('#rewardcost').html(Math.max(parseFloat($('#rewardcost').html()) - 1, 0).toFixed(2));
    }
  });
}
function fbs(request_id) {
  var data = {
    'data[Request][id]': request_id
  };
  $.post('fbs.php', data, function(data) {
    addreward(request_id, 1);
  });
}
function saveoffermessage() {
  var data = ($('#offermessageform').formSerialize());
  $.post('saveoffermessage.php', data, function(data) {
    setTimeout('document.location.reload()', 1000);
  });
}
function offermessageform(request_id) {
  tb_show('', 'editoffermessage.php?data[Request][id]=' + request_id + '&width=500&height=300', null);
}
function postimprovesuggestion() {
  if($('#suggestion').val() != 'Type your message here') {
    var data = ($('#improveform').formSerialize());
    $.post('postimprovesuggestion.php', data, function(res) {
      if(res.Errors) {
        $.each(res.Errors, function(index, item){
          alert(item);
        });
      } else {
        $('#suggestion').val('Type your message here');
        alert('Your message has been sent to the MapDispatch.com team. Thanks so much!');
      }
    }, 'json');
  }
}
function unrestrict(requestid) {
  var data ={
    'data[Request][action]': 'unrestrict',
    'data[Request][id]': requestid
  };
  $.post('requestaction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      $('#unrestrict' + res.Request.id).html('');
    }
  }, 'json');
}
function showdenyform(offerid) {
  tb_show('', 'denyform.php' + '?data[Offer][id]=' + offerid + '&height=' + 300 + '&width=' + 700, null);
}
function phoned(id) {
  var data = {
    'data[User][action]':  'phoned',
    'data[User][id]': id
  }
  $.post('useraction.php', data, function(res) {
    $('#phoned' + res).html('YES');
  });
}
function submitsource() {
  var data = ($('#usersourceform').formSerialize());
  $.post('useraction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      //parent.tb_remove();
      tb_show('', 'alert.php?alert=' + escape('Thank you!') + '&height=' + 250 + '&width=' + 300, null);
      setTimeout('parent.tb_remove()', 1000);
    }
  }, 'json');
}
function showroute(item) {
  var directions  = new GDirections(map, null);
  GEvent.addListener(directions, 'load', function() {
    setTimeout(function() {
      map.removeOverlay(directions.getMarker(0));
      map.removeOverlay(directions.getMarker(1));
      if(currentroute) {
        map.removeOverlay(currentroute);
      }
      /*
      if(m1) {
        map2.removeOverlay(m1);
        map3.removeOverlay(m2);
      }
             */
      map.addOverlay(directions.getPolyline());
      currentroute = directions.getPolyline();
    //map2.setCenter(directions.getMarker(0).getLatLng(), 12);
    //m1 = new GMarker(directions.getMarker(0).getLatLng());
    //map2.addOverlay(m1);
    //map3.setCenter(directions.getMarker(1).getLatLng(), 12);
    //m2 = new GMarker(directions.getMarker(1).getLatLng());
    //map3.addOverlay(m2);
    }
    , 0);
  });
  directions.loadFromWaypoints([item.from + '@' + item.fromlat + ',' + item.fromlon, item.to + '@' + item.tolat + ',' + item.tolon], {
    locale: 'en_US'
  });
}
function check_limit(t_obj){
  var count = 500;
  if (t_obj.val().length > count) {
    t_obj.val(t_obj.val().substring(0, count));
  }
}
function acceptpriceoffer(request_id, offer) {
  var data = {
    'data[Priceoffer][action]': 'accept',
    'data[Priceoffer][request_id]': request_id,
    'data[Priceoffer][offer]': offer
  };
  $.post('priceofferaction.php', data, function(res) {
    setTimeout('document.location.reload()', 1000);
  });
}
function deletepriceoffer(id) {
  var data = {
    'data[Priceoffer][action]': 'delete',
    'data[Priceoffer][id]': id
  };
  $.post('priceofferaction.php', data, function(res) {
    setTimeout('document.location.reload()', 1000);
  });
}
function offerprice() {
  var data = ($('#newpriceofferform').formSerialize());
  if(isNaN($('#newprice').val())) {
    alert('Please, enter a valid number higher than the current offer.');
  }
  else {
    $.post('priceofferaction.php', data, function(res) {
      if(res == -1) {
        alert('Sorry, but you have already suggested a price!');
      }
      else if (res == 0) {
        alert('Sorry, but your suggested price must be higher than the current offer!');
      }
      else {
        $('#priceofferslist').html(res);
      }
    });
  }
}
function movetypechanged(all) {
  if($('#kind').val() == '12') {
    $('#hours').show();
    $('#fromlabel').html('Location');
    $('#loclabel').html('Please provide location');
    $('#loclabel1').html('Please provide, as completely and precisely as possible, your location.');
    $('#tolabel').html('');
    $('#tostreet').hide().val($('#fromstreet').val());
    $('#tocity').hide().val($('#fromcity').val());
    $('#toprovince').hide().val($('#fromprovince').val());
  } else {
    $('#hours').hide();
    $('#fromlabel').html('Pick up Where?');
    $('#loclabel').html('Please provide pickup and delivery locations');
    $('#loclabel1').html('Please provide, as completely and precisely as possible, the pickup and delivery addresses.');
    $('#tolabel').html('<span class="red">*</span> Deliver Where?');
    $('#tostreet').show();
    $('#tocity').show();
    $('#toprovince').show();
  }
  if(($('#kind').val() == '1') ||
    ($('#kind').val() == '2') ||
    ($('#kind').val() == '13')) {
    $('#people').hide();
    if(all) {
      $('#people1').attr('checked', true);
    }
  } else {
    $('#people').show();
    if(all) {
      if(($('#kind').val() == '3') ||
        ($('#kind').val() == '6')) {
        $('#people1').attr('checked', true);
      } else {
        $('#people2').attr('checked', true);
      }
    }
  }
  if($('#kind').val() == '13') {
    $('#trailer').show();
    $('#boatsize').show();
  } else {
    $('#trailer').hide();
    $('#boatsize').hide();
  }
  if($('#kind').val() == '3' ||
    $('#kind').val() == '4' ||
    $('#kind').val() == '5' ||
    $('#kind').val() == '6' ||
    $('#kind').val() == '7' ||
    $('#kind').val() == '8' ||
    $('#kind').val() == '9' ||
    $('#kind').val() == '10' ||
    $('#kind').val() == '11') {
    $('#description').show();
  } else {
    $('#description').hide();
  }
}
function clearcardform() {
  $('#cardnum').val('');
  $('#cardmonth').val('');
  $('#cardyear').val('');
  $('#cardcode').val('');
}
function fillcardform(id) {
  var data = {
    'data[Card][id]': id,
    'data[Card][action]': 'get'
  };
  $.post('cardaction.php', data, function(res) {
    switch(res.Card.type) {
      case 'v':
        $('#newvisa').attr('checked', true);
        break;
      case 'm':
        $('#newmaster').attr('checked', true);
        break;
      case 'a':
        $('#newamex').attr('checked', true);
        break;
    }
    $('#cardnum').val(res.Card.num);
    $('#cardmonth').val(res.Card.month);
    $('#cardyear').val(res.Card.year);
    $('#cardcode').val(res.Card.code);
    $('#firstname').val(res.Card.firstname);
    $('#lastname').val(res.Card.lastname);
    $('#address1').val(res.Card.address1);
    $('#address2').val(res.Card.address2);
    $('#city').val(res.Card.city);
    $('#state').val(res.Card.state);
    $('#zip').val(res.Card.zip);
    $('#country').val(res.Card.country);
  }, 'json');
}
function rateanswerform(offerid) {
  tb_show('', 'rateanswer.php?data[Rating][id]=' + offerid + '&height=350&width=700', null);
}
function accepttime(offer_id, timestatus) {
  var data = {
    'data[Offer][action]': 'accepttime',
    'data[Offer][id]': offer_id,
    'data[Offer][timestatus]': timestatus
  };
  $.post('offeraction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      if(res.Offer.timestatus == 1) {
        tb_show('', 'alert.php?alert=' + escape('An email has been sent informing the original dispatcher of your confirmation.') + '&height=' + 350 + '&width=' + 700, null);
      }
      setTimeout('document.location = "offerdetails.php?showflag=yes&data[Offer][id]=' + offer_id + '#pickuptime"', 5000);
    }
  }, 'json');
}
function offertime(offer_id, timestatus) {
  var data = {
    'data[Offer][action]': 'newtime',
    'data[Offer][id]': offer_id,
    'data[Offer][date]': $('#date').val(),
    'data[Offer][time]': $('#time').val(),
    'data[Offer][timestatus]': timestatus
  };
  $.post('offeraction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      tb_show('', 'alert.php?alert=' + escape('Your email has been sent. Please look for a confirmation of your time change from your counterparty.') + '&height=' + 350 + '&width=' + 700, null);
      setTimeout('document.location.replace("offerdetails.php?displaytime=yes&data[Offer][id]=' + offer_id + '#timebm")', 5000);
    }
  }, 'json');
}
function offerdatechanged(newdate) {
  var data = {
    'date': newdate
  };
  $.post('getcalendar.php', data, function(res) {
    $('#offerdate').html(res);
  });
}
function deletediscount(id) {
  if(confirm('Sure you want to delete this discount code?')) {
    var data = {
      'data[Discount][action]': 'delete',
      'data[Discount][id]': id
    };
    $.post('discountaction.php', data, function(res) {
      $('#discountlist').html(res);
      parent.tb_remove();
    });
  }
}
function editdiscount() {
  var data = ($('#editdiscountform').formSerialize());
  $.post('discountaction.php', data, function(res) {
    $('#discountlist').html(res);
    parent.tb_remove();
  });
}
function newdiscount() {
  var data = ($('#newdiscountform').formSerialize());
  $.post('discountaction.php', data, function(res) {
    $('#discountlist').html(res);
    parent.tb_remove();
  });
}
function editdiscountform(id) {
  tb_show('', 'editdiscountform.php?data[Discount][id]=' + id + '&height=' + 350 + '&width=' + 700, null);
}
function newdiscountform() {
  tb_show('', 'newdiscountform.php' + '?height=' + 350 + '&width=' + 700, null);
}
function reducecost() {
  tb_show('', 'reducecost.php' + '?height=' + 350 + '&width=' + 700, null);
}
function canceloffer(id) {
  if(confirm('Are you sure? You won\'t be able to rerequest it later.')) {
    var data = {
      'data[Offer][id]': id
    };
    $.post('canceloffer.php', data, function(data) {
      tb_show('', 'offercancelled.php' + '?height=' + 200 + '&width=' + 300, null);
      setTimeout('document.location.replace("https://www.mapdispatch.com/myprofile.php")', 5000);
    });
  }
}
function countdown_clock(target, current, format) {
  html_code = '<div id="countdown" style="padding: 5px; font-weight: bold;" class="fourteen"></div>';
  document.write(html_code);
  targetdate = new Date(target);
  currentdate = new Date(current);
  clientdate = new Date();
  offset  = currentdate.getTime() - clientdate.getTime();
  //alert(offset);
  countdown(targetdate.getFullYear() - 2000, targetdate.getMonth(), targetdate.getDate(), targetdate.getHours(), targetdate.getMinutes(), offset, format);
}
function countdown(year, month, day, hour, minute, offset, format) {
  clientdate = new Date();
  Today = new Date(clientdate.getTime() + offset);
  Todays_Year = Today.getFullYear() - 2000;
  Todays_Month = Today.getMonth();
  Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
    Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
  Target_Date = (new Date(year, month, day, hour, minute, 00)).getTime();
  Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
  if(Time_Left < 0)
    Time_Left = 0;
  switch(format) {
    case 0:
      document.all.countdown.innerHTML = Time_Left + ' seconds';
      break;
    case 1:
      days = Math.floor(Time_Left / (60 * 60 * 24));
      Time_Left %= (60 * 60 * 24);
      hours = Math.floor(Time_Left / (60 * 60));
      Time_Left %= (60 * 60);
      minutes = Math.floor(Time_Left / 60);
      Time_Left %= 60;
      seconds = Time_Left;
      dps = 's';
      hps = 's';
      mps = 's';
      sps = 's';
      if(days == 1) dps = '';
      if(hours == 1) hps = '';
      if(minutes == 1) mps = '';
      if(seconds == 1) sps = '';
      str = 'This provisional request will expire in: <span style="text-decoration: blink; font-weight: bold; color: #ff0000">' + days + ' day' + dps + ' ';
      str += hours + ' hour' + hps + ' ';
      str += minutes + ' minute' + mps + ' and ';
      str += seconds + ' second' + sps + '</span>';
      $('#countdown').html(str);
      break;
    default:
      document.all.countdown.innerHTML = Time_Left + ' seconds';
  }
  setTimeout('countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' + offset + ',' + format + ');', 1000);
}
function override(id) {
  var data = {
    'data[User][id]': id,
    'data[User][action]': 'override'
  };
  $.post('useraction.php', data, function(data) {
    $('#userlist').html(data);
  });
}
function cardoverride(id) {
  var data = {
    'data[User][id]': id,
    'data[User][action]': 'requestoverride'
  };
  $.post('useraction.php', data, function(data) {
    tb_show('', 'cardoverride2.php' + '?height=' + 350 + '&width=' + 700, null);
    setTimeout('document.location.replace("index.php")', 10000);
  });
}
function cardoverrideform(id) {
  tb_show('', 'cardoverride.php' + '?data[User][id]=' + id + '&height=' + 350 + '&width=' + 700, null);
}
function savetimeout(timeout) {
  var data = {
    'data[Settings][action]': 'savetimeout',
    'data[Settings][requesttimeout]': timeout
  };
  $.post('settingsaction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      alert('Settings saved');
    }
  }, 'json');
}
function deleterequest(id) {
  if(confirm('You are about to delete selected request. Would you like to proceed?')) {
    var data = {
      'data[Request][action]': 'delete',
      'data[Request][id]': id
    };
    $.post('requestaction.php', data, function(res) {
      $('#requestlist').html(res);
    });
  }
}
function togglerefined() {
  if($('#refined1').is(':visible')) {
    $('#refined1').hide();
    $('#refined2').hide();
    $('#refined3').hide();
    $('#refinedbut').hide();
  } else {
    $('#refined1').show();
    $('#refined2').show();
    $('#refined3').show();
    $('#refinedbut').show();
  }
}
function submitstatusform() {
  var request_id = $('#r_id').val();
  if(request_id) {
    var data = {
      'data[Request][id]': request_id
    };
    $.post('checkid.php', data, function(res) {
      if(res == 1) {
        document.shortstatusform.submit();
      }
      else {
        alert('That is not a valid move number');
      }
    });
  } else {
    alert('Please enter move #');
  }
}
function calcfee(cost) {
  if(cost) {
    $('#feecalc1').show();
    $('#feecalc2').show();
    $('#priceslider').show();
    var suggested = $('#cost').html();
    var pos = cost / suggested * 100;
    if(pos < 65) {
      $('#priceslider').css('left', 20);
    } else if (pos > 125) {
      $('#priceslider').css('left', 742);
    }
    else {
      $('#priceslider').css('left', 68 + 10.1 * (pos - 65));
    }
    var data = {
      'cost': cost
    };
    $.post('calcfee.php', data, function(res) {
      $('#fee').html(res.fee);
      $('#total').html(res.total);
    }, 'json');
  //$('#fee').html((Math.round(cost / 100 * 15 * 100) / 100).toFixed(2));
  //$('#total').html((Math.round(cost * (1 + 1 / 100 * 15) * 100) / 100).toFixed(2));
  } else {
    $('#feecalc1').hide();
    $('#feecalc2').hide();
    $('#priceslider').hide();
  }
}
function deleteimage(num) {
  if(confirm('You are about to delete the selected image. Would you like to proceed?')) {
    $('#uploadtext' + num).html('');
    $('#path' + num).val('');
  }
}
function submitlogin() {
  document.loginform.submit();
}
function paid(id) {
  if(confirm('You are about to confirm payment. Would you like to proceed?')) {
    var data = {
      'data[Cashrequest][action]': 'confirm',
      'data[Cashrequest][id]': id
    };
    $.post('cashaction.php', data, function(res) {
      $('#cashrequestlist').html(res);
    });
  }
}
function myprofile() {
  document.location = 'https://www.mapdispatch.com/myprofile.php';
}
function approverating(id) {
  if(confirm('You are about to approve selected rating. Would you like to proceed?')) {
    var data = {
      'data[Rating][action]': 'approve',
      'data[Rating][id]': id
    };
    $.post('ratingaction.php', data, function(res) {
      $('#ratinglist').html(res);
    });
  }
}
function declinerating(id) {
  if(confirm('You are about to decline selected rating. Would you like to proceed?')) {
    var data = {
      'data[Rating][action]': 'decline',
      'data[Rating][id]': id
    };
    $.post('ratingaction.php', data, function(res) {
      $('#ratinglist').html(res);
    });
  }
}
function laborratechanged(movetype) {
  $('#laborrateaction' + movetype).html('<a href="javascript:savelaborrate(' + movetype + ')" class="button" id="but3">SAVE RULE</a>');
}
function savelaborrate(movetype) {
  $('#laborrateaction' + movetype).html('Please, wait...');
  var data = {
    'data[Laborrate][action]': 'edit',
    'data[Laborrate][movetype]': movetype,
    'data[Laborrate][flat]': $('#flat' + movetype).val(),
    'data[Laborrate][hourly]': $('#hourly' + movetype).val(),
    'data[Laborrate][timeout]': $('#timeout' + movetype).val(),
    'data[Laborrate][pricealert]': $('#pricealert' + movetype).val()
  };
  $.post('laborrateaction.php', data, function(res) {
    $('#laborrate' + movetype).html(res);
  });
}
function fixedrulechanged(movetype) {
  $('#fixedruleaction' + movetype).html('<a href="javascript:savefixedrule(' + movetype + ')" class="button" id="but3">SAVE RULE</a>');
}
function savefixedrule(movetype) {
  $('#fixedruleaction' + movetype).html('Please, wait...');
  var data = {
    'data[Fixedrule][action]': 'edit',
    'data[Fixedrule][movetype]': movetype,
    'data[Fixedrule][fixed]': $('#fixed' + movetype).val(),
    'data[Fixedrule][extra]': $('#extra' + movetype).val(),
    'data[Fixedrule][timeout]': $('#timeout' + movetype).val(),
    'data[Fixedrule][lmhours]': $('#lmhours' + movetype).val(),
    'data[Fixedrule][lmcharge]': $('#lmcharge' + movetype).val(),
    'data[Fixedrule][lmtype]': $('#lmtype' + movetype).val(),
    'data[Fixedrule][lwhours]': $('#lwhours' + movetype).val(),
    'data[Fixedrule][lwcharge]': $('#lwcharge' + movetype).val(),
    'data[Fixedrule][lwtype]': $('#lwtype' + movetype).val(),
    'data[Fixedrule][pricealert]': $('#pricealert' + movetype).val()
  };
  $.post('fixedruleaction.php', data, function(res) {
    $('#fixedrule' + movetype).html(res);
  });
}
function deleteuser(id) {
  if(confirm('You are about to delete selected user. Would you like to proceed?')) {
    var data = {
      'data[User][action]': 'delete',
      'data[User][id]': id
    };
    $.post('useraction.php', data, function(res) {
      $('#userlist').html(res);
    });
  }
}
function removenotifications(id) {
  if(confirm('You are about to stop sending notifications to this user. Would you like to proceed?')) {
    var data = {
      'data[User][action]': 'removenotifications',
      'data[User][id]': id
    };
    $.post('useraction.php', data, function(res) {
      $('#userlist').html(res);
    });
  }
}
function addnotifications(id) {
  if(confirm('You are about to start sending notifications to this user. Would you like to proceed?')) {
    var data = {
      'data[User][action]': 'addnotifications',
      'data[User][id]': id
    };
    $.post('useraction.php', data, function(res) {
      $('#userlist').html(res);
    });
  }
}
function deletepricerule(movetype, id) {
  var data = {
    'data[Pricerule][action]': 'delete',
    'data[Pricerule][id]': id,
    'data[Pricerule][movetype]': movetype
  };
  $.post('priceruleaction.php', data, function(res) {
    $('#rules' + movetype).html(res);
  });
}
function deletesumrule(id) {
  var data = {
    'data[Sumrule][action]': 'delete',
    'data[Sumrule][id]': id
  };
  $.post('sumruleaction.php', data, function(res) {
    $('#sumrules').html(res);
  });
}
function addpricerule(movetype) {
  var data = ($('#newrule' + movetype).formSerialize());
  $.post('priceruleaction.php', data, function(res) {
    $('#rules' + movetype).html(res);
  });
}
function addsumrule() {
  var data = ($('#newsumrule').formSerialize());
  $.post('sumruleaction.php', data, function(res) {
    $('#sumrules').html(res);
  });
}
function toggletimes() {
  if($('#loccorrect').is(':checked')) {
    $('#times').show();
  //$('#redarrow').hide();
  } else {
    $('#times').hide();
  //$('#redarrow').show();
  }
}
function submitenter(callback, e) {
  var keycode;
  if (window.event) {
    keycode = window.event.keyCode;
  } else if (e) {
    keycode = e.which;
  } else {
    return true;
  }
  if (keycode == 13) {
    //alert('dochange');
    callback();
    return false;
  }
  else {
    return true;
  }
}
function addslashes(str) {
  return str.replace('/(["\'\])/g', "\\$1").replace('/\0/g', "\\0");
}
function clearafterlogin() {
  var d = new Date();
  d.setDate(d.getDate() - 1);
  document.cookie='afterlogin=no; expires=' + d.toGMTString();
}
function checkoffertime(request_id, time, date, error) {
  //alert(request_id.val() + ':' + time.val() + ':' + date.val());
  error.hide();
  if((time.val() != '') && (date.val() != '')) {
    var data = {
      'data[Time][request_id]': request_id.val(),
      'data[Time][time]': time.val(),
      'data[Time][date]': date.val()
    };
    $.post('checkoffertime.php', data, function(data) {
      //alert(data);
      if(data > 0) {
      } else {
        error.show();
      }
    });
  }
}
function checktime(from, to, error) {
  error.hide();
  if((from.val() != '') && (to.val() != '')) {
    var data = {
      'data[Time][from]': from.val(),
      'data[Time][to]': to.val()
    };
    $.post('checktime.php', data, function(data) {
      if(data > 0) {
      } else {
        error.show();
      }
    });
  }
}
function submitrequest() {
  document.forms['newrequestform'].submit();
}
function ajaxlogin() {
  $('#loginerrors').hide();
  var data = ($('#loginform1').formSerialize());
  //alert(data);
  $.post('ajaxlogin.php', data, function(res) {
    if(res.Errors) {
      $('#loginerrorlist').children().remove();
      $('#loginerrors').show();
      $.each(res.Errors, function(index, item){
        $('#loginerrorlist').append($( "<li>" + item + "</li>" ));
      });
    } else {
      parent.tb_remove();
      if(res.Login.execute) {
        setTimeout(res.Login.execute, 0);
      } else {
        document.location = res.Login.afterlogin;
      }
    }
  }, 'json');
}
function cancelrequest(id) {
  if(confirm('Are you sure you want to cancel this posting?')) {
    var data = {
      'data[Request][id]': id
    };
    $.post('cancelrequest.php', data, function(data) {
      document.location = 'https://www.mapdispatch.com/myprofile.php';
    });
  }
}
function addcardform(page, user_id) {
  tb_show('', 'newcardform.php' + '?data[Card][page]=' + page + '&data[User][id]=' + user_id + '&height=' + 700 + '&width=' + 700, null);
}
function sendanswer() {
  $('#but').html('Sending...');
  var data = ($('#answerform').formSerialize());
  $.post('sendanswer.php', data, function(data) {
    //$('#questions').html(data);
    tb_show('', 'alert.php?alert=' + escape('An email has been sent to your counterparty.') + '&height=' + 250 + '&width=' + 500, null);
    setTimeout('document.location.reload()', 1000);
  });
}
function sendquestion() {
  $('#but').html('Sending...');
  var data = ($('#questionform').formSerialize());
  $.post('sendquestion.php', data, function(data) {
    //$('#questions').html(data);
    tb_show('', 'alert.php?alert=' + escape('An email has been sent to the dispatcher.') + '&height=' + 250 + '&width=' + 500, null);
    setTimeout('document.location.reload()', 1000);
  });
}
function postrating() {
  var data = ($('#rateform').formSerialize());
  $.post('postrating.php', data, function(data) {
    document.location = 'rated.php?data[Rate][rate]=' + data.Rate.rate + '&data[Request][id]=' + data.Rate.request_id;
  }, 'json');
}
function rateanswer() {
  var data = ($('#rateanswerform').formSerialize());
  $.post('ratingaction.php', data, function(res) {
    if(res.Errors) {
      $.each(res.Errors, function(index, item){
        alert(item);
      });
    } else {
      tb_show('', 'alert.php?alert=' + escape('Your answer has been posted.') + '&height=' + 350 + '&width=' + 700, null);
      setTimeout('document.location = "http://mapdispatch.com/publicprofile.php?data[User][id]=' + res.User.id + '"', 5000);
    }
  }, 'json');
}
function savemessage() {
  var data = ($('#editmessageform').formSerialize());
  $.post('savemessage.php', data, function(data) {
    //$('#messagelist').html(data);
    //parent.tb_remove();
    setTimeout('document.location.reload()', 1000);
  });
}
function selectcard(requestid, cardid) {
  var data = {
    'data[Request][id]': requestid,
    'data[Card][id]': cardid
  };
  $.post('cardselected.php', data, function(data) {
    /*requested.php?data[Request][id]='.$data['Request']['id'*/
    alert('Card selected');
  });
}
function sendmessage() {
  $('#but').html('Sending...');
  var data = ($('#messageform').formSerialize());
  $.post('sendmessage.php', data, function(data) {
    //$('#questions').html(data);
    tb_show('', 'alert.php?alert=' + escape('An email has been sent to your counterparty.') + '&height=' + 250 + '&width=' + 500, null);
    setTimeout('document.location.reload()', 1000);
  });
}
function editmessageform(messageid) {
  tb_show('', 'editmessage.php' + '?data[Message][id]=' + messageid + '&height=' + 350 + '&width=' + 700, null);
}
function messageform(offerid) {
  tb_show('', 'message.php' + '?data[Offer][id]=' + offerid + '&height=' + 300 + '&width=' + 500, null);
}
function showroutes(show) {
  $.each(show.Request, function(index, item){
    var directions  = new GDirections(map, null);
    GEvent.addListener(directions, 'load', function() {
      setTimeout(function() {
        var marker = directions.getMarker(0);
        map.removeOverlay(marker);
        pickupIcon = new GIcon(G_DEFAULT_ICON);
        pickupIcon.iconSize = new GSize(32, 32);
        switch(item.status) {
          case '0':
            pickupIcon.image = "http://mapdispatch.com/images/greenA.png";
            break;
          case '1':
            pickupIcon.image = "http://mapdispatch.com/images/yellowA.png";
            break;
          case '3':
            pickupIcon.image = "http://mapdispatch.com/images/redA.png";
            break;
        }
        markerOptions = {
          icon:pickupIcon
        };
        var pickupMarker = new GMarker(marker.getLatLng(), {
          icon: pickupIcon
        });
        GEvent.addListener(pickupMarker, 'click', function() {
          if(currentroute) {
            map.removeOverlay(currentroute);
          }
          /*
          if(m1) {
            map2.removeOverlay(m1);
            map3.removeOverlay(m2);
          }
                         */
          map.addOverlay(directions.getPolyline());
          currentroute = directions.getPolyline();
          pickupMarker.openInfoWindowHtml('<center><h3><a href="requestdetails.php?data[Request][id]=' + item.id + '">' + item.label + '<br/>Offer $' + item.cost + '</a></h3><a href="requestdetails.php?data[Request][id]=' + item.id + '"><img alt="" width="75" height="75" class="illustr2" src="requestimage.php?id=' + item.id + '" /></a><br/><h3>Pickup</h3></center>');
        //map2.setCenter(directions.getMarker(0).getLatLng(), 12);
        //m1 = new GMarker(directions.getMarker(0).getLatLng());
        //map2.addOverlay(m1);
        //map3.setCenter(directions.getMarker(1).getLatLng(), 12);
        //m2 = new GMarker(directions.getMarker(1).getLatLng());
        //map3.addOverlay(m2);
        });
        map.addOverlay(pickupMarker);
        marker = directions.getMarker(1);
        map.removeOverlay(marker);
        destinationIcon = new GIcon(G_DEFAULT_ICON);
        destinationIcon.iconSize = new GSize(32, 32);
        switch(item.status) {
          case '0':
            destinationIcon.image = "http://mapdispatch.com/images/greenB.png";
            break;
          case '1':
            destinationIcon.image = "http://mapdispatch.com/images/yellowB.png";
            break;
          case '3':
            destinationIcon.image = "http://mapdispatch.com/images/redB.png";
            break;
        }
        markerOptions = {
          icon:destinationIcon
        };
        var destinationMarker = new GMarker(marker.getLatLng(), {
          icon: destinationIcon
        });
        GEvent.addListener(destinationMarker, 'click', function() {
          if(currentroute) {
            map.removeOverlay(currentroute);
          }
          /*
          if(m1) {
            map2.removeOverlay(m1);
            map3.removeOverlay(m2);
          }
                         */
          map.addOverlay(directions.getPolyline());
          currentroute = directions.getPolyline();
          destinationMarker.openInfoWindowHtml('<center><h3><a href="requestdetails.php?data[Request][id]=' + item.id + '">' + item.label + '<br/>Offer $' + item.cost + '</a></h3><a href="requestdetails.php?data[Request][id]=' + item.id + '"><img alt="" width="75" height="75" class="illustr2" src="requestimage.php?id=' + item.id + '" /></a><br/><h3>Destination</h3></center>');
        //map2.setCenter(directions.getMarker(0).getLatLng(), 12);
        //m1 = new GMarker(directions.getMarker(0).getLatLng());
        //map2.addOverlay(m1);
        //map3.setCenter(directions.getMarker(1).getLatLng(), 12);
        //m2 = new GMarker(directions.getMarker(1).getLatLng());
        //map3.addOverlay(m2);
        });
        map.addOverlay(destinationMarker);
        var poly = directions.getPolyline();
        map.removeOverlay(poly);
      }, 0);
    });
    directions.loadFromWaypoints([item.from + '@' + item.fromlat + ',' + item.fromlon, item.to + '@' + item.tolat + ',' + item.tolon], {
      preserveViewport: true,
      locale: 'en_US'
    });
  });
}
//directions  = new GDirections(map, document.getElementById("map_dirs"));
//
function checkpayment(id) {
  var data = {
    'data[Card][user_id]': id,
    'data[Offer][id]': $('#offer_id').val()
  };
  $.post('checkpayment.php', data, function(data) {
    if(data > 0) {
      document.location = 'offered.php?data[Offer][id]=' + $('#offer_id').val();
    } else {
      alert('Please add at least one card');
    }
  });
}
function postrequestsearchform() {
  var address = $('#address').val();
  if(!address) {
    address = $('#address2').val();
  }
  geocoder.getLocations(
    address,
    function(points) {
      if (points.Status.code != G_GEO_SUCCESS) {
        $('#lat').val('');
        $('#lon').val('');
        document.forms['requestsearchform'].submit();
      } else {
        $('#address').val(points.Placemark[0].address);
        $('#lat').val(points.Placemark[0].Point.coordinates[1]);
        $('#lon').val(points.Placemark[0].Point.coordinates[0]);
        //map.setCenter(point, 15);
        document.forms['requestsearchform'].submit();
      }
    });
}
function changepassword() {
  $('#profileerrors').hide();
  var data = ($('#changepasswordform').formSerialize());
  $.post('changepassword.php', data, function(res) {
    if(res.Errors) {
      $('#profileerrorlist').children().remove();
      $('#profileerrors').show();
      $.each(res.Errors, function(index, item){
        $('#profileerrorlist').append($( "<li>" + item + "</li>" ));
      });
    } else {
      parent.tb_remove();
      alert('Your password has been updated.');
    }
  }, 'json');
}
function saveprofile() {
  $('#profileerrors').hide();
  var data = ($('#editprofileform').formSerialize());
  $.post('saveprofile.php', data, function(res) {
    if(res.Errors) {
      $('#profileerrorlist').children().remove();
      $('#profileerrors').show();
      $.each(res.Errors, function(index, item){
        $('#profileerrorlist').append($( "<li>" + item + "</li>" ));
      });
    } else {
      if($('#email')) {
        $('#email').html(res.User.email);
        $('#zip').html(res.User.zip);
        parent.tb_remove();
      } else {
        document.location.reload();
      }
    }
  }, 'json');
}
function editprofileform(id) {
  tb_show('', 'editprofileform.php' + '?data[User][id]=' + id + '&height=' + 600 + '&width=' + 600, null);
}
function changepasswordform() {
  tb_show('', 'changepasswordform.php?height=250&width=400', null);
}
function deletecard(page, user_id, id) {
  if(confirm('You are about to remove this card. Do you want to proceed?')) {
    var data = {
      'data[Card][page]': page,
      'data[Card][action]': 'delete',
      'data[Card][user_id]': user_id,
      'data[Request][id]': $('#request_id').val(),
      'data[Card][id]': id
    };
    $.post('cardaction.php', data, function(data) {
      $('#cards').html(data);
    });
  }
}
function addcard() {
  $('#newcarderrors').hide();
  var data = ($('#newcardform').formSerialize());
  $('#cardprocess').html('<h2>Please, wait...</h2>');
  $.post('checkcard.php', data, function(res) {
    if(res.Errors) {
      $('#newcarderrorlist').children().remove();
      $('#newcarderrors').show();
      $.each(res.Errors, function(index, item){
        $('#newcarderrorlist').append($( "<li>" + item + "</li>" ));
      });
      $('#cardprocess').html('<a href="javascript:addcard();" class="button" id="but4">ADD</a>');
    } else {
      $.post('cardaction.php', data, function(res) {
        $('#cards').html(res);
        parent.tb_remove();
        $('#cardprocess').html('<a href="javascript:addcard();" class="button" id="but4">ADD</a>');
      });
    }
  }, 'json');
}
function userpicuploadform() {
  tb_show('', 'userpicform.php' + '?' + 'height=' + 500 + '&width=' + 600, null);
}
function changeuserpic(path) {
  $.get('setuserpic.php', {
    id: $('#user_id').val(),
    path: path
  });
}
function updateuserpic() {
  $.get('setuserpic.php', {
    id: $('#user_id').val(),
    path: $('#path').val()
  }, function(data) {
    document.location = 'registered.php';
  });
}
function showalert() {
  var alertpath = getcookie('alertpath');
  if (alertpath) {
    var alertwidth = getcookie('alertwidth');
    var alertheight = getcookie('alertheight');
    var alertparams = getcookie('alertparams');
    var alerttime = getcookie('alerttime');
    $(document).ready(function() {
      tb_show('', alertpath + '?' + alertparams + '&height=' + alertheight + '&width=' + alertwidth, null);
    });
    //alert(alerttime);
    if(alerttime) {
      setTimeout('parent.tb_remove()', alerttime);
    }
    var d = new Date();
    d.setDate(d.getDate() - 1);
    document.cookie='alertpath=no; expires=' + d.toGMTString();
    document.cookie='alertwidth=no; expires=' + d.toGMTString();
    document.cookie='alertheight=no; expires=' + d.toGMTString();
    document.cookie='alertparams=no; expires=' + d.toGMTString();
    document.cookie='alerttime=no; expires=' + d.toGMTString();
  }
}
function makenavigation(id) {
  $('a.search' + id).bind('click', function(event) {
    event.preventDefault();
    $.get(this.href, {}, function(response) {
      $('#' + id).html(response)
    })
  });
  $('p.nav').show();
/*
    $('div#loading').ajaxStart(function() {
        $(this).text("Loading...");
    });
    $('div#loading').ajaxComplete(function() {
        $(this).html("&nbsp;");
    });
         */
}
function getcookie(name) {
  var start = document.cookie.indexOf(name + "=");
  var len = start + name.length + 1;
  if ((!start) && (name != document.cookie.substring(0, name.length))) {
    return null;
  }
  if (start == -1)
    return null;
  var end = document.cookie.indexOf(';', len);
  if (end == -1)
    end = document.cookie.length;
  return unescape(document.cookie.substring(len, end));
}
function showonmap(address, lat, lon) {
  var point;
  if ((lat.val() != '') && (lon.val() != '')) {
    point = new GLatLng(lat.val(), lon.val());
    map.addOverlay(new GMarker(point));
    map.setCenter(point, 15);
  } else {
    if (address != '') {
      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            alert('Address not found');
            lat.val('');
            lon.val('');
          } else {
            lat.val(point.lat());
            lon.val(point.lng());
            map.addOverlay(new GMarker(point));
            map.setCenter(point, 15);
          }
        });
    }
  }
}
function changeroute(what) {
  var address = '';
  var addressinput, latinput, loninput;
  if(what == 'from') {
    addressinput = $('#from');
    latinput = $('#fromlat');
    loninput = $('#fromlon');
    if(($('#fromstreet').val() != '') || ($('#fromcity').val() != '') || ($('#fromprovince').val() != '')) {
      address = $('#fromstreet').val() + ', ' + $('#fromcity').val() + ', ' + $('#fromprovince').val();
    }
  } else {
    addressinput = $('#to');
    latinput = $('#tolat');
    loninput = $('#tolon');
    if(($('#tostreet').val() != '') || ($('#tocity').val() != '') || ($('#toprovince').val() != '')) {
      address = $('#tostreet').val() + ', ' + $('#tocity').val() + ', ' + $('#toprovince').val();
    }
  }
  directions.clear();
  if(address != '') {
    geocoder.getLocations(
      address,
      function(variants) {
        if (!variants || variants.Status.code != 200) {
          //alert('Sorry, we were unable to geocode this address: ' + address);
          latinput.val('');
          loninput.val('');
        } else {
          addressinput.val(variants.Placemark[0].address);
          latinput.val(variants.Placemark[0].Point.coordinates[1]);
          loninput.val(variants.Placemark[0].Point.coordinates[0]);
          if($('#kind').val() == 12) {
            $('#to').val($('#from').val());
            $('#tolat').val($('#fromlat').val());
            $('#tolon').val($('#fromlon').val());
          }
          if (($('#fromlat').val() != '') && ($('#fromlon').val() != '') && ($('#tolat').val() != '') && ($('#tolon').val() != '')) {
            GEvent.addListener(directions, 'load', function() {
              setTimeout(function() {
                var marker = directions.getMarker(0);
                map.removeOverlay(marker);
                if(prevStart) {
                  map.removeOverlay(prevStart);
                }
                var icon = new GIcon()/*G_PAUSE_ICON*/;
                icon.image = "http://mapdispatch.com/images/pickup.png";
                icon.iconSize = new GSize(110, 30);
                icon.iconAnchor = new GPoint(9, 30);
                icon.infoWindowAnchor = new GPoint(5, 1);
                var pickupMarker = new GMarker(marker.getLatLng(), {
                  icon: icon
                });
                map.addOverlay(pickupMarker);
                prevStart = pickupMarker;
                marker = directions.getMarker(1);
                map.removeOverlay(marker);
                if(prevFinal) {
                  map.removeOverlay(prevFinal);
                }
                icon = new GIcon()/*G_PAUSE_ICON*/;
                icon.image = "http://mapdispatch.com/images/destination.png";
                icon.iconSize = new GSize(110, 30);
                icon.iconAnchor = new GPoint(9, 30);
                icon.infoWindowAnchor = new GPoint(5, 1);
                var destinationMarker = new GMarker(marker.getLatLng(), {
                  icon: icon
                });
                map.addOverlay(destinationMarker);
                prevFinal = destinationMarker;
                var route = directions.getRoute(0);
                var routetext = '<table>';
                for(i = 0; i < route.getNumSteps(); i++) {
                  routetext = routetext + '<tr>';
                  routetext = routetext + '<td style="vertical-align: top;">' + (i + 1) + '</td>';
                  routetext = routetext + '<td style="vertical-align: top;">' + route.getStep(i).getDescriptionHtml() + '</td>';
                  routetext = routetext + '<td style="vertical-align: top;">' + route.getStep(i).getDistance().html + '</td>';
                  routetext = routetext + '<td style="vertical-align: top;">' + route.getStep(i).getDuration().html + '</td>';
                  routetext = routetext + '</td></tr>'
                }
                routetext = routetext + '</table>';
                $('#distance').val(directions.getDistance().meters * 0.000621371192);
                $('#time').val(directions.getDuration().seconds / 60);
                $('#distancetext').text(Math.round(directions.getDistance().meters * 0.000621371192 * 100) / 100);
                $('#timetext').text(Math.round(directions.getDuration().seconds / 60));
                $('#directions').val(routetext);
              }, 0);
            });
            directions.loadFromWaypoints([$('#from').val() + '@' + $('#fromlat').val() + ',' + $('#fromlon').val(), $('#to').val() + '@' + $('#tolat').val() + ',' + $('#tolon').val()], {
              locale: 'en_US'
            });
          }
        }
      });
  } else {
    latinput.val('');
    loninput.val('');
  }
}
function checkdates() {
  if($('#date1check').is(':checked')) {
    $('#date1').attr('disabled', false);
    $('#time1from').attr('disabled', false);
    $('#time1to').attr('disabled', false);
  } else {
    $('#date1').attr('disabled', true);
    $('#time1from').attr('disabled', true);
    $('#time1to').attr('disabled', true);
  }
  if($('#date2check').is(':checked')) {
    $('#date2').attr('disabled', false);
    $('#time2from').attr('disabled', false);
    $('#time2to').attr('disabled', false);
  } else {
    $('#date2').attr('disabled', true);
    $('#time2from').attr('disabled', true);
    $('#time2to').attr('disabled', true);
  }
  if($('#date3check').is(':checked')) {
    $('#date3').attr('disabled', false);
    $('#time3from').attr('disabled', false);
    $('#time3to').attr('disabled', false);
  } else {
    $('#date3').attr('disabled', true);
    $('#time3from').attr('disabled', true);
    $('#time3to').attr('disabled', true);
  }
}
function getcost(data) {
  //var data = {
  //    'data[type]': type,
  //    'data[distance]': distance,
  //    'data[people]': people
  //};
  $.post('getcost.php', data, function(res) {
    $('#cost').html(res);
    $('#suggested').val(res);
    if(res < 200) {
      $('#reducecost').show();
    } else {
      $('#reducecost').hide();
    }
  });
}
function getcostold(type, distance) {
  var cost = 0;
  var dist = distance * 2;
  var extra;
  switch(type) {
    case '1':
      cost = 3;
      if (dist > 1 / 6) {
        extra = (dist - (1 / 6)) / (1 / 6);
        cost = cost + 0.25 * extra;
      }
      break;
    case '2':
      cost = 3;
      if (dist > 1 / 6) {
        extra = (dist - (1 / 6)) / (1 / 6);
        cost = cost + 0.25 * extra;
      }
      break;
    case '3':
      cost = 40;
      if (dist < 10) {

      } else if ((dist >= 10) && (dist < 25)) {
        cost = cost + 1.25 * dist;
      } else if ((dist >= 25) && (dist < 40)) {
        cost = cost + 0.85 * dist;
      } else {
        cost = cost + 0.5 * dist;
      }
      break;
    case '4':
      cost = 40;
      if (dist < 10) {

      } else if ((dist >= 10) && (dist < 25)) {
        cost = cost + 1.25 * dist;
      } else if ((dist >= 25) && (dist < 40)) {
        cost = cost + 0.85 * dist;
      } else {
        cost = cost + 0.5 * dist;
      }
      break;
  }
  return cost;
}

