var tabs = ["configurationGlobal", "configurationCaptions", "configurationControls", "configurationNavigation", "configurationNavigationCaptions", "configurationNavigationAlbumCaptions"];
var slideshowWidth = "640";
var slideshowHeight = "400";
var oldResult = "";
var updateForm = false;
var http_request = false;
var attributes = "";
var startWithAlbumID = "monokai";
//var loadingPreset = false;

if (/msie/i.test (navigator.userAgent)) //only override IE
{
	document.nativeGetElementById = document.getElementById;
	document.getElementById = function(id)
	{
		var elem = document.nativeGetElementById(id);
		if(elem)
		{
			//make sure that it is a valid match on id
			if(elem.attributes['id'].value == id)
			{
				return elem;
			}
			else
			{
				//otherwise find the correct element
				for(var i=1;i<document.all[id].length;i++)
				{
					if(document.all[id][i].attributes['id'].value == id)
					{
						return document.all[id][i];
					}
				}
			}
		}
		return null;
	};
}

addEvent(window, 'load', initSlideshow);

function addEvent(el, evnt, func) {
	if(el.addEventListener) {
		return el.addEventListener(evnt, func, false)
	} else if(el.attachEvent) {
		return el.attachEvent('on'+evnt, func)
	} else {
		return false
	}
}

function initSlideshow() {
	if (document.getElementById("configuratorForm") != null) {
		refreshSlideshow();
	}
}

function validateNumber(min, max, ref) {
	if (!isNumber(ref.value)) ref.value = min;
	if (ref.value < min) ref.value = min;
	if (ref.value > max) ref.value = max;
}

function validateNumberOrPercentage(min, max, ref) {
	if (!isNumberOrPercentage(ref.value)) ref.value = min;
	if (ref.value.charAt(ref.value.length - 1) == "%") {
		v = Number(ref.value.substr(0, ref.value.length - 1));
		if (v < 0) ref.value = "0%";
		if (v > 100) ref.value = "100%";
	} else {
		if (ref.value < min) ref.value = min;
		if (ref.value > max) ref.value = max;
	}
}

function isNumber(s) {
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c < '0' || c > '9') && !(c == '.' || c == '-')) return false;
	}
	return true;
}

function isNumberOrPercentage(s) {
	for (i = 0; i < s.length - 1; i++) {
		var c = s.charAt(i);
		if ((c < '0' || c > '9') && !(c == '.' || c == '-')) return false;
	}
	c = s.charAt(s.length - 1);
	return ((c >= '0' && c <= '9') || (c == "%"));
}

function toggleDiv(divID, caller, defaultValue) {
	var value = true;
	if (caller.checked) {
		caller.value = true;
		value = defaultValue;
	} else {
		caller.value = false;
		value = !defaultValue;
	}
	if (value) {
		document.getElementById(divID).style.display = "inline";
	} else {
		document.getElementById(divID).style.display = "none";
	}
}

function toggleBlock(divID, caller) {
	//alert(document.getElementById(divID).style.display.length);
	if (document.getElementById(divID).style.display.length == 0) {
		if (caller.className == "blockExpanded") {
			document.getElementById(divID).style.display = "block";
		} else {
			document.getElementById(divID).style.display = "none";
		}
	}
	if (document.getElementById(divID).style.display == "none") {
		caller.className = "blockExpanded";
		document.getElementById(divID).style.display = "block";
	} else {
		caller.className = "blockCollapsed";
		document.getElementById(divID).style.display = "none";
	}
}


function showTab(caller, divID) {
	for (i = 0; i < tabs.length; i++) {
		if (tabs[i] != divID) {
			document.getElementById(tabs[i]).style.display = "none";
		} else {
			document.getElementById(tabs[i]).style.display = "block";
		}
	}
	var menu = document.getElementById("configMenu");
	var anchors = menu.getElementsByTagName("a");
	if (caller == null) return;
	for (i = 0; i < anchors.length; i++) {
		if (anchors[i] == caller) {
			anchors[i].id = "selectedTab";
		} else {
			anchors[i].id = "";
		}
	}
}

function makePOSTRequest(url, parameters) {
	http_request = false;
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType("text/html");
		}
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert("Cannot create XMLHTTP instance");
		return false;
	}
	http_request.onreadystatechange = alertContents;
	http_request.open("POST", url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//http_request.setRequestHeader("Content-length", parameters.length);
	//http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}

function alertContents() {
	var msg = document.getElementById("configMessage");
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var response = http_request.responseText;
			var JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(response.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + response + ')');
			oldResult = JSON_object.xml;
			msg.innerHTML = "&nbsp;";
			//alert(response);//JSON_object.configurationVariables);
			//alert(JSON_object.configurationVariables);
			updateFlash(JSON_object.xml, JSON_object.configurationVariables);
		} else {
			// fail silently
			//alert("There was a problem with the request.");
		}
	}
}

function getValue(tag) {
	if (tag.tagName == "INPUT") {
		if (tag.type == "text" || tag.type == "hidden") {
			attributes += tag.name + "=" + tag.value + "&";
		}
		if (tag.type == "checkbox") {
			if (tag.checked) {
				attributes += tag.name + "=" + tag.value + "&";
			} else {
				attributes += tag.name + "=false&";
			}
		}
		if (tag.type == "radio") {
			if (tag.checked) {
				attributes += tag.name + "=" + tag.value + "&";
			}
		}
	}
	
	if (tag.tagName == "SELECT") {
		attributes += tag.name + "=" + tag.options[tag.selectedIndex].value + "&";
	}
	
}

function getValues(currentElem) {
	var i = 0;
	var currentElemChild = currentElem.childNodes[i];
	if (currentElem) {
		while (currentElemChild) {
			getValues(currentElemChild);
			i++;
			currentElemChild = currentElem.childNodes[i];
		}
		getValue(currentElem);
	}
}

function sendFormToPHP(p) {
	obj = document.getElementById("configuratorForm");
	attributes = p + "&";
	getValues(obj);
	makePOSTRequest("/swf/demo/v2/configurationHandler.php", attributes);
}

function updateFlash(xmlString, configurationVariables) {
	var configurationForm = document.getElementById("configuratorForm");	
	var p = configurationVariables.split("|");
	for (i = 0; i < p.length; i++) {
		v = p[i].split(">");
		if (v[0] != "") {
			if (updateForm) {
				setValue(configurationForm[v[0]], v[1]);
			}
		}
	}
	
	//if (loadingPreset) setPresetInfo();
	//alert(xmlString);
	swfobject.embedSWF(
		"/swf/demo/v2/monoslideshow_demo.swf?v=2.16",
		"monoslideshow",
		slideshowWidth, slideshowHeight,
		"10.0.0",
		false,
		{xml: escape(xmlString)},
		{allowscriptaccess: "always", allowfullscreen: "true", bgcolor: configurationForm.albumConfiguration_backgroundColor.value},
		{}
	);
	
}

function setValue(tag, val) {
	if (tag == "" || tag == null) return;
	if (tag.tagName == "INPUT") {
		if (tag.type == "text") {
			tag.value = val;
		}
		if (tag.className == "color") {
			tag.value = val;
			document.getElementById(tag.name).color.fromString(val);
		}
		if (tag.type == "checkbox") {
			if (val == "true") {
				tag.checked = true;
			} else {
				tag.checked = false;
			}
		}
		if (tag.type == "radio") {
			tag.checked = val;
		}
	}   
	if (tag.tagName == "SELECT") {
		for (var i = 0; i < tag.options.length; i++) {
			if (tag.options[i].value == val) {
				tag.selectedIndex = i;
			}
		}
	}
}

function refreshSlideshow() {
	var configurationForm = document.getElementById("configuratorForm");
	var msg = document.getElementById("configMessage");
	updateForm = false;
	msg.innerHTML = "<div class=\"loadingIcon\"></div>Refreshing slideshow...";
	configurationForm.doAction.value = "REFRESH";
	configurationForm.action = "javascript:sendFormToPHP(\'doAction=REFRESH\');";
	configurationForm.submit();
}

function loadPreset() {
	var configurationForm = document.getElementById("configuratorForm");
	var msg = document.getElementById("configMessage");
	updateForm = true;
	msg.innerHTML = "<div class=\"loadingIcon\"></div>Loading preset...";
	configurationForm.doAction.value = "LOAD_PRESET";
	configurationForm.action = "javascript:sendFormToPHP(\'doAction=LOAD_PRESET\');";
	configurationForm.submit();
}

function getXML() {
	var configurationForm = document.getElementById("configuratorForm");
	configurationForm.doAction.value = "GET_XML";
	updateForm = false;
	configurationForm.action = "/swf/demo/v2/configurationHandler.php";
	configurationForm.submit();
}

function downloadConfigurationVariables() {
	var configurationForm = document.getElementById("configuratorForm");
	configurationForm.doAction.value = "DOWNLOAD_CONFIGURATION_VARIABLES";
	updateForm = false;
	configurationForm.action = "/swf/demo/v2/configurationHandler.php";
	configurationForm.submit();
}