window.onload = function() {
  //setStates();
  //window.location.reload(true);
}

var root = '';//'http://independentescortservices.com/';

var isOk = true;

function chkIt(td, name, text){
  el = document.getElementById(td);
  if(el.lastChild) el.removeChild(el.lastChild);
  if(document.getElementById(name).value == ''){
   isOk = false;
   if(!el.lastChild){
    myTextNode = document.createTextNode(text + " can't be empty");
    el.appendChild(myTextNode);
    el.style.color = "rgb(255,0,0)";
    //isOk = false;
   }
  }
}
//document.formS.rCountry

function chkItForSelect(td, name, text){
  el = document.getElementById(td);
  var inx = document.getElementById(name).selectedIndex;
  optText = document.getElementById(name).options[inx].text;
  //if(inx == -1){
  if(optText == 'select'){
   if(!el.lastChild){
    myTextNode = document.createTextNode(text + " must be selected");
    el.appendChild(myTextNode);
    el.style.color = "rgb(255,0,0)";
    isOk = false;
   }
  }else if(el.lastChild) el.removeChild(el.lastChild);

  if(name == 'country' && optText == 'United States'){
     //chkItForSelect('state_td', 'state', 'State');
     chkIt('zipcode_td', 'zipcode', 'Zip code');
  }
}


//form sign up takes place at the end of ajaxRecipTextResponse()
//which is called from checkItems() - anisochronous behaviour
function checkItems(){
  //alert("a");
  isOk = true; //reassign

  
  chkIt('recip_td', 'recip', 'Your reciprocal page');

  chkItForSelect('type_td', 'type', 'Website Type');
  chkIt('title_td', 'title', 'Title');
  chkIt('url_td', 'url', 'URL');
  //chkIt('ban_url_td', 'ban_url', 'Banner URL');//optional
  chkIt('email_td', 'email', 'Your Email');

///

  //anisochronous check of reciprocal... (last step) 
  if(document.getElementById('recip').value != ''){
    var recipURL = document.getElementById('recip').value;
    var url = root + 'link_ajax_recip.php?recip='
              +recipURL.ReplaceAll("http://","");

    runAjax(url);
  }

}

/*function checkEscaCity(escaCity){
  var bool = false;
  var i = document.formS.sCity.selectedIndex;
  var selected_text = document.formS.sCity.options[i].text;
  if(escaCity == selected_text) bool = true;
  return bool;
}
*/

function isChecked(name){
  return document.getElementById(name).checked;
}


   ////////////////////////////////////////////////////
   //////AJAX CHEKING RECIPROCAL!!!////////////////////
   ////////////////////////////////////////////////////

   function initRequest() {
       if (window.XMLHttpRequest) {
           return new XMLHttpRequest();
       } else if (window.ActiveXObject) {
           isIE = true;
           return new ActiveXObject("Microsoft.XMLHTTP");
       }
   }

  function AjaxAnywhere() {

    this.id = AjaxAnywhere.defaultInstanceName;
    this.formName = null;
    this.notSupported = false;
    this.delayBeforeContentUpdate = true;
    this.delayInMillis = 100;

    if (window.XMLHttpRequest) {
        this.req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            this.req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                this.req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e1) {
                this.notSupported = true;
            }
        }
    }

    if (this.req == null || typeof this.req == "undefined")
        this.notSupported = true;

    return this.req;
  }

  function runAjax(url) {
      
      var req = AjaxAnywhere();
      req.onreadystatechange = function() {
        if (req.readyState == 4) {
          if (req.status == 200) { 
		    ajaxRecipTextResponse(req.responseText); 
		  } 
		  else if (req.status == 204) { }
        }
      };
      req.open("POST", url, true);
      req.send(null);
  }

  function ajaxRecipTextResponse(responseText) {
	  //alert(trim(responseText));
	  //alert(trim(responseText).length);

      if(responseText.length == 11){ //<!--okey--> 11 - okey
         el = document.getElementById("recip_td");
         if(el.lastChild) el.removeChild(el.lastChild);
		 if(!el.lastChild){
	        myTextNode = document.createTextNode(
                         "Your reciprocal link is verified successfully!");
      	    el.appendChild(myTextNode);
	        el.style.color = "rgb(0,125,123)";
			//el.style.background=color; 
            el.style.fontWeight='bold'; 
		 }
      }else if(responseText.length == 9){ //<!--wr--> 9 - wrong
         el = document.getElementById("recip_td");
         if(el.lastChild) el.removeChild(el.lastChild);

         isOk = false; //Recibprocal link not found
 	     if(!el.lastChild){
	        myTextNode = document.createTextNode(
                         "Incorrect reciprocal link...");
      	    el.appendChild(myTextNode);
	        el.style.color = "rgb(255,0,0)";
	     }
      }else if(responseText.length == 10){ //<!--not--> 10 - not found
         el = document.getElementById("recip_td");
         if(el.lastChild) el.removeChild(el.lastChild);

         isOk = false; //Recibprocal link not found
 	     if(!el.lastChild){
	        myTextNode = document.createTextNode(
                         "Our banner was not found on your page...");
      	    el.appendChild(myTextNode);
	        el.style.color = "rgb(255,0,0)";
	     }
      }else if(responseText.length == 8){ //<!--a--> 8 - already
         el = document.getElementById("recip_td");
         if(el.lastChild) el.removeChild(el.lastChild);

         isOk = false; //Recibprocal link not found
 	     if(!el.lastChild){
	        myTextNode = document.createTextNode(
              "Profile for this reciprocal already exists. "+
			  "You need another reciprocal for the new profile.");
      	    el.appendChild(myTextNode);
	        el.style.color = "rgb(255,0,0)";
	     }
      }else{ 
         //modified (in ajax_recip.php) url	  
         document.getElementById('recip').value = responseText;

         el = document.getElementById("recip_td");
         if(el.lastChild) el.removeChild(el.lastChild);
		 if(!el.lastChild){
	        myTextNode = document.createTextNode(
                         "Your reciprocal link is verified successfully!");
      	    el.appendChild(myTextNode);
	        el.style.color = "rgb(0,125,123)";
			//el.style.background=color; 
            el.style.fontWeight='bold'; 
		 }
	  }
      
	  
	  if(isOk){
	    //alert("submit");
 	    //the end point of anisochronous actions initiated by checkItems()
        
		document.formLinkSignup.submit();
      }
	  
   }

  function uploadImg(last_id)
  {
	  document.getElementById('last_id').value = last_id;
	  alert(document.getElementById('escaName').value);
	  document.getElementById('esca_name').value = document.getElementById('escaName').value;
      document.getElementById('img').form.submit(); // all inputs are submitted at once...
      //document.getElementById('img2').form.submit(); // all inputs are submitted at once...
      //document.getElementById('img3').form.submit(); // all inputs are submitted at once...
      //document.getElementById('img4').form.submit(); // all inputs are submitted at once...
  }

  function checkFileType(img_field)
  {
 	var re_text = /\.jpg/i;     //    /\.png|\.gif|\.jpg/i;
    var filename = img_field.value;
	
    if (filename.search(re_text) == -1)
    {
        alert("Please, browse files with (.jpg) extension only");
        //value of input file tag is not changeable - browser security
		//so we create new object and copy all old element parts to it...
        var input = document.createElement('input');
        input.type = img_field.type;
		input.id = img_field.id;
        input.name = img_field.name;
		input.size = img_field.size;
		input.style.width = img_field.style.width;
     	input.onkeypress = function () {blur()}
		input.onchange = function () {checkFileType(this)}
        img_field.parentNode.replaceChild(input,img_field);
    }
  }


  //////////////////////////////////////
  //////// usefull JS methods //////////
  //////////////////////////////////////

  function trim(str) {
    sInString = str.replace( /^\s+/g, "" );// strip leading
    return str.replace( /\s+$/g, "" );// strip trailing
  }


  //used for textarea
  function clearEv(e){
     if (e.preventDefault) e.preventDefault()
	 e.cancelBubble = true;
	 if(e.stopPropagation) e.stopPropagation();
	 return (e.returnValue = false);
  }

  function symbolLimit(event,source, grantee, limit) {
     if (source.value.length > limit) 
        if ((event.charCode||'').match(/0-9a-z/i)) return clearEv(event);

     function sl(){
        if(!source) return
        if (source.value.length > limit) {
            source.value = source.value.substring(0, limit);
        }
        else {
                source.nextSibling.value = limit - source.value.length;
        }
        source.value == '' ? grantee.innerHTML = '&nbsp;' : grantee.innerHTML = source.value;
     }
     source.onkeyup = sl;
     setTimeout(sl,0)
  }

  //using: value.ReplaceAll("&","<N>");
  String.prototype.ReplaceAll = function(stringToFind,stringToReplace){
     var temp = this;
     var index = temp.indexOf(stringToFind);
     while(index != -1){
        temp = temp.replace(stringToFind,stringToReplace);
        index = temp.indexOf(stringToFind);
     }
     return temp;
  }
  
  
