function goToPage(page)
{
	window.location.replace(page);
}

gBrowser = "";
function detectBrowser()
{	
	browser = navigator.appName;

	//detecting older netscapes
	if (!document.all)
		browser = "old netscape"
	else if(navigator.userAgent.indexOf("Opera") > -1)
		browser = "opera";
	else if (navigator.userAgent.indexOf("MSIE") > -1)
		browser = "ie";
	else if (navigator.appName == "Netscape" && document.all)
		browser = "netscape";
	else
		browser = "unknown";
	gBrowser = browser;
	return browser;
}


function isset(varname)
{
	res = (typeof( window[varname] ) != "undefined");
	if(res)
		return true;

	return eval("window." + varname) ? true : false;
}


function isFunction(a) 
{
	return typeof a == 'function';
}

function isObject(a) 
{
	return (typeof a == 'object' && !!a) || isFunction(a);
}

function isArray(a) 
{
	return isObject(a) && a.constructor == Array;
}



function setElementText(textObj, text)
{
	//textObj.childNodes[0] = "asd";
	if(!gBrowser)
		detectBrowser();

	//if(gBrowser == "ie" || gBrowser == "opera")
		textObj.innerHTML = text;
	/*else
	{
		//alert(newEl);
		textObj.removeChild(textObj.childNodes[0]);
		preface = textObj.childNodes[0];
		newEl = document.createElement(text);
	
		//textObj.appendChild(newEl);
		//textObj.childNodes[0].set("A");//alert(textObj.childNodes[0].setXMLValue);//textObj[0] = text;
		//alert(newEl);
	}*/
}

//////////////////
userBrowser = whichBrs();
function whichBrs()
{
	var agent = navigator.userAgent.toLowerCase();
	if(agent.indexOf("opera") != -1)				return 'Opera';
	if(agent.indexOf("staroffice") != -1)			return 'Star Office';
	if(agent.indexOf("beonex") != -1)				return 'Beonex';
	if(agent.indexOf("chimera") != -1)				return 'Chimera';
	if(agent.indexOf("netpositive") != -1)			return 'NetPositive';
	if(agent.indexOf("phoenix") != -1)				return 'Phoenix';
	if(agent.indexOf("firefox") != -1)				return 'Firefox';
	if(agent.indexOf("bonecho") != -1)				return 'Firefox';
	if(agent.indexOf("safari") != -1)				return 'Safari';
	if(agent.indexOf("skipstone") != -1)			return 'SkipStone';
	if(agent.indexOf("msie") != -1)					return 'Internet Explorer';
	if(agent.indexOf("netscape") != -1)				return 'Netscape';
	if(agent.indexOf("mozilla/5.0") != -1)			return 'Mozilla';
	if(agent.indexOf('\/') != -1)
	{
		if(agent.substr(0,agent.indexOf('\/')) != 'mozilla')
			return navigator.userAgent.substr(0,agent.indexOf('\/'));
		return 'Netscape';
	}
	else if (agent.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agent.indexOf(' '));
	else return navigator.userAgent;
}

////////////////////////

function showHideLayer(name, action)
{
	object = getElement(name);
	if(!object)
		alert("Objektet hittades inte");
	
	var state = "visible";
	if(action == "hide")
		state = "hidden";
	else if(action == "swap")
	{
		// This does not work correctly. The style attribute does only work inline (<div style="visibility: hidden;">)
		state = -1;
		state = object.style.visibility;

		if(state == -1) // No change
			return false;
		//alert(state);
		if(state == "hidden")
			state = "visible";
		else
			state = "hidden";
	}
	object.style.visibility = state;
}

function showHideLayerDisplay(name, action)
{
	object = getElement(name);
	var state = "block";
	if(action == "hide")
		state = "none";
	else if(action == "swap")
	{
		// This does not work correctly. The style attribute does only work inline (<div style="visibility: hidden;">)
		state = -1;
		state = object.style.display;

		if(state == -1) // No change
			return false;
		//alert(state);
		if(state == "none")
			state = "block";
		else
			state = "none";
	}
	object.style.display = state;
}

function getElement(name)
{
	if (document.getElementById)
		return document.getElementById(name);
	else if (document.all)
		return document.all[name];
	else if (document.layers)
		return document.layers[name];
	return -1;
}

function externalLinks()
{ 
	if (!document.getElementsByTagName)
		return; 
	
	var anchors = document.getElementsByTagName("a"); 
	for (var i = 0; i < anchors.length; i++)
	{ 
		var anchor = anchors[i]; 
		if(anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") 
			anchor.target = "_blank"; 
	}
}

var showVC = false;
var currentId = 0;

var vcPosx = 0;
var vcPosy = 0;




function ismaxlength(obj)
{
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length > mlength)
		obj.value = obj.value.substring(0, mlength);
}

function mailFormCheck(form)
{
	if(form.subject.value.length < 2)
	{
		alert("Ooops, du glömde skriva din rubrik");
		return false;
	}

	if(form.message.value.length < 2)
	{
		alert("Ooops, du glömde skriva ditt meddelande");
		return false;
	}

	if(form.contName.value.length < 2)
	{
		alert("Ooops, du glömde skriva ditt namn");
		return false;
	}

	if(form.contMail.value.length < 5)
	{
		alert("Ooops, du glömde skriva din epostadress");
		return false;
	}

	if(form.contPhone.value.length < 5)
	{
		alert("Ooops, du glömde skriva ditt telefonnummer");
		return false;
	}
	
	return true;
}


function selectImage(theImage, action, active)
{
	if(!theImage)
		return;

	if(action == "hover")
	{
		if(theImage.clicked && theImage.clicked == true)
			;
		else
			theImage.className = active ? "selected" : "";
	}
	else if(action == "click")
	{
		theImage.clicked = active ? true : false;
		theImage.className = active ? "selected" : "";
	}
}

openedBox = Array();
selectedImages = Array();
function showInfo(theImage, kind, name)
{
	obj = getElement(name);
	if(!obj)
		return;

	
	

	if(openedBox[kind] != null)
	{
		openedBox[kind].style.display = "none";
	}

	
	if(openedBox[kind] != obj)
	{
		obj.style.display = "block";
		openedBox[kind] = obj;
		selectImage(theImage, "click", 1);

		selectImage(selectedImages[kind], "click", 0);
		selectedImages[kind] = theImage;
	}
	else
	{
		obj.style.display = "none";
		openedBox[kind] = null;
		selectedImages[kind] = null;
		selectImage(theImage, "click", 0);
	}
}

// This must be called when service is changed
function clearStoredOrder()
{
	indices = Array("actIndex", "actName", "timeData", "timeName", "lengthData", "lengthName", "numParticipants", "isPackage");

	for(i = 0; i < indices.length; i++)
	{
		delete schedStoredOrder[indices[i]];
	}
}

function schedGetServiceStartTime(theParent, todayHumanDate)
{
	containerName = "serviceTimeContainer";
	
	actIndex = theParent.options[theParent.selectedIndex].value;

	if(schedStoredOrder["actIndex"] && schedStoredOrder["actIndex"] == actIndex)
		return;

	if(actIndex == -1) // Description field selected = no effect
		return;

	// Clear selection to make sure timestamps etc are not remebered if the service is changed
	clearStoredOrder();

	// Log selection
	schedStoredOrder["actIndex"] = actIndex;
	schedStoredOrder["actName"] = theParent.options[theParent.selectedIndex].text;
	schedStoredOrder["humanDateValidationText"] = todayHumanDate;
	
	sndReq("t_ajax.php", containerName, "getServiceTime", actIndex, "start");
}


// Is called when time is set to show the length options
// orderId is sent when admin are changing an order
function schedGetServiceLengthOptions(theParent, actIndex, isPackage, orderId)
{
	containerName = "serviceLengthContainer";

	if(actIndex == -1) // Description field selected = no effect
		return;
	
	selectedTime = theParent.options[theParent.selectedIndex].value;

	if(selectedTime == -1)	// Description field selected = no effect
		return;

	
	
	// Check if num participants is auto. If so, set value here
	theForm = theParent.form;
	if(theForm.numParticipants)
	{
		if(theForm.numParticipants.value == "auto")
			schedStoreNumParticipants("auto");
	}

	// Log selection
	schedStoredOrder["timeData"] = selectedTime;
	schedStoredOrder["timeName"] = theParent.options[theParent.selectedIndex].text;
	schedStoredOrder["isPackage"] = isPackage;

	if(!schedStoredOrder["lengthData"])
	{

		obj = theParent.form.orderLength;
		if(obj && isArray(obj))
			schedStoredOrder["lengthData"] = obj.options[obj.selectedIndex].value;
	}


	// lengthPreset is sent when admin are changing time - for making length stay
	lengthPreset = schedStoredOrder["lengthData"] ? schedStoredOrder["lengthData"] : -1;
	
	if(!isPackage)
		sndReq("t_ajax.php", containerName, "getServiceTime", actIndex, "length", selectedTime, orderId, lengthPreset);
}


function schedStoreLength(theParent, auto)
{
	if(auto)
	{
		schedStoredOrder["lengthData"] = theParent.lengthKey.value;
		schedStoredOrder["lengthName"] = theParent.lengthName.value;
	}
	else
	{
		schedStoredOrder["lengthData"] = theParent.options[theParent.selectedIndex].value;
		schedStoredOrder["lengthName"] = theParent.options[theParent.selectedIndex].text;
	}
}

function schedStoreNumParticipants(theParent)
{
	/*if(actIndex == -1) // Description field selected = no effect
		return;*/

	if(theParent == "auto")
	{
		schedStoredOrder["numParticipants"] = "auto";
	}
	else
	{
		schedStoredOrder["numParticipants"] = theParent.options[theParent.selectedIndex].text;
	}
	
}

function schedUpdateStartTime(theParent, serviceId, orderId)	// Admin edit order function
{
	/*alert(theParent.value);
	shedStoredOrder[theParent.id] = theParent.value;
	if(theParent.id == "month")
		shedStoredOrder[theParent.id]++;	// increase because [0] index.*/

	//alert(schedStoredOrder["timeData"]);
	//alert(schedStoredOrder["lengthData"]);

	if(!schedStoredOrder["timeData"])
	{
		obj = theParent.form.timeStart;
		if(obj)
			schedStoredOrder["timeData"] = obj.options[obj.selectedIndex].value;
	}

	containerName = "serviceTimeStartContainer";
	theForm = theParent.form;

	orderDate = theForm.year.value + "-" + (parseInt(theForm.month.value)+1) + "-" + theForm.day.value;

	sndReq("t_ajax.php", containerName, "getServiceStartTime", orderDate, serviceId, schedStoredOrder["timeData"], schedStoredOrder["lengthData"], orderId);
}

function schedValidateAdminOrder(theForm)
{	
	return true;
}

function schedValidateCustomOpen(theForm)
{
	// Make sure end is after start
	preText = "FEL: ";

	//if()

	if(parseInt(theForm.timeStart.value) >= parseInt(theForm.timeEnd.value))
	{
		alert("Sluttiden måste vara senare än starttiden!");
		return false;
	}
	return true;

}

schedStoredOrder = Array();
function schedValidateOrder(theForm)
{	
	preText = "Ordern är inte färdig, ";
	// Check if activity is selected
	if(!regAssert(schedStoredOrder["actIndex"], 0, preText + "du måste välja aktivitet"))
		return false;

	// Check if num participants is selected
	if(!regAssert(schedStoredOrder["numParticipants"], 0, preText + "du måste ange antal deltagare"))
		return false;

	// Check if time is selected
	if(!regAssert(schedStoredOrder["timeData"], 0, preText + "du måste välja tid"))
		return false;

	if(!schedStoredOrder["isPackage"])
	{
		// Check if length is selected
		
		if(theForm.lengthKey)	// Auto length
		{
			schedStoreLength(theForm, true);
		}
		
		if(!regAssert(schedStoredOrder["lengthData"], 0, preText + "du måste välja tidsperiod"))
			return false;
	}

	confirmMess = "Du har valt att boka " + schedStoredOrder["actName"] + " på ";
	confirmMess += schedStoredOrder["humanDateValidationText"];

	if(schedStoredOrder["numParticipants"] != "auto")
		confirmMess += " för " + schedStoredOrder["numParticipants"] + " personer";

	if(schedStoredOrder["isPackage"])
		confirmMess += " med start";

	confirmMess += " klockan " + schedStoredOrder["timeName"];

	if(!schedStoredOrder["isPackage"])
		confirmMess += " (" + schedStoredOrder["lengthName"] + ")";

	confirmMess += ".\nGodkänn (OK) för att slutföra denna order.";
	return confirm(confirmMess);
}

function validateOrderFinish(theForm)
{	
	// Check contact info
	if(!regAssert(theForm.contName.value != "", 0, "Du måste ange ditt namn"))
		return false;

	if(!regAssert(theForm.contMail.value != "", 0, "Du måste ange E-postadress"))
		return false;

	if(!regAssert(theForm.contPhone.value != "", 0, "Du måste ange ditt telefonnummer"))
		return false;

	if(!regAssert(theForm.acceptedRules.checked, 0, "Du måste godkänna reglerna"))
		return false;
}


function regAssert(statement, obj, message)
{
	if(statement)
		return true;


	if(obj)
	{
		resetFormElementBorders(obj.form);
		obj.borderColorOrig = obj.style.borderColor;
		obj.style.borderColor = "rgb(255,0,0)";
	}
	alert(message);
	return false;
}

function renderDynSchedule(theForm, selectedId)
{
	if(!theForm.year)
		return;

	// New date, time and length
	y = theForm.year.value;
	m = parseInt(theForm.month.value)+1;
	d = theForm.day.value;
	t = theForm.timeStart.value;
	l = theForm.orderLength ? theForm.orderLength.value : 0;

	if(theForm.lengthKey)
		l = theForm.lengthKey.value;

	


	containerName = "dynamicSchedule";
	sndReq("t_ajax.php", containerName, "renderDynSchedule", y, m, d, t, l, selectedId);
}

function pageScroll(yUnits)
{
	horUnits = 0;
    window.scrollBy(horUnits,yUnits);
}

function validateAdminCreateOrder(theForm)
{
	orderLength = theForm.orderLength.options[theForm.orderLength.selectedIndex].value;

	if(orderLength == -1)
	{
		alert("Du måste ange tidsperiod");
		return false;
	}


	confirmMess = "Vill du slutföra denna order?";
	return confirm(confirmMess);

}


function showHideChangeMail(theParent, orderId, reservationId, serviceId, action)
{
	create = orderId == 0;

	obj1 = getElement("autoChangeMail");
	obj2 = getElement("autoChangeMailAdmin");
	containerName = "changeMailContainer";
	container = getElement(containerName);
	theForm = theParent.form;


	if(!(obj1 && obj2 && container))
		return;

	// Check if one of the remove buttons is checked
	removeOrder = getElement("validateRemove");
	removeReservation = getElement("removeReservationValidate");

	if(removeOrder && removeReservation)
	{
		if(removeOrder.checked)
			action = "removeOrder";
		else if(removeReservation.checked)
			action = "removeReservation";
	}


	if(obj1.checked || obj2.checked)
	{
		// Show parent
		container.style.display = "block";

		// Collect info
		timeStart		= theForm.timeStart.value;
		orderLength = 0;
		
		if(theForm.orderLength)
			orderLength			= theForm.orderLength.value;
		else if(theForm.lengthKey)
			orderLength			= theForm.lengthKey.value;

		numParticipants = theForm.numParticipants.value;

		/*contName		= theForm.contName.value;
		contMail		= theForm.contMail.value;
		contPhone		= theForm.contPhone.value;
		extraInfo		= theForm.extraInfo.value;*/




		if(timeStart == -1)
		{
			alert("Ingen tid vald");
			return;
		}

		// Send req
		sndReq("t_ajax.php", containerName, "renderMailText", orderId, timeStart, orderLength, numParticipants, reservationId, serviceId, action);
		
	}
	else
	{
		container.style.display = "none";
	}
}


function removeBtnCB(theParent)
{
	saveBtn = getElement("submitSave");
	eraseOrderBtn = getElement("submitEraseButton");
	eraseReservationButton = getElement("removeReservationButton");
	orderSubmit = getElement("orderSubmit");

	// Show this button if hidden by another function
	if(eraseOrderBtn)
		eraseOrderBtn.style.visibility = "visible";

	// Hide irrelevant buttons
	if(saveBtn)
		saveBtn.style.visibility = theParent.checked ? "hidden" : "visible";
	if(eraseReservationButton)
		eraseReservationButton.style.visibility = theParent.checked ? "hidden" : "visible";
	if(orderSubmit)
		orderSubmit.style.visibility = theParent.checked ? "hidden" : "visible";

	args = getArgs();

	if(theParent.checked == false)
	{
		showHideChangeMail(theParent, args["id"], 0, 0, "");
		return;
	}

	// Get remove-reservation-checkbox and uncheck if checked.
	removeReservation = getElement("removeReservationValidate");
	if(removeReservation)
		removeReservation.checked = false;

	args = getArgs();
	if(args["id"])
		showHideChangeMail(theParent, args["id"], 0, 0, "removeOrder");
}

function removeReservationBtnCB(theParent, id, reservationId, serviceId)
{
	saveBtn = getElement("submitSave");
	eraseOrderBtn = getElement("submitEraseButton");
	orderSubmit = getElement("orderSubmit");
	eraseReservationButton = getElement("removeReservationButton");

	// Show this button if hidden by another function
	if(eraseReservationButton)
		eraseReservationButton.style.visibility = "visible";

	// Hide irrelevant buttons
	if(saveBtn)
		saveBtn.style.visibility = theParent.checked ? "hidden" : "visible";
	if(eraseOrderBtn)
		eraseOrderBtn.style.visibility = theParent.checked ? "hidden" : "visible";
	if(orderSubmit)
		orderSubmit.style.visibility = theParent.checked ? "hidden" : "visible";


	args = getArgs();
	if(theParent.checked == false)
	{
		showHideChangeMail(theParent, args["id"], 0, 0, "");
		return;
	}


	// Get remove-order-checkbox and uncheck if checked.
	removeOrder = getElement("validateRemove");
	if(removeOrder)
		removeOrder.checked = false;
	showHideChangeMail(theParent, id, reservationId, serviceId, 'removeReservation');
}

function listDayOrders(date)
{
	//alert("A");

	// ordersToday (div)
}



function getArgs()
{ 
	var args = new Object(); 
	var query = location.search.substring(1); 
	var pairs = query.split("&"); 
	for(var i = 0; i < pairs.length; i++)
	{ 
		pos = pairs[i].indexOf('='); 
		if(pos == -1)
			continue; 
		argname = pairs[i].substring(0,pos); 
		value = pairs[i].substring(pos+1); 
		args[argname] = unescape(value); 
	} 
	return args; 
}