// Misc. Javascript for Peakware.com
// Created by Terrill Thompson, terrillthompson.com
// Last update: August 2, 2011

var resizeTime = new Date() - 5000;

$(document).ready(function() {

	// August 2011, added support for bookened ads 
	// Based on code used for September 2010 Energizer ads	
	if(window.attachEvent) {
		window.attachEvent("onload", positionBookends);
		window.attachEvent("onresize", positionBookends);	
	} 
	else {
		window.addEventListener("load", positionBookends, false);
		window.addEventListener("resize", positionBookends, false);
	}
	//end bookend code

	$('#dialog').dialog({
		autoOpen: false,
		hide: 'slide',
		width: 500,
		height: 300
	});

	$("a.nonclickable").click(function(event){
		event.preventDefault();
	});

	if (typeof whichMap != 'undefined') { 
		if (whichMap == 'addapeak') { 
			//add relevant event listeners to show, hide & filter options based on users choices
			$('#peakName').change(function() { 
				var peakName = $(this).val();
				//doubtful, but see if other useful fields have been populated yet
				var continent = $('#continent').val();
				var elevation = $('#elevation').val();
				var elevationUnit = $('#elevationUnit').val();
				var ajaxUrl = 'scripts/ajax4dupes.php';
				$.post(ajaxUrl, {
					peakName : peakName,
					continent : continent,
					elevation : elevation, 
					elevationUnit : elevationUnit
				}, function (data) { 
					if (data != 0) $('#dupes').html(data).show();
					else $('#dupes').hide();
				});
			});
			$('#continent').change(function() { 
				var continent = $(this).val();
				selectChildren('continent',continent,'country');
				selectChildren('continent',continent,'country2');
				selectChildren('continent',continent,'range');
				if (continent != 'North America') { 
					$('#state1Div').hide();
					$('#state2Div').hide();
					$('#province1Div').hide();
					$('#province2Div').hide();
				}
				else { 
					$('#state1Div').show();
					$('#state2Div').show();
					$('#province1Div').show();
					$('#province2Div').show();
				}
				focusMapToArea('continent',continent);
			});
			$('#country').change(function() { 
				var country = $(this).val();
				makeStateVisible(country);
			});
			$('#range').change(function() { 
				var range = $(this).val();
				selectChildren('range',range,'subrange');
				focusMapToArea('area',range);
			});
		}
		else if (whichMap == 'addaroute' || whichMap == 'editroute') { 
			//add listeners & handlers for route reset buttons
			$('#reset_map').click(function(event) {
				event.preventDefault();		
				$('#waypoints').empty();
				$('#trkpoints').empty();
				$('#distance').empty();
				clearMap();
			});
			$('#reset_all').click(function(event) {
				//same as above but also honor normal reset functionality 
				$('#waypoints').empty();
				$('#trkpoints').empty();
				$('#distance').empty();
				clearMap();
			});
		}
		else if (whichMap == 'person') { 
			//add listeners & handlers for mapChoice radio buttons
			$("input[name='mapChoice']").click(function(event) { 
				processMarkers(whichMap,null,personId);
				/*
				var mapChoice = $("input[name='mapChoice']:checked").val();
				var ajaxUrl = createUrl(whichMap,map.getZoom(),id,1);		
				if (typeof ajaxUrl != 'undefined') showMarkers(whichMap,ajaxUrl,1);
				*/
			});
		}
		else if (whichMap == 'editroute') { 
		/*
			$("#map").click(function(event) { 
				if (following) { 
					following = false;
					markerCursor.setMap(null);
					google.maps.event.removeListener(mouseMove);
				}
			});
		*/	
		}
	}
	function showCamError(camId) { 

		$("#"+camId).removeClass("loading");
		$("#"+camId).empty();
		$("#"+camId).append("Cam Unavailable");
		$.post('../incs/camtracker.php',{ camId: camId });
	}
	
	$("a.logLink").hover(function(event) { 
		//this function performed on mouseover
		event.preventDefault();
		var logLink = $(this).attr("href");
		var pk = getUrlParam(logLink,'pk');
		var log = getUrlParam(logLink,'log');
		var ajaxUrl = 'scripts/ajaxLogPreview.php?pk=' + pk + '&id=' + log;
		$("#preview")
			.jqm({
			modal: false, 
			overlay: 0,
			ajax: ajaxUrl
		})
	.jqmShow();
	},
	function () { 
		//this function performed on mouseout
		$("#preview").jqmHide();
	});
	
	$("a.photoLink").click(function(event) { 
		//display photo full size in a jqmodal div
		event.preventDefault();
		var photoLink = $(this).attr("href");
		/* Original...
		var fileName = getUrlParam(photoLink,'fileName');
		var fileDir = getUrlParam(photoLink,'fileDir');
		//The above replaced with the following...
		*/
		var photo = getUrlParam(photoLink,'photo');
		var imgWidth = getUrlParam(photoLink,'width');
		var imgHeight = getUrlParam(photoLink,'height');
		//var imgTag = '<img src="' + fileDir + fileName + '" ';
		var imgTag = '<img src="/img.php?src=' + photo + '" ';
		var imgTag = imgTag + 'style="width:' + imgWidth + 'px;height:' + imgHeight + 'px" ';
		var imgTag = imgTag + 'alt=""/>';
		var imgTag = imgTag + '<p>Click off the photo to make it disappear.</p>' + "\n";
		$("#preview")
			.html(imgTag)
			.jqm({
			modal: false, 
			overlay: 70
		})
		.jqmShow();
	});

	$("a.moveLink").click(function(event) { 
		event.preventDefault();
		var moveLink = $(this).attr("href");
		var photoId = getUrlParam(moveLink,'photo');
		var ajaxUrl = 'scripts/ajax4photos.php';
		$.post(ajaxUrl, {
			action : 'promptForPeak',
			photoId : photoId
		}, function (data) { 
			$("#dialog")
				.html(data)
				.data('title.dialog','Move Photo')
				.data('width.dialog',500)
				.data('height.dialog',300)
				.data('buttons.dialog',{"Find": function() {
					//$(this).dialog("close");
					if (document.getElementById('peakSearch')) { 
						var peakSearch = document.getElementById('peakSearch').value;
						$.post(ajaxUrl, { 
							action : 'showPeakChoices',
							photoId : photoId,
							peakName: peakSearch
						}, function (data) { 		
							if (data == "0") { 
								$("#dialog")
								.html('<p>No matching peaks were found.</p>')
								.data('buttons.dialog',{"ok": function() { 
									$(this).dialog("close");
								}})
								.dialog("open");
							}
							else { 
								$("#dialog")
								.html(data)
								.data('buttons.dialog',{"ok": function() { 
									var peakId = $("input[@name='peakId']:checked").val(); 
									var peakName = $("input[@name='peakId']:checked").attr('title'); 
									var desc = $("#desc_" + photoId).val();
									$.post(ajaxUrl, { 
										action: 'movePhoto',
										photoId: photoId,
										desc: desc,
										newPeak: peakId
									}, function (data) {
										$("#dialog").dialog("close");
										if (data == "ok") { 
											var divId = 'photo' + photoId;
											$("#" + divId).slideUp("slow");
										}
										else { 
											msg = 'Sorry, we are unable to move photo #' + photoId;
											alert (msg);
										}
									});
								}})
								.dialog("open");
							}
						});
					}
				}})
				.dialog("open");		
			});
	});
		
	$("a.delPhotoLink").click(function(event) { 
		event.preventDefault();
		var delLink = $(this).attr("href");
		var photoId = getUrlParam(delLink,'photo');
		var ajaxUrl = 'scripts/ajax4photos.php';
		$.post(ajaxUrl, {
			action : 'deletePhoto',
			photoId : photoId
		}, function (data) { 
			if (data == "ok") { 
				var divId = 'photo' + photoId;
				$("#" + divId).slideUp("slow");
			}
			else { 
				msg = 'Sorry, we are unable to delete photo #' + photoId;
				alert (msg);
			}
		});
	});

	$("a.delLogLink").click(function(event) { 
		event.preventDefault();
		var delLink = $(this).attr("href");
		var logId = getUrlParam(delLink,'log');
		var parentId = getUrlParam(delLink,'pk');
		deleteItem('log',logId,'peak',parentId);
	});

});

function positionBookends() { 
	//run this only if both bookend divs are present
	if (document.getElementById('bookend-left-package') && document.getElementById('bookend-right-package')) { 
		if (new Date() - resizeTime > 100) resizeTime = new Date();
		else return false;
		var browserWidth = getBrowserWidth();

		if (browserWidth >= 1400) { 
			//reposition bookends based on user's screen resolution
			var mainLeftPos = (screen.width-980)/2;
			var bookendLeftPos = (mainLeftPos-220) + 'px';
			var bookendRightPos = (mainLeftPos+970) + 'px';
			var bookendRightRightPos = (mainLeftPos+980+220) + 'px';
			document.getElementById('bookend-left-package').style.left=bookendLeftPos;
			document.getElementById('bookend-right-package').style.left=bookendRightPos;
			document.getElementById('bookend-right-package').style.right=bookendRightPos;			
		}
		else { 
			//attach to the outer edges 
			document.getElementById('bookend-left-package').style.left=0;
			document.getElementById('bookend-right-package').style.right=0;
			if (document.getElementById('bookend-right-package').style.removeAttribute) { //IE
				document.getElementById('bookend-right-package').style.removeAttribute('left');
			}
			else document.getElementById('bookend-right-package').style.removeProperty('left');
		}
		document.getElementById('bookend-left-package').style.visibility='visible';
		document.getElementById('bookend-right-package').style.visibility='visible';
		return true;
	}
}

function getBrowserWidth() { 

	var viewportwidth;
 
	// standards compliant browsers 
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth;
	}
 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)	
 	else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
       viewportwidth = document.documentElement.clientWidth;
	}
 
	// older versions of IE 
	else {
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
	}
	return viewportwidth;
}
		
function checkAllBoxes() {
	if ($('#checkAll').attr('checked')) { 
		$(".checkBox").attr('checked', true);
	}
	else { 
		$(".checkBox").attr('checked', false);
	}	
}

function ajaxFileUpload(userId) {

	//starting setting some animation when the ajax starts and completes
	$("#loading").
		ajaxStart(function(){
			$(this).show();
			// $("#myPhotoDiv").hide();
			// $("#uploadMsg").show().addClass("waiting");
		})
		.ajaxComplete(function(){
			$(this).hide();
			// $("#myPhotoDiv").show();
			// $("#uploadMsg").removeClass("waiting");
		});
		
		/*
			preparing ajax file upload
			url: the url of script file handling the uploaded files
			fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
			dataType: it support json, xml
			secureuri:use secure protocol
			success: call back function when the ajax complete
			error: callback function when the ajax failed
		*/
		var phpUrl = 'scripts/doajaxfileupload.php?userId=' + userId;
		$.ajaxFileUpload
		(
			{
				url:phpUrl, 
				secureuri:false,
				fileElementId:'fileToUpload',
				dataType: 'json',
				success: function (data, status) {
					if(typeof(data.error) != 'undefined') {
						if(data.error != '') {
							$("#uploadMsg").html(data.error);
						}
						else {
							//alert(data.msg);
							$("#uploadMsg").html(data.msg);
							$("#uploadMsg").addClass("alert");
							$("#photoVerb").text('Replace this');
							//force a refresh of image
							var imgSrc = $("#myPhoto img").attr('src');
							if(typeof(imgSrc) == 'undefined') {
								//create a new img element
								var imgTag = '<img alt="" src="img.php?p=1&amp;src= ';
								imgTag += userId + '"/>';
								$("#myPhoto").html(imgTag);								
							}
							else { 
								//refresh the img element with new src
								var timestamp = new Date().getTime();
								$("#myPhoto img")
									.attr('src',imgSrc+'&amp;'+timestamp)
									.removeAttr("width")
									.removeAttr("height");
							}
						}
					}
				},
				error: function (data, status, e) {
					$("#uploadMdsg").append(e);
				}
			}
		)
		return false;
}

function toggleVisibility(obj,span) {

	if ($("#" + obj).is(":hidden")) {
		$("#" + obj).slideDown("slow");
		$("#" + span).html('Hide');
	}
	else { 
		$("#" + obj).slideUp("slow");
		$("#" + span).html('Show');		
	}
};

function makeStateVisible(country) { 

	if (country == 'United States' || country == '204') { 
		if ($("#stateField").is(":hidden")) {
			//if province fields are visible, hide and clear them
			if ($("#provinceField").is(":visible")) {
				$("#provinceField").hide();
				$("#province").attr("selectedIndex","-1"); 
			}
			if ($("#province2Field").is(":visible")) {
				$("#province2Field").hide();
				$("#province2").attr("selectedIndex","-1"); 
			}
			//then show state fields
			$("#stateField").slideDown("slow");
			$("#state2Field").slideDown("slow");
		}
	}
	else if (country == 'Canada' || country == '179') { 
		if ($("#provinceField").is(":hidden")) {
			//if state fields are visible, hide and clear them
			if ($("#stateField").is(":visible")) { 
				$("#stateField").hide();
				$("#state").attr("selectedIndex","-1");
			}
			if ($("#state2Field").is(":visible")) { 
				$("#state2Field").hide();
				$("#state2").attr("selectedIndex","-1");
			}
			//then show province fields
			$("#provinceField").slideDown("slow");
			$("#province2Field").slideDown("slow");
		}
	}
	else { //this is neither US or Canada. Hide and clear all state and province fields
		if ($("#stateField").is(":visible")) { 
			$("#stateField").slideUp("slow");
			$("#state").attr("selectedIndex","-1");
		}
		if ($("#state2Field").is(":visible")) { 
			$("#state2Field").slideUp("slow");
			$("#state2").attr("selectedIndex","-1");
		}
		if ($("#provinceField").is(":visible")) { 
			$("#provinceField").slideUp("slow");
			$("#province").attr("selectedIndex","-1");
		}
		if ($("#province2Field").is(":visible")) { 
			$("#province2Field").slideUp("slow");
			$("#province2").attr("selectedIndex","-1");
		}
	}
}

// functions for manipulating peak links
var numNewLinks=0;

function addLink() { 
	numNewLinks++;
	var newLink = 	"<li>\n";
	var titleField = 'newTitle' + numNewLinks;
	var urlField = 'newUrl' + numNewLinks;
	newLink = newLink + '<label for="' + titleField + '">Title:</label> ';
	newLink = newLink + '<input type="text" name="' + titleField + '" ';
	newLink = newLink + 'id="' + titleField + '"/><br/>' + "\n";
	newLink = newLink + '<label for="' + urlField + '">URL:</label> ';
	newLink = newLink + '<input type="text" name="' + urlField + '" ';
	newLink = newLink + 'id="' + urlField + '"/></li>' + "\n";
	$("#linkEditor")
		.append(newLink)
		.slideDown("slow")
	;
}


function deleteItem(what,id,pType,pid) { 
	var params = "what=" + what + "&id=" + id;
	if (typeof(pType) != 'undefined' && typeof(pid) != 'undefined')
		params = params + "&pType=" + pType + "&pid=" + pid;
	$.ajax({ 
		type: "POST",
		url: "http://" + location.host + "/scripts/ajaxDelete.php",
		data: params,
		dataType: "text",
		success: function(result){
			if (trim(result) == 'ok') { 
				var selector = "#" + what + id;
				$(selector).slideUp("slow"); 
			}
			else alert ('Sorry. You can not delete that ' + what + ':' + result + '!');
		}
	});

}

function trim (str, charlist) {
	// http://kevin.vanzonneveld.net
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: mdsjack (http://www.mdsjack.bo.it)
	// +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
	// +      input by: Erkekjetter
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +      input by: DxGx
	// +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
	// +    tweaked by: Jack
	// +   bugfixed by: Onno Marsman
	// *     example 1: trim('    Kevin van Zonneveld    ');
	// *     returns 1: 'Kevin van Zonneveld'
	// *     example 2: trim('Hello World', 'Hdle');
	// *     returns 2: 'o Wor'
	// *     example 3: trim(16, 1);
	// *     returns 3: 6
 
	var whitespace, l = 0, i = 0;
	str += '';
    
	if (!charlist) {
		// default list
		whitespace ="\n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
	} else {
		// preg_quote custom list
		charlist += '';
		whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
	}
    
	l = str.length;
	for (i = 0; i < l; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	} 
	l = str.length;
	for (i = l - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

// functions for synchronizing continents, countries, ranges, and subranges

function buildChildren(thisField,thisValue) { 
	if (thisField == 'continent') { 
		selectChildren(thisField,thisValue,'country');
		selectChildren(thisField,thisValue,'range');
	}
	else if (thisField == 'range') { 
		selectChildren(thisField,thisValue,'subRange');
	}
}

function updateOptions(selectbox, xml) {
	//remove all current options, add one blank option
	$('#'+selectbox)
		.find('option')
		.remove()
		.end()
		.append('<option value=""></option>'+"\n")
	;
	//parse xml and add new option for each child found
	$("child",xml).each(function(i) { 
		var id = $(this).attr("id");
		var name = $(this).attr("name");
		$('#'+selectbox)
			.append('<option value="' + id + '">' + name + '</option>' + "\n")
		;
	});
}

function selectChildren(parentField,parentValue,childField){
	//remove all existing options from childField select element
	//removeAllOptions(childField);
	//get new options via AJAX
	var phpUrl = 'data/getchildren.php';
	$.ajax({ 
		type: "GET",
		url: "data/getchildren.php",
		data: "pf=" + parentField + "&pv=" + parentValue + "&cf=" + childField,
		dataType: "xml",
		success: function(xml){
			updateOptions(childField,xml);
		}
	});
}

// widely used general purpose functions

function changeSpan(span,content) { 
	document.getElementById(span).innerHTML=content;
}

function checkRadio(boxToCheck,boxToUncheck) { 
	if (boxToCheck) { 
		document.getElementById(boxToCheck).checked = true;
	}
	if (boxToUncheck) {
		document.getElementById(boxToCheck).checked = false;
	}
}
		
function getUrlParam(url,param) {

	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec(url);
	if( results == null )
		return "";
	else
		return results[1];
}
	
$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};


