/*
South Dakota Travel Community JS Components
L&S DC - 7/2007
*/

/*#######################################
###	Photo Gallery Functions
#######################################*/

function deleteItem(libType,libId)
{
	//alert(libType + ' ' + libId);
	 if (confirm('Are you sure you wish to delete thie library item?'))
	{	
		document.getElementById('deletionType').value = libType;
		document.getElementById('deletionId').value = libId;
		document.forms['librarySearchForm'].submit();
	}
}

function showNextPhotoDetail()
{
	var photoIdArray = new Array();
	photoIdArray = photoIdList.split(',');
	var curPhotoId = document.getElementById("detailBoxId").value;
	var curType = inputBType = document.getElementById("detailBoxType").value;
	
	var NextId = 0;
	for (i = 0; i < photoIdArray.length; i++)
	{
		if(photoIdArray[i] == curPhotoId)
		{
			//Current Id found, increment and get next
			NextId = i+1;
			break;
		}
	}
	
	if(NextId >= photoIdArray.length)
	{	NextId = photoIdArray[0];		}
	else
	{	NextId = photoIdArray[NextId];		}
	
	openDetail(curType,NextId);
//	alert(curPhotoId);
//	alert(NextId);
	
}
function showPrevPhotoDetail()
{
	var photoIdArray = new Array();
	photoIdArray = photoIdList.split(',');
	var curPhotoId = document.getElementById("detailBoxId").value;
	var curType = inputBType = document.getElementById("detailBoxType").value;
	
	var NextId = 0;
	for (i = 0; i < photoIdArray.length; i++)
	{
		if(photoIdArray[i] == curPhotoId)
		{
			//Current Id found, increment and get next
			NextId = i-1;
			break;
		}
	}
	
	if(NextId < 0)
	{	NextId = photoIdArray[photoIdArray.length-1];		}
	else
	{	NextId = photoIdArray[NextId];		}
	
	openDetail(curType,NextId);
//	alert(curPhotoId);
//	alert(NextId);
}

function openDetail(type,id,edit) {
	toggleDisplay(document.getElementById("photodetail"),true);
	var selects = document.getElementsByTagName("select");
		for(var s=0; s<selects.length; s++) { selects[s].style.visibility = "hidden"; }
	getDetail(type,id,edit);
}
function getDetail(type,id,edit) {
	var qs = "?item="+escape(type)+"&id="+escape(id)+"&edit="+escape(edit);
	var params = {"type":type,"edit":edit};
	//alert(qs);
	var ajaxobj = new AjaxObject("get","/_com/community/gallery/ajax_detail.asp",qs,displayDetail);
		ajaxobj.setHandlerParam(params);
		ajaxobj.execute();
}
function displayDetail(xmlHttp,params) {
	var data = eval('(' + xmlHttp.responseText + ')'); // create json object
	//alert(xmlHttp.responseText);
	var viewport = getViewPortDimensions();
	var pcontainer = document.getElementById("photodetail");
	var pimg = document.getElementById("photoimage");
		pimg.setAttribute("title","");
		pimg.onclick = function() {};
		pimg.style.cursor = "";
	var pdate = document.getElementById("photodate");
		pdate.innerHTML = "";
	var ploc = document.getElementById("photolocation");
		ploc.innerHTML = "";
	var pcat = document.getElementById("photocategory");
		pcat.innerHTML = "";
	var pdesc = document.getElementById("photodescription");
		pdesc.innerHTML = "";
	var staf = document.getElementById("sendtoafriend");
	var inputBID = document.getElementById("detailBoxId");
	var inputBType = document.getElementById("detailBoxType");	
	if(data.length > 0) {
		inputBType.value = params.type
		if(params.type == "photo") {
			inputBID.value = data[0].id;
			var maxwidth = Math.ceil(viewport.width * 0.6);
			var maxheight = Math.ceil(viewport.height * 0.6);
			var imgsrc_root = '/_com/community/gallery/_image.asp?image='+data[0].id;
			pimg.innerHTML = '<img src="'+imgsrc_root+'&w='+maxwidth+'&h='+maxheight+'" /><br />';
				if(data[0].width > maxwidth || data[0].height > maxheight) {
					pimg.setAttribute("title","Click for a full sized image");
					pimg.onclick = function() { window.open(imgsrc_root); };
					pimg.style.cursor = "pointer";
				}
			var detailwidth = data[0].width;
			if(maxheight < data[0].height) { detailwidth = (data[0].width * maxheight) / data[0].height; }
			if(maxwidth < detailwidth) { detailwidth = maxwidth; }
			pcontainer.style.width = Math.floor(detailwidth) + "px";
			//pcontainer.style.left = Math.floor((viewport.width-detailwidth)/2) + "px";
			if(staf !== null) {
				staf.onclick = function() {
						launchSendToAFriend(data[0].id,"",data[0].user);
					};
			}
		} else if(params.type == "video") {
			pcontainer.style.width = "345px";
			//pcontainer.style.left = Math.floor((viewport.width-345)/2) + "px";
			//pimg.innerHTML = '<embed src="/_com/community/gallery/_videoplayer.swf" swLiveConnect="FALSE" width="330" height="290" quality="high" scale="exactfit" flashvars="videofile=/_com/community/gallery/videos/6.flv" wmode="" id="vp" name="vp" menu="false" devicefont="false" bgcolor="#FFFFFF" salign="lt" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>';
			//pimg.innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="330" height="290" id="_videoplayer" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="/_com/community/gallery/_videoplayer.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="videofile=/_com/community/gallery/videos/'+data[0].id+'.flv""><embed src="/_com/community/gallery/_videoplayer.swf" quality="high" bgcolor="#ffffff" width="330" height="290" name="_videoplayer" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="videofile=/_com/community/gallery/videos/'+data[0].id+'.flv" /></object>';
			var so = new SWFObject("/_com/community/gallery/_videoplayer.swf", "_videoplayer", "330", "290", "8", "#FFFFFF");
				so.addVariable("videofile","/_com/community/gallery/_video.asp?video="+data[0].id);
				so.write("photoimage");
			if(staf !== null) {
				staf.onclick = function() {
						launchSendToAFriend("",data[0].id,data[0].user);
					};
			}
		}
		if(params.edit !== true) {
			if(data[0].date.length > 0) {
				pdate.innerHTML = data[0].date;
				if(data[0].loc.length > 0 || data[0].category.length > 0) {
					pdate.innerHTML += " &nbsp;|&nbsp;";
				}
			} else {
				pdate.innerHTML = "";
			}
			if(data[0].loc.length > 0) {
				ploc.innerHTML = data[0].loc;
				if(data[0].category.length > 0) {
					ploc.innerHTML += " &nbsp;|&nbsp;";
				}
			} else {
				ploc.innerHTML = "";
			}
			if(data[0].category.length > 0) {
				pcat.innerHTML = data[0].category;
			} else {
				pcat.innerHTML = "";
			}
			if(data[0].desc.length > 0) {
				pdesc.innerHTML += "" + data[0].desc;
			} else {
				pdesc.innerHTML = "";
			}
			if(staf !== null) { toggleDisplay(staf,true); }
		} else {
			var date_id = params.type+"|Date|"+data[0].id;
				pdate.innerHTML = '<p>Date Taken: <input type="text" id="'+date_id+'" name="field" size="10" maxlength="10" value="'+data[0].date+'" /> &nbsp; <input type="button" value="Save" onclick="javascript:saveData(\''+date_id+'\');" /></p>';
			var location_id = params.type+"|Location|"+data[0].id;
				ploc.innerHTML = '<p>Location: <input type="text" id="'+location_id+'" name="field" size="40" maxlength="100" value="'+data[0].loc+ '" /> &nbsp; <input type="button" value="Save" onclick="javascript:saveData(\''+location_id+'\');" /></p>';
			pcat.innerHTML = "";
			var description_id = params.type+"|Description|"+data[0].id;
				pdesc.innerHTML = '<p>Desc: <input type="text" id="'+description_id+'" name="field" size="40" maxlength="255" value="'+data[0].desc+ '" /> &nbsp; <input type="button" value="Save" onclick="javascript:saveData(\''+description_id+'\');" /></p>';
				pdesc.innerHTML = pdesc.innerHTML + '<p><a href="#" onclick="javascript:deleteItem(\'' + params.type + '\',' + data[0].id + ');return false;">Delete</a></p>';
											
			if(staf !== null) {
				toggleDisplay(staf,false);
			}
		}
	} else {
		pimg.innerHTML = 'Image could not be found or is pending approval. &nbsp; &nbsp; &nbsp; ';
	}
}

function saveData(info) {
	var qs = "";
	var params = info.split("|");
	if(params.length == 3) {
		var obj = document.getElementById(info);
		if(obj !== null) {
			qs = "?value="+escape(obj.value)+"&info="+escape(info);
			var ajaxobj = new AjaxObject("get","/_com/community/gallery/ajax_save.asp",qs,showConfirm);
				ajaxobj.execute();
		}
	}
}
function showConfirm(xmlHttp) { alert(xmlHttp.responseText); }

function closePhotoDetail() {
	var vp = document._videoplayer;
		if(typeof vp != "undefined") {
			if(typeof vp.stopVideo != "undefined") { vp.stopVideo(); }
		}
	toggleDisplay(document.getElementById("photodetail"),false);
	var selects = document.getElementsByTagName("select");
		for(var s=0; s<selects.length; s++) { selects[s].style.visibility = "visible"; }
}

/*#######################################
###	Validation Functions
#######################################*/
function validateLogin(form) {
	var msg = "";
	if(form.sn.value.length == 0) { msg += "Please enter your screen name.\n" }
	if(form.password.value.length == 0) { msg += "Please enter your password.\n" }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateNewAccount(form) {
	var msg = "";
	if(form.sn.value.length < 5) { msg += "Screen Name must be at least 5 characters.\n"; }
	if(!checkEmailAddress(form.email.value)) { msg += "Please enter a valid email address.\n"; }
	if(form.password.value.length < 6) { msg += "Password must be at least 6 characters.\n"; }
	if(form.password.value != form.password2.value) { msg += "Passwords must match.\n"; }
	if(!form.accept.checked)  { msg += "You must accept the terms and conditions.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateUploadPhoto(form) {
	var msg = "";
	if(form.upld_file1.value.length == 0 &&
		form.upld_file2.value.length == 0 &&
		form.upld_file3.value.length == 0) { msg += "Please select at least one photo to upload.\n"; }
	if(!form.agree.checked) {  msg += "You must accept the terms and conditions.\n";  }
	if(form.upld_description.value.indexOf('\n') > -1) {  msg += "Please remove all line-breaks from your photo description.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	cnfrm = confirm("It may take some time to upload your photo(s) depending on the size\nof the file(s) you're attempting to upload in addition to your internet connection speed.\n\nAre you sure you wish to continue?");
	if(cnfrm) {
		toggleDisplay("wait_for_processing",true);
		toggleDisplay("community_uploadphoto",false);
	}
	return cnfrm;
}

function validateUploadVideo(form) {
	var msg = "";
	if(form.upld_file1.value.length == 0) { msg += "Please select at least one photo to upload.\n"; }
	if(!form.agree.checked) {  msg += "You must accept the terms and conditions.\n";  }
	if(form.upld_description.value.indexOf('\n') > -1) {  msg += "Please remove all line-breaks from your photo description.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	cnfrm = confirm("It may take some time to upload your video depending on the size\nof the file you're attempting to upload in addition to your internet connection speed.\n\nAre you sure you wish to continue?");
	if(cnfrm) {
		toggleDisplay("wait_for_processing",true);
		toggleDisplay("community_uploadvideo",false);
	}
	return cnfrm;
}

function validateComment(form) {
	var msg = "";
	if(form.comment.value.length == 0) { msg += "Please enter a comment.\n" }
	if(checkHTML(form.comment.value)) { msg += "Please remove all HTML tags or characters.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateEntry(form) {
	var msg = "";
	//if(form.comment.value.length == 0) { msg += "Please enter a comment.\n" }
	//if(checkHTML(form.comment.value)) { msg += "Please remove all HTML tags or characters.\n"; }
	if(!form.agree.checked) {  msg += "You must accept the terms and conditions.\n";  }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateForgotPassword(form) {
	var msg = "";
	if(form.sn.value.length == 0) { msg += "Please enter your screen name.\n" }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateResetPassword(form) {
	var msg = "";
	if(form.password.value.length < 6) { msg += "Password must be at least 6 characters.\n"; }
	if(form.password.value != form.password2.value) { msg += "Passwords must match.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}

function validateEmailAddress(form) {
	var msg = "";
	if(!checkEmailAddress(form.email.value)) { msg += "Please enter a valid email address.\n"; }
	if(form.email.value != form.email2.value) { msg += "Email addresses must match.\n"; }
	if(msg != "") {
		alert("Form Validation Error\n\n"+msg+"\nPlease complete the form and re-submit.");
		return false;
	}
	return true;
}


function checkHTML(str) {
	var reHTML = /([<>]|(\&lt)|(\&gt))/g;
	return reHTML.test(str);
}
function checkEmailAddress(email) {
	var reEmail = /^([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+$/i;
	return reEmail.test(email);
}
function limitText(field,display,maxlength) {
	if (field.value.length > maxlength) {
		field.value = field.value.substring(0,maxlength);
	} else {
		display.innerHTML = "" + (maxlength-field.value.length) + " characters left";
	}
}

function checkScreenName(obj) {
	var input = document.getElementById(obj);
	if(input !== null) {
		if(input.value.length >= 5) {
			var qs = "?sn="+input.value
			var ajaxobj = new AjaxObject("get","/_com/community/ajax_checkscreenname.asp",qs,displayScreenNameCheck);
				ajaxobj.execute();
		} else {
			alert("Please enter your desired Screen Name (5 character minimum).");
		}
	}
}
function displayScreenNameCheck(xmlHttp) {
	if(xmlHttp.responseText != "0") { alert("IN USE --\nSorry, the Screen Name you have chosen is not available."); }
	else { alert("OK --\nYour desired screen name is available."); }
}

/*#######################################
###	Upload Popup Functions
#######################################*/
function shareVideos(url, upu) {
	var cnfrm = confirm("ATTENTION!\nThis page may take some time to load.\nIf you are unable to view this page after a couple of minutes, please try again later.\n\nAre you sure you wish to continue.");
	if(cnfrm) {
	    var vupld = window.open(url + "?upu=" + upu, "vupld", "height=700,width=600,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
			vupld.focus();
	}
}

function sharePhotos(u) {
	var pupld = window.open(u,"pupld","height=700,width=600,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
		pupld.focus();
}

function popupToLibrary(u) {
	var o = window.opener;
	if(o !== null) {
	    o.location.href = u; // "/travelcommunity/vacationviewer/library.asp"
		window.close();
		o.focus();
	}
}

function validateOpener(url) {
	var o = window.opener;
	if(o === null) {
		alert("Opener Does Not Exist");
		if(url.length > 0) { location.href = url; }
	}
}

function launchSendToAFriend(photo,video,user) {
	var lstaf = window.open("/_com/community/gallery/sendtoafriend.asp?photo="+photo+"&video="+video+"&user="+user,"staf","height=700,width=600,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
		lstaf.focus();
}

/*#######################################
###	Miscellaneous Functions
#######################################*/

/* submits form for next data page */
function gotoPage(p) {
	var form = document.forms[document.forms.length-1];
		form.page.value = p;
		form.submit();
}
/* copies content from one element to another */
function duplicateContent(_src,_dest) {
	src = _src;
	dest = _dest;
	if(typeof src == "string") { src = document.getElementById(src); }
	if(typeof dest == "string") { dest = document.getElementById(dest); }
	dest.innerHTML = src.innerHTML;
}

function showUploadHelp() {
	 window.open("/_com/community/gallery/uploadhelp.html","help","height=400,width=500,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
}

function setAttachmentToggle() {
	var pt = document.getElementById("attachphoto_trigger");
	var ps = document.getElementById("attachphoto");
	var vt = document.getElementById("attachvideo_trigger");
	var vs = document.getElementById("attachvideo");
	var ef = document.getElementById("entryfile");
	var acb = document.getElementById("addtolibrary");
	var ui = document.getElementById("upload_info");
	if(ps !== null) {
		toggleDisplay(ps,true);
		ps.onclick = function() {
				if(ef !== null) { ef.value = ""; }
				if(acb !== null) { acb.checked = false; }
				if(ui !== null) { toggleDisplay(ui,false); }
			};
	}
	if(vs !== null) {
		toggleDisplay(vs,false);
		vs.onclick = function() {
				if(ef !== null) { ef.value = ""; }
				if(acb !== null) { acb.checked = false; }
				if(ui !== null) { toggleDisplay(ui,false); }
			};
	}
	if(ef !== null) {
		ef.onchange = function() {
				if(ef.value.length > 0) {
					if(ps !== null) { ps.selectedIndex = -1; }
					if(vs !== null) { vs.selectedIndex = -1; }
					if(ui !== null) { toggleDisplay(ui,true); }
				}
			};
	}
	if(pt !== null) {
		pt.onclick = function() {
				toggleDisplay(ps,true);
				toggleDisplay(vs,false);
				if(ui !== null) { toggleDisplay(ui,false); }
			};
	}
	if(vt !== null) {
		vt.onclick = function() {
				toggleDisplay(vs,true);
				toggleDisplay(ps,false);
				if(ui !== null) { toggleDisplay(ui,false); }
			};
	}
}

function getViewPortDimensions() {
	var viewportwidth;
	var viewportheight;
	if (typeof window.innerWidth != 'undefined') {
	 	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	} else if (typeof document.documentElement != 'undefined' &&
			typeof document.documentElement.clientWidth != 'undefined' &&
		document.documentElement.clientWidth != 0) {
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	} else {
	 	// older versions of IE
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	return {"width":viewportwidth,"height":viewportheight};
}
