﻿  
    //get the class of an element
    function getClss(el) {
        var clss = el.getAttribute('class')
        if(!clss){
            clss = el.className
        }
        return !clss ? '' : clss       
    }
    
    //get all text boxes marked as needing to be unique
    function getUniqueFields() {
       
        var ufields = document.getElementsByTagName('input');
        if (ufields){
            for(var i=0;i < ufields.length;i++){
                if (getClss(ufields[i]).indexOf('unique') > -1) {
                    //get all input fields which have a 'unique*' class
                    var uid = !ufields[i].id ? ufields[i].id : ufields[i].getAttribute('id');
                    //the string after unique in the class name denotes type of unique to ascertain...
                    var utype = getClss(ufields[i]).substr(6);
                    
                    if (uid){
                        clearInterval(gufTime);
                        cuTime = setInterval(function() {checkUniques(uid,utype);},1000);
                    }
                }
            }
        }
    }
  
    function checkUniques(field,utype) {
        //alert(field)
        var ufield = document.getElementById(field);
        if(ufield.value != ''){
            var xmlhttp = createXHRobj();
            if (xmlhttp){
                //open xmlhttp request              
			    xmlhttp.open("GET", "ajax/testUniques.aspx?type="+utype+"&text="+escape(ufield.value),true);
			    xmlhttp.onreadystatechange=function() {
			       
				    if (xmlhttp.readyState==4) {
				        var response = xmlhttp.responseText;
				        //alert(response)
				        //if zero then a dupe has not been found
				        if (response != "0"){
				            if (!document.getElementById('warn_'+field)){
				                var dupeTxt = response.substring(2);
				                var warn = document.createElement('span');
				                warn.setAttribute('id','warn_'+field);
				                warn.setAttribute('class','dupewarning');
				                warn.appendChild(document.createTextNode(dupeTxt));
				                ufield.parentNode.insertBefore(warn,ufield.nextSibling);
				            }           
				        } else {
				            //a dupe not found, so remove any warning previously posted
				            if (document.getElementById('warn_'+field)){
				                ufield.parentNode.removeChild(document.getElementById('warn_'+field))
				            }
				        }
				    }
			    }
			    xmlhttp.send(null);
            }
        }
    }
   
    var cuTime
    //HACKS! since can't run proper onload, keep checking every second until page is loaded, then clear interval
    var gufTime = setInterval(function() {getUniqueFields()},1000);


