// JavaScript Document
// Client functionality and checks for the Designs pages
//


// Called to display a theme preview
function previewcode(theme_id, default_color_id) {
	var color_id = '';
	if (stored_color_scheme[theme_id]) color_id = stored_color_scheme[theme_id];
	   else color_id = default_color_id;
	
	urlvar = "/sitebuilder/controlpanel/preview.php?vars=" + color_id + "-" + theme_id + "-0";
    if (screen) {
      screenwidth = screen.width - 100;
	  screenheight = screen.height -200;
    }
	
	   previewWindow = window.open(urlvar, 'previewWin', 'scrollbars=yes,resizable=yes,width='+screenwidth+',height='+screenheight);
}



// Set
// Called whenever someone clicks on a color swatch
//var request1 = createRequest();
//var stored_color_scheme = '';
function set(image,image_src,theme_id,color_id,title) {
	// swap image
	image.src=image_src;
	// swap color name label
	var labeldiv = document.getElementById("colorlabel_" + theme_id);
	replaceText(labeldiv, title);
	// turn on selected indicator if this is a selected color scheme and theme
	var selectdiv = document.getElementById("selectindicator_" + theme_id);
	clearText(selectdiv);
	if ((color_id==stored_selected_color) && (theme_id==stored_theme)) {
		selectdiv.innerHTML = '<span class="new"><strong>Design Selected</strong> <input type="checkbox" checked disabled></span>';
//		var selectimg = document.createElement("img");
//		selectimg.setAttribute("src", "/images/selectcheck.gif");
//		selectdiv.appendChild(selectimg);
	}
	
	// modify new select/update link
	linkdiv = document.getElementById("select_label_" + theme_id);
	if ((color_id==stored_selected_color) && (theme_id==stored_theme)) replaceText(linkdiv, "Update");
		else replaceText(linkdiv, "Select Design");
				
	// store the selected color scheme and theme
	stored_color_scheme[theme_id] = color_id;
	
	// clear any custom options that may be loaded
	closeCustomOptions(theme_id);
}

// Jump Page
// User is selecting another design page to jump to
function jumpPage(page_id) {
	var jumpurl = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'pg=' + page_id + '&do=getpage';
	
	// refresh global variables so they don't stale
	stored_color_scheme = new Array();
	stored_color_scheme[stored_theme] = stored_selected_color;
	
	fetchData(jumpurl,send_data,'pagebody');
}

// Search Themes
// User is selecting to narrow down the displayed themes by a search
function searchThemes() {
	var jumpurl = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var formobj = document.getElementById("searchmenu");
	var search_id = formobj.options[formobj.selectedIndex].value;
	var send_data = 'search_id=' + search_id + '&do=search';
	
	// refresh global variables so they don't stale
	stored_color_scheme = new Array();
	stored_color_scheme[stored_theme] = stored_selected_color;
	
	fetchData(jumpurl,send_data,'pagebody');
}

// Load Custom Options
// Given the theme ID and color ID, calls the server to retrieve HTML for the custom options div for this theme
function loadCustomOptions(theme_id, default_color_id) {
	var color_id = '';
	if (stored_color_scheme[theme_id]) color_id = stored_color_scheme[theme_id];
	   else color_id = default_color_id;
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=load_custom_options&theme_id=' + theme_id + '&color_id=' + color_id;
	
	var div_to_load = 'custom_body_' + theme_id;
	fetchData(url,send_data,div_to_load,'Loading...');
}

// Load Custom Options
// Given the theme ID and color ID, calls the server to retrieve HTML for the custom options div for this theme
function loadCustomOptionsSummary(theme_id, default_color_id) {
	var color_id = '';
	if (stored_color_scheme[theme_id]) color_id = stored_color_scheme[theme_id];
	   else color_id = default_color_id;
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=load_custom_options_summary&theme_id=' + theme_id + '&color_id=' + color_id;
	
	var div_to_load = 'custom_body_' + theme_id;
	fetchData(url,send_data,div_to_load,'Loading...');
}

// Close Custom Options
// Given the theme ID, removes any content that's in the custom options div for this theme
function closeCustomOptions(theme_id) {
	var div_to_load = document.getElementById('custom_body_' + theme_id)
	if (div_to_load != null) clearText(div_to_load);
}

// Swap Saved Custom Selection
// This function is called when the user has changed the sropdown menu selection for a given customizeable option. Swaps the thumbnail image and
// adds a "delete" link if the selected image is a user-uploaded file. Removes any previous "delete" link if this is a public file.
// Parameters:
// menulist - handle to the selection dropdown menu
// option id - custom option ID
// theme_id - theme ID
function swapSavedCustomSelection(menulist, option_id, theme_id) {
	var img_url = menulist[menulist.selectedIndex].value;
	var thumbnail_obj = document.getElementById('customthumb_' + theme_id + '_' + option_id);

	thumbnail_obj.src = img_url;

	// add or clear the "delete" link
	var link_div = document.getElementById('deletelink_' + theme_id + '_' + option_id);
	if (img_url.indexOf("wedshare_sites/") > 0) link_div.innerHTML = '<span>[ <a href="javascript:deleteUploadedFile(\'' + urlToFilename(img_url) + '\',\'' + theme_id + '\');"> delete file </a> ]</span>';
		else clearText(link_div);
		
	// clear the upload field
	var uploadoptions_div = document.getElementById('upload_options_' + theme_id + '_' + option_id);
}

// Refresh Custom Upload Body
// Called anytime a change is made to the upload file field of a custom option. If a filename is in the field,
// we want to display options for that filename before upload. If nothing is in the field, we want to hide the
// upload-specific options.
function refreshCustomUploadBody(option_id, theme_id) {
	var upload_obj = document.getElementById('uploadimg_' + theme_id + '_' + option_id);
	var uploadoptions_div = top.document.getElementById('upload_options_' + theme_id + '_' + option_id);
	if (upload_obj.value != '') {
		var send_data = 'do=load_upload_options&theme_id=' + theme_id + '&option_id=' + option_id + '&filename=' + escape(upload_obj.value);
		var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
		fetchData(url,send_data,'upload_options_' + theme_id + '_' + option_id);
	} else {
		clearText(uploadoptions_div);
	}
}


// Select Theme
// User has selected to set a theme and color scheme to his website
function selectTheme(theme_id, default_color_id) {
	var color_id = '';
	if (stored_color_scheme[theme_id]) color_id = stored_color_scheme[theme_id];
	   else color_id = default_color_id;

	request = createRequest();
	
	// response handler
	request.onreadystatechange=function() {
		if (request.readyState < 4) {
			var selectdiv = document.getElementById("selectindicator_" + theme_id);
//selectdiv.innerHTML='<span class="ajaxmessage">Publishing...</span>';
			var newdiv = document.createElement("span");
			var newtext = document.createTextNode("Publishing...");
			clearText(selectdiv);
			newdiv.appendChild(newtext);
			newdiv.setAttribute("class", "ajaxmessage");
			newdiv.setAttribute("className", "ajaxmessage"); // fix for IE wierdness
			selectdiv.appendChild(newdiv);
			// ---
		} else if (request.readyState == 4) {
			if (request.status == 200) {
				if (request.responseText != 'OK') alert("There was a problem publishing your website: \n" + request.responseText);
				
				// reset previous select/update link
				var linkdiv = document.getElementById("select_label_" + stored_theme);
				if (linkdiv != null) {
					replaceText(linkdiv, "Select Design");
				}
				// modify new select/update link
				linkdiv = document.getElementById("select_label_" + theme_id);
				if (linkdiv != null) {
					replaceText(linkdiv, "Update");
				}
				// turn off any previous indicator
				var olddiv = document.getElementById("selectindicator_" + stored_theme);
				if (olddiv != null) clearText(olddiv);
				
				// turn on selected indicator since this is a selected color scheme and theme
				var selectdiv = document.getElementById("selectindicator_" + theme_id);
//				clearText(selectdiv);
//				var selectimg = document.createElement("img");
//				selectimg.setAttribute("src", "/images/selectcheck.gif");
//				selectdiv.appendChild(selectimg);
				selectdiv.innerHTML = '<span class="new"><strong>Design Selected</strong> <input type="checkbox" checked disabled></span>';
				
				// update the global variables
				stored_color_scheme[theme_id] = color_id;
				stored_selected_color = color_id;
				stored_theme = theme_id;
			} else {
				alert("Error: Request status is " + request.status);
			}
		}
	}
	
	
	// send request
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var dataToSend = 'do=select_theme&theme_id=' + theme_id + '&color_id=' + color_id;
	
	request.open('POST',url,true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(dataToSend);
}

// Upload Custom Image
function uploadCustomImage(option_id, theme_id) {
	var framedoc = getFrameDocument('iframe_' + theme_id + '_' + option_id); // get a handle to the frame
	var upload_obj = framedoc.getElementById('uploadimg_' + theme_id + '_' + option_id); //get a handle to the file upload field
	
	// add the selected crop method to the form
	var radiogroup = document.getElementsByName('heightresolve_' + theme_id + '_' + option_id);
	var selected_value;
	for (i=0; i<radiogroup.length; i++){
		if (radiogroup[i].checked==true){
			selected_value=radiogroup[i].value;
			break;
		}
	}	
	framedoc.forms[0].heightresolve.value = selected_value; // set the frame form's hidden value for the crop method
	
	// start the graphical progress indicator
	var progressicon = document.createElement("img");
	progressicon.setAttribute("src", "/images/indicator.gif");
	var container_div = document.getElementById('deletelink_' + theme_id + '_' + option_id);
	clearText(container_div);
	container_div.appendChild(progressicon);
	
	// submit the form
	framedoc.forms[0].submit();
	
}

// Get Frame Document
// Returns a handle to the document inside a frame or iframe. Accepts the ID of a frame as the parameter
// Compatible with: 
// - Internet Explorer 6 (Win), 5.5 (Win), and higher
// - Mozilla 1.7.5 (all) - Firefox 1.0, Camino 0.8, K-Meleon 0.9, etc.
// - Safari 1.2.4
// - Opera 7.54 (Win)
function getFrameDocument(frameid) {
  var oIframe = document.getElementById(frameid);
  var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
  if (oDoc.document)
    oDoc = oDoc.document;
  return oDoc;
}

// Add Option
// Adds an option to a dropdown menu.
// menu_id - the id of the dropdown menu
// text - text to display for the new option
// value - option value
function addOption(menu_id,text,value) {
	var selectbox = document.getElementById(menu_id);
	var optn = document.createElement("OPTION");
	selectbox.options[selectbox.options.length] = new Option(text,value);
	selectbox.options[(selectbox.options.length - 1)].selected = true;
}

// URL to Filename
// Given a URL or path to a file, returns just the filename portion
function urlToFilename(url) {
	var url_array=url.split("/");
	return url_array[(url_array.length - 1)];
}

// Delete Uploaded File
// Given a filename, sends a request to the server to delete the file.
function deleteUploadedFile(filename, theme_id) {
	request = createRequest();
	var div_to_load = document.getElementById("custom_body_" + theme_id);
	
	// response handler
	request.onreadystatechange=function() {
		if (request.readyState == 4) {
			if (request.status == 200) {
		
				// refresh custom body div
				clearText(div_to_load);
				div_to_load.innerHTML = request.responseText;
			} else {
				alert("Error: Request status is " + request.status);
			}
		}
	}
	
	// clear the div
	div_to_load.innerHTML = '<span class="ajaxmessage">Loading...</span>';
	
	// send the request
	var color_id = '';
	if (stored_color_scheme[theme_id]) color_id = stored_color_scheme[theme_id];
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=delete_custom_image&theme_id=' + theme_id + '&color_id=' + color_id + '&filename=' + filename;
	
	request.open('POST',url,true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(send_data);
}

// Apply Changes
// Save the selected custom options as this theme's settings.
// Parameters:
// theme_id - the ID of the theme that is being saved
// num_options - the number of displayed options for this theme
function applyChanges(theme_id, color_id, num_options) {
	request = createRequest();
	
	// start the progress indicator
	var feedback_div = document.getElementById('feedback_' + theme_id);
	var progressicon = document.createElement("img");
	progressicon.setAttribute("src", "/images/indicator.gif");
	clearText(feedback_div);
	feedback_div.appendChild(progressicon);
	
	// post the "publishing" message
	var publishing_div = document.getElementById("selectindicator_" + theme_id);
	publishing_div.innerHTML='<span class="ajaxmessage">Publishing...</span>';
	
	// response handler
	request.onreadystatechange=function() {
		if (request.readyState == 4) {
			if (request.status == 200) {
				// modify new select/update link
				linkdiv = document.getElementById("select_label_" + theme_id);
				if (linkdiv != null) {
					replaceText(linkdiv, "Update");
				}
				
				// turn off any previous indicator
				var olddiv = document.getElementById("selectindicator_" + stored_theme);
				if (olddiv != null) clearText(olddiv);
				
				// update the global variables
				stored_color_scheme[theme_id] = color_id;
				stored_selected_color = color_id;
				stored_theme = theme_id;
				
				// post feedback
				 postTempMessage('feedback_' + theme_id, request.responseText, 5) ; //post a temporary feedback message lasting 5 seconds
				 publishing_div.innerHTML = '<span class="new"><strong>Design Selected</strong> <input type="checkbox" checked disabled></span>';  // indicate this theme is selected
			} else {
				alert("Error: Request status is " + request.status);
			}
		}
	}
	
	// send the request
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=apply_changes&theme_id=' + theme_id + '&color_id=' + color_id;
	
	// get the option selections
	for (i=1; i <= num_options; i++) {
		var dropdown = document.getElementById('existingimg_' + theme_id + '_' + i);
		var this_value = dropdown.options[dropdown.selectedIndex].value;
		this_value = escape(this_value);
		
		send_data = send_data + ('&existingimg_' + theme_id + '_' + i + '=' + this_value);
	}
	
	// get the font selections
	var title_font = document.getElementById('title_font_' + theme_id);
	  var title_font_value = title_font.options[title_font.selectedIndex].value;
	var couple_font = document.getElementById('couple_font_' + theme_id);
	  var couple_font_value = couple_font.options[couple_font.selectedIndex].value;
	var date_font = document.getElementById('date_font_' + theme_id);
	  var date_font_value = date_font.options[date_font.selectedIndex].value;
	var header_font = document.getElementById('header_font_' + theme_id);
	  var header_font_value = header_font.options[header_font.selectedIndex].value;
	var title_size = document.getElementById('title_size_' + theme_id);
	  var title_size_value = title_size.options[title_size.selectedIndex].value;
	var couple_size = document.getElementById('couple_size_' + theme_id);
	  var couple_size_value = couple_size.options[couple_size.selectedIndex].value;
	var date_size = document.getElementById('date_size_' + theme_id);
	  var date_size_value = date_size.options[date_size.selectedIndex].value;
	var header_size = document.getElementById('header_size_' + theme_id);
	  var header_size_value = header_size.options[header_size.selectedIndex].value;
	send_data = send_data + ('&title_font' + '=' + title_font_value + '&couple_font' + '=' + couple_font_value + '&date_font' + '=' + date_font_value + '&header_font' + '=' + header_font_value);
	send_data = send_data + ('&title_size' + '=' + title_size_value + '&couple_size' + '=' + couple_size_value + '&date_size' + '=' + date_size_value + '&header_size' + '=' + header_size_value);
	
	// get the color options
	if (document.getElementById('stored_c1_theme' + theme_id) != null)  {
		if (document.getElementById('highestcolornum_' + theme_id + '_' + color_id) != null) var highestcolornum = document.getElementById('highestcolornum_' + theme_id + '_' + color_id).value;
			else var highestcolornum = '0';

		for (var counter = 0; counter <= highestcolornum; counter++) {
			if (document.getElementById('stored_c' + counter + '_theme' + theme_id) != null)
				send_data = send_data + ('&c' + counter + '=' + document.getElementById('stored_c' + counter + '_theme' + theme_id).value);
		}
		send_data = send_data + '&highestcolornum=' + highestcolornum;
	}
	
	request.open('POST',url,true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(send_data);
}

// Reset Defaults
// Resets defaults, or removes any records set for custom images
// Parameters:
// theme_id - the ID of the theme that is being saved
// color_id - the ID of the selected color
function resetDefaults(theme_id, color_id) {
	request = createRequest();
	var div_to_load = document.getElementById("custom_body_" + theme_id);

	// response handler
	request.onreadystatechange=function() {
		if (request.readyState == 4) {
			if (request.status == 200) {
				// refresh custom body div
				clearText(div_to_load);
				div_to_load.innerHTML = request.responseText;
			} else {
				alert("Error: Request status is " + request.status);
			}
		}
	}
	
	// send the request
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=reset_defaults&theme_id=' + theme_id + '&color_id=' + color_id;
	request.open('POST',url,true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(send_data);
}

// empty function so that the design page's color picker will be compatible with the e-Stationery's
function refreshPreview(site_id) {

	
}

// Sets the given color to the color scheme's default
function resetColorToSchemeDefault(site_id, color_id, color_number, field_id) {
	var url = '/sitebuilder/controlpanel/colorandtheme.ajaxsocket.php';
	var send_data = 'do=get_default_color&site_id=' + site_id + '&color_number=' + color_number + '&color_id=' + color_id;
	
	// send the request to the server
	request = createRequest();
	request.onreadystatechange=function() {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var newcode = request.responseText;
				document.getElementById('stored_c' + field_id).value = newcode;
				document.getElementById('imgbox' + field_id).innerHTML = '<table width="15" height="15" cellpadding="0" cellspacing="0" border="1" bordercolor="#B0C4DE"><tr><td bgcolor="#' + newcode + '"></td></tr></table>';
			} else {
				alert("Error: Request status is " + request.status);
			}
		}
	}
	request.open('POST',url,true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(send_data);
}




