var valid = true;

function trim_spaces() {
    var temp_string  = this;
    while(temp_string.substring(0, 1) == " ")
        temp_string = temp_string.substring(1);
    while(temp_string.substring(temp_string.length - 1) == " ")
        temp_string = temp_string.substring(0, temp_string.length - 2);
    return temp_string;
}
String.prototype.trim=trim_spaces;

function isEmail(who) {
	function isEmpty(who) {
		var testArr=who.split("");
		if(testArr.length==0)
			return true;
		var toggle=0;
		for(var i=0; i<testArr.length; i++) {
			if(testArr[i]==" ") {
				toggle=1;
				break;
			}
		}
		if(toggle)
			return true;
		return false;
	}

	function isValid(who) {
		var invalidChars=new Array("~","!","@","#","$","%","^","&","*","(",")","+","=","[","]",":",";",",","\"","'","|","{","}","\\","/","<",">","?");
		var testArr=who.split("");
		for(var i=0; i<testArr.length; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[i]==invalidChars[j]) {
					return false;
				}
			}
		}
		return true;
	}

	function isfl(who) {
		var invalidChars=new Array("-","_",".");
		var testArr=who.split("");
		which=0;
		for(var i=0; i<2; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[which]==invalidChars[j]) {
					return false;
				}
			}
			which=testArr.length-1;
		}
		return true;
	}

	function isDomain(who) {
		var invalidChars=new Array("-","_",".");
		var testArr=who.split("");
		if(testArr.length<2||testArr.length>4) {
			return false;
		}
		for(var i=0; i<testArr.length; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[i]==invalidChars[j]) {
					return false;
				}
			}
		}
		return true;
	}


	var testArr=who.split("@");
	if(testArr.length<=1||testArr.length>2) {
		return false;
	}
	else {
		if(isValid(testArr[0])&&isfl(testArr[0])&&isValid(testArr[1])) {
			if(!isEmpty(testArr[testArr.length-1])&&!isEmpty(testArr[0])) {
				var testArr2=testArr[testArr.length-1].split(".");
				if(testArr2.length>=2) {
					var toggle=1;
					for(var i=0; i<testArr2.length; i++) {
						if(isEmpty(testArr2[i])||!isfl(testArr2[i])) {
							toggle=0;
							break;
						}
					}
					if(toggle&&isDomain(testArr2[testArr2.length-1]))
						return true;
					return false;
				}
				return false;
			}
		}
	}
}

/* With RegExp */
function isEmail2(who) {
	//var email=/^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*\.([A-Za-z]){2,4}$/i;
	var email=/^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*$/i;
	return(email.test(who));
}

function URL(url){
	if(url.length==0) eval('throw "Invalid URL ['+url+'];');
	this.url=url;
	this.port=-1;
	this.query=(this.url.indexOf('?')>=0)?this.url.substring(this.url.indexOf('?')+1):'';
	if(this.query.indexOf('#')>=0) this.query=this.query.substring(0,this.query.indexOf('#'));
	this.protocol='';
	this.host='';
	var protocolSepIndex=this.url.indexOf('://');
	if(protocolSepIndex>=0){
		this.protocol=this.url.substring(0,protocolSepIndex).toLowerCase();
		this.host=this.url.substring(protocolSepIndex+3);
		while (this.host.indexOf('/')==0)
		{
			this.host=this.host.substring(1);
		}
		if(this.host.indexOf('/')>=0) this.host=this.host.substring(0,this.host.indexOf('/'));
		var atIndex=this.host.indexOf('@');
		if(atIndex>=0){
			var credentials=this.host.substring(0,atIndex);
			var colonIndex=credentials.indexOf(':');
			if(colonIndex>=0){
				this.username=credentials.substring(0,colonIndex);
				this.password=credentials.substring(colonIndex);
			}else{
				this.username=credentials;
			}
			this.host=this.host.substring(atIndex+1);
		}
		var portColonIndex=this.host.indexOf(':');
		if(portColonIndex>=0){
			this.port=this.host.substring(portColonIndex);
			this.host=this.host.substring(0,portColonIndex);
		}
		this.file=this.url.substring(protocolSepIndex+3);
		this.file=this.file.substring(this.file.indexOf('/'));
	}else{
		this.file=this.url;
	}
	if(this.file.indexOf('?')>=0) this.file=this.file.substring(0, this.file.indexOf('?'));
	var refSepIndex=url.indexOf('#');
	if(refSepIndex>=0){
		this.file=this.file.substring(0,refSepIndex);
		this.reference=this.url.substring(this.url.indexOf('#'));
	}else{
		this.reference='';
	}
	this.path=this.file;
	if(this.query.length>0) this.file+='?'+this.query;
	if(this.reference.length>0) this.file+='#'+this.reference;

	this.getPort=getPort;
	this.getQuery=getQuery;
	this.getProtocol=getProtocol;
	this.getHost=getHost;
	this.getUserName=getUserName;
	this.getPassword=getPassword;
	this.getFile=getFile;
	this.getReference=getReference;
	this.getPath=getPath;
	this.getArgumentValue=getArgumentValue;
	this.getArgumentValues=getArgumentValues;
	this.toString=toString;

	/* Returns the port part of this URL, i.e. '8080' in the url 'http://server:8080/' */
	function getPort(){
		return this.port;
	}

	/* Returns the query part of this URL, i.e. 'Open' in the url 'http://server/?Open' */
	function getQuery(){
		return this.query;
	}

	/* Returns the protocol of this URL, i.e. 'http' in the url 'http://server/' */
	function getProtocol(){
		return this.protocol;
	}

	/* Returns the host name of this URL, i.e. 'server.com' in the url 'http://server.com/' */
	function getHost(){
		return this.host;
	}

	/* Returns the user name part of this URL, i.e. 'joe' in the url 'http://joe@server.com/' */
	function getUserName(){
		return this.username;
	}

	/* Returns the password part of this url, i.e. 'secret' in the url 'http://joe:secret@server.com/' */
	function getPassword(){
		return this.password;
	}

	/* Returns the file part of this url, i.e. everything after the host name. */
	function getFile(){
		return this.file;
	}

	/* Returns the reference of this url, i.e. 'bookmark' in the url 'http://server/file.html#bookmark' */
	function getReference(){
		return this.reference;
	}

	/* Returns the file path of this url, i.e. '/dir/file.html' in the url 'http://server/dir/file.html' */
	function getPath(){
		return this.path;
	}

	/* Returns the FIRST matching value to the specified key in the query.
	   If the url has a non-value argument, like 'Open' in '?Open&bla=12', this method
	   returns the same as the key: 'Open'...
	   The url must be correctly encoded, ampersands must encoded as &amp;
	   I.e. returns 'value' if the key is 'key' in the url 'http://server/?Open&amp;key=value' */
	function getArgumentValue(key){
		var a=this.getArgumentValues();
		if(a.length<1) return '';
		for(i=0;i<a.length;i++){
			if(a[i][0]==key) return a[i][1];
		}
		return '';
	}

	/* Returns all key / value pairs in the query as a two dimensional array */
	function getArgumentValues(){
		var a=new Array();
		var b=this.query.split('&amp;');
		var c='';
		if(b.length<1) return a;
		for(i=0;i<b.length;i++){
			c=b[i].split('=');
			a[i]=new Array(c[0],((c.length==1)?c[0]:c[1]));
		}
		return a;
	}

	/* Returns a String representation of this url */
	function toString(){
		return this.url;
	}
}

function disValid(el, title) {
    el.style.backgroundColor="#FFA090";
    el.title += title;
    valid = false;
}

function validate(Sender) {
    valid = true;
    if (!self.dontValid)
    for (var i = 0; i < Sender.elements.length; i++) {
        var el = Sender.elements[i];
        var type = el.type;
        var alt = el.getAttribute("alt");
        var value = el.value;
        //alert("name='" + el.name + "'; type='" + type + "'; alt='" + alt + "'; value='" + value + "'");
        if (!el.isDisabled && type != "checkbox" && type != "radio" && type != "submit" && type != "image" ) {
            el.style.backgroundColor="";
            el.title = "";
            if (alt != null && value != null && alt.indexOf("mustChoose") > -1 && value.length > 0) {
                var noEmpty = null;
                if (alt.indexOf("ifNoEmpty") > -1) {
                    var noEmptyName = alt.substring(alt.indexOf("ifNoEmpty(") + 10, alt.indexOf(")", alt.indexOf("ifNoEmpty(") + 10));
                    noEmpty = Sender.elements[noEmptyName];
                }
                if (value == MSG_NOT_CHOOSEN && (!noEmpty || noEmpty.value.length > 0))
                    disValid(el, alt.substring(alt.indexOf("mustChoose(") + 11, alt.indexOf(")", alt.indexOf("mustChoose(") + 11)))
            }
            if (alt != null && value != null && alt.indexOf("email") > -1 && value.length > 0) {
                if (!isEmail2(value))
                    disValid(el, "E-mail incorrect. ");
            }
            if (alt != null && value != null && alt.indexOf("url") > -1 && value.length > 0) {
				if (new URL(value).getHost().length==0){
					if (value.toLowerCase().indexOf("mailto:") !=0 || !isEmail(value.substring(7)))
                    disValid(el, "URL incorrect. Use full URL with protocol name");
				}
            }

            if (alt != null && value != null && alt.indexOf("float") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-\\" + decSep + "]");
                var re2 = new RegExp("-?\\d*\\" + decSep + "?\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Must be a float number. ");
            }
            if (alt != null && value != null && alt.indexOf("integer") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-]");
                var re2 = new RegExp("-?\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Must be a integer number. ");
            }
            if (alt != null && value != null && alt.indexOf("natural") > -1 && value.length > 0) {
                var re1 = new RegExp("\\D");
                if (value.search(re1) > -1)
                    disValid(el, "Must be a natural number. ");
            }
            if (alt != null && value != null && alt.indexOf("taskNumber") > -1 && document.getElementById("REG_NAME_ID").value != "") {            
                if(value.indexOf("#") == 0)
                    value = value.substring(1);
                var re1 = new RegExp("\\D");
                if (value.search(re1) > -1 || value.length == 0) {
                    disValid(el, "Incorrect task number.");
                    alert("Incorrect task number.");
                    return false;
                }
            }
            if (alt != null && value != null && alt.indexOf("color") > -1 && value.length > 0) {
                if (!colorValid(value))
                    disValid(el, "Must be a color value in format \"#dddddd\". ");
            }
            if (alt != null && value != null && alt.indexOf("date") > -1 && value.length > 0) {
                var pattern = "";
                var mStart =  alt.indexOf('date(');
                if (mStart > -1) {
                    var mFinish = alt.indexOf(')', mStart + 1);
                    if (mFinish == -1) {
                        pattern = alt.substring(mStart + 5, alt.length);
                    } else {
                        pattern = alt.substring(mStart + 5, mFinish);
                    }
                }
                var calendar  = new Calendar(1, null, selected, closeHandler)
                var res2 = calendar.parseDate(value, pattern, true);
                if (res2 == null || res2.indexOf("%") != -1) // function toDate defined in calendar.js
                    disValid(el, "Must be a date in format '" + pattern + "'. ");
                else {                    
                    el.value = res2;
                }
            }

            var minLength = null;
            if (alt != null) {
                var mStart = alt.indexOf('>');
                if (mStart > -1) {
                    var mFinish = alt.indexOf(';', mStart + 1);
                    if (mFinish == -1) {
                        minLength = parseInt(alt.substring(mStart + 1, alt.length), 10);
                    } else {
                        minLength = parseInt(alt.substring(mStart + 1, mFinish), 10);
                    }
                }
            }

            var maxLength = el.getAttribute("maxlength");
            if ((maxLength != null && maxLength < value.length) || (minLength != null && minLength >= value.trim().length))
                disValid(el, "This field has length of " + value.length + " chars, but it's maximum length is " + maxLength + " and minimum length is " + minLength + ". ");

        }
    }
    if (!valid) {
        alert("Please correct highlighted field data and fill in all required (*) custom fields.");
        return false;
    } else {
        return allow(Sender);
    }
}


// color falue validaiting
function colorValid(val) {
    re = new RegExp("#[abcdef\\d]{6}", "i");
    if (val.match(re) == val)
        return true;
    else
        return false;
}


// "CLOSE_MSG" block begin
var isSubmitting = false;
var is_new = false;

function allow(sender) {
    isSubmitting = true;
    sender.onsubmit = function() {return false;};
    return true;
}

window.onbeforeunload = function() {
    if (isSubmitting == false)
        for (var j=0;j < document.forms.length; j++)
            if (document.forms[j].alt=='checkunload' && isDirty(document.forms[j]))
                return WIN_CLOSE_MSG;
    return;
}

function isDirty(form) {
    if (is_new) {
        return true;
    }
    if (form.updateFCKEditor) { // test of FCKeditor replace textarea(s) of form
        // updateFCKEditor contains function of text set to textarea(s). Calls all functions in the functions array
        for (var i = 0 ; i < form.updateFCKEditor.length ; i++)
            form.updateFCKEditor[i].call();
    }
    if (form.elements)
        for (var i = 0; i < form.elements.length; i++) {
            var control = form.elements[i];
            if (control.type != 'submit' && control.type != 'hidden' && control.type != 'button' && !control.disabled && control.getAttribute("ignoreModified") == null && getControlValue(control) != getControlDefaultValue(control))
                return true;
        }
    return false;
}

function getControlValue(control) {
    switch (control.type) {
        case 'checkbox':
            return control.checked;
        case 'select-one':
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].selected)
                     return control.options[i].value;
        case 'select-multiple':
            var val = '';
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].selected)
                     val += control.options[i].value + '\n';
            return val;
        default:
            return control.value;
    }        
}

function getControlDefaultValue(control) {
    switch (control.type) {
        case 'checkbox':
            return control.defaultChecked;
        case 'select-one':
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].defaultSelected)
                     return control.options[i].value;
            if (control.options[0])
                return control.options[0].value;
            else
                return null;
        case 'select-multiple':
            var val = '';
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].defaultSelected)
                     val += control.options[i].value + '\n';
            return val;
        default:
            return control.defaultValue;
    }
}
// "CLOSE_MSG" block end