var N4 = document.layers?true:false;
var DOM2 = document.getElementById?true:false;

function ShowLayer(livello)
{
	var livelloNas=N4?document.layers[livello]:DOM2?document.getElementById(livello).style:document.all[livello].style;
	/*livelloNas.visibility="visible";*/
	livelloNas.display="block";
}
		
function HideLayer(livello)
{
	var livelloMostra=N4?document.layers[livello]:DOM2?document.getElementById(livello).style:document.all[livello].style;
	/*livelloMostra.visibility="hidden";*/
	livelloMostra.display="none";
}

function checkCellulare(phoneNo)
{
	var phoneRE = /^\+\d{12}$/;
	if (phoneNo.match(phoneRE))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function verifica()
{
	var form, ok;
	ok = true;
	form = document.contatti;
	
	HideLayer("cognomeErr");
	if (form.cognome.value == "")
	{
		ok = false;
		ShowLayer("cognomeErr");
	}
		
	/*HideLayer("telErr");
	if (form.tel.value != "")
	{
		var telefonoRE = /^\d{8,12}$/;
		var telefonoNo = form.tel.value;
		if (!telefonoNo.match(telefonoRE))
		{
			ok = false;
			ShowLayer("telErr");
		}
	}*/
	
	HideLayer("emailErr");
	if (form.email.value != "")
	{
		var emailRE = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
		var email = form.email.value;
		if (!email.match(emailRE))
		{
			ok = false;
			ShowLayer("emailErr");
		}
	}
	
	HideLayer("privacyErr");
	if (!form.privacy[0].checked)
	{
		ok = false;
		ShowLayer("privacyErr");
	}
	
	if (ok==true)
	{
		//alert("Andiamo avanti");
		form.submit();
	}
	else
		alert("Attenzione: ricontrolla attentamente i dati inseriti");
		
}

function showImage(img,desc,w,h,s)
{
	winImage = window.open("","Image","toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars="+s+",resizable=no,innerWidth="+w+",innerHeight="+h+",left=10,top=10");
	winImage.document.writeln("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
	winImage.document.writeln("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
	winImage.document.writeln("<head>");
	winImage.document.writeln("<title>"+desc+"<\/title>");
	winImage.document.writeln("<\/head>");
	winImage.document.writeln("<body  style=\"margin:0px;\">");
	winImage.document.writeln("<a href=\"#\" onclick=\"window.close();\"><img src=\""+img+"\" border=\"0\" alt=\"Click per uscire\" \/><\/a>");
	winImage.document.writeln("<\/body><\/html>");
	winImage.document.close();
}


/*****************************************
*  lista localita'
*****************************************/
function Elenca(id)
{
    var e = document.getElementById(id);
    var a = document.getElementById("LISTA").getElementsByTagName("span");
    if (e.style.display != "Block")
    {
        for (var i=0; i<a.length; i++)
        {
            if (a[i].className == "VOCI")
            {
                a[i].style.display = "None";
            }
        }
        e.style.display = "Block";
    }
    else
    {
        e.style.display = "None";
    }
}

/*****************************************
* Google maps
*****************************************/

//<![CDATA[

var gmarkers = [];
var htmls = [];

function load() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.setCenter(new GLatLng(-16.171875, 45.089035564831036), 1);
	}
}

function changeGPoint(long,lat,zoomlevel,name) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.setCenter(new GLatLng(lat,long), zoomlevel);
		var icon = new GIcon();
		icon.image = "img/icons/boat.png";
		icon.shadow = "img/icons/boat_shadow.png";
		icon.iconSize = new GSize(13, 20);
		icon.shadowSize = new GSize(18, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);	
		GDownloadUrl("markers/"+name+".xml", function(data, responseCode) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			var e = document.getElementById("localita");
			var listalocalita="<table>\n";
			for (var i = 0; i < markers.length; i++) {
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
				map.addOverlay(createMarker(point,markers[i].getAttribute("city"),i,icon));
				if (i%4==0) {
					listalocalita+="\t<tr>\n";
				}
				listalocalita+="\t\t<td><a href=\"javascript:myclick(" + i + ")\">"+markers[i].getAttribute("city")+"</a></td>\n";
				if (i%4==3) {
					listalocalita+="\t</tr>\n";
				}
			}
			if (i%4==2) {
				listalocalita+="\t\t<td>&nbsp;</td>\n\t</tr>\n";
			} else if (i%4==1) {
				listalocalita+="\t\t<td>&nbsp;</td>\n\t\t<td>&nbsp;</td>\n\t</tr>\n";
			} else if (i%4==0) {
				listalocalita+="\t\t<td>&nbsp;</td>\n\t\t<td>&nbsp;</td>\n\t\t<td>&nbsp;</td>\n\t</tr>\n";
			} 
			listalocalita+="</table>\n";
			e.innerHTML = listalocalita;
		});
	}
}



// Creates a marker at the given point with the given number label
function createMarker(point, city, i, icon) {
	var marker = new GMarker(point, icon);
	var html = "<b>" + city + "</b>";
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	gmarkers[i] = marker;
	htmls[i] = html;
	return marker;
}

function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

//]]>


/**************************************
Calendario
**************************************/

function Calendar (cname, id, date)
{
	// Used to notify the calendar that it is attached to a single html field.
	this.fallback_single = 0;
	
	// Used to notify the claendar that it is attached to 3 html fields.
	this.fallback_multi = 1;
	
	// Used to notify the calendar that it is attached to both field sets.
	this.fallback_both = 2;
	
	// Read-only calendar
	this.viewOnly = false;
	
	// Allows the user to select weekends
	this.allowWeekends = true;
	
	// Allows the user to select weekdays
	this.allowWeekdays = true;
	
	// The minimum date that the user can select (inclusive)
	this.minDate = "--";
	
	// The maximum date that the user can select (exclusive)
	this.maxDate = "--";
	
	// Allow the user to scroll dates
	this.scrolling = true;
	
	// The id of this calendar
	this.name = cname;
	
	// The first day of the week in the calendar (0-Sunday, 6-Saturday)
	this.firstDayOfWeek = 0;
	
	// Fallback method
	this.fallback = this.fallback_both;
	
	// Sets the date and strips out time information
	this.calendarDate = date;
	this.calendarDate.setUTCHours(0);
	this.calendarDate.setUTCMinutes(0);
	this.calendarDate.setUTCSeconds(0);
	this.calendarDate.setUTCMilliseconds(0);
	
	// The field id that the calendar is attached to.
	// For single input, this is used "as is". for the
	// Multi-input, it is given a suffix for _day, _month
	// and _year inputs.
	this.attachedId = id;
	
	// The left and right month control icons
	this.controlLeft = "&#171;";
	this.controlRight = "&#187;";
		
	// The left and right month control icons (when disabled)
	this.controlLeftDisabled = "";
	this.controlRightDisabled = "";
	
	// The css classes for the calendar and header
	this.calendarStyle = "cal_calendar";
	this.headerStyle = "cal_header";
	this.headerCellStyle = "cal_cell";
	this.headerCellStyleLabel = "cal_labelcell";
	
	// The css classes for the rows
	this.weekStyle = "cal_week";
	this.evenWeekStyle = "cal_evenweek";
	this.oddWeekStyle = "cal_oddweek";
	
	// The css classes for the day elements
	this.dayStyle = "cal_day";
	this.disabledDayStyle = "cal_disabled";
	this.commonDayStyle = "cal_common";
	this.holidayDayStyle = "cal_holiday";
	this.eventDayStyle = "cal_event";
	this.todayDayStyle = "cal_today";
	
	// specifies the labels for this calendar
	// this.dayLabels = new Array("Sun", "Mon", "Thu", "Wed", "Tue", "Fri", "Sat");
	this.dayLabels = new Array("Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab");
	/*this.monthLabels = new Array(
		"January", "February", "March", "April"
		, "May", "June", "July", "August"
		, "September", "October", "November", "December");*/
	this.monthLabels = new Array(
		"Gennaio", "Febbraio", "Marzo", "Aprile"
		, "Maggio", "Giugno", "Luglio", "Agosto"
		, "Settembre", "Ottobre", "Novembre", "Dicembre");
	
	// Specifies the dates of any event. The events are to be defined as arrays,
	// with element 0 being the date and element 1 being an id.
	this.eventDates = new Array();
	
	// Attach event handlers to any fallback fields.
	if (this.viewOnly == false) {
	
		setFieldValue(this.attachedId, this.calendarDate);
		
		if ((this.fallback = this.fallback_both) || (this.fallback = this.fallback_single)) {
			eval("document.getElementById(\"" + this.attachedId + "\").onchange = function () {updateFromSingle("+this.name+", this);}");
		}

		if ((this.fallback = this.fallback_both) || (this.fallback = this.fallback_multi)) {

			eval("document.getElementById(\"" + this.attachedId + "_day\").onchange = function () {updateFromMultiDay("+this.name+", this);}");
			eval("document.getElementById(\"" + this.attachedId + "_month\").onchange = function () {updateFromMultiMonth("+this.name+", this);}");
			eval("document.getElementById(\"" + this.attachedId + "_year\").onchange = function () {updateFromMultiYear("+this.name+", this);}");
			
		}
	} 
	
	selectEvent = new Function();
}

function updateFromSingle (sender, helper) {
	newDate = new Date (helper.value);
	newDate.setUTCDate(newDate.getUTCDate()+1);
	sender.calendarDate = newDate;

	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiDay (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCDate();
		return false;
	}

	sender.calendarDate.setUTCDate(helper.value);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiMonth (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCMonths() -1;
		return false;
	}
	
	sender.calendarDate.setUTCMonth(helper.value-1);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiYear (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCFullYear();
		return false;
	}
	
	sender.calendarDate.setUTCFullYear(helper.value);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function getFirstCalendarDate (calendar)
{
	return new Date (
		calendar.calendarDate.getUTCFullYear()
		, calendar.calendarDate.getUTCMonth()
		, 1
	);
}

function renderCalendar (calendar)
{
	calHtml1 =  ("<table id=\"cal_" + calendar.attachedId + "\" class=\"" + calendar.calendarStyle +"\">");
	calHtml1 += ((calendar.scrolling)?buildHeader(calendar):buildStaticHeader(calendar));
	calHtml1 += buildCalendarTable (calendar);
	calHtml1 += ("</table>");
	
	document.getElementById("cal_" + calendar.attachedId + "_display").innerHTML = calHtml1;
}

function scrollMonthBack (calendar)
{
	calendar.calendarDate.setUTCMonth(calendar.calendarDate.getUTCMonth() - 1);
	setFieldValue(calendar.attachedId, calendar.calendarDate);
	renderCalendar (calendar);
}

function selectDate (calendar, day)
{
	if (!calendar.viewOnly) {
		calendar.calendarDate.setUTCDate(day);
		setFieldValue(calendar.attachedId, calendar.calendarDate);
		renderCalendar (calendar);
	}
}

function scrollMonthForward (calendar)
{
	calendar.calendarDate.setUTCMonth(calendar.calendarDate.getUTCMonth() + 1);
	setFieldValue(calendar.attachedId, calendar.calendarDate);
	renderCalendar (calendar);
}

function setFieldValue(fieldId, date) {
	document.getElementById(fieldId).value = date.getUTCFullYear() + "/" + (date.getUTCMonth()+1) + "/" + date.getUTCDate();
	document.getElementById(fieldId + "_year").value = date.getUTCFullYear();
	document.getElementById(fieldId + "_month").selectedIndex = date.getUTCMonth();
	document.getElementById(fieldId + "_day").value = date.getUTCDate();
}

function buildHeader (calendar)
{

	enableLeft = true;
	enableRight = true;
	
	if (calendar.minDate != "--") 
	{
		if (calendar.calendarDate.getUTCFullYear() <= calendar.minDate.getUTCFullYear())
		{
			if (calendar.calendarDate.getUTCMonth() <= calendar.minDate.getUTCMonth())
			{
				enableLeft = false;
			}
		}
	}

	if (calendar.maxDate != "--") 
	{
		if (calendar.calendarDate.getUTCFullYear() >= calendar.maxDate.getUTCFullYear())
		{
			if (calendar.calendarDate.getUTCMonth() >= calendar.maxDate.getUTCMonth())
			{
				enableRight = false;
			}
		}
	}

	calHtml2 = "";
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">");
	calHtml2 +=  (
		"<td class=\""
		+ calendar.headerCellStyle
		+ ((enableLeft)?("\" onclick=\"scrollMonthBack(" + calendar.name + ")"):"")
		+ "\">"
		+ ((enableLeft)?calendar.controlLeft:calendar.controlLeftDisabled)
		+ "</td>");
	calHtml2 +=  (
		"<td colspan=\"5\" class=\""
		+ calendar.headerCellStyleLabel
		+ "\">"
		+ calendar.monthLabels[calendar.calendarDate.getUTCMonth()] 
		+ ", " + calendar.calendarDate.getUTCFullYear()
		+ "</td>");
	calHtml2 +=  (
		"<td class=\""
		+ calendar.headerCellStyle
		+ ((enableRight)?("\" onclick=\"scrollMonthForward(" + calendar.name + ")"):"")
		+ "\">"
		+ ((enableRight)?calendar.controlRight:calendar.controlRightDisabled)
		+ "</td>");
	
	calHtml2 += ("</tr>");
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">")

	for (i = 0; i < 7; i++) {
		showDay = i + calendar.firstDayOfWeek;
		if (showDay > 6) showDay = showDay - 7;
		calHtml2 +=  (
			"<td class=\""
			+ calendar.headerCellStyle
			+ "\">"
			+ calendar.dayLabels[showDay]
			+ "</td>");
	}

	calHtml2 += ("</tr>");
	return calHtml2
}

function buildStaticHeader (calendar)
{
	calHtml2 = "";
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">");
	calHtml2 +=  (
		"<td colspan=\"7\" class=\""
		+ calendar.headerCellStyleLabel
		+ "\">"
		+ calendar.monthLabels[calendar.calendarDate.getUTCMonth()] 
		+ ", " + calendar.calendarDate.getUTCFullYear()
		+ "</td>");	
	calHtml2 += ("</tr>");
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">")

	for (i = 0; i < 7; i++) {
		showDay = i + calendar.firstDayOfWeek;
		if (showDay > 6) showDay = showDay - 7;
		calHtml2 +=  (
			"<td class=\""
			+ calendar.headerCellStyle
			+ "\">"
			+ calendar.dayLabels[showDay]
			+ "</td>");
	}

	calHtml2 += ("</tr>");
	return calHtml2
}




function RenderDayDisabled (calendar, currentDate)
{
	calHtml += ('<td class="day">');
	calHtml += ("<span class=\"" + calendar.disabledDayStyle + "\">");
	calHtml += (currentDate.getUTCDate());
	calHtml += ("</span>");
	calHtml += ("</td>");
}

function RenderDayEnabled (calendar, currentDate, dayStyle)
{
	currentDayStyle = dayStyle;
	calHtml += ('<td class="day">');
	calHtml += ("<span class=\"" + dayStyle + "\" onclick=\"selectDate(" + calendar.name + ", " + currentDate.getUTCDate() + ")\">");
	calHtml += (currentDate.getUTCDate());
	calHtml += ("</span>");
	calHtml += ("</td>");
}

function RenderDayEvent (calendar, currentDate, dayStyle, eventId)
{
	currentDayStyle = dayStyle;
	calHtml += ('<td class="day">');
	calHtml += ("<span class=\"" + dayStyle + "\" onclick=\"selectDate(" + calendar.name + ", " + currentDate.getUTCDate() + "); " + calendar.name + ".selectEvent('" + eventId + "')\">");
	calHtml += (currentDate.getUTCDate());
	calHtml += ("</span>");
	calHtml += ("</td>");
}

function buildCalendarTable (calendar)
{
	currentDate = getFirstCalendarDate(calendar);
	odd = 0;
	while (currentDate.getUTCDay() != calendar.firstDayOfWeek)
	{
		currentDate.setUTCDate(currentDate.getUTCDate() - 1);
	}

	calHtml = "";
	do
	{
		odd += 1;

		calHtml +=  (
			"<tr class=\"" + (((odd%2)==0) ? calendar.evenWeekStyle : calendar.oddWeekStyle) + "\">")

		for (i = 0;i < 7;i++)
		{
			currentDayStyle = calendar.dayStyle;
			currentEventStyle = calendar.commonDayStyle;
			currentDateString = currentDate.getUTCFullYear() + "/" + (currentDate.getUTCMonth()+1) + "/" + currentDate.getUTCDate();

			if (currentDate < calendar.minDate) 
			{
				RenderDayDisabled (calendar, currentDate);
			} 
			else if (currentDate > calendar.maxDate) 
			{
				RenderDayDisabled (calendar, currentDate);
			} 
			else if (currentDate.getUTCMonth() != calendar.calendarDate.getUTCMonth())
			{
				RenderDayDisabled (calendar, currentDate);
			}
			else if (currentDate.getUTCDate() == calendar.calendarDate.getUTCDate())
			{
				if ((currentDate.getUTCDay() == 0) || (currentDate.getUTCDay() == 6))
				{
					if (calendar.allowWeekends == true)
					{
						RenderDayEnabled (calendar, currentDate, calendar.todayDayStyle);
					} 
					else 
					{
						RenderDayDisabled (calendar, currentDate);	
						month = calendar.calendarDate.getUTCMonth();
						calendar.calendarDate.setUTCDate(calendar.calendarDate.getUTCDate()+1);
						if (month != calendar.calendarDate.getUTCMonth())
						{
							renderCalendar(calendar);
						}
						setFieldValue(calendar.attachedId, calendar.calendarDate);
					}
				} else {
					if (calendar.allowWeekdays == true)
					{
						RenderDayEnabled (calendar, currentDate, calendar.todayDayStyle);
					} 
					else 
					{
						RenderDayDisabled (calendar, currentDate);	
						month = calendar.calendarDate.getUTCMonth();
						calendar.calendarDate.setUTCDate(calendar.calendarDate.getUTCDate()+1);
						if (month != calendar.calendarDate.getUTCMonth())
						{
							renderCalendar(calendar);
						}
						setFieldValue(calendar.attachedId, calendar.calendarDate);
					}
				}
			}
			else if ((currentDate.getUTCDay() == 0) || (currentDate.getUTCDay() == 6))
			{
				if (calendar.allowWeekends == true)
				{
				
					style = calendar.holidayDayStyle
					
					for (j=0; j < calendar.eventDates.length; j++)
					{
						if (calendar.eventDates[j][0] == currentDateString) 
						{
							style = calendar.eventDayStyle;
							RenderDayEvent (calendar, currentDate, style, calendar.eventDates[j][0]);
						}
					}
					
					if (style == calendar.holidayDayStyle)
					{
						RenderDayEnabled (calendar, currentDate, style);
					}
				} 
				else 
				{
					RenderDayDisabled (calendar, currentDate);	
				}
			} else {
				if (calendar.allowWeekdays == true)
				{
					style = calendar.commonDayStyle

					for (j=0; j < calendar.eventDates.length; j++)
					{
						if (calendar.eventDates[j][0] == currentDateString) 
						{
							style = calendar.eventDayStyle;
							RenderDayEvent (calendar, currentDate, style, calendar.eventDates[j][0]);
						}
					}

					if (style == calendar.commonDayStyle)
					{
						RenderDayEnabled (calendar, currentDate, style);
					}
				} 
				else 
				{
					RenderDayDisabled (calendar, currentDate);	
				}
			}

			currentDate.setUTCDate(currentDate.getUTCDate() + 1);	
		}
		
		calHtml += ("</tr>");
		

	} while (currentDate.getUTCMonth() == calendar.calendarDate.getUTCMonth());
	return calHtml;
}

// lightbox_plus.js
// == written by Takuya Otani <takuya.otani@gmail.com> ===
// == Copyright (C) 2006 SimpleBoxes/SerendipityNZ Ltd. ==
/*
	Copyright (C) 2006 Takuya Otani/SimpleBoxes - http://serennz.cool.ne.jp/sb/
	Copyright (C) 2006 SerendipityNZ - http://serennz.cool.ne.jp/snz/

	This script is licensed under the Creative Commons Attribution 2.5 License
	http://creativecommons.org/licenses/by/2.5/

	basically, do anything you want, just leave my name and link.
*/
/*
	Original script : Lightbox JS : Fullsize Image Overlays
	Copyright (C) 2005 Lokesh Dhakar - http://www.huddletogether.com
	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/
*/
// ver. 20060131 - fixed a bug to work correctly on Internet Explorer for Windows
// ver. 20060128 - implemented functionality of echoic word
// ver. 20060120 - implemented functionality of caption and close button
// === utilities ===
function addEvent(object, type, handler)
{
	if (object.addEventListener) {
		object.addEventListener(type, handler, false);
	} else if (object.attachEvent) {
		object.attachEvent(['on',type].join(''),handler);
	} else {
		object[['on',type].join('')] = handler;
	}
}
function WindowSize()
{ // window size object
	this.w = 0;
	this.h = 0;
	return this.update();
}
WindowSize.prototype.update = function()
{
	var d = document;
	this.w =
	  (window.innerWidth) ? window.innerWidth
	: (d.documentElement && d.documentElement.clientWidth) ? d.documentElement.clientWidth
	: d.body.clientWidth;
	this.h =
	  (window.innerHeight) ? window.innerHeight
	: (d.documentElement && d.documentElement.clientHeight) ? d.documentElement.clientHeight
	: d.body.clientHeight;
	return this;
};
function PageSize()
{ // page size object
	this.win = new WindowSize();
	this.w = 0;
	this.h = 0;
	return this.update();
}
PageSize.prototype.update = function()
{
	var d = document;
	this.w =
	  (window.innerWidth && window.scrollMaxX) ? window.innerWidth + window.scrollMaxX
	: (d.body.scrollWidth > d.body.offsetWidth) ? d.body.scrollWidth
	: d.body.offsetWidt;
	this.h =
	  (window.innerHeight && window.scrollMaxY) ? window.innerHeight + window.scrollMaxY
	: (d.body.scrollHeight > d.body.offsetHeight) ? d.body.scrollHeight
	: d.body.offsetHeight;
	this.win.update();
	if (this.w < this.win.w) this.w = this.win.w;
	if (this.h < this.win.h) this.h = this.win.h;
	return this;
};
function PagePos()
{ // page position object
	this.x = 0;
	this.y = 0;
	return this.update();
}
PagePos.prototype.update = function()
{
	var d = document;
	this.x =
	  (window.pageXOffset) ? window.pageXOffset
	: (d.documentElement && d.documentElement.scrollLeft) ? d.documentElement.scrollLeft
	: (d.body) ? d.body.scrollLeft
	: 0;
	this.y =
	  (window.pageYOffset) ? window.pageYOffset
	: (d.documentElement && d.documentElement.scrollTop) ? d.documentElement.scrollTop
	: (d.body) ? d.body.scrollTop
	: 0;
	return this;
};
function UserAgent()
{ // user agent information
	var ua = navigator.userAgent;
	this.isWinIE = this.isMacIE = false;
	this.isGecko  = ua.match(/Gecko\//);
	this.isSafari = ua.match(/AppleWebKit/);
	this.isOpera  = window.opera;
	if (document.all && !this.isGecko && !this.isSafari && !this.isOpera) {
		this.isWinIE = ua.match(/Win/);
		this.isMacIE = ua.match(/Mac/);
		this.isNewIE = (ua.match(/MSIE 5\.5/) || ua.match(/MSIE 6\.0/));
	}
	return this;
}
// === lightbox ===
function LightBox(option)
{
	var self = this;
	self._imgs = new Array();
	self._wrap = null;
	self._box  = null;
	self._open = -1;
	self._page = new PageSize();
	self._pos  = new PagePos();
	self._ua   = new UserAgent();
	self._expandable = false;
	self._expanded = false;
	self._expand = option.expandimg;
	self._shrink = option.shrinkimg;
	return self._init(option);
}
LightBox.prototype = {
	_init : function(option)
	{
		var self = this;
		var d = document;
		if (!d.getElementsByTagName) return;
		var links = d.getElementsByTagName("a");
		for (var i=0;i<links.length;i++) {
			var anchor = links[i];
			var num = self._imgs.length;
			if (!anchor.getAttribute("href")
			  || anchor.getAttribute("rel") != "lightbox") continue;
			// initialize item
			self._imgs[num] = {src:anchor.getAttribute("href"),w:-1,h:-1,title:'',cls:anchor.className};
			if (anchor.getAttribute("title"))
				self._imgs[num].title = anchor.getAttribute("title");
			else if (anchor.firstChild && anchor.firstChild.getAttribute && anchor.firstChild.getAttribute("title"))
				self._imgs[num].title = anchor.firstChild.getAttribute("title");
			anchor.onclick = self._genOpener(num); // set closure to onclick event
		}
		var body = d.getElementsByTagName("body")[0];
		self._wrap = self._createWrapOn(body,option.loadingimg);
		self._box  = self._createBoxOn(body,option);
		return self;
	},
	_genOpener : function(num)
	{
		var self = this;
		return function() { self._show(num); return false; }
	},
	_createWrapOn : function(obj,imagePath)
	{
		var self = this;
		if (!obj) return null;
		// create wrapper object, translucent background
		var wrap = document.createElement('div');
		wrap.id = 'overlay';
		with (wrap.style) {
			display = 'none';
			position = 'fixed';
			top = '0px';
			left = '0px';
			zIndex = '50';
			width = '100%';
			height = '100%';
		}
		if (self._ua.isWinIE) wrap.style.position = 'absolute';
		addEvent(wrap,"click",function() { self._close(); });
		obj.appendChild(wrap);
		// create loading image, animated image
		var imag = new Image;
		imag.onload = function() {
			var spin = document.createElement('img');
			spin.id = 'loadingImage';
			spin.src = imag.src;
			spin.style.position = 'relative';
			self._set_cursor(spin);
			addEvent(spin,'click',function() { self._close(); });
			wrap.appendChild(spin);
			imag.onload = function(){};
		};
		if (imagePath != '') imag.src = imagePath;
		return wrap;
	},
	_createBoxOn : function(obj,option)
	{
		var self = this;
		if (!obj) return null;
		// create lightbox object, frame rectangle
		var box = document.createElement('div');
		box.id = 'lightbox';
		with (box.style) {
			display = 'none';
			position = 'absolute';
			zIndex = '60';
		}
		obj.appendChild(box);
		// create image object to display a target image
		var img = document.createElement('img');
		img.id = 'lightboxImage';
		self._set_cursor(img);
		addEvent(img,'click',function(){ self._close(); });
		addEvent(img,'mouseover',function(){ self._show_action(); });
		addEvent(img,'mouseout',function(){ self._hide_action(); });
		box.appendChild(img);
		var zoom = document.createElement('img');
		zoom.id = 'actionImage';
		with (zoom.style) {
			display = 'none';
			position = 'absolute';
			top = '15px';
			left = '15px';
			zIndex = '70';
		}
		self._set_cursor(zoom);
		zoom.src = self._expand;
		addEvent(zoom,'mouseover',function(){ self._show_action(); });
		addEvent(zoom,'click', function() { self._zoom(); });
		box.appendChild(zoom);
		addEvent(window,'resize',function(){ self._set_size(true); });
		// close button
		if (option.closeimg) {
			var btn = document.createElement('img');
			btn.id = 'closeButton';
			with (btn.style) {
				display = 'inline';
				position = 'absolute';
				right = '10px';
				top = '10px';
				zIndex = '80';
			}
			btn.src = option.closeimg;
			self._set_cursor(btn);
			addEvent(btn,'click',function(){ self._close(); });
			box.appendChild(btn);
		}
		// caption text
		var caption = document.createElement('span');
		caption.id = 'lightboxCaption';
		with (caption.style) {
			display = 'none';
			position = 'absolute';
			zIndex = '80';
		}
		box.appendChild(caption);
		// create effect image
		if (!option.effectpos) option.effectpos = {x:0,y:0};
		else {
			if (option.effectpos.x == '') option.effectpos.x = 0;
			if (option.effectpos.y == '') option.effectpos.y = 0;
		}
		var effect = new Image;
		effect.onload = function() {
			var effectImg = document.createElement('img');
			effectImg.id = 'effectImage';
			effectImg.src = effect.src;
			if (option.effectclass) effectImg.className = option.effectclass;
			with (effectImg.style) {
				position = 'absolute';
				display = 'none';
				left = [option.effectpos.x,'px'].join('');;
				top = [option.effectpos.y,'px'].join('');
				zIndex = '90';
			}
			self._set_cursor(effectImg);
			addEvent(effectImg,'click',function() { effectImg.style.display = 'none'; });
			box.appendChild(effectImg);
		};
		if (option.effectimg != '') effect.src = option.effectimg;
		return box;
	},
	_set_photo_size : function()
	{
		var self = this;
		if (self._open == -1) return;
		var imag = self._box.firstChild;
		var targ = { w:self._page.win.w - 30, h:self._page.win.h - 30 };
		var orig = { w:self._imgs[self._open].w, h:self._imgs[self._open].h };
		// shrink image with the same aspect
		var ratio = 1.0;
		if ((orig.w >= targ.w || orig.h >= targ.h) && orig.h && orig.w)
			ratio = ((targ.w / orig.w) < (targ.h / orig.h)) ? targ.w / orig.w : targ.h / orig.h;
		imag.width  = Math.floor(orig.w * ratio);
		imag.height = Math.floor(orig.h * ratio);
		self._expandable = (ratio < 1.0) ? true : false;
		if (self._ua.isWinIE) self._box.style.display = "block";
		self._box.style.top  = [self._pos.y + (self._page.win.h - imag.height - 30) / 2,'px'].join('');
		self._box.style.left = [((self._page.win.w - imag.width - 30) / 2),'px'].join('');
		self._show_caption(true);
	},
	_set_size : function(onResize)
	{
		var self = this;
		if (self._open == -1) return;
		self._page.update();
		self._pos.update();
		var spin = self._wrap.firstChild;
		if (spin) {
			var top = (self._page.win.h - spin.height) / 2;
			if (self._wrap.style.position == 'absolute') top += self._pos.y;
			spin.style.top  = [top,'px'].join('');
			spin.style.left = [(self._page.win.w - spin.width - 30) / 2,'px'].join('');
		}
		if (self._ua.isWinIE) {
			self._wrap.style.width  = [self._page.win.w,'px'].join('');
			self._wrap.style.height = [self._page.h,'px'].join('');
		}
		if (onResize) self._set_photo_size();
	},
	_show_action : function()
	{
		var self = this;
		if (self._open == -1 || !self._expandable) return;
		var obj = document.getElementById('actionImage');
		if (!obj) return;
		obj.src = (self._expanded) ? self._shrink : self._expand;
		obj.style.display = 'inline';
	},
	_hide_action : function()
	{
		var self = this;
		var obj = document.getElementById('actionImage');
		if (obj) obj.style.display = 'none';
	},
	_zoom : function()
	{
		var self = this;
		if (self._expanded) {
			self._set_photo_size();
			self._expanded = false;
		} else if (self._open > -1) {
			var imag = self._box.firstChild;
			self._box.style.top  = [self._pos.y,'px'].join('');
			self._box.style.left = '0px';
			imag.width  = self._imgs[self._open].w;
			imag.height = self._imgs[self._open].h;
			self._show_caption(false);
			self._expanded = true;
		}
		self._show_action();
	},
	_show_caption : function(enable)
	{
		var self = this;
		var caption = document.getElementById('lightboxCaption');
		if (!caption) return;
		if (caption.innerHTML.length == 0 || !enable) {
			caption.style.display = 'none';
		} else { // now display caption
			var imag = self._box.firstChild;
			with (caption.style) {
				top = [imag.height + 10,'px'].join(''); // 10 is top margin of lightbox
				left = '0px';
				width = [imag.width + 20,'px'].join(''); // 20 is total side margin of lightbox
				height = '1.2em';
				display = 'block';
			}
		}
	},
	_show : function(num)
	{
		var self = this;
		var imag = new Image;
		if (num < 0 || num >= self._imgs.length) return;
		var loading = document.getElementById('loadingImage');
		var caption = document.getElementById('lightboxCaption');
		var effect = document.getElementById('effectImage');
		self._open = num; // set opened image number
		self._set_size(false); // calc and set wrapper size
		self._wrap.style.display = "block";
		if (loading) loading.style.display = 'inline';
		imag.onload = function() {
			if (self._imgs[self._open].w == -1) {
				// store original image width and height
				self._imgs[self._open].w = imag.width;
				self._imgs[self._open].h = imag.height;
			}
			if (effect) {
				effect.style.display = (!effect.className || self._imgs[self._open].cls == effect.className)
					? 'block' : 'none';
			}
			if (caption) caption.innerHTML = self._imgs[self._open].title;
			self._set_photo_size(); // calc and set lightbox size
			self._hide_action();
			self._box.style.display = "block";
			self._box.firstChild.src = imag.src;
			self._box.firstChild.setAttribute('title',self._imgs[self._open].title);
			if (loading) loading.style.display = 'none';
		};
		self._expandable = false;
		self._expanded = false;
		imag.src = self._imgs[self._open].src;
	},
	_set_cursor : function(obj)
	{
		var self = this;
		if (self._ua.isWinIE && !self._ua.isNewIE) return;
		obj.style.cursor = 'pointer';
	},
	_close : function()
	{
		var self = this;
		self._open = -1;
		self._hide_action();
		self._wrap.style.display = "none";
		self._box.style.display  = "none";
	}
};
// === main ===


addEvent(window,"load",function() {
	var lightbox = new LightBox({
		loadingimg:'img/layout/loading.gif',
		expandimg:'img/layout/expand.gif',
		shrinkimg:'img/layout/shrink.gif',
		effectimg:'img/layout/watermark.png',
		effectpos:{x:-15,y:-15},
		effectclass:'effectable',
		closeimg:'img/layout/close.gif'
	});
});


