function suckerfish(type, tag, parentId) {
	if (window.attachEvent) {
		window.attachEvent("onload", function() {
			var sfEls = (parentId==null)?document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
			type(sfEls);
		});
	}
}


sfFocus = function(sfEls) {
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onfocus=function() {
			this.className+=" sffocus";
		}
		sfEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}
}

suckerfish(sfFocus, "INPUT");
suckerfish(sfFocus, "TEXTAREA");

function createmap() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
		 
	  map.setCenter(new GLatLng(42.883700, 12.667665),12);	  
	  map.addControl(new GSmallZoomControl());
	  map.addControl(new GMapTypeControl());
	    var point = new GPoint(12.667665, 42.883700);

		
		var mark = new GMarker(point);
			GEvent.addListener(mark, "mouseover", function() {
                       mark.openInfoWindowHtml("<p><strong>Cantina Poggio Turri</strong> <br />via Poggio Turri, 1 <br /> 06036 Montefalco (Pg)</p>");
                     });
		map.addOverlay(mark);	
      }
}	


if ('undefined' == typeof Node)
    Node = { ELEMENT_NODE: 1, TEXT_NODE: 3 };

MSG_BLANK              = ' obbligatorio/required';
MSG_NOT_A_VALID_EMAIL  = ' indirizzo non valido/address not valid';
MSG_NOT_A_DATE         = ' data errata/ wrong date';
MSG_NOT_AN_INTEGER     = ' numero non valido/not valid number';

REGEX_AUTO_FIELD = /^[^_]+(_Req)?(_(Int|Email|Date))?$/;
REGEX_BLANK = /^\s*$/;
REGEX_EMAIL = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
REGEX_DAY = /^(0?[1-9]|[1-2][0-9]|3[01])$/;
REGEX_MONTH = /^(0?[1-9]|1[0-2])$/;
REGEX_TYPED_FIELD = /_(Int|Email|Date)(_([0-9.]+))?(_([0-9.]+))?$/;
REGEX_YEAR = /^[0-9]{2,4}$/;

function addFormChecks() {
    var forms = document.forms;
    for (var index = 0; index < forms.length; ++index) {
        var form = forms.item(index);
        Event.observe(form, 'submit', checkForm);
    }
	 
} // addFormChecks

function checkForm(e) {
    // Compatibilità con MSIE e gli altri...
    e = e || window.event;
    var form = e.target || e.srcElement;
	
    var errors = '';
    var faulty = null;
	
	for (var index = 0; index < form.elements.length; ++index) {
        var field = form.elements.item(index);
        // Verifica sintassi
        if (!field.id.match(REGEX_AUTO_FIELD))
            continue;
        var value = getFieldValue(field);
        // Campo obbligatorio?
        if (field.id.match(/_Req/) && value.match(REGEX_BLANK)) {
            errors += '<li>' + getFieldName(field) + MSG_BLANK + '</li>';
            faulty = faulty || field;
            continue;
        }
	// Campo tipizzato?
	var match = field.id.match(REGEX_TYPED_FIELD);
	if (match) {
	    var type = match[1];
	    var error = checkTypedField(value, type);
	    if (error) {
		errors += '<li>' +getFieldName(field) + error + '</li>';
		faulty = faulty || field;
	    }
	}
    }
    if (!faulty)
        return;
		if (!$('error')) {		 
  			new Insertion.Bottom("module", '<ul id=\"error\">' + errors + '</ul>');
		}
		else {
			$('error').replace('<ul id=\"error\">' + errors + '</ul>');			
		}
	Event.stop(e);
    faulty.focus();
	
} // checkForm

function checkTypedField(value, type) {
    // Valori predefiniti
    var val;
    if ('Int' == type) {
        try {
            val = parseInt(value, 10);
	    if (String(val) != value & value!="")
	    	throw val;
        } catch (e) {
            return MSG_NOT_AN_INTEGER;
        }
    }
	
	if ('Email' == type) {
		var address= value;
		if (!address.match(REGEX_EMAIL)) {
        	return MSG_NOT_A_VALID_EMAIL;
		}     
    }
  
      if ('Date' == type) {
        var comps = value.split('/');
        if (3 != comps.length || !comps[0].match(REGEX_DAY) ||
            !comps[1].match(REGEX_MONTH) ||
            !comps[2].match(REGEX_YEAR))
            return MSG_NOT_A_DATE;
    }
    return null;
} // checkTypedField

function getFieldName(field) {
    var label = getLabelFor(field);
    if (!label)
        return field.name;
    var text = '';
    var node = label.firstChild;
    // Percorso in profondità, eliminata la ricorsione, del frammento sotto l'etichetta
    while (true) {
        if (Node.ELEMENT_NODE == node.nodeType && node.hasChildNodes())
            node = node.firstChild;
        else if (Node.TEXT_NODE == node.nodeType)
            text += node.nodeValue;
        if (node.nextSibling)
            node = node.nextSibling;
        else {
            node = node.parentNode;
            if (node == label)
                break;
            node = node.nextSibling;
        }
    }
    return text;
} // getFieldName

function getFieldValue(field) {
    if ('INPUT' == field.tagName)
        return field.value;
	if ('TEXTAREA' == field.tagName)
        return field.value;
    if ('SELECT' == field.tagName) {
        var value = '';
        if (-1 < field.selectedIndex) {
            var opt = field.options[field.selectedIndex];
            value = opt.value;
            if (!value && !('value' in opt))
                value = opt.text;
        }
        return value;
    }
    return '';
} // getFieldValue

function getLabelFor(field) {
    var labels = document.getElementsByTagName('label');
    for (var index = 0; index < labels.length; ++index) {
        var label = labels.item(index);
        if (label.htmlFor == field.id)
            return label;
    }
    return null;
} // getLabelFor

function createDateTime(){
	for(var
		p		= function(){return document.createElement("p")},
		addClassName	= function(p, name){p.className = name; return p},
		value		= function(p, text){p.appendChild(document.createTextNode(text)); return p},
		span		= document.getElementsByTagName("span"),
		i		= 0,
		text		= new Array(2);
	i < span.length; i++
	) {
		if(span[i].className === "datetime") {
			text = span[i].firstChild.nodeValue.split("-");
			span[i].removeChild(span[i].firstChild);
			span[i].appendChild(value(addClassName(p(), "day-month"), text[0]));

			span[i].appendChild(value(addClassName(p(), "year"), text[1]));
		}
	}
};

function initCalendar() {
	var dpck = new DatePicker({
          relative	         : 'date-from_Req',
          language	         : 'it',
		  disableFutureDate  : false
         });
		 var dpck2 = new DatePicker({
          relative	         : 'date-to_Req',
          language	         : 'it',
		  disableFutureDate  : false
         });	
}

function applicationStartUp() {	
	addFormChecks();
	createDateTime();
	if ($('map')) {	createmap(); }
	if($("date-from_Req"))	{ initCalendar(); }
	if ($('slide-images')) { initSlideshow(); }
}

Event.observe (window, 'load', applicationStartUp, false); 
