// Initial Set-up

var api_key = "a74b6953df805decb9532c7530265941";
var brand_name = "Demo Taxi Company";
var dispatch_number = "+448003102626";
var phone_number = localStorage.getItem('phone_number');
var customer_id = localStorage.getItem('customer_id');
var customer_hash = localStorage.getItem('customer_hash');
var current_page = "home";
var last_page = "loading";

// JSON Variables
var drivers;
var userdata = new Array();
var jobdata = new Array();
var taxidata = new Array();
var pegman1;
var line;
var pushToken='NA';

// PhoneGap
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
    document.addEventListener("backbutton", onBackKeyDown, false);
    document.addEventListener("menubutton", onMenuKeyDown, false);
  }

function onBackKeyDown(){
	if(current_page=='step4')moveToPage('step3');
	else if(current_page!='home')moveToPage('home');
    return false;
}

function onMenuKeyDown(){
	snapper.open('left');
}

function getPhoneGapPath() {

    var path = window.location.pathname;
    path = path.substr( path, path.length - 10 );
    return 'file://' + path;

};


function playAudio(file) {
    // Play the audio file at url
    var my_media = new Media(getPhoneGapPath()+"audio/"+file+".mp3",
        // success callback
        function () {
            console.log("playAudio():Audio Success");
        },
        // error callback
        function (err) {
            console.log("playAudio():Audio Error: " + err);
        }
    );
    // Play audio
    my_media.play();
}

// iWebCab JS
function parseQueryString() {
	var url = window.location.pathname;
    var queryStringIdx = url.indexOf('?');
    var pairs = url.substr(queryStringIdx + 1)
                   .split('&')
                   .map(function(p) { return p.split('='); });
    var result = { };
    for (var i = 0; i < pairs.length; i++) {
        result[decodeURIComponent(pairs[i][0])] = decodeURIComponent(pairs[i][1]);
    }

    return result;
}

function moveToPage(new_page){
	if(current_page!='welcome')last_page = current_page;
	$(".appPage:visible, .loadingPage:visible").fadeOut(200,function(){
		$("#page_"+new_page).fadeIn(200);
		if(new_page!='home' && new_page!='step2' && new_page!='payment'){
			if(new_page=='step1' || new_page=='step3'){
				$("#close").show();
				$("#menu").hide();
				$("#back").hide();
			}else{
				$("#close").hide();
				$("#back").show();
				$("#menu").hide();
			}
		}else{
			$("#close").hide();
			$("#back").hide();
			$("#menu").show();
            google.maps.event.trigger(map, 'resize');
            map.setZoom(map.getZoom());
		}
		current_page = new_page;
		$(".page-content").css({'height':"100%"});
	});
	
	
	$(".nav-item").find("em").addClass("unselected-nav");
	$(".nav-item").find("em").removeClass("selected-nav");
	if(new_page=='home'){
		$(".home-nav").find("em").addClass("selected-nav");
		$(".home-nav").find("em").removeClass("unselected-nav");
	}else if(new_page=='step2' || new_page=='step1'){
		$(".contact-nav").find("em").addClass("selected-nav");
		$(".contact-nav").find("em").removeClass("unselected-nav");
	}else if(new_page=='payment'){
		$(".payment-nav").find("em").addClass("selected-nav");
		$(".payment-nav").find("em").removeClass("unselected-nav");
	}
	
}

function iwc_startup(){
	loadScript();
	document.title=brand_name;
	$(".brandname").html(brand_name);
	$(".dispatch-nav").attr("href","tel:"+dispatch_number);
	setInterval(function(){getdrivers();},15000);
}

function getdrivers(){
	$.getJSON("https://cp.iwebcab.com/public_api/"+api_key+"/drivers.json",function (recvdata){
		drivers = recvdata;
		setMarkers(map,drivers);
	});
}

function getjob(){
	if(phone_number==null){
		resync_pickup_time();
		return;
	}
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/check_live_bookings.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
			},
			function (recvdata){
				if(recvdata['jobdata']['result']!='error'){
					jobdata = recvdata['jobdata'];
				}else{
					jobdata = new Array();
				}
				if(recvdata['taxidata']['result']!='error'){
					taxidata = recvdata['taxidata'];
				}else{
					taxidata = new Array();
				}
				
				update_job_screen();
				resync_pickup_time();
			},'json');
}

function update_job_screen(){
	$("#status-pickuptime").removeClass("topbarhide");
	$("#status-pickuptime").addClass("topbarshow");	

	if(jobdata['job_id']!=null){
		$("#status-job").removeClass("topbarhide");
		$("#status-job").addClass("topbarshow");	
		$("#pickupicon").hide();
		$(".jumpBack").hide();
		$(".selected-addy").html("Your Booking Reference is "+jobdata['job_id']);
		pegman1.setPosition(new google.maps.LatLng(jobdata['pickup_lat'], jobdata['pickup_long']));
		map.setOptions({ draggable : false, disableDoubleClickZoom: true });
		
		if(jobdata['status']=='W'){
			$("#status-job p").html("Awaiting An Available Driver.");			
			if(pegman1!=null){
				pegman1.setVisible(true);
			  	map.setCenter(pegman1.position);
			}
		}else if(jobdata['status']=='P'){
			$("#status-job p").html("Awaiting Driver Response.");		
			if(pegman1!=null){
				pegman1.setVisible(true);
				var bounds = new google.maps.LatLngBounds();
				bounds.extend(pegman1.position);
				bounds.extend(gmark['Cab'+jobdata['taxi_id']].position);
				map.fitBounds(bounds);
				linedriver();
			}
		}else if(jobdata['status']=='1'){
			$("#status-job p").html("Your Driver Is On The Way!");		
			if(pegman1!=null){
				pegman1.setVisible(true);
				var bounds = new google.maps.LatLngBounds();
				bounds.extend(pegman1.position);
				bounds.extend(gmark['Cab'+jobdata['taxi_id']].position);
				map.fitBounds(bounds);
				linedriver();
			}
		}else if(jobdata['status']=='A'){
			$("#status-job p").html("Your Driver Is Arriving!");
			$("#status-pickuptime").removeClass("topbarshow");
			$("#status-pickuptime").addClass("topbarhide");				
			if(pegman1!=null){
				pegman1.setVisible(true);
				var bounds = new google.maps.LatLngBounds();
				bounds.extend(pegman1.position);
				bounds.extend(gmark['Cab'+jobdata['taxi_id']].position);
				map.fitBounds(bounds);
				linedriver();
			}
		}else if(jobdata['status']=='2'){
			if(line!=null)line.setVisible(false);
			$("#status-job p").html("In Vehicle - Driving.");
			$("#status-pickuptime").removeClass("topbarshow");
			$("#status-pickuptime").addClass("topbarhide");				
			if(pegman1!=null)pegman1.setVisible(false);
			
			if(gmark['Cab'+jobdata['taxi_id']]!=null){
				map.setCenter(gmark['Cab'+jobdata['taxi_id']].position);
				gmark['Cab'+jobdata['taxi_id']].setIcon(taxiimage['PegRide']);
				map.setZoom(16);
			}
		}
		
	}else{
		$("#status-job").addClass("topbarhide");
		$("#status-job").removeClass("topbarshow");	
		$("#pickupicon").show();
		if(pegman1!=null)pegman1.setVisible(false);
		map.setOptions({ draggable : true, disableDoubleClickZoom: true });
		if(line!=null)line.setVisible(false);
	}
	
	if(taxidata['taxi_id']!=null){
		$("#status-driver").removeClass("topbarhide");
		$("#status-driver").addClass("topbarshow");	
		$("#status-driver p").html(taxidata['first_name']+' '+taxidata['last_name']+' - '+taxidata['reg_plate']);
	}else{		
		$("#status-driver").addClass("topbarhide");
		$("#status-driver").removeClass("topbarshow");	
	}
	
	main_button_update();
}

function apply_name(fn, ln){
	userdata['first_name']=fn;
	userdata['last_name']=ln;
	$(".firstnameField").val(fn);
	$(".lastnameField").val(ln);
	$(".passengernameField").val(fn+" "+ln);
}

function apply_email(em){
	userdata['email']=em;
	$(".emailField").val(em);
}


function linedriver(){
var lineCoordinates = [
    pegman1.position,
    gmark['Cab'+jobdata['taxi_id']].position
  ];
  
  if(line==null){
  line = new google.maps.Polyline({
    path: lineCoordinates,
    geodesic: true,
    strokeColor: '#000000',
    strokeOpacity: 0.25,
    strokeWeight: 4
  });
  line.setMap(map);
  }else{
	line.setVisible(true);
  	line.setPath(lineCoordinates);
  }
}

function is_verified(){
	if(phone_number==null)verify_now();
	else if(customer_hash==null)verify_now();
	else{
		$.post("https://cp.iwebcab.com/public_api/"+api_key+"/customer_verified.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					moveToPage('step3');
					apply_name(recvdata['first_name'],recvdata['last_name']);
					apply_email(recvdata['email']);
				}else if(recvdata['result']=='valid-cin'){
					moveToPage('step2');
				}else {
					localStorage.setItem('customer_hash',null);
					customer_hash = null;
					localStorage.setItem('customer_id',null);
					customer_id = null;
					localStorage.setItem('phone_number',null);
					phone_number = null;
					verify_now();
				}
			},'json');
	}
}

function verify_now(){
	moveToPage('step1');
}

$(document).on("click", "#b_verify_pn", function(){
	
	phone_number = $("#mobileField").val();
	localStorage.setItem('phone_number',phone_number);
	$("#verify-button").hide();
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/reset_account_code.json",
			{
				'phone_number': phone_number,
			},
			function (recvdata){
				if(recvdata['result']=='existing'){
					$("#success-existing, #form-sec-code").show();
					$("#mobileField").attr('readonly', true);
				}
				else {
					$("#success-pinsent, #form-sec-code").show();
					$("#mobileField").attr('readonly', true);
				}
			},'json');
});

$(document).on("click", "#b_authenticate", function(){
	
	var seccode = $.md5(api_key+'-'+$("#seccodeField").val());
	$("#authenticate-button").hide();
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/validate_customer_hash.json",
			{
				'phone_number': phone_number,
				'customer_hash': seccode,
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					localStorage.setItem('customer_hash',seccode);
					customer_hash = seccode;
					localStorage.setItem('customer_id',recvdata['customer_id']);
					customer_id = recvdata['customer_id'];
					moveToPage('step3');
				}else if(recvdata['result']=='valid-cin'){
					localStorage.setItem('customer_hash',seccode);
					customer_hash = seccode;
					localStorage.setItem('customer_id',recvdata['customer_id']);
					customer_id = recvdata['customer_id'];
					apply_name(recvdata['first_name'],recvdata['last_name']);
					apply_email(recvdata['email']);
					moveToPage('step2');
				}else {
					$("#authenticate-button").show();
					$("#security_code_bad").show().delay(3000).fadeOut(400);
				}
			},'json');
});


function main_button_update(){
	
	if(jobdata['job_id']!=null){
		if(jobdata['taxi_id']!=0 && (jobdata['status']=='1' || jobdata['status']=='A')){
			$("#b_pickup_now").css({'background-color': '#FF7F2A'});
			$("#b_pickup_now p").html("Call My Driver");
		}else if(jobdata['taxi_id']!=0 && (jobdata['status']=='2')){
			$("#b_pickup_now").css({'background-color': '#00AAFF', 'color':'#ffffe4'});
			$("#b_pickup_now p").html("Make Payment");
		}else if((jobdata['taxi_id']==0 && (jobdata['status']=='W'))||(jobdata['taxi_id']!=0 && (jobdata['status']=='P'))){
			$("#b_pickup_now").css({'background-color': '#FF0000', 'color':'#ffffe4'});
			$("#b_pickup_now p").html("Cancel Job");
		}else{
			$("#b_pickup_now").css({'background-color': '#00cb79', 'color':'#ffffe4'});
			$("#b_pickup_now p").html("Pick Me Up Here");
		}
	}else{
		if($("#b_pickup_now p").html()!='Pick Me Up Here'){
			$("#b_pickup_now").css({'background-color': '#00cb79', 'color':'#ffffe4'});
			$("#b_pickup_now p").html("Pick Me Up Here");
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
			    if(status == google.maps.GeocoderStatus.OK) {
			        pickup_data = results[0];
	        
			        $(".selected-addy").html(results[0]['address_components'][0]['short_name']+ " "+results[0]['address_components'][1]['short_name']);
			        $(".houseField").val(results[0]['address_components'][0]['short_name'])
			        $(".roadnameField").val(results[0]['address_components'][1]['short_name']);
			     	$("#map_canvas").height($(window).height()-($(".fixed-header-clear").height()));
				
			    };
			});
		}
	}
}

$(document).on("click",".payment-nav",function(){
	if(phone_number==null)verify_now();
	else if(customer_hash==null)verify_now();
	else{
		$.post("https://cp.iwebcab.com/public_api/"+api_key+"/customer_verified.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					apply_name(recvdata['first_name'],recvdata['last_name']);
					apply_email(recvdata['email']);
					$("#page_step2").find("p:eq(0)").html("You can update your information by completing the following form.");	
					moveToPage('payment');
					$("#div_b_new_card").show();
					$("#new_card").hide();
				}else if(recvdata['result']=='valid-cin'){
					moveToPage('step2');
				}else {
					localStorage.setItem('customer_hash',null);
					customer_hash = null;
					localStorage.setItem('customer_id',null);
					customer_id = null;
					localStorage.setItem('phone_number',null);
					phone_number = null;
					verify_now();
				}
			},'json');
	}
});

$(document).on("click",".contact-nav",function(){
	if(phone_number==null)verify_now();
	else if(customer_hash==null)verify_now();
	else{
		$.post("https://cp.iwebcab.com/public_api/"+api_key+"/customer_verified.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					apply_name(recvdata['first_name'],recvdata['last_name']);
					apply_email(recvdata['email']);
					$("#page_step2").find("p:eq(0)").html("You can update your information by completing the following form.");
					moveToPage('step2');
				}else if(recvdata['result']=='valid-cin'){
					moveToPage('step2');
				}else {
					localStorage.setItem('customer_hash',null);
					customer_hash = null;
					localStorage.setItem('customer_id',null);
					customer_id = null;
					localStorage.setItem('phone_number',null);
					phone_number = null;
					verify_now();
				}
			},'json');
	}
});

$(document).on("click",".b_add_new_card",function(){
	if(phone_number==null)verify_now();
	else if(customer_hash==null)verify_now();
	else{
		$.post("https://cp.iwebcab.com/public_api/"+api_key+"/add_new_card.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
				'creditcard': $("#cardnumberField").val(),
				'expiry':$("#cardexpmonthField").val()+$("#cardexpyearField").val(),
				'cvv':$("#cvvcodeField").val()
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					apply_card(recvdata['l4d'],recvdata['type']);
					$("#cc_success").show().delay(3000).fadeOut(400);
				}else {
					$("#cc_fail").show().delay(3000).fadeOut(400);
				}
			},'json');
	}
});


$(document).on("click", "#b_pickup_now", function(){
	if(jobdata['job_id']!=null){
		if(jobdata['taxi_id']!=0 && (jobdata['status']=='1' || jobdata['status']=='A')){
			window.location='tel:+'+taxidata['mobile_number'];
		}else if(jobdata['taxi_id']!=0 && (jobdata['status']=='2')){
			moveToPage('payment');
			$("#div_b_new_card").show();
			$("#new_card").hide();
		}else if((jobdata['taxi_id']==0 && (jobdata['status']=='W'))||(jobdata['taxi_id']!=0 && (jobdata['status']=='P'))){
			moveToPage('canceljob');
		}else{
			is_verified();
		}
	}else{
		is_verified();
	}
});

$(document).on("click","#b_new_card",function(){
	$("#div_b_new_card").hide();
	$("#new_card").show();
});
	
$(document).on("click", ".home-nav, #back", function(){
	if(current_page=='step4')moveToPage('step3');
	else moveToPage('home');
});

$(document).on("click", ".home-nav, #close, #b_keep_job", function(){
	moveToPage('home');
});

$(document).on("click", ".jumpBack", function(){
	curloc=myloc;
	map.panTo(myloc.position);
	map.setZoom(15);
	$(".jumpBack").hide();
	resync_curloc();
});

$(document).on("click", "#b_update_info", function(){
	$("#b_update_info").hide();
	
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/update_customer_profile.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
				'first_name':	$("#firstnameField").val(),
				'last_name':	$("#lastnameField").val(),
				'email':	$("#emailField").val(),
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					apply_name($("#firstnameField").val(), $("#lastnameField").val());
					apply_email($("#emailField").val());
					if($("#page_step2").find("p:eq(0)").html()=="You can update your information by completing the following form."){
						$("#pi_success").show().delay(3000).fadeOut(400);
					}else{
						moveToPage('step3');
					}
				}else{
					$("#pi_bad").show().delay(3000).fadeOut(400);
				}
			},'json');
});


$(document).on("click", "#b_cancel_job", function(){
	$("#b_cancel_job").hide();
	
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/cancel_job.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
				'job_id':	jobdata['job_id']
			},
			function (recvdata){
				getjob();
				moveToPage('home');
			},'json');
});

$(document).on("click","#b_job_1",function(){
	moveToPage('step4');
});

$(document).on("click","#b_job_2",function(){
	
	$("#b_job_2").hide();
	
	var pickup_parsed = $("#houseField").val()+' '+$("#roadnameField").val()+', ';
	
	$.each(pickup_data['address_components'], function(key,val){
		if(key==0 || key==1)return true;
		if(key>4)return false;
		pickup_parsed = pickup_parsed + val['long_name'] + ', ';
	});
	pickup_parsed = pickup_parsed.slice(0,-2);
	
	$.post("https://cp.iwebcab.com/public_api/"+api_key+"/instant_booking.json",
			{
				'phone_number': phone_number,
				'customer_id': customer_id,
				'customer_hash': customer_hash,
				'passenger_name':	$("#passengernameField").val(),
				'passenger_total':	$("#passengersField").val(),
				'cases_total':	$("#casesField").val(),
				'wheelchair': $("#wheelchairField").val(),
				'pickup_address':	pickup_parsed,
				'pickup_lat':	curloc.lat(),
				'pickup_long':	curloc.lng(),
				'notes': $("#notesField").val(),
			},
			function (recvdata){
				if(recvdata['result']=='valid'){
					moveToPage('home');
					getjob();
				}else{
					$("#pd_bad").html(recvdata['error']);
					$("#pd_bad").show().delay(3000).fadeOut(400);
					$("#b_job_2").show();
				}
			},'json');
	
});

$(document).on("click",".ZoomIn",function(){
	var currentZoomLevel = map.getZoom();
	if(currentZoomLevel != 0 && currentZoomLevel!=17){
		map.setZoom(currentZoomLevel + 1);
	}     
});
$(document).on("click",".ZoomOut",function(){
	var currentZoomLevel = map.getZoom();
	if(currentZoomLevel != 0){
		map.setZoom(currentZoomLevel - 1);
	}     
});

var tbc = 0;
function top_card_anim(){
	var ni = ($(".topbarshow").length);
	if(ni==1 && $(".topbarshow").is(":visible"))return;
	tbc = ++tbc % ni;
	$(".topbar:visible").fadeOut(500,function(){$(".topbarshow:eq("+tbc+")").fadeIn(500)});
}
// Google Maps
var map;
var curloc;
var myloc;
var pickup_data;
var taxiimage = new Array();
var gmark = new Array();

function loadScript() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize&libraries=geometry,places';
	document.body.appendChild(script);
}

var onSuccess = function(position) {
	curloc = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	
	if(jobdata['job_id']==null){
		map.panTo(curloc);
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng': curloc}, function(results, status) {
		    if(status == google.maps.GeocoderStatus.OK) {
		        pickup_data = results[0];
						        
					if(jobdata['job_id']==null){
				        $(".selected-addy").html(results[0]['address_components'][0]['short_name']+ " "+results[0]['address_components'][1]['short_name']);
				        $(".houseField").val(results[0]['address_components'][0]['short_name'])
				        $(".roadnameField").val(results[0]['address_components'][1]['short_name']);
				     	$("#map_canvas").height($(window).height()-($(".fixed-header-clear").height()));
					}
		    };
		});
}else{
		$(".selected-addy").html("Your Booking Reference is "+jobdata['job_id']);
}

myloc.setPosition(curloc);

google.maps.event.addListener(map, "dragend", function() {resync_curloc();}); 
google.maps.event.addListener(map, "dblclick", function() {resync_curloc();});

google.maps.event.addListener(map, 'bounds_changed', function(event) {
    if (this.getZoom()>17){
        this.setZoom(17);
    }
}); 
};

// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: '    + error.code    + '\n' +
      'message: ' + error.message + '\n');
}

function resync_curloc(){
	if(jobdata['job_id']!=null){
		$(".selected-addy").html("Your Booking Reference is "+jobdata['job_id']);
		return;
	}
    curloc = map.getCenter();
    $(".jumpBack").show();
    
    if(myloc.position.equals(curloc))$(".jumpBack").hide();
    var geocoder = new google.maps.Geocoder();
    
	resync_pickup_time();
	
	geocoder.geocode({'latLng': curloc}, function(results, status) {
        if(status == google.maps.GeocoderStatus.OK) {
        	pickup_data = results[0];
       		$(".selected-addy").html(results[0]['address_components'][0]['short_name']+ " "+results[0]['address_components'][1]['short_name']);
            $(".houseField").val(results[0]['address_components'][0]['short_name'])
            $(".roadnameField").val(results[0]['address_components'][1]['short_name']);
			$("#map_canvas").height($(window).height()-($(".fixed-header-clear").height()));
        };
    });   
}

function initialize() {

	navigator.geolocation.getCurrentPosition(onSuccess, onError);
	   			   

 var myOptions = {
  zoom: 15,
  center: new google.maps.LatLng(51.0453246,-114.0581012),
  streetViewControl: false,
  scrollwheel: false,
  navigationControl: false,
  mapTypeControl: false,
  disableDefaultUI: true,
  scaleControl: false,
  draggable: true,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};


	getdrivers();
	
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
$("#map_canvas").height($(window).height()-($(".fixed-header-clear").height()));

if($(window).height()>748){
	$("#map_canvas").append('<img src="images/pickuplarge.png" id="pickupicon" style="position: absolute; top:50%; left:50%;  margin-top: -190px; margin-left: -58px; z-index:10000;">');
}else{
	$("#map_canvas").append('<img src="images/pickuplarge.png" id="pickupicon" style="position: absolute; top:50%; left:50%;  margin-top: -133px; margin-left: -76px; -moz-transform:scale(0.4); -webkit-transform:scale(0.4); transform:scale(0.4); z-index:10000;">');
}

var dmarker = new google.maps.Marker({
        position: map.getCenter(),
        map: map
      });
   
$("#map_canvas").append('<img src="images/locate-button.png" class="jumpBack" style="cursor: pointer; display: none; position: absolute; bottom: 120px; right: -45px; -moz-transform:scale(0.3); -webkit-transform:scale(0.3); transform:scale(0.3); z-index:10000;">');
$("#map_canvas").append('<img src="images/zoom-in.png" class="ZoomIn" style="cursor: pointer; position: absolute; bottom: 94px; right: -45px; -moz-transform:scale(0.3); -webkit-transform:scale(0.3); transform:scale(0.3); z-index:10000;">');
$("#map_canvas").append('<img src="images/zoom-out.png" class="ZoomOut" style="cursor: pointer; position: absolute; bottom: 60px; right: -45px; -moz-transform:scale(0.3); -webkit-transform:scale(0.3); transform:scale(0.3); z-index:10000;">');


$("#map_canvas").append('<div id="topbarstats" style="position: relative; padding-top: 2px; margin-left: 30px; margin-right: 30px; z-index:10000;">'+
		'<div id="status-pickuptime" class="big-notification topbar topbarshow alpha50" style="position: relative; width: 100%; color: #ffffff; padding-top: 0px; margin-top: 0px;">'+
	        '<h4 class="center-text uppercase" style="font-weight: bold; padding-top: 2px; padding-bottom: 0px; margin-bottom: 0px;">Estimated Pickup Time:</h4>'+
	        '<p class="center-text" style="margin-bottom: 0px; padding-top: 3px; margin-bottom: 0px; padding-bottom: 0px;">.. Minutes</p>'+
	    '</div>'+
		'<div id="status-job" class="big-notification alpha50 topbar topbarhide" style="position: relative; width: 100%; display: none; color: #ffffff; padding-top: 0px; margin-top: 0px;">'+
	        '<h4 class="center-text uppercase" style="font-weight: bold; padding-top: 2px; padding-bottom: 0px; margin-bottom: 0px;">Your Booking Status</h4>'+
	        '<p class="center-text" style="margin-bottom: 0px; padding-top: 3px; margin-bottom: 0px; padding-bottom: 0px;">Awaiting Driver Acceptance</p>'+
	    '</div>'+
		'<div id="status-driver" class="big-notification alpha50 topbar topbarhide" style="position: relative; width: 100%; display: none; color: #ffffff; padding-top: 0px; margin-top: 0px;">'+
	        '<h4 class="center-text uppercase" style="font-weight: bold; padding-top: 2px; padding-bottom: 0px; margin-bottom: 0px;">Your Driver is:</h4>'+
	        '<p class="center-text" style="margin-bottom: 0px; padding-top: 3px; margin-bottom: 0px; padding-bottom: 0px;">Awaiting Allocation</p>'+
	    '</div>'+
    '</div>');

  
setInterval(function(){top_card_anim();},4000);

 myloc = new google.maps.Marker({
    clickable: false,
    icon: new google.maps.MarkerImage('images/location-orb.png',
                                                    new google.maps.Size(22,22),
                                                    new google.maps.Point(0,0),
                                                    new google.maps.Point(11,11)),
	    shadow: null,
	    zIndex: 999,
	    map: map
	});

taxiimage['Available'] = new google.maps.MarkerImage('images/driver-green.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['Away'] = new google.maps.MarkerImage('images/driver-red.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['NoAnswer'] = new google.maps.MarkerImage('images/driver-red.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['Busy'] = new google.maps.MarkerImage('images/driver-blue.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['BusyPending'] = new google.maps.MarkerImage('images/driver-blue.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);


taxiimage['BusyNoAnswer'] = new google.maps.MarkerImage('images/driver-blue.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['Pending'] = new google.maps.MarkerImage('images/driver-blue.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['Offline'] = new google.maps.MarkerImage('images/driver-blue.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['PegWait'] = new google.maps.MarkerImage('images/peg-man1.png',
	new google.maps.Size(70, 78),
	new google.maps.Point(0,0),
	new google.maps.Point(23, 78)
);

taxiimage['PegRide'] = new google.maps.MarkerImage('images/peg-man2.png',
	new google.maps.Size(70, 83),
	new google.maps.Point(0,0),
	new google.maps.Point(20, 83)
);


   
	
 pegman1 = new google.maps.Marker({
    position: map.getCenter(),
    clickable: false,
    icon: taxiimage['PegWait'],
    shadow: null,
    zIndex: 999,
    map: map
	});
}

function setMarkers(map, locations) { 
	for (var i = 0; i < locations.length; i++) { 
	var cablocation = locations[i]; 
	
	if(gmark['Cab'+cablocation['taxi_id']]==undefined){
	  			if(cablocation['online']=='N'){
		    		cablocation['status']='Offline';
		    	}
		    	if(cablocation['status']=='Offline' || cablocation['status']=='Away' || cablocation['status']=='AwayNoAnswer'){
		    		var vi=false;
		    	}else{
		    		var vi=true;
		    	}
			    var myLatLng = new google.maps.LatLng(cablocation['lat'], cablocation['long']); 
			 
			    var marker = new google.maps.Marker({ 
			        position: myLatLng, 
			        visible: vi,
			        map: map, 
			        icon: taxiimage[cablocation['status']]
			    });
			     
			    if(cablocation['taxi_id']==jobdata['taxi_id'] && jobdata['status']==2){
		   			marker.setIcon(taxiimage['PegRide']);
		   			map.setCenter(myLatLng);
		   		}
	 
			    gmark['Cab'+cablocation['taxi_id']]=marker;
			 		   		
		    }else{
		    	if(cablocation['online']=='N'){
		    		cablocation['status']='Offline';
		    	}
		    	var myLatLng = new google.maps.LatLng(cablocation['lat'], cablocation['long']);
		   		gmark['Cab'+cablocation['taxi_id']].setPosition(myLatLng);
		   		if(cablocation['status']=='Offline' || cablocation['status']=='Away' || cablocation['status']=='AwayNoAnswer'){
		    		var vi=false;
		    	}else{
		    		var vi=true;
		    	}
		    	gmark['Cab'+cablocation['taxi_id']].setVisible(vi);
		    	
		   		if(cablocation['taxi_id']==jobdata['taxi_id'] && jobdata['status']==2){
		   			gmark['Cab'+cablocation['taxi_id']].setIcon(taxiimage['PegRide']);
		   			map.setCenter(myLatLng);
					map.setZoom(16);
		   		}else if(cablocation['taxi_id']==jobdata['taxi_id'] && (jobdata['status']=='A' || jobdata['status']==1)){
		   			linedriver();
		   		}
		   		
		   		
		   		else gmark['Cab'+cablocation['taxi_id']].setIcon(taxiimage[cablocation['status']]);
		    }
	}
	setTimeout(function(){getjob();},500)
 } 
 
 
 function resync_pickup_time(){
 	 	
    google.maps.event.trigger(map, 'resize');
    map.setZoom(map.getZoom());
            
    if(jobdata['job_id']==null || (jobdata['job_id']!=null && jobdata['taxi_id']==0)){
	 	var distance = 99999999999999;
	 	$.each(drivers, function(key,val){
	 		if(val['status']!='Available')return true;
	 		var cabdist = google.maps.geometry.spherical.computeDistanceBetween(curloc, gmark['Cab'+val['taxi_id']].position)*0.000621371192;
	 		if(distance>cabdist){
	 			distance=cabdist;
	 		}
	 	});
    }else{
	 	var distance = 99999999999999;
    	if(gmark['Cab'+jobdata['taxi_id']]!=null){
    		var cabdist = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(jobdata['pickup_lat'],jobdata['pickup_long']), gmark['Cab'+jobdata['taxi_id']].position)*0.000621371192;
			if(distance>cabdist){
				distance=cabdist;
			}
    	}else{
    		distance=99999999999998;
    	}
    }
 	if(distance==99999999999999){
 		$("#status-pickuptime p").html("No Drivers Available");
 	}else if(distance==99999999999998){
 		$("#status-pickuptime p").html("Loading...");
 	}else if(distance<0.35){
 		$("#status-pickuptime p").html("1 Minute");
 	}else{
 		$("#status-pickuptime p").html(Math.round(distance*3)+" Minutes");
 	}
 }