$(document).ready( function() {
	svsnStandard();
});

function svsnStandard() {
	
	$(".focus").focus();
	
	$("table.list-table.sortable > thead > tr > th.sort").click( function() {
		
		var baseurl = $(this).parents("table").attr("rel");		
		var sort = $(this).attr("id");
		var dir = $(this).attr("rel");
		
		url = baseurl + "&sort=" + sort + "&dir=" + dir;		

		location.href = url;
	});
	
	$("table.list-table.sortable").each( function() {
		
		var sort = $(this).children("thead").attr("id");
		var dir = $(this).children("thead").attr("rel");
		
		var jq = "thead > tr > th#" + sort;
		
		if( dir == "asc" ) {
			$(this).find(jq).removeClass("sortUp").addClass("sortDown").attr("rel", "desc");			
		}
		else if( dir == "desc") {
			$(this).find(jq).removeClass("sortDown").addClass("sortUp").attr("rel", "asc");			
		}
		
		

	});
	
	//when a form of class copyOnSubmit is submitted,
	//it will check to see if there are any inputs with a 
	//class of copyFrom.  It will copy the value from the
	//input's rel attribute, and then proceed with normal
	//submit.
	$("form.copyOnSubmit").submit( function() {
		$("input.copyFrom").each( function() {
			var copyFromJq = "input#" + $(this).attr("rel");
			$(this).val($(copyFromJq).val());			
		});		
		return true;
	});
	
	//this allows one select to control whether another
	//element is disabled or not.  when the select option is
	//changed, if the new option has a rel attribute of enable, the
	//element specified in the select tag's rel attribute will
	//be enabled.  else, it will be disabled.
	$("select.disableRel").each( function() {
		var myself = this;
		
		$(this).change( function() {
			var toBeDisabledJq = "#" + $(myself).attr("rel");
			var selectedJq = "#" + $(myself).attr("id") + " > option:selected";
			var doWhat = $(selectedJq).attr("rel");
			
			if( doWhat == 'enable') {
				$(toBeDisabledJq).removeAttr("disabled");
				$(toBeDisabledJq)
					.children("[rel=defaultOnEnable]")
					.attr("selected", "true");			
			}
			
			else if (doWhat == 'disable') {
				$(toBeDisabledJq).attr("disabled", "true");
				$(toBeDisabledJq)
					.children("[rel=defaultOnDisable]")
					.attr("selected", "true");						
			}				
		});
		
		$(this).change();		
	});
	
	$("input.datepicker").each( function() {
		$(this).date_input();
	});
	
	$("div#gpsMap").each( function() {
		var mapID = $(this).attr("id");
		var coord = $(this).attr("rel");
		var latlng = getLatLng(coord);
		var zoom = 15;
				
		if(isNaN(latlng.lat())) {
			zoom = 6;
			latlng = new GLatLng('37.54', '-78.62');
		}
		
		var map = svsnMap(mapID, latlng.lat(), latlng.lng(), zoom);
		var marker = new GMarker(latlng, {draggable: true});
		
		map.addOverlay(marker);	
												
		GEvent.addListener(marker, "dragend", function() {
			var endPoint = marker.getPoint();
			fillLatLngInputs(coord, endPoint);						
		});
	});
	
	//Attaches to an input button.  When button is clicked, the address
	//specified by the input part of the rel tag will be mapped in the 
	//div specified by the map part of the rel tag.
	$("input.map-address").each( function() {
		$(this).unbind('click');
		$(this).click( function() {
			var args = parseQuery($(this).attr("rel"));
			var mapID = args['map'];
			var mapQ = "div#" + mapID;
			var inputQ = "input#" + args['input'];
			var address = $(inputQ).val();
			var map = null;
			var geocoder = new GClientGeocoder();
			
			address = address != '' ? address : 'roanoke, va';
						
			geocoder.getLatLng(address, function(latlng) {
				map = svsnMap(mapID, latlng.lat(), latlng.lng(), 15);
															
				if($(mapQ).hasClass("marker-set-lat-lng")) {
					var marker = new GMarker(latlng, {draggable: true});
					var coord = $(this).attr("rel");
					
					map.addOverlay(marker);	
					fillLatLngInputs(coord, latlng);
										
					GEvent.addListener(marker, "dragend", function() {
						var endPoint = marker.getPoint();
						fillLatLngInputs(coord, endPoint);						
					});
				}	
				
			});
				
				
		});		
	});
	
	
	//Attaches an onclick event to a radio input with class toggleID.
	//This is used to either show or hide the element with the ID
	//specified in the input's rel tag.
	$(".modifyShowMembers").each(function() {
		
		$(this).change( function() {
			var selectjq = "select#" + $(this).attr("id") + " > option:selected:first";
			var crmOrgID = $(selectjq).val().split('-')[1];			
			var href = $("a#showMembers").attr("href").split('&crmOrgID')[0];
			href = href + "&crmOrgID=" + crmOrgID;
			$("a#showMembers").attr("href", href);
		})
	});
	
		
	//Attaches an onclick event to a radio input with class toggleID.
	//This is used to either show or hide the element with the ID
	//specified in the input's rel tag.
	$(":radio.toggleRow").each(function() {
		
		$(this).click( function() {
			if( $(this).hasClass("show") ){
				var idToToggle = "tr#" + $(this).attr("rel");
				$(idToToggle).show();
			}
			else if( $(this).hasClass("hide") ) {
				var idToToggle = "tr#" + $(this).attr("rel");
				$(idToToggle).hide();
			}
		})
		
		//this will simulate a click if the input is checked.
		if($(this).attr("checked")) {
			$(this).click();
		}
	});
	
	
	//Attaches an onclick event to a radio input with class switchRow.
	//This is used to switch which table rows are displayed.
	$(":radio.switchRow").each(function() {
		
		$(this).click( function() {
			
			var args = parseQuery($(this).attr("rel"));
			var show = args['show'];
			var hide = args['hide'];
			var showArray = show.split(",");
			var hideArray = hide.split(",");
			
			for(i=0; i<hideArray.length; i++) {
				var hideJq = "tr#" + hideArray[i];	
				$(hideJq).hide();	
			}
			
			for(i=0; i<showArray.length; i++) {
				var showJq = "tr#" + showArray[i];	
				$(showJq).show();	
			}			
		})
		
		//this will simulate a click if the input is checked.
		if($(this).attr("checked")) {
			$(this).click();
		}
	});
	
	//Places default values in input boxes that are removed
	//when element is focused event.
	//Default values found in rel attribute.
	$(".jq-input-default-value").each( function() {
		$(this)
			.val( $(this).attr("rel") )
			.focus( function() {
				if( $(this).val() == $(this).attr("rel") ) {
					$(this).val("");
				}			
			})
			.blur( function() {
				if( jQuery.trim($(this).val()) == "") {
					$(this).val( $(this).attr("rel") );
				}
			});	
	});
		
	//adds an onclick event to any td with class
	//toggle-info-row.  when clicked, it will show/hide
	//the div whose id is specified by the td's rel attribute.
	$("div.toggle-info-row").each( function() {
		var me = $(this);
		$(this).unbind('click');
		$(this).click( function() {
			if( $(this).hasClass("show") ){
				var idToToggle = "div#" + $(this).attr("rel");
				$(idToToggle).slideDown(300, function() {
					$(me).removeClass("show").addClass("hide");	
				});
				
			}
			else if( $(this).hasClass("hide") ) {
				$(this).siblings("div").find(".hide").click();
				
				var idToToggle = "div#" + $(this).attr("rel");
				$(idToToggle).slideUp(300, function() {
					$(me).removeClass("hide").addClass("show");	
				});
			}
		})
	});
	
	//used to load a sibling via ajax.
	//finds the first sibling of the current element
	//and loads the url found in it's rel tag into itself.
	$("div.load-sibling-on-click").each( function() {
		var me = $(this);
		$(this).unbind('click');
		$(this).click( function() {
			if( $(this).hasClass("show") ){
				var sibling = $(this).next();
				var url = $(sibling).attr("rel");
				$(me).removeClass("show").addClass("loading");
				$(sibling).hide().load(url, function() {
					svsnStandard();
					$(this).slideDown(300, function() {
						$(me).removeClass("loading").addClass("hide");	
					});
				});
			}
			else if( $(this).hasClass("hide") ) {
				var sibling = $(this).next();
				$(sibling).slideUp(300, function() {
					$(me).removeClass("hide").addClass("show");			
					$(this).empty();
				}).empty();
				
			}			
		});
	});
	
	//used to show a sibling's content.
	//finds the first sibling of the current element
	//and calls the show function on it.
	$("div.show-sibling-on-click").each( function() {
		var me = $(this);
		$(this).unbind('click');
		$(this).click( function() {
			if( $(this).hasClass("show") ){
				var sibling = $(this).next();
				$(sibling).show();
				$(me).removeClass("show").addClass("hide");
			}
			else if( $(this).hasClass("hide") ) {
				var sibling = $(this).next();
				$(sibling).hide();
				$(me).removeClass("hide").addClass("show");				
			}			
		});
	});
	
	//used to reload an element's parent div with
	//new ajax content.
	//the url of the content to load is found in the element's
	//rel attribute.
	$(".reloadMyDiv").click( function() {
		var divToLoad = $(this).parents("div.ajax-container").get(0);
		$(divToLoad).prev().removeClass("hide").addClass("loading");		
		var urlToLoad = $(this).attr("rel");
		$(divToLoad).load(urlToLoad, function() {
			svsnStandard();
			$(divToLoad).prev().removeClass("loading").addClass("hide");
		});		
	});
	
	
	//used to select certain options in a select multiple
	//tag.  will select all options with the specified rel.
	$(".select").click( function() {
		var args = parseQuery($(this).attr("rel"));
		var name = args['name'];
		var rel = args['rel'];
		var jqstring = "";
		
		jqstring = "select[name=" + name + "] > option";
		$(jqstring).removeAttr("selected");
		
		switch(rel) {
			case "all":
				jqstring = "select[name=" + name + "] > option";
				break;
			default:
				jqstring = "select[name=" + name + "] > option[rel=" + rel + "]";
		} 
		
		$(jqstring).attr("selected", "true");
	});
	
	
	//used to copy options from selects specified in rel to
	//select specified in rel.
	$(".copy-options").click( function() {
		var args = parseQuery($(this).attr("rel"));
		var from = args['from'].split(',');
		var to = args['to'];
		var from0 = from[0];
		var from1 = from[1];
		
		var from0jq = "select[name=" + from0 + "] :selected";
		var from1jq = "select[name=" + from1 + "] :selected";
		var tojq = "select[name=" + to +"]";
		
		$(from0jq).clone().appendTo(tojq);
		$(from1jq).clone().appendTo(tojq);
		
		var toselect = tojq + " > option";
		$(toselect).removeAttr("selected");
		
	});
	
	//used to remove selected options from select specified
	//in rel
	$(".remove-options").click( function() {
		var selected = $(this).attr("rel");
		
		var jqstring = "select[name=" + selected + "] :selected";
		
		$(jqstring).remove();
	});
	
	
	//used to remove selected options from select specified
	//in rel
	$(".select-all").click( function() {
		var jqstring = "select[name=" + $(this).attr("rel") + "] > option";
		$(jqstring).attr("selected", "true");
		return true;
	});
	
	//used to count remaining characters left to type in a textarea.
	$(".count").keyup( function() {
		var counterjq = "#" + $(this).attr("rel");
		var max = $(this).attr("id");	
		
		var remain = max - $(this).val().length;
		var countstring = "<label>" + remain + " characters remain</label>";
		$(counterjq).html(countstring);	
	});
	
	$(".count").each( function() {
		var myself = this;
		$(this).keyup( function() {
			var counterjq = "#" + $(myself).attr("rel");
			var max = $(myself).attr("id");	
			
			var remain = max - $(myself).val().length;
			var countstring = "<label>" + remain + " characters remain</label>";
			$(counterjq).html(countstring);	
		});
		
		$(this).keyup();
	});
	
	
	//used to reload a table row's td fields with new data.
	//the url that will return json data to be used in reloading
	//is found in the tr's rel attribute.
	//each td should have an id, which maps to a variable in the json
	//data set, and it should have a rel, which specifies how the
	//data should be rendered.
	$("tr.reloadMyTDs").each( function() {
		var jsonURL = $(this).attr("rel");
		$(this).removeClass("reloadMyTDs");
		var myself = this;
		$.get(jsonURL, function(data){
			data = data.replace(/<META[^>]*>/, "");
			data = eval('(' + data + ')');
			
			$(myself).children("td").each( function() {
				var type = $(this).attr("rel");
				var property = $(this).attr("id");
				var mydata = data[property];
				var injectInto = $(this);
				
				if($(this).children("div").length) {
					injectInto = $(this).children("div").get(0);					
				}
				
				switch(type) {
					case "yesno":
						if(mydata) {
							mydata = "Yes";
						} else {
							mydata = "No";
						}
						break;
					case "numeric":
						break;
					case "varchar":
						break;
					default:
						break;					
				}
				
				$(injectInto).html(mydata);
			});		
		});		
	})
		
	
	//this will add the javascript necessary to enable a
	//swishy box.  if the button being pressed has a class
	//of left to right, it will take all selected elements
	//from the left select, and place them in the right
	//select, if the button has a class of right to left,
	//then vice-a-versa.
	$("input.swishy-button").click( function() {
		if($(this).hasClass("left-to-right")) {
			$("select.left-swishy option:selected").each( function() {
				$(this).remove().removeAttr("selected").appendTo("select.right-swishy");
			});
		} else if($(this).hasClass("right-to-left")){
			$("select.right-swishy option:selected").each( function() {
				$(this).remove().removeAttr("selected").appendTo("select.left-swishy");
			});
		}
		$("select.right-swishy").sortOptions();
		$("select.left-swishy").sortOptions();

		return false;
	});
	
	
	//this will attach a click event to an anchor tag, which
	//will do an ajax delete of the item, and then remove the
	//item's row from the table.
	$("a.confirm").click( function() {
		var confirmMessage = "Are you sure you want to " + $(this).attr("title") + "?"; 
		return confirm(confirmMessage);
	});
	
	//this will attach a click event to an anchor tag, which
	//will do an ajax delete of the item, and then remove the
	//item's row from the table.
	$("input.confirm:not('.click-attached')").each( function() {
		//this will prevent more than one on click event being
		//bound to this anchor.
		$(this).addClass("click-attached");
			
		$(this).click( function() {
			var confirmMessage = "Are you sure you want to " + $(this).attr("title") + "?"; 
			return confirm(confirmMessage);
		});
	});


	//converts any table with the tablesorter class into
	//a sortable table
	//optionally, if the table also has a class of 'pager',
	//this function will create pagination in the div whose
	//id specified by the table's rel attribute.
	$("table.tablesorter:not('.sorted')").each( function() {
		
		$(this).addClass("sorted").tablesorter({
						
			//this enables us to sort based on the inner html
			//of the first div in a td.
			textExtraction: function(node) {
				var retVal = null;
				retVal = $(node).children("div").html();
				if(retVal == null) {
					retVal = $(node).html();
				}
				return retVal;
			}
		});
		
		//this is a cheap and dirty way of disabling certain
		//columns from the sorter.  Ideally, these columns would
		//be specified in advance by passing a headers argument to
		//the tablesorter function.
		$("th.dont-sort").each( function() {
			$(this).removeClass("header");
			$(this).unbind("click");			
		});
		
		if( $(this).hasClass("pager") ) {
			var pagerID = "div#" + $(this).attr("rel");
			var pagerHTML = 
				'<form>' +
				'<img src="images/tablesorter/first.png" class="first"/>' +
				'<img src="images/tablesorter/prev.png" class="prev"/>' +
				'<input type="text" class="pagedisplay"/>' +
				'<img src="images/tablesorter/next.png" class="next"/>' +
				'<img src="images/tablesorter/last.png" class="last"/>' +
				'<select class="pagesize">' +
					'<option selected="selected" value="25">25</option>' +
					'<option value="50">50</option>' +
					'<option value="75">75</option>' +
					'<option value="100">100</option>' +
				'</select>' +
				'</form>';			
		
			$(pagerID).append(pagerHTML);
					
			$(this).tablesorterPager({
				container: $(pagerID),
				size: 25,
				positionFixed: false
			});
		}
		
	});
	
	
	//this block will grab a json string containing
	//the 'message' and some other assorted and related info
	//from the url specified in the div's rel tag, and it will
	//populate the message div and show if there is a message
	//present.
	$("div#status-message-container").each( function() {
		
		if(jQuery.trim($(this).html()).length == 0) {
			var me = $(this);
			var messageURL = $(this).attr("rel");
			$.get(messageURL, function(data){
				data = data.replace(/<META[^>]*>/, "");
				data = eval('(' + data + ')');
							
				if(data.HASMESSAGE) {
					
					if(data.MESSAGECLASS == "error") {
						var html = '<div class="tb-error-message">' + 
							unescape(data.MESSAGE) +
							'<input class="input-button" type="button" onclick="tb_remove()" value="OK" />' +
							'</div>';
						$(me).html(html);
						$(me).removeAttr("class");
						$(me).addClass(data.MESSAGECLASS);				
					} else {
						$(me).html(unescape(data.MESSAGE));
						$(me).removeAttr("class");
						$(me).addClass(data.MESSAGECLASS);
					}	
				} else {
					$(me).html("");
					$(me).removeAttr("class");
					$(me).hide();
				}
				
				renderMessage();
			});
		}
		else {
			renderMessage();			
		}
	});	
	
	$(".goToNextWhenFull").each( function() {
		var max = $(this).attr("maxlength");	
		var nextField = $(this).attr("next");	
		$(this).keyup( function () {
			if ($(this).val().length >= max) {
				//alert("nextField: " + nextField);
				var nF = "[name=" + nextField + "]";
				$(nF).focus();
			};
		});		
	});	
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function renderMessage() {
	var cls = $("div#status-message-container").attr("class");
	
	if( cls == "error") {
		var t = "Error";
		var a = "#TB_inline?width=250&height=200&inlineId=status-message-container&modal=true";
		var g = false;
		tb_show(t,a,g);
	}
	else {
		$("div#status-message-container").show();
		setTimeout(function() {
			$("div#status-message-container").fadeOut(300);
		}, 9000);	
	}
}

function svsnMap(id, lat, lng, zoom, zoomControl) {
  	lat = typeof(lat) != 'undefined' ? lat : '37.54';
	lng = typeof(lng) != 'undefined' ? lng : '-78.62';
	zoom = typeof(zoom) != 'undefined' ? zoom : 12;
	zoomControl = typeof(zoomControl) != 'undefined' ? zoomControl : 'szc';
	
	var mapQ = "div#" + id;
	var map = new GMap2($(mapQ).get(0));
	
	switch(zoomControl) {
		case "szc":
			map.addControl(new GSmallZoomControl());
			break;
		default:
			break;		
	}
	
	map.setCenter(new GLatLng(lat, lng), zoom);
	
	return map;
}

function fillLatLngInputs(coord, latlng) {
	coord = typeof(coord) != 'undefined' ? coord : 'degminsec';
	
	switch(coord) {
		case "degminsec":
			fillDegMinSecInputs(latlng);
			break;
		default:
			break;	
	}
	
}

function fillDegMinSecInputs(latlng) {
	var lat =  latlng.lat();
	var lng = latlng.lng();
	
	var latDeg = parseInt(lat);
	var lngDeg = parseInt(lng);
	
	var latMinSec = Math.abs( (lat - latDeg) * 60);
	var lngMinSec = Math.abs( (lng - lngDeg) * 60);
	
	var latMin = parseInt( latMinSec );
	var lngMin = parseInt( lngMinSec );
	
	var latSec = parseInt(( latMinSec - latMin ) * 60);
	var lngSec = parseInt(( lngMinSec - lngMin ) * 60);
	
	$("input#latDeg").val(latDeg);
	$("input#latMin").val(latMin);
	$("input#latSec").val(latSec);

	$("input#lngDeg").val(lngDeg);
	$("input#lngMin").val(lngMin);
	$("input#lngSec").val(lngSec);
}

function getLatLng(coord) {
	coord = typeof(coord) != 'undefined' ? coord : 'degminsec';
	var retVal = null;
	
	switch(coord) {
		case "degminsec":
			retVal = getDegMinSec();
			break;
		default:
			break;
	}
	
	return retVal;	
}

function getDegMinSec(latlng) {
	//this only works for north america.
	var latDeg = parseInt($("input#latDeg").val());
	var latMin = parseInt($("input#latMin").val());
	var latSec = parseInt($("input#latSec").val());

	var lat = latDeg + (((latMin * 60) + latSec) / 3600);

	var lngDeg = parseInt($("input#lngDeg").val());
	var lngMin = parseInt($("input#lngMin").val());
	var lngSec = parseInt($("input#lngSec").val());
	
	var lng = lngDeg - (((lngMin * 60) + lngSec) / 3600);
	
	return new GLatLng(lat, lng);
}



// Delete Popup Script --->

function ConfirmDelete(delName){
	return confirm("Do you really want to delete " + delName + "?")
}
function ConfirmArchive(arcName){
	return confirm("Do you really want to Archive " + arcName + "?")
}
