/**
	Protoform(class) v1.1 18/03/2009
	Copyright (c) 2008 Filippo Buratti; info [at] cssrevolt.com [dot] com; http://www.filippoburatti.net/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

REGEX_AUTO_FIELD  = /^[^_]+(_Req)?(_(Tel|Num|Int|Email|Url|Customdate|Date))?$/;
REGEX_BLANK       = /^\s*$/;
REGEX_EMAIL       = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{1,})+\.)+([a-zA-Z0-9]{2,})+$/;
REGEX_TEL         = /^([0-9]*\-?\ ?\/?[0-9]*)$/;
REGEX_NUM		  = /^[-+]?\d+(\.\d+)?$/;
REGEX_URL         = /^(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
REGEX_DAY         = /^(0?[1-9]|[1-2][0-9]|3[01])$/;
REGEX_MONTH       = /^(0?[1-9]|1[0-2])$/;
REGEX_YEAR        = /^[0-9]{2,4}$/;
REGEX_TYPED_FIELD = /_(Tel|Num|Int|Email|Url|Customdate|Date)$/;

var ProtoformDates = 0;

var Protoform = Class.create({

initialize: function(form, options) {	  	
	this.options = {
      		ajax: false
    	}
		Object.extend(this.options, options || {});
	this.form      		= $el(form);
  if (this.options.ajax == true) {
    var i = document.createElement('input');
    i.type = 'hidden';
    i.name = 'xhr';
    i.value = '1';
    this.form.appendChild(i);
  }
  //alert(this.form);
	this.formProcess 	= this.checkForm.bindAsEventListener(this);
        
        Event.observe(form, "submit", this.formProcess);
        
	//this.form.observe("submit", this.formProcess );
	this.hoverFocus();
},

addEvents: function (obj) {
  Event.observe(obj, "focus", function(){
    Element.addClassName(obj, "hoverfocus");
  });
  Event.observe(obj, "blur", function(){
    Element.removeClassName(obj, "hoverfocus");
  });
},

hoverFocus: function() { 
  
  
  //alert(this.form);
  //alert(this.form.select);
  
  var ins = this.form.getElementsByTagName('input');
  for (var i = 0; i < ins.length; i++) {
    var inn = ins[i];
    
    this.addEvents(inn);
    
    /*Event.observe(inn,'focus',function() {
      Element.addClassName(this,'hoverfocus');
    }.bind(inn));*/
    /*Event.observe(item,'blur',function() {
      Element.removeClassName(this,'hoverfocus');
    }.bind(item));*/
  }
  
  
 	/*this.form.select('input', 'textarea').each(function(item) {
    	Event.observe(item,'focus',function() {
      		Element.addClassName(this,'hoverfocus');
    	}.bind(item));
    	Event.observe(item,'blur',function() {
      		Element.removeClassName(this,'hoverfocus');
    	}.bind(item));
	});*/
},
	
checkForm: function(event) {

  ProtoformDates = 0;
	Event.stop(event);
    var errors	= '';
    var faulty	= null;
	if ($('response')) { $('response').remove(); }

  var elements = new Array();
  var toLast = new Array();
  
  this.form.getElements().each(function(formElements) {
    var idField			= (formElements.readAttribute && formElements.readAttribute('class')) ? formElements.readAttribute('class') : formElements.className; // DF added the last part, because the readAttribute method is not working in IE8.
    if (idField.match(/_Last/)) {
      toLast[toLast.length] = formElements;
    } else {
      elements[elements.length] = formElements;
    }
  }.bindAsEventListener(this));

  for (var i = 0; i < toLast.length; i++) {
    elements[elements.length] = toLast[i];
  }

	$A(elements).each(function(formElements) {
		var value 			= ($F(formElements)!= null) ? $F(formElements) : '' ;
		//var idField			= formElements.readAttribute('class') ? formElements.readAttribute('class') : '';
		var idField			= (formElements.readAttribute && formElements.readAttribute('class')) ? formElements.readAttribute('class') : formElements.className; // DF added the last part, because the readAttribute method is not working in IE8.
		
		var typedField 		= idField.match(REGEX_TYPED_FIELD);
		var errorMessage	= (formElements.readAttribute) ? formElements.readAttribute('title') : formElements.getAttribute("title");

    var id = formElements.id;

    if (id == 'confirmemail') {
      if (value != $('email').value) {
            errors += '<li>' + errorMessage + '</li>';
            faulty = faulty || formElements;
            return;
      }
    }
		
		if (!idField.match(REGEX_AUTO_FIELD)) {
            //return;
		}
		
		if (idField.match(/_Req/) && value.match(REGEX_BLANK)) {
      // DF added the if statement, because if the original delivery date field is empty,
      // and one has selected that one or more products should be delivered elsewhere,
      // the bottom field produced an error, so treat it as it was not empty.
      if (idField.match(/_Req_Customdate/)) {
        var type = typedField[1];
	    	var error = this.checkField(value, type, formElements);
	    	if (error) {
          errors += '<li>' + errorMessage + '</li>';
          faulty = faulty || formElements;
	    	}
      } else {
        errors += '<li>' + errorMessage + '</li>';
        faulty = faulty || formElements;
        return;
      }
    }
		
		if (typedField  && !value.match(REGEX_BLANK)) {
	    	var type = typedField[1];		
	    	var error = this.checkField(value, type, formElements);
	    	if (error) {
				errors += '<li>' + errorMessage + '</li>';
				faulty = faulty || formElements;
	    	}
		}
	}.bindAsEventListener(this));
	
	if (errors==0) {
		if (this.options.ajax){
			this.sendData(); 
		} else {
			this.form.submit();
		}
	} else {
	
		if (!$('error')) {	
			this.form.insert({before:new Element('ul', {id:'error'}).update(errors)});
		} else {
      if (!$('error').update) {
        $('error').innerHTML = errors;
      } else {
        $('error').update(errors);
      }
      if ($('error_floater')) {
        $('error_floater').style.display = 'block';
      }
		}
		faulty.focus();
	}
},
	
checkField: function (value, type, formElements) {


  //return true;
	switch (type) {
		case 'Tel':
			var phone= value;
      // The following 2 lines is so that we can remove the spaces
      phone = phone.split(' ');
      phone = phone.join('');
      if (phone.length < 8) {
        return true;
      }
			if (!phone.match(REGEX_TEL)) { return true; }     
			break;
		case 'Num':
			var number= value;
			if (!number.match(REGEX_NUM)) { return true; }     
			break;
		case 'Tel':
			var phone= value;
			if (!phone.match(REGEX_TEL)) { return true; }     
			break;
		case 'Email':
			var address= value;
			if (!address.match(REGEX_EMAIL)) { return true; }     
			break;
		case 'Url':
			var resource= value;
			if (!resource.match(REGEX_URL)) { return true; }
			break;
		case 'Customdate':
			return CustomDateCheck(value, type, formElements);
			break;
		case 'Date':
			var comps = value.split('/');
        	if (3 != comps.length || !comps[0].match(REGEX_DAY) || !comps[1].match(REGEX_MONTH) || !comps[2].match(REGEX_YEAR)) { return true; }
			break;
		default:
			return null;
	}

}.bind(this), 
	
sendData: function(event) {
	var url 	= (this.options.url) ? (this.options.url) : this.form.readAttribute('action');
	var reqType	= this.form.readAttribute('method');
	var pars 	= this.form.serialize();
	var myAjax 	= new Ajax.Request( url, { method: reqType, parameters: pars, onCreate: this.showLoad.bind(this), onComplete: this.getResponse.bind(this) });
},
	
showLoad: function() {
	this.form.insert({after:'<p id="working">loading...</p>'});
	if ($('error')) { $('error').remove(); }
},
	
getResponse: function(transport) {
	$('working').remove();
	var newData = transport.responseText;
	this.form.insert({after:newData}).reset();
}	
  
});

function CustomDateCheck (value, type, formElements) {

  ProtoformDates++;

  if (ProtoformDates > 1) {
    var dd = document.getElementById('delivery_date_bottom');
    if (formElements == dd) {
      return false;
    }
  }

	var monthNames = new Array();
	monthNames['januar'] = 1;
	monthNames['februar'] = 2;
	monthNames['marts'] = 3;
	monthNames['april'] = 4;
	monthNames['maj'] = 5;
	monthNames['juni'] = 6;
	monthNames['juli'] = 7;
	monthNames['august'] = 8;
	monthNames['september'] = 9;
	monthNames['oktober'] = 10;
	monthNames['november'] = 11;
	monthNames['december'] = 12;

	var split1 = value.split('-'); // dd-mm-yyyy / dd/mm-yyyy

	var dd = 'NULL';
	var mm = 'NULL';
	var yyyy = 'NULL';

	if (split1.length === 3) { // DD-MM-YYYY
		dd = split1[0];
		mm = split1[1];
		yyyy = split1[2];

		if ( (yyyy.toString()).length == 2 ) {
			yyyy = '20' + yyyy; // There are no orders from before 2000, and i dont thing this code will last for 1000 years, so i think this i legal to do
		}
	} else if (split1.length === 2) { // DD/MM-YYYY ?
		var split2 = (split1[0]).split('/');
		if (split2.length === 2) { // DD/MM

			dd = split2[0];
			mm = split2[1];
			yyyy = split1[1];

		}
	} else { // None of the above
		var split3 = value.split(' ');

		if (split3.length !== 3) {

			var split4 = value.split('/');

			if (split4.length === 3) {

				dd = split4[0];
				mm = split4[1];
				yyyy = split4[2];


			}

		} else { // dd mm yyyy

			dd = split3[0];
			dd = dd.replace('.', '');
			mm = split3[1];

			if (IsNumeric(mm)) {
				if (mm <= 9) {
					mm = '0' + mm;
				}
			} else {
				mm = mm.toLowerCase();
				mm = monthNames[mm];
				mm = '0' + mm;
			}

			yyyy = split3[2];

		}
	}

	if ( (yyyy.toString()).length == 2 ) {
		yyyy = '20' + yyyy; // There are no orders from before 2000, and i dont thing this code will last for 1000 years, so i think this i legal to do
	}

	if (dd > 31) {
		return true;
	}

	if (mm > 12) {
		return true;
	}

	if (!IsNumeric(dd + '-' + mm + '-' + yyyy)) {
		return true;
	}

	dd = parseInt(dd, 10);
	mm = parseInt(mm, 10);
	yyyy = parseInt(yyyy);

	var d = new Date();
	var cDD = d.getDate();
	var cMM = d.getMonth() + 1; // Goes from 0 - 11
	var cYY = d.getFullYear();

  if (yyyy < cYY) {
    return true;
  } else if (yyyy == cYY) {
    if (mm < cMM) {
      return true;
    } else if (mm == cMM) {
      if (dd < cDD) {
        return true;
      }
    }
  }

	/*if (dd < cDD) {

    alert("dd mm yy");
		if (mm < cMM) {
      alert("mm yy");
			if (yyyy < cYY) {
        alert("yy");
				return true;
			}
		}
	}
  /*if (mm < cMM) {

    alert("mm yy");
    if (yyyy < cYY) {
      alert("yy");
      return true;
    }
  }
  if (yyyy < cYY) {

    alert("yy");
    return true;
  }*/

	return false;

	/*var dateBelowCurrent = yyyy < cYY ? ( mm < cMM ? ( dd < cDD ) : true ) : true;

	console.info(dateBelowCurrent);


	console.info('******');
	console.info(dd);
	console.info(mm);
	console.info(yyyy);
	console.info('--');
	console.info(cDD);
	console.info(cMM);
	console.info(cYY);*/

	return dateBelowCurrent;
}

function IsNumeric(sText) {
	var ValidChars = "0123456789.-";
	var IsNumber = true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

