var url;
var startD = new Date();
var DSTday = 14; // 14-mar-10
var STday = 7; // 7-nov-10
var TzOffset;
var BCTzOffset;
var camera;
var pictureURL;
var pictureURLbig;
var pictureURLsmall;
var pictureURLthumb;
var pictureHTML;
var baseSize;
var size;
var playMode = 0;
var playFrameCount = 0;
var playFrameCountMax = 60;
var playFrameErrorCount = 0;
var playFrameErrorCountMax = 10;
var	playFrameLoaded = 0;
var picNotfound;
var errPic;
var cachepic = new Image();
var cacheZoom = new Image();
var helpWindow;
var bigWindow;
var smallWindow;
var HTMLWindow;
var clipWindow;
var SmallCamPattern = new RegExp("_LowRes");


function closeWindows() {
	closeHTMLWindows();
	if (typeof bigWindow != 'undefined') {
		if (!bigWindow.closed) {
			bigWindow.close();
		}
	}
	if (typeof smallWindow != 'undefined') {
		if (!smallWindow.closed) {
			smallWindow.close();
		}
	}
	if (typeof helpWindow != 'undefined') {
		if (!helpWindow.closed) {
			helpWindow.close();
		}
	}
}

function closeHTMLWindows() {
	if (typeof HTMLWindow != 'undefined') {
		if (!HTMLWindow.closed) {
			HTMLWindow.close();
		}
	}
	if (typeof clipWindow != 'undefined') {
		if (!clipWindow.closed) {
			clipWindow.close();
		}
	}
}

function hex(n) {
	var h = parseInt(n).toString(16);
	return (h.length%2)?"0"+h:h
}

function updateURL(theForm) {
	playMode = 0;
	makeURL(theForm);
}

function submitIt(theForm) {
	playMode = 0;
	return submitDate(theForm);
}

function makeURL(theForm) {
//	var url = "http://birdcam.kodak.com/thruway/archive/";
//	var url = "http://shakymon.com/thruway/archive/";
//	var url = "archive/";
	var url = "http://rfalconcam.com/gallery/processed/";
	var cam = "MainCamera_LowRes";
//	var camBig = "MainCamera_HighRes";
	var camBig = "MainCamera";
	var camSmall = "MainCamera_LowRes";
	var camThumb = "MainCamera_Thumbnail";
//	var camThumb = "MainCamera_LowRes";
	camera = theForm.camera.selectedIndex;
	if (camera == 0) {
		cam = "MainCamera";
		if (size == 0) cam = "MainCamera_LowRes";
//		camBig = "MainCamera_HighRes";
//		camSmall = "MainCamera_LowRes";
		camThumb = "MainCamera_Thumbnail";
		camBig = "MainCamera";
//		camThumb = "MainCamera_LowRes";
	}
	if (camera == 1) {
		cam = "Camera1";
		if (size == 0) cam = "Camera1_LowRes";
		camBig = "Camera1";
		camSmall = "Camera1_LowRes";
		camThumb = "Camera1_Thumbnail";
//		camThumb = "Camera1_LowRes";
	}
	if (camera == 2) {
		cam = "Camera2";
		if (size == 0) cam = "Camera2_LowRes";
		camBig = "Camera2";
		camSmall = "Camera2_LowRes";
		camThumb = "Camera2_Thumbnail";
//		camThumb = "Camera2_LowRes";
	}
	if (camera == 3) {
		cam = "Camera3";
		if (size == 0) cam = "Camera3_LowRes";
		camBig = "Camera3";
		camSmall = "Camera3_LowRes";
		camThumb = "Camera3_Thumbnail";
//		camThumb = "Camera3_LowRes";
	}
	if (camera == 4) {
		cam = "Camera4";
		if (size == 0) cam = "Camera4_LowRes";
		camBig = "Camera4";
		camSmall = "Camera4_LowRes";
		camThumb = "Camera4_Thumbnail";
//		camThumb = "Camera4_LowRes";
	}
	makeDate(theForm);
	var month = startD.getMonth() + 1;
	var year = startD.getFullYear();
	if (month < 10) month = "0"+month;
	var day = startD.getDate();
	if (day < 10) day = "0"+day;
	var minute = startD.getMinutes();
	if (minute < 10) minute = "0"+minute;
	var hour = startD.getHours();
	if (hour < 10) hour = "0"+hour;
	pictureURL = url+cam+"/"+year+month+day+"/"+cam+"_"+year+month+day+"-"+hour+minute+"00.jpg"
	var cam2 = cam;
	var cam3 = cam;
	pictureURLbig = url+camBig+"/"+year+month+day+"/"+camBig+"_"+year+month+day+"-"+hour+minute+"00.jpg"
	pictureURLsmall = url+camSmall+"/"+year+month+day+"/"+camSmall+"_"+year+month+day+"-"+hour+minute+"00.jpg"
	pictureURLthumb = url+camThumb+"/"+year+month+day+"/"+camThumb+"_"+year+month+day+"-"+hour+minute+"00.jpg"
}

function makeThumbHTML(theForm) {
	if (playMode != 0) {
		playMode = 0;
		playFrameLoaded = 1;
	}
//	var thumbSize = size;
	var thumbSize = 1;
	submitDate(theForm);
	if (picNotFound) {
		alert('There is no picture available for this camera at the selected time. Please choose another time or camera.');
		return;
	}
	size = thumbSize;
	makeURL(theForm);
	var sizeInfo = "(small)";
	var url = pictureURLsmall;
	if (size == 1) {
		sizeInfo = "(large)"
		url = pictureURLbig;
		if (camera == 0) {
			sizeInfo = "(very large)"
		}
	}		
	pictureHTML = "<a href=\"" +
			url +
//			"?\" target=_blank><img src=\"" + 
			"\"><img src=\"" + 
			pictureURLthumb +
//			"\" height=86 width=129></a>" +
//			"?\" ></a>" +
			"\"></a>" +
//			" " + sizeInfo;
			"";

	HTMLWindow = window.open("rfc-thumbsup.html",'thumbnailHTML','width=420,height=420,scrollbars,resizable,menubar');
	HTMLWindow.focus();
}

function makeMovieHTML(theForm) {
	if (playMode != 0) {
		playMode = 0;
		playFrameLoaded = 1;
	}
	var movieSize = size;
	submitDate(theForm);
	if (picNotFound) {
		alert('There is no picture available for this camera at the selected time. Please choose another time or camera.');
	}
	else {
	size = movieSize;

		clipWindow = window.open("rfc-clipmaker.html",'clipHTML','width=400,height=450,scrollbars,resizable,menubar');
		clipWindow.focus();
	}
}

function reload() {
//alert('In reload');
	playFrameLoaded = 0;
	cachepic.src = pictureURL;
}

function setDefault(theForm) {
	var startTime, startAMPMidx;
	var startMinute, startHour, year, month, day;
	var cookieStartDate, cookieCamera, cookieSize;
	startD = new Date();
// if no cookie, set start time to now - 1 minute
	cookieStartDate = cookieVal("startDate");
//	document.write("startdate: ",cookieStartDate,"<br>");
	if (cookieStartDate != -1) {
//		startD.setTime(Date.parse(cookieStartDate));
		startD.setTime(cookieStartDate);
		startMinute = startD.getMinutes();
	}
	else {
		startMinute = startD.getMinutes();
		startMinute += (getTzOffset()-1);
		startD.setMinutes(startMinute);
	}
	setFormDateTime(theForm)
// if cookie, set the camera to 1
	cookieCamera = cookieVal("camera");
	if (cookieCamera != -1) {
		setCamera(theForm,cookieCamera);
	}
	else {
		setCamera(theForm,1);
	}
//	document.write("camera: ",cookieCamera,"<br>");
// if cookie, set the image size
	cookieSize = cookieVal("size");
//	document.write("size: ",cookieSize,"<br>");
	if (cookieSize != -1) {
//		theForm.size.options[cookieSize].selected=true;
//		size = cookieSize;
		size = baseSize;
	}
	else {
		size = baseSize;
	}
	makeURL(theForm);
	reload();
}

function makeDate(theForm) {
	var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var now = new Date();
	var year = now.getFullYear();
	if (year % 4 == 0) {
		monthDays[1] = 29;
	}
	// get date
	var month = theForm.month.selectedIndex;
	var day = theForm.day.selectedIndex + 1;
	if (day > monthDays[month]) {
		var monthName = theForm.month.options[theForm.month.selectedIndex].text;
		alert(monthName+" does not have "+day+" days");
		day = monthDays[month];
		theForm.day.options[day-1].selected=true;
	}
	// get time
	var hour = theForm.startHour.selectedIndex + (theForm.startAMPM.selectedIndex * 12);
	var minute = theForm.startMinute.selectedIndex;
	// convert to date object
	startD = new Date();
	startD.setDate(1);
	startD.setMonth(month);
	startD.setDate(day);
	startD.setHours(hour);
	startD.setMinutes(minute);
	startD.setSeconds(0);
}

function submitDate(theForm) {
	closeHTMLWindows();
	size = baseSize;
	var now = new Date();
	var minute = now.getMinutes();
	minute += getTzOffset();
	now.setMinutes(minute);
	makeDate(theForm);
	// is time later than now?
	if (startD.getTime() > now.getTime()) {
		if (playMode == 1) {
			playMode = 0;
			startD.setTime(now.getTime());
			setFormDateTime(theForm);
		}
		else {
			minute = now.getMinutes();
			if (minute < 10) minute = "0"+minute;
			var hour = now.getHours();
			var ampm = " AM";
			if (hour >= 12) {
				ampm = " PM";
				hour -=12;
			}
			if (hour == 0) hour = 12;
			var month = now.getMonth() + 1;
			var day = now.getDate();
			var year = now.getFullYear()-2000;
			alert("You must choose a time earlier than now.\n"+
				"The current Birdcam time is "+month+"/"+day+"/0"+year+" "+hour+":"+minute+ampm+".");
			startD.setTime(now.getTime());
			setFormDateTime(theForm);
//			return false
		}
	}
	// If we made it to here, everything's valid, so set the cookie and load the image
	makeURL(theForm);
	setCookies(startD,camera,size);
	reload();
	return false;
//	return true;
}

function setCookies(startDate,camera,size) {

// cookies expire in 2 weeks
//	var expires = new Date();
//	expires.setTime(startDate.getTime());
//	var day = expires.getDate();
//	day+=14;
//	expires.setDate(day);

// cookies expire on midnight of Jan 1, next year
	var expires = new Date(startDate.getFullYear()+1,0,1,0,0,0);

	var expDate = expires.toGMTString();
//	alert("expDate: "+expDate);
//	document.cookie = "startDate="+startDate.toGMTString()+";expires="+expDate;
	document.cookie = "startDate="+startDate.getTime()+";expires="+expDate;
	document.cookie = "camera="+camera+";expires="+expDate;
	document.cookie = "size="+size+";expires="+expDate;
}

function cookieVal(cookieName) {
	thisCookie = document.cookie.split("; ");
  	    for (i=0; i<thisCookie.length; i++) {
//	document.write("thisCookie[",i,"]: ",thisCookie[i],"<br>");
  	        if (cookieName == thisCookie[i].split("=")[0]) {
  	        	return thisCookie[i].split("=")[1];
  	        }
   	    }
	return -1;
}
function setCamera(theForm,cam) {
	theForm.camera.options[cam].selected=true;
	camera = cam;
}

function setFormDateTime(theForm) {
	var startMinute = startD.getMinutes();
	var startHour = startD.getHours();
// convert 24 hour to am/pm
	startAMPMidx = 0;
	if (startHour >= 12) {
		var startAMPMidx = 1;
		startHour -= 12;
	}
	theForm.startHour.options[startHour].selected=true;
	theForm.startMinute.options[startMinute].selected=true;
	theForm.startAMPM.options[startAMPMidx].selected=true;
// get start month, and  day
	var month = startD.getMonth() + 1;
	var day = startD.getDate();
	theForm.month.options[month-1].selected=true;
	theForm.day.options[day-1].selected=true;
//document.write("date: ",month,"/",day,"<br>");
//document.write("start: ",startHour,":",startMinute," ",startAMPMidx,"<br>");
}

function cycleCamera(theForm,direction) {
	camera += direction;
	if (camera > 4) camera=0;
	if (camera < 0) camera=4;
	setCamera(theForm,camera);
	submitIt(theForm);
}

function bigPic(theForm) {
	if (playMode != 0) {
		playMode = 0;
		playFrameLoaded = 1;
	}
	submitDate(theForm);
	size = 1;
	makeURL(theForm);
	bigWindow = window.open(pictureURLbig,'bigPic','width=720,height=500,scrollbars,resizable');
	bigWindow.focus();
}

function smallPic(theForm) {
	if (playMode != 0) {
		playMode = 0;
		playFrameLoaded = 1;
	}
	submitDate(theForm);
	size = 0;
	makeURL(theForm);
	smallWindow = window.open(pictureURLsmall,'smallPic','width=400,height=300,scrollbars,resizable');
	smallWindow.focus();
}

function prevPic(theForm) {
	makeDate(theForm);
	var startMinute = startD.getMinutes();
	startMinute--;
	startD.setMinutes(startMinute);
	checkDST(-1);
	setFormDateTime(theForm);
	submitIt(theForm);
}

function nextPic(theForm) {
	makeDate(theForm);
	var startMinute = startD.getMinutes();
	startMinute+=addMozillaDST(1);
	startD.setMinutes(startMinute);
	checkDST(1);
	setFormDateTime(theForm);
	submitIt(theForm);
}

function addMozillaDST(minutes) { // fixes  "1 AM" trap in Mozilla-base browsers
	var mozillaMinutes = minutes;
	if (minutes > 0) {
		var t = new Date();
		t.setTime(startD.getTime());
		t.setMinutes(t.getMinutes()+minutes);
		if (t.getTime() <= startD.getTime()) {
			mozillaMinutes+=60;	
		}
	}
	return mozillaMinutes;
}

function forwardPlay(theForm) {
	makeDate(theForm);
	playMode=1
	playFrameCount = 0;
	playFrameErrorCount = 0;
	playFrames(theForm);
}

function backwardPlay(theForm) {
	makeDate(theForm);
	playMode= -1;
	playFrameCount = 0;
	playFrameErrorCount = 0;
	playFrames(theForm);
}

function stopPlay(theForm) {
	playMode= 0;
}

function gotoNow(theForm) {
	size = baseSize;
	playMode= 0;
	var now = new Date();
	var minute = now.getMinutes();
	minute += (getTzOffset()-1);
	now.setMinutes(minute);
	makeDate(theForm);
	startD.setTime(now.getTime());
	setFormDateTime(theForm);
	submitIt(theForm);
}

function playFrames(theForm) {
	if (playMode != 0 && playFrameCount < playFrameCountMax && playFrameErrorCount < playFrameErrorCountMax) {

		if (playFrameLoaded == 1) {
//		if (document.campicture.complete) {
			var startMinute = startD.getMinutes();
			startMinute += addMozillaDST(playMode);
			startD.setMinutes(startMinute);
			checkDST(playMode);
			setFormDateTime(theForm);
			submitDate(theForm);
			playFrameCount++;
		}
		timerID = setTimeout("playFrames(document.camArchive)", 500);
	}
	else if (playFrameErrorCount > 0) {
  		document.campicture.src = errPic;
	}
}

function showHelp() {
	var fileName = /.*\/(.*)\.html/;
	var url = location.pathname;
	var result = url.match(fileName);
	var helpURL = "rfc-help/rfc-help.html";
	var pattern = new RegExp("rfc-archive","i");
	var pattern2 = new RegExp("rfc-bigscreen\\.html","i");
	if (!pattern.test(url) && !pattern2.test(url)) {
		helpURL = "rfc-help/"+result[1]+"-help.html";
	}
	helpWindow = window.open(helpURL,'help','width=400,height=450,scrollbars,resizable');
	helpWindow.focus();
}

function getTzOffset() {
	TzOffset = startD.getTimezoneOffset();
	if (TzOffset > 720) TzOffset -= 1440;
	TzOffset -= BCTzOffset;
	return TzOffset;
}

function checkDST(direction) {
	var month = startD.getMonth() + 1;
	var day = startD.getDate();
	if (month == 3 && day == DSTday) {
		var hour = startD.getHours()
		if (hour == 2) {
			if (direction < 0) {
				hour--;
			}
			else {
				hour++;
			}
			startD.setHours(hour);
		}
	
	}			
}

function setDST(DSTday,STday) {
	var month = startD.getMonth() + 1;
	var day = startD.getDate();
	if ((month == 3 && day >= DSTday) || (month > 3 && month < 11) || 
	    (month ==11 && day < STday)) {
		BCTzOffset = 240;
	}			
	else {
		BCTzOffset = 300;
	}
}

function getBaseSize() {
	var path = location.pathname
	var pattern = new RegExp("rfc-archive","i");
	var pattern2 = new RegExp("rfc-clipper\\.html","i");
	if (pattern.test(path) || pattern2.test(path)) {
		baseSize=0;
	}
	else {
		baseSize=1;
	}
}

function dynamicWindow(url,height,width) {
	var t = new Date();
	var url2 = url + "?" + t.getTime();
	bcWindow = window.open(url2,'bcWindow',
		'width='+width+',height='+height);
	bcWindow.focus();
}

function newWindow(url,height,width) {
	bcWindow = window.open(url,'bcWindow',
		'width='+width+',height='+height);
	bcWindow.focus();
}

function mapWindow(url) {
	bcmapWindow = window.open(url,'bcmapWindow',
		'width=550,height=450,scrollbars,resizable');
	bcmapWindow.focus();
}

function weatherWindow() {
	bcweatherWindow = window.open('rfc-weather.html','bcweatherWindow',
		'width=160,height=120');
	bcweatherWindow.focus();
}

function radarWindow() {
	bcradarWindow = window.open('rfc-radar.html','bcradarWindow',
		'width=600,height=450,scrollbars,resizable');
	bcradarWindow.focus();
}


function campicLoaded() {
//alert('in campicLoaded');
	playFrameErrorCount = 0;
	playFrameLoaded = 1;
}

function campicError() {
//alert('in campicError');
	playFrameErrorCount++;
	playFrameLoaded = 1;
}

function campicAbort() {
//alert('in campicAbort');
//	playMode = 0;
	playFrameLoaded = 1;
}

function cachepicLoaded() {
//alert('in cachepicLoaded');
	pictureH = cachepic.height;
	pictureW = cachepic.width;

	if (pictureH == 0 && pictureW == 0) {
		cachepicError();
		return ;
	} 	
	document.campicture.src = cachepic.src;
  	picNotFound = false;
}

function cachepicError() {
//alert('in cachepicError playMode='+playMode);
	if (playMode == 0) {
		var now = new Date();
  		document.campicture.src = errPic+"?"+now.getTime();
  		picNotFound = true;
	}
	else {
		playFrameErrorCount++;
		playFrameLoaded = 1;
	}
}

function cachepicAbort() {
//alert('in cachepicAbort');
//	playMode = 0;
	playFrameLoaded = 1;
}

cachepic.onload=cachepicLoaded;
cachepic.onerror=cachepicError;
cachepic.onabort=cachepicAbort;

getBaseSize();
size = baseSize;
errPic = 'rfc-pix/nopic' + size + '.gif'

setDST(DSTday,STday);

