/*
	FSI Sir Speedy sendfile.js
	Paul Farning - ISITE Design
	12.22.08
	
	JS for Send A File widget
	
*/

//jQuery dom ready
$(document).ready(function() {

	// make all columns equal height and disable though not available
	$(".step").autoHeight().not(":first,.enabled").addClass("disabled").find("input,select,textarea,button").attr("disabled","disabled");

	// form validate
	$("#form-sendfile").validate(sendfile.validate);

	// build map and hijack form submit
	$(".gmap").each(function(i){ Mapping.buildGMap($(this),i); });
	$("#locationsearch").click(function() {
		Mapping.searchLocations($.trim($("#addressInput").val())); 
		return false;
	});
	
	// process steps
	$("#locations").bind("click",sendfile.step1);
	//$("#step2 input").bind("change",sendfile.step2);
	$("#step2 input").blur(sendfile.step2);
	$("#step3 input#file1").bind("change",sendfile.step3);

	// redirect on confirmation
	if($(".confirmation a#redirectlocation").length > 0) {
		setTimeout('window.location=$("#redirectlocation").attr("href")',10000);
	}
	
});// goodnight, jQuery

// make everything the same height
jQuery.fn.autoHeight = function() {	
	var h = 0;
	var p = jQuery.browser.msie && parseInt(jQuery.browser.version)<7? "height" : "minHeight";
	return this.each(function() {
		h = parseInt($(this).height()) > h ? parseInt($(this).height()) : h;		
	}).css(p,h+"px");;
};

// validation defaults
jQuery.validator.setDefaults({
	errorElement: "strong",
	errorPlacement: function(error, element) {
		if(element.prev("label").length != 0) {
			element.prev("label").after(error);
		} else {
			element.parent("li").find("label:eq(0)").after(error);	
		}
	}
});

// combination of fields required with one error for all
jQuery.validator.addMethod("phoneCombo", function(value, element, param) {
	if($("input.phone").eq(0).val()==""||$("input.phone").eq(1).val()==""||$("input.phone").eq(2).val()=="") {
		$("input.phone:not(:eq(3))").addClass("error");
		return false;
	} else {
		$(".phone").removeClass("error");
		return true;
	}
}, "Phone Number is Required");

// check phone number fields are numberic and within range
jQuery.validator.addMethod("phoneNumeric", function(value, element, param) {
	if(!sendfile.isNumeric($("input.phone").eq(0).val(),999,3)||!sendfile.isNumeric($("input.phone").eq(1).val(),999,3)||!sendfile.isNumeric($("input.phone").eq(2).val(),9999,4)) {
		$("input.phone:not(:eq(3))").addClass("error");
		return false;
	} else {
		$(".phone").removeClass("error");
		return true;
	}
}, "Phone Number is Not Valid Format");

// disallow .exe files
jQuery.validator.addMethod("badExt", function(value, element, param) {
	param = typeof param == "string" ? param : "exe";
	return !value.match(new RegExp(".(" + param + ")$", "i")); 
}, "File Type is Not Allowed");

//disallow *?,<>|
jQuery.validator.addMethod("badChars", function(value, element, param) {
	//alert("Runing Validation");
		/*if(value.match(new RegExp("[\*\?\,\<\>\|]", "i")))
		{
			//clearFileInputField(element);
			return false;
		}
		return true;*/
	return !value.match(new RegExp("[\*\?\,\<\>\|]", "i")); 
	//return false;
}, "Bad Filename.");

//disallow duplicates
jQuery.validator.addMethod("dupeUpload", function(value, element, param) {
	//alert("Runing Validation");
	
	if(value.length == 0){return true;} //if this element is empty no validation required
	
	//comparisons must make sure that we are not checking the field we are validating
	//Comparison occuring by element name - should provide uniqueness
	if(document.getElementById('file1'))
		{myfile1 = document.getElementById('file1');}
	else
		{myfile1 = document.getElementById('file1quote');}
	myfiles = new Array(myfile1, 
	document.getElementById('file2'), 
	document.getElementById('file3'), 
	document.getElementById('file4'), 
	document.getElementById('file5'));
	
	//alert("Element 1 - ID: " + element.id + " - innerHTML: " + value + "\n" + "myFile - ID: " + myfile1.id + " - innerHTML: " + myfile1.files[0].fileName);
	
	for(loopCounter=0; loopCounter < 5; loopCounter++)
	{
		//alert(myfiles[loopCounter].id + "\n" + myfiles[loopCounter].value);

		if(element.id != myfiles[loopCounter].id && myfiles[loopCounter].value != "")
		{
			//alert("Processing " +  (myfiles[loopCounter].value != "") + " against " + value);
			//if (myfiles[loopCounter].files[0] && value == myfiles[loopCounter].files[0].fileName)
			if (value == myfiles[loopCounter].value)
			{
				clearFileInputField(element);
				//alert("Element 1 - ID: " + element.id + " - innerHTML: " + value + "\n" + "myFile - ID: " + myfiles[loopCounter].id + " - innerHTML: " + myfiles[loopCounter].files[0].fileName);
				//alert('Duplicate File Detected');
				return false; 
			}
		}
	}
	return true;
}, "Duplicates Detected.");

// sendfile object
var sendfile = {
	
	isNumeric: function(value,m,l) {
		if (!value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
		if (parseInt(value)>m || value.toString().length<l) return false;
		return true;
	},
	validate: {
		rules: {
			firstname: { required: true },
			lastname: { required: true },
			phone3: {
				phoneCombo: true,
				phoneNumeric: true
			},
			email: {
				required: true,
				email: true
			},
			/*file1: 		{ badExt: "exe", required: true },
			file1quote: { badExt: "exe" }, // quote files are optional
			file2: 		{ badExt: "exe" },
			file3: 		{ badExt: "exe" },
			file4: 		{ badExt: "exe" },
			file5: 		{ badExt: "exe" },
			file1: 		{ badChars: ""},
			file1quote: { badChars: ""},
			file2: 		{ badChars: ""},
			file3: 		{ badChars: ""},
			file4: 		{ badChars: ""},
			file5: 		{ badChars: ""},
			file5: 		{ dupeUpload: ""},
			file4: 		{ dupeUpload: ""},
			file3: 		{ dupeUpload: ""},
			file2: 		{ dupeUpload: ""},
			file1: 		{ dupeUpload: ""},
			file1quote: { dupeUpload: ""},*/
			file5: 		{ dupeUpload: "", badExt: "exe", badChars: "" },
			file4: 		{ dupeUpload: "", badExt: "exe", badChars: "" },
			file3: 		{ dupeUpload: "", badExt: "exe", badChars: "" },
			file2: 		{ dupeUpload: "", badExt: "exe", badChars: "" },
			file1: 		{ dupeUpload: "", badExt: "exe", required: true, badChars: "" },
			file1quote: { dupeUpload: "", badExt: "exe", badChars: "" },
			comments: { maxlength: 64000 }
		},
		messages: {
			firstname: "First Name is Required",
			lastname: "Last Name is Required",
			email: {
				required: "Email Address is Required",
				email: "Email Address is Not Valid Format"
			},
			comments: "Maximum comment length is 64,000 characters"
		},
		submitHandler: function(form) {
			$("button").attr("disabled","disabled").addClass("disabled");
			$("#safLoadingTrigger").click();
			form.submit();
		}
	},
	selectMapLocation : function(id){
		$("#"+id).click();
		sendfile.step1();
		tb_remove();
		return false;	
	},
	step1 : function(){	
		if($("#locations input:checked").length!=0) {
			$("#step1").addClass("complete");
			$("#step2").removeClass("disabled").find("input,select,button,textarea").removeAttr("disabled");
			setCookie("locator",$("#locations input:checked").val());
		}		
	},
	step2 : function(){		
		var fields = [];
		$("#firstname,#lastname,#phone1,#phone2,#phone3,#email").each(function(){	
			var filled = $.trim($(this).val()).length==0 ? false : true;
			fields.push(filled);			
		});		
		if($.inArray(false,fields) == -1) {
			$("#step2").addClass("complete");
			//If this is Request a Quote; check step three since everything is optional
			if ($.find("#file1quote").length > 0) {
				$("#step3").addClass("complete");
			}
			//alert("step2 added class 'complete'");
			$("#step3").removeClass("disabled").find("input,select,button,textarea").removeAttr("disabled");
			//alert("removed disabled class");
		}		
	},
	step3 : function(){		
		var fields = [];
		$("#file1").each(function(i){	
			var filled = $.trim($(this).val()).length==0 ? false : true;
			fields.push(filled);
		});		
		if($.inArray(false,fields) == -1) {
			$("#step3").addClass("complete");
		}
	}
//	step3 : function(){	
//		if($("#step3 input#file1").val().length!=0) {
//			$("#step3").addClass("complete");
//		}		
//	}
};


// sendfile mapping object
var Mapping = {
	
	map: null,
	addressMarker: null,
	geocoder: null,

	// build GMap from vcard
	buildGMap: function($el,i) {
		
		// status
		$("#addressInput").before('<strong id="status" class="error"></strong>');
		
		$el.attr("id","map"+i).addClass("mapped").html("");									  
	
		if (GBrowserIsCompatible()) {						
			
			Mapping.map 	= new GMap2($el.get(0));
			Mapping.map.addControl(new GSmallMapControl());
			Mapping.map.addControl(new GMapTypeControl());
			var tomap = $el.hasClass("generic") ? "United States" : Mapping.p.address + " " + Mapping.p.locality + ", " + Mapping.p.region + " " + Mapping.p.zip;
			Mapping.geocoder = new GClientGeocoder()
			Mapping.geocoder.getLatLng(tomap, function(point) {
				if (!point) { return } else {
					if ($el.hasClass("generic")) {
						Mapping.map.setCenter(point, 3);
					} else {
						Mapping.map.setCenter(point, 14);
						var infoaddress = "<br />" + Mapping.p.locality + ", " + Mapping.p.region + " " + Mapping.p.zip;
						var locMarker = Mapping.createMarker("center",point,Mapping.p.name,Mapping.p.address,infoaddress);
						Mapping.map.addOverlay(locMarker);
						GEvent.addDomListener($("p.location")[0], 'click', function() { GEvent.trigger(locMarker, 'click');	});	
					}
				}
			});
			window.onunload=GUnload;
		}
	},
	
	// generic marker create function. takes point for location and address info for infowindow
	createMarker: function(index,point,name,streetaddress,locality,phone,id) {
//		if(index=="center") {
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.shadow = "/images/css/icon_gmarker_location_shadow.png";
			baseIcon.iconSize = new GSize(50, 39);
			baseIcon.shadowSize = new GSize(70, 39);
			baseIcon.iconAnchor = new GPoint(25, 39);
			baseIcon.infoWindowAnchor = new GPoint(39, 2);
			baseIcon.imageMap = [0,0,0,39,39,50,50,0];
			var locationIcon = new GIcon(baseIcon);
			locationIcon.image = "/images/css/icon_gmarker_location.gif";
			markerOptions = { icon:locationIcon };
//		} else {
//			var baseIcon = new GIcon(G_DEFAULT_ICON);
//			baseIcon.shadow = "/images/css/markers/icon_gmarker_shadow.png";
//			baseIcon.iconSize = new GSize(24, 32);
//			baseIcon.shadowSize = new GSize(41, 32);
//			baseIcon.iconAnchor = new GPoint(12, 32);
//			baseIcon.infoWindowAnchor = new GPoint(24, 2);
//			baseIcon.imageMap = [0,0,0,32,32,24,24,0];
//			var letter = String.fromCharCode("A".charCodeAt(0) + index).toLowerCase();
//			var letteredIcon = new GIcon(baseIcon);
//			letteredIcon.image = "/images/css/markers/icon_gmarker_" + letter + ".gif";
//			markerOptions = { icon:letteredIcon };
//		}
		var marker 	= new GMarker(point,markerOptions);
		var html 	= "<h4>"+name+"</h4><p>"+streetaddress+"<br />"+locality+"<br />"+phone+"</p>";
		html 		+= '<a class="btn btn-selectthislocation" onclick="sendfile.selectMapLocation(\''+id+'\')" href="#">Select this Location</a>';
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
		});
		return marker;
	},

	// catch submit of locator form
	searchLocations: function(address) { 
		if(address=="") { $("#status").show().text('City and State or ZIP is Required'); return false; }
		Mapping.geocoder.getLatLng(address, function(latlng) {
			if (!latlng) {
				var m = address || "address";
				$("#status").show().text('City, State or ZIP is not Recognizable');
			} else {
				$("#status").hide();
				Mapping.searchLocationsNear(latlng);
			}
		});
	},

	searchLocationsNear: function(center) {
		var radius = document.getElementById("radiusSelect").value;
		var searchUrl = '/customcf/distanceSearch_genxml.cfm?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
		//var searchUrl = "samplelocations.xml";
		
		GDownloadUrl(searchUrl, function(data) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName('marker');
			
			Mapping.map.clearOverlays();
			
			var $sidebar = $("#locations");
			$sidebar.show();
			$sidebar.find("ol").empty();
			if (markers.length == 0) {
				$sidebar.append('<h3 class="noresults">No results found.</h3>');
				Mapping.map.setCenter(new GLatLng(40, -100), 3);
				return;
			}
			$sidebar.remove(".noresults");
			var bounds = new GLatLngBounds();
			for (var i = 0; i < markers.length; i++) {
				var name 			= markers[i].getAttribute('name');
				var streetaddress 	= markers[i].getAttribute('streetaddress');
				var locality	 	= markers[i].getAttribute('locality');
				var distance 		= parseFloat(markers[i].getAttribute('distance'));
				var point			= new GLatLng(parseFloat(markers[i].getAttribute('lat')),parseFloat(markers[i].getAttribute('lng')));
				var phone 			= markers[i].getAttribute('phone');
				var id			 	= markers[i].getAttribute('id');
				var marker 			= Mapping.createMarker(i,point, name, streetaddress, locality, phone, id);
				Mapping.map.addOverlay(marker);
				var sidebarEntry = Mapping.createSidebarEntry(i,marker, name, streetaddress, locality, distance, phone, id);
				$sidebar.find("ol").append(sidebarEntry);
				bounds.extend(point);	
			}
			$(".step").autoHeight();
			Mapping.map.setCenter(bounds.getCenter(), Mapping.map.getBoundsZoomLevel(bounds));
		});
	},
	
	createSidebarEntry: function(index, marker, name, streetaddress, locality, distance, phone, id) {
		var html = '<li><input id="'+id+'" type="radio" value="'+id+'" name="locationselect" />' +
					'<label for="'+id+'">'+
					'<strong>'+name+'</strong><br />'+
					streetaddress + '<br />'+
					locality + '</label></li>';					
		return html;
	}

};

function clearFileInputField(theElement) {
    //document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
    theElement.parentNode.innerHTML = theElement.parentNode.innerHTML;
    document.getElementById('duplicateMessage').style.visibility = 'visible';
    document.getElementById('duplicateMessage').style.display = 'block';
}

