/***** MEDIA UPLOAD ******/
function switch_mediaupload_tab(tab) {
	document.getElementById('form_pic').style.display='none';
	document.getElementById('form_vid').style.display='none';
	document.getElementById('form_zip').style.display='none';

	document.getElementById('tab_pic').style.background='#FFFFFF';
	document.getElementById('tab_vid').style.background='#FFFFFF';
	document.getElementById('tab_zip').style.background='#FFFFFF';

	document.getElementById('form_'+tab).style.display='block';
	document.getElementById('tab_'+tab).style.background='#DDDDDD';
}

function begin_form_uploading(formref) {
	// Lock Buttons
	formref.form.button_add.disabled=true; 
	if (formref.form.button_reset)
		formref.form.button_reset.disabled=true; 

	// Lock the rest and show graphic
	type = formref.form.type.value;
	if (type == 'vid') { 
//		formref.form.media_file.readOnly=true; 
//		formref.form.fileaddress_video.readOnly=true; 
		formref.form.embed_video.readOnly=true; 
//		document.getElementById('form_vid_uploading').style.display='block';
		document.getElementById('form_uploading').style.bottom='250px';
		document.getElementById('form_uploading').style.display='block';
	} else if (type == 'zip') {
//		formref.form.media_file.disabled=true; 
//		document.getElementById('form_zip_uploading').style.display='block';		
		document.getElementById('form_uploading').style.bottom='150px';
		document.getElementById('form_uploading').style.display='block';
	} else if (type == 'pic') {
//		formref.form.media_file.disabled=true; 
		formref.form.fileaddress_picture.readOnly=true; 
		document.getElementById('form_uploading').style.bottom='120px';
//		document.getElementById('form_pic_uploading').style.display='block';		
		document.getElementById('form_uploading').style.display='block';		
	} else if (type == 'minisite' || type == 'mediacontest') {
		formref.form.title.readOnly=true;
		formref.form.description.readOnly=true;
//		document.getElementById('form_uploading').style.bottom='120px';
		document.getElementById('form_uploading').style.display='block';		
	}

	// Submit
	formref.form.submit();
}


/***** MEDIA INFO ******/

// CreateRequestObject is defined in main.js

var http_submit_request = false;

function ajaxSubmitInfo(url, parameters) {
	http_submit_request = false;

	// Create the connection
	http_submit_request = createRequestObject('text/html');
	if (!http_submit_request)
		return false;
      
	http_submit_request.onreadystatechange = processSubmitResult;
	http_submit_request.open('POST', url, true);
	http_submit_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_submit_request.setRequestHeader("Content-length", parameters.length);
	http_submit_request.setRequestHeader("Connection", "close");
	http_submit_request.send(parameters);
}

function processSubmitResult() {
	if (http_submit_request.readyState == 4) {
		if (http_submit_request.status == 200) {

			//alert(http_submit_request.responseText);
			var resultstring = http_submit_request.responseText;

			// debug output from AJAX result
//			document.getElementById('testoutput').innerHTML = resultstring;

			// process JSON result
			var result = eval('(' + resultstring + ')');

			// if errors existed
			if (result.ERRORS.length > 0) {

				// Clear out the old errors
				clear_media_messages('form_errors_list');

				// Add the new errors
				append_media_messages('form_errors_list', result.ERRORS);

				// Display the error box
				document.getElementById('form_errors').style.display='block';

			// No errors, success!
			} else {

				// Hide the error messages
				document.getElementById('form_errors').style.display='none';

				// Clear & Save the success messages
				clear_media_messages('form_success_list');
				append_media_messages('form_success_list', result.SUCCESS);

				// Display the success msgs
				document.getElementById('form_success').style.display='block';

				// Clear all non-sticky form fields except category & private/public
				reset_media_info_fields();

				// Get the form info
				var form = document.getElementById('media_info_form');

				// If server says no more files of that type, go to the results page
				if (result.NEXTSTEP != '') { 

					// forward to media_info page again for processing
					document.location=result.NEXTSTEP;
					return true;
				}

				// if type is pic
				if (form.type.value == 'pic' && mediaupload_pics.length > 1) {

					// shorten the pic file arrays array by one to remove the processed element
					mediaupload_pics.splice(0, 1);

					// Use the new first picture for thumbnail & full size popup 
					var previewimg = document.getElementById('currentimgpreview');
					previewimg.src = mediaupload_pics[0].thumb_url;
					previewimg.height = mediaupload_pics[0].height;
					previewimg.width = mediaupload_pics[0].width;

					// If we are on the last image, hide the slide show without updating
					if (mediaupload_pics.length == 1) {

						document.getElementById('otherimgs').style.display = 'none';

					// More pictures left, update the slide show
					} else {

						// Manage the thumbnail slider I chose
						// remove the beginning of the thumbnail image arrays
						slide_thumb_thumbnails.splice(0, 1);
						slide_thumb_widths.splice(0, 1);
						slide_thumb_heights.splice(0, 1);
						slide_thumb_popups.splice(0, 1);

						// advance the thumbnail slider to image index 1
						changeImage(0);

						// tidy up thumbnail slider counters & indexes
						document.getElementById('slide_thumb_total').innerHTML = slide_thumb_thumbnails.length; 
					}

				// else type is vid
				} else if (form.type.value = 'vid') {

					// shorten the vid file array by one to remove the processed element
					mediaupload_vids.splice(0, 1);

					// Show new current file
					updateVideoPreview();

					// Hide the "Other Videos" box if no more are left
					if (mediaupload_vids.length == 1) {

						document.getElementById('othervids').style.display = 'none';

					// More videos left
					} else{
						// Update the rest of the video preview
						updateOtherVideoPreview();

					}
				}


			// end if
			}

		} else {

			// update the result box insteadl
			alert('Could not read the AJAX result.');
		}
	}
}

function updateVideoPreview() {
	if (mediaupload_vids.length > 0) {

		// Get the video info text
		var videotext = getVideoText(0);

		// Write the HTML
		document.getElementById('vidpreviewtext').innerHTML = videotext;
	}
}

function updateOtherVideoPreview() {
	var videotext = '';

	// Get the rest of the video info texts
	for (var i = 1; i < mediaupload_vids.length; i++) {
		videotext = videotext + getVideoText(i);
	}

	// Write the HTML
	document.getElementById('othervidstext').innerHTML = videotext;
}

function getVideoText(i){
	var videotext = '';

	// Put the basic text for this video
	videotext = "<div class=\"ovid\"><img src=\"" + mediaupload_vids[i].thumb_url + "\">";

	// Link? 
	if (mediaupload_vids[i].file_url != '')
		videotext = videotext + "<a href=\"" + mediaupload_vids[i].file_url + "\">";

	// Set the title
	if (mediaupload_vids[i].filename.length > 35) 
		videotext = videotext + mediaupload_vids[i].filename.substring(0, 20) + "..." + mediaupload_vids[i].filename.substring(mediaupload_vids[i].filename.length-8);
	else
		videotext = videotext + mediaupload_vids[i].filename;

	// Link? 
	if (mediaupload_vids[i].file_url != '')
		videotext = videotext + "</a>";

	// newline
	videotext = videotext + "<br>";

	// Append extended text for local videos
	if (mediaupload_vids[i].source_type == 'upload') {
		var filesize = mediaupload_vids[i].filesize/1024/1024;
		filesize = filesize.toFixed(2);
		videotext = videotext + "Vitals: " + mediaupload_vids[i].fileformat + " - " + filesize + "MB - " + mediaupload_vids[i].playtime;
	} else if (mediaupload_vids[i].source_type == 'embed_code') {
		videotext = videotext + "Embeded Flash Video";
	} else if (mediaupload_vids[i].source_type == 'reference') {
		videotext = videotext + "Remotely hosted";
	}
	videotext = videotext + "</div>";

	return videotext;
}

function submitMediaInfo(url) {
	var form = document.getElementById('media_info_form');

	// Set the values for each text field
	var poststr =	"action="	+ escape(encodeURI( form.action.value )) +  
			"&type="	+ escape(encodeURI( form.type.value )) + 
			"&hide_header="	+ escape(encodeURI( form.hide_header.value )) + 
			"&title="	+ escape(encodeURI( form.title.value )) + 
			"&category_id="	+ escape(encodeURI( form.category_id.value )) + 
			"&description="	+ escape(encodeURI( form.description.value )) + 
			"&credit="	+ escape(encodeURI( form.credit.value )) + 
			"&skier="	+ escape(encodeURI( form.skier.value )) + 
			"&location="	+ escape(encodeURI( form.location.value ));

	// Grab the current filename if required
	if (form.type.value == 'pic')
		poststr = poststr + "&filename=" + escape(encodeURI( mediaupload_pics[0].filename ));
	else if (form.type.value == 'vid') 
		poststr = poststr + "&filename=" + escape(encodeURI( mediaupload_vids[0].filename )); 

	// Determine the value of the radio button
	for(var i = 0; i < form.public_gallery.length; i++) {
		if (form.public_gallery[i].checked) {
			poststr = poststr + "&public_gallery=" + escape(encodeURI( form.public_gallery[i].value ));
			break;
		}
	}

	// Determine the value of the save-all checkbox
	if (form.save_all.checked == 1)
		poststr = poststr + "&save_all=on"; 
	else
		poststr = poststr + "&save_all="; 

	// Submit the form
	ajaxSubmitInfo(url, poststr);
}

function ack_warnings(url) {
	// Create the connection
	var http_request = createRequestObject('text/html');
	if (!http_request)
		return false;

	// Tell the server to clear the warnings
	http_request.open('POST', url + '/action/ack_warnings/', true);
	http_request.send(null);

	// Remove the warnings from the page
	clear_media_messages('form_warnings_list');

	// Hide the box
	document.getElementById('form_warnings').style.display='none';

	return false;
}

function ack_errors(url) {
	// Create the connection
	var http_request = createRequestObject('text/html');
	if (!http_request)
		return false;

	// Tell the server to clear the errors
	http_request.open('POST', url + '/action/ack_errors/', true);
	http_request.send(null);

	// Remove the errors from the page
	clear_media_messages('form_errors_list');

	// Hide the box
	document.getElementById('form_errors').style.display='none';

	return false;
}

function clear_media_messages(container) {
	// Clear the UL list
	var form_msgs_list = document.getElementById( container );
	var form_msgs_list_items = form_msgs_list.getElementsByTagName('li');
	while (form_msgs_list_items.length) {
		form_msgs_list.removeChild(form_msgs_list_items[0]);
	}
}

function append_media_messages(container, msgs) {
	var form_msgs_list = document.getElementById( container );
	for (msg in msgs) {
		var newli = document.createElement('li');
		newli.innerHTML = msgs[msg];
		form_msgs_list.appendChild(newli);
	}
}

function reset_media_info_fields() {
	var form = document.getElementById('media_info_form');

	// Reset non-sticky fields
	if (form.sticky_title.checked != 1)
		form.title.value = '';
	if (form.sticky_category_id.checked != 1)
		form.category_id.value = 0;
	if (form.sticky_description.checked != 1)
		form.description.value = '';
	if (form.sticky_credit.checked != 1)
		form.credit.value = '';
	if (form.sticky_skier.checked != 1)
		form.skier.value = '';
	if (form.sticky_location.checked != 1)
		form.location.value = '';
}
