// JavaScript Document

$(document).ready(function(){
	//States Map Tool Tip
	$("#theMap area").each( function(){
									//console.log( this.id );
									$( this ).tooltip({ 
													track: true, 
													delay: 0, 
													showURL: false, 
													opacity: 1, 
													fixPNG: true, 
													showBody: " - ", 
													extraClass: "pretty fancy", 
													top: -15, 
													left: 5 
												});
									$( this ).mouseover( function(){
																  $( '#OR_A' ).highlightFade( { start:'#FF3C00', end:'#FDF6BF', interval:10, speed:10 } );
																  });
									$( this ).mouseout( function(){
																  $( '#OR_A' ).highlightFade( { start:'#FF3C00', end:'#D6D6D6', interval:10, speed:10 } );
																  });
	});
	
	$("#states_list_div li a").each( function(){
									//console.log( this.id );
									$( this ).tooltip({ 
																track: true, 
																delay: 0, 
																showURL: false, 
																opacity: 1, 
																fixPNG: true, 
																showBody: " - ", 
																extraClass: "pretty fancy", 
																top: 5, 
																left: 25 
															});	
									});
	
	$('#dialogbox').jqm({modal:false,onLoad:dialogLoad,target:$('#dialogbox div.contents')[0],onShow:dialogShow});
	$( "#add_business" ).validate({
		rules: {
			business_name: {
				required: true,
				minlength: 5,
				maxlength: 255
			},
			business_contact: {
				required: true,
				minlength: 5,
				maxlength: 255
			},
			business_address_1: {
				required: true,
				minlength: 5,
				maxlength: 255
			},
			business_city:  {
				required: true
			},
			business_state:  {
				required: true
			},
			business_zip:  {
				required: true
			},
			latitude: {
				required: true
			},
			longitude: {
				required: true
			},
			highway_1: {
				required: true
			},
			brst_business_categories_id: {
				required: true
			},
			business_package: {
				required: true
			},
			tos: {
				required: true
			}
		},
		messages: {
			business_name:  {
				required: "Please enter your Business Name!",
				minlength: "Business Name must consist of at least 5 characters",
				maxlength: "Business Name must consist of maximun 256 characters"
			},
			business_contact: {
				required: "Please provide the contact name for Business!",
				minlength: "Contact Name must consist of at least 5 characters",
				maxlength: "Contact Name must consist of maximun 256 characters"
			},
			business_address_1: {
				required: "Please enter a Business Address",
				minlength: "Address must consist of at least 5 characters",
				maxlength: "Address must consist of maximun 256 characters"
			},
			business_city: {
				required: "Please provide business town / city!"
			},
			business_state: {
				required: "Please provide business state!"
			},
			business_zip: {
				required: "Please provide business zip code!"
			},
			latitude: {
				required: "Please provide a map location!"
			},
			longitude: {
				required: "Please provide a map location!"
			},
			highway_1: {
				required: "Please select atleast 1 highway!"
			},
			brst_business_categories_id: {
				required: "Please select a Category!"
			},
			business_package: {
				required: "Please select atleast one Package"
			},
			tos: {
				required: "Please accept our Term of Services!"
			}
		}
	});
	
	$( "#add_poi" ).validate({
		rules: {
			poi_name: {
				required: true,
				minlength: 5,
				maxlength: 255
			},
			brst_towns_id: {
				required: true
			},
			latitude: {
				required: true
			},
			longitude:  {
				required: true
			},
			highway_1: {
				required: true
			}
		},
		messages: {
			poi_name:  {
				required: "Please enter your POI Name!",
				minlength: "POI Name must consist of at least 5 characters",
				maxlength: "POI Name must consist of maximun 256 characters"
			},
			latitude: {
				required: "Please provide a map location!"
			},
			longitude: {
				required: "Please provide a map location!"
			},
			highway_1: {
				required: "Please select atleast 1 highway!"
			},
			brst_towns_id: {
				required: "Please select a Town!"
			}
		}
	});
	$( "#login_form" ).validate({
		rules: {
			username: {
				required: true
			},
			password: {
				required: true
			}
		},
		messages: {
			username:  {
				required: "Please enter your username!"
			},
			password: {
				required: "Please provide your password!"
			}
		}
	});
	$( "#frm_forgot_username" ).validate({
		rules: {
			email: {
				required: true
			}
		},
		messages: {
			email:  {
				required: "Please enter your username!"
			}
		}
	});
	$( "#frm_forgot_password" ).validate({
		rules: {
			username: {
				required: true
			},
			email: {
				required: true
			}
		},
		messages: {
			username:  {
				required: "Please enter your username!"
			},
			email: {
				required: "Please provide your password!"
			}
		}
	});
	
	initiUploadFile('upload_file.php', { saving_path: $('#saving_path').val(), max_width:500, thumb_width:200, thumb_height:125, upload:'Upload'});
});

function showToolTip( the_obj ){
	//alert( the_obj );
	$( the_obj ).tooltip({ 
						track: true, 
						delay: 0, 
						showURL: false, 
						opacity: 1, 
						fixPNG: true, 
						showBody: " - ", 
						extraClass: "pretty fancy", 
						top: -15, 
						left: 5 
					});	
}
	
function highlightText( container_id, start_color, end_color ){
	//alert( 'Fading ..' )
	$( container_id ).highlightFade( { start:start_color, end:end_color, interval:10, speed:10 } );
}

/*
	*******************************************************
	FOR GOOGLE MAPS 
	*******************************************************
*/
function myupdateMarker(marker, ele_lat, ele_lng) {
  var latlng = marker.getPoint();
  var lat = Math.round(latlng.y * 100) / 100;
  var lng = Math.round(latlng.x * 100) / 100
  
 // console.log( lat );
 if( ele_lat = "lat" ) ele_lat = "#latitude";
 if( ele_lng = "lng" ) ele_lng = "#longitude";
  //alert( ele_lat );
  //alert( ele_lng );
  //console.log( $(ele_lat ) );
  
  $( ele_lat ).attr("value", latlng.y);
  $( ele_lng ).attr("value", latlng.x);
  
  //$("#latitude" ).val("something");
  //$("#town_name" ).val("testing");
  $("#geoloc", top.document).html("(latitude: " + latlng.y + " , longitude: " + latlng.x + " )");
  //console.log($("#maplocation",top.document));
  //alert("(" + Math.round(latlng.y * 100) / 100 + ", " +Math.round(latlng.x * 100) / 100 + ")")
  
}
function drawMap() {
    if (google.maps.BrowserIsCompatible()) {
      var map = new google.maps.Map2(document.getElementById('map'));
      map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
    }
}

/*function loadMap( target_div ) {
google.load(target_div, "2.x", {callback: drawMap });
}
*/function loadMap() {
      map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(37.4419, -122.1419), 6);
      map.addOverlay(new GMarker(map.getCenter()));
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAA-O3c-Om9OcvXMOJXreXHAxQGj0PqsCtxKvarsoS-iqLdqZSKfxS27kJqGZajBjvuzOBLizi931BUow&async=2&callback=loadMap";
  document.body.appendChild(script);
}
function loadPage( target, page, indexes, values, effect, callback ){
	//console.log( target );
	params = {};
	if( values != null && indexes != null ){
		for( i=0; i<values.length; i++ ){
			params[indexes[i]] = values[i];
		}
	}
	//console.log( params );
	$.post( page, params, function(data){
								   var targetEl = $( target );
								   switch( effect ){
									   case "fade":
										   $( target ).fadeOut("slow", function(){
																			$( target ).html( data );								
																				});
										   $( target ).fadeIn( "slow");
										   
										   break;
										case "JSON":
											eval( callback );
											break;
										default:
											$( target ).html( data );
								   }
								  });
		   
}
function test(){
	alert( 'testing..' );
}
function rotateAds(  ad_container, delay_time, page, indexes, values, effect ){
	window.setTimeout(function() {
		//alert(ad_container);
		loadPage( ad_container, page, indexes, values, effect );
	}, delay_time);
}

function showDialog( ){
	//alert( 'show' );
	//loadPage( "#testLoad", "new_highway.php", null, null, null );
	$('#dialogbox').jqmShow();
	//$('#loading').jqmShow(); 	
}
var dialogShow = function(hash){
	//alert( 'Shown' );
	hash.w.show();
	loadPage( "#dialogbox div.contents", "new_highway.php", null, null, null );
};
var dialogLoad = function(hash){
	//alert( 'Loaded' );
	//console.log( hash.w );
	//$('form',hash.w).ajaxForm(); 
};

///////////// CROP AND UPLOAD ////////////////////////////
//show and hide the loading message
function loadingmessage( msg, show_hide){
	if(show_hide=="show"){
		$('#loader').show();
		$('#progress').show().text(msg);
		$('#uploaded_image').html('');
		
	}else if(show_hide=="hide"){
		$('#loader').hide();
		$('#progress').text('').hide();
		
	}else{
		$('#loader').hide();
		$('#progress').text('').hide();
		$('#uploaded_image').html('');
	}
}

function initiUploadFile( processing_file, extra_params ) {
		 $('#loader').hide();
		 $('#progress').hide();
		 var myUpload = $('#upload_link').upload( {
		   name: "the_file",
		   action: processing_file,
		   enctype: 'multipart/form-data',
		   params: extra_params,
		   autoSubmit: true,
		   onSelect: function() {
			   	//alert( 'slected' );
				$('#upload_status').html('').hide();
				loadingmessage( 'File Selected...', 'show');
		   },
		   onSubmit: function() {
			   	//alert( 'submited' );
		   		$('#upload_status').html('').hide();
				loadingmessage( 'Please wait, uploading file...', 'show');
				//console.log( myUpload );
		   },
		   onComplete: function(response) {
			   	//alert( 'completed' );
		   		loadingmessage('', 'hide');
				//console.log( response );
				response = unescape(response);
				var response = response.split("|");
				//console.log( response );
				var responseType = response[0];
				var responseMsg = response[1];
				if(responseType=="success"){
					var current_width = response[2];
					var current_height = response[3];
					var image_file_name = response[4];
					//display message that the file has been uploaded
					$('#upload_status').show().html('<span class="error_black">Success, The image has been uploaded</span>');
					//put the image in the appropriate div
					$('#uploaded_image').html( '' ); //Remove anything old
					$('#uploaded_image').html('<img src="'+responseMsg+'" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" /><div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:'+$('#thmb_w').val()+'px; height:'+$('#thmb_h').val()+'px;"><img src="'+responseMsg+'" style="position: relative;" id="thumbnail_preview" alt="Thumbnail Preview" /></div>')
					//find the image inserted above, and allow it to be cropped
					//alert( ratio );
					var ratio = $('#thmb_h').val() / $('#thmb_w').val();
					//ratio = 1;
					//alert( ratio );
					$('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:'+ratio, onSelectChange: preview, autoHide:false }); 
					$('#image_file_name').val(image_file_name);
					//display the hidden form
					$('#thumbnail_form').show();
				}else if(responseType=="error"){
					$('#upload_status').show().html('<span class="error_red">Error, '+responseMsg+'</span>');
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}else{
					$('#upload_status').show().html('<span class="error_red">Unexpected Error, Please try again<br>'+response+'</span>');
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}
		   }
		});
		 
		return myUpload;
}

//create a preview of the selection
function preview(img, selection) { 
	//console.log( 'previewd' );
	//console.log( img );
	//console.log( selection );
	//get width and height of the uploaded image.
	var current_width = $('#uploaded_image').find('#thumbnail').width();
	var current_height = $('#uploaded_image').find('#thumbnail').height();
	//console.log( current_width );
	//console.log( current_height );
	var scaleX = $('#thmb_w').val() / selection.width; 
	var scaleY = $('#thmb_h').val() / selection.height; 
	//console.log( scaleX );
	//console.log( scaleY );
	
	$('#uploaded_image').find('#thumbnail_preview').css({ 
		width: Math.round(scaleX * current_width) + 'px', 
		height: Math.round(scaleY * current_height) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
	});
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
} 

function selectUploadTab( trigger, thmb_w, thmb_h ){
	var x1 = $('#x1').val();
	if( x1 == "nill" ){
		$('#field').val(trigger);
		$('#thmb_w').val(thmb_w);
		$('#thmb_h').val(thmb_h);
		$( '#the_tabs div' ).attr( "class" , "form_tab" );
		$('#'+trigger+'_tab' ).attr( "class" , "form_tab_selected" );
		$('#progress').html( "" ).hide();
		$('#upload_status').html( "" ).hide();
		$('#uploaded_image').html( "" );
		$.scrollTo( $( '#the_tabs' ), {duration:500} );
	}else {
		if( confirm( 'Are You sure You want to discard without saving?\n\nSave the thumbnail first!' ) ){
			$('#x1').val("nill");
			selectUploadTab( trigger, thmb_w, thmb_h );
		}else {
			return false;
		}
	}
}

function createThumbnail(processing_file){
	//create the thumbnail
	//$('#save_thumb').click(function() {
		var field = $('#field').val();
		var thmb_w = $('#thmb_w').val();
		var thmb_h = $('#thmb_h').val();
		var saving_path = $('#saving_path').val();
		var image_file_name = $('#image_file_name').val();
		var x1 = $('#x1').val();
		var y1 = $('#y1').val();
		var x2 = $('#x2').val();
		var y2 = $('#y2').val();
		var w = $('#w').val();
		var h = $('#h').val();
		if(x1=="" || x1 == "nill" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
			alert("You must make a selection first");
			return false;
		}else{
			//hide the selection and disable the imgareaselect plugin
			$('#uploaded_image').find('#thumbnail').imgAreaSelect({ disable: true, hide: true }); 
			loadingmessage('Please wait, saving thumbnail....', 'show');
			$.ajax({
				type: 'POST',
				url: processing_file,
				data: 'save_thumb=Save Thumbnail&x1='+x1+'&y1='+y1+'&x2='+x2+'&y2='+y2+'&w='+w+'&h='+h+'&field='+field+'&thmb_w='+thmb_w+'&thmb_h='+thmb_h+'&image_file_name='+image_file_name+'&saving_path='+saving_path,
				cache: false,
				success: function(response){
					loadingmessage('', 'hide');
					response = unescape(response);
					var response = response.split("|");
					var responseType = response[0];
					var responseLargeImage = response[1];
					var responseThumbImage = response[2];
					var field_name = response[3];
					var thmb_image_name = response[4];
					if(responseType=="success"){
						$('#upload_status').show().html('<span class="error_black">Success , The thumbnail has been saved!</span>');
						//load the new images
						$('#uploaded_image').html('<img src="'+responseThumbImage+'" alt="Thumbnail Image" align="left"/>&nbsp;&nbsp;<a href="javascript:deleteimage(\''+responseLargeImage+'\', \''+responseThumbImage+'\', \''+processing_file+'\' , \''+field_name+'\');"><< Delete This Image</a>');
						//hide the thumbnail form
						$('#thumbnail_form').hide();
						$('#'+field_name+'_img').html('<img src="'+responseThumbImage+'" alt="Thumb Image"/>');
						$('#'+field_name).val( thmb_image_name );
						//Reset for other upload
						 $('#x1').val('nill');
					}else{
						$('#upload_status').show().html('<span class="error_red">Unexpected Error , Please try again<br>'+response+'</span>');
						//reactivate the imgareaselect plugin to allow another attempt.
						var ratio = $('#thmb_h').val() / $('#thmb_w').val();
						$('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:'+ratio, onSelectChange: preview }); 
						$('#thumbnail_form').show();
					}
				}
			});
			
			return false;
		}
	//});
}

//delete the image when the delete link is clicked.
function deleteimage(large_image, thumbnail_image, processing_file, field_name){
	if( confirm( 'Are You sure you want to delet this image?' ) ){
		loadingmessage('Please wait, deleting images...', 'show');
		$.ajax({
			type: 'POST',
			url: processing_file,
			data: 'a=delete&large_image='+large_image+'&thumbnail_image='+thumbnail_image,
			cache: false,
			success: function(response){
				loadingmessage('', 'hide');
				response = unescape(response);
				var response = response.split("|");
				var responseType = response[0];
				var responseMsg = response[1];
				if(responseType=="success"){
					$('#upload_status').show().html('<span class="error_black">Success , '+responseMsg+'</span>');
					$('#uploaded_image').html('');
					$('#'+field_name+'_img').html('<span class="error_red">Image Deleted</span>');
					$('#'+field_name).val( "" );
				}else{
					$('#upload_status').show().html('<span class="error_red">Unexpected Error , Please try again<br>'+response);
				}
			}
		});
	}
}

function updateHighways( response ){
	if( response == null ){
		//alert( 'Updating Highways' );
		loadPage( "#the_temp", "new_highway.php", ['mode'], ['get_highways'], 'JSON' ,'updateHighways( data );');
	}else {
		eval( response );
		//alert( "Updating ..... "+data );
		var highway_1 = $("#highway_1").selectedValues();
		var highway_2 = $("#highway_2").selectedValues();
		var highway_3 = $("#highway_3").selectedValues();
		var highway_4 = $("#highway_4").selectedValues();
		var highway_5 = $("#highway_5").selectedValues();
				
		$("#highway_1").removeOption(/./, true);
		$("#highway_2").removeOption(/./);
		$("#highway_3").removeOption(/./);
		$("#highway_4").removeOption(/./);
		$("#highway_5").removeOption(/./);
		
		$("#highway_1").addOption(data);
		$("#highway_2").addOption(data);
		$("#highway_3").addOption(data);
		$("#highway_4").addOption(data);
		$("#highway_5").addOption(data);
		
		$("#highway_1").selectOptions(highway_1);
		$("#highway_2").selectOptions(highway_2);
		$("#highway_3").selectOptions(highway_3);
		$("#highway_4").selectOptions(highway_4);
		$("#highway_5").selectOptions(highway_5);
		
	}
}