window.onload = function() {
  setStates();
  //window.location.reload(true);
}

var root = '';//'http://escortsthumb.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'){
    isOk = false;
    if(!el.lastChild){
      myTextNode = document.createTextNode(text + " must be selected");
      el.appendChild(myTextNode);
      el.style.color = "rgb(255,0,0)";
    }
  }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
  //return isOk;
  
  chkIt('recip_td', 'recip', 'Your reciprocal page');

  //recip check moved to the end - becaus of anisochronous nature
  //must be the last so no other action could overcome

  chkIt('name_td', 'escaName', 'Your Name');
  chkIt('email_td', 'escaEmail', 'Your Email');
  //chkItForSelect('country_td', 'country', 'Country');
  chkIt('city_td', 'city', 'City');
  chkIt('phone_td', 'phone', 'Phone');
  ///

  chkItForSelect('age_td', 'age', 'Age');
  chkItForSelect('height_td', 'height', 'Height');
  chkItForSelect('weight_td', 'weight', 'Weight');

  chkItForSelect('chest_td', 'chest', 'Chest Size');
  chkItForSelect('waist_td', 'waist', 'Waist Size');
  chkItForSelect('hip_td', 'hip', 'Hip Size');

  ///
  el = document.getElementById('specialty_td');
  if(document.formSignup.straight.checked ||
     document.formSignup.masseuse.checked ||
     document.formSignup.girlfriend.checked ||
     document.formSignup.dominatrix.checked ||
     document.formSignup.submissive.checked ||
     document.formSignup.bisexual.checked ||
     document.formSignup.lesbian.checked ||
     document.formSignup.gay.checked ||
     document.formSignup.dancer.checked ||
     document.formSignup.couple.checked){
      if(el.lastChild) el.removeChild(el.lastChild);
  }else{
   isOk = false;
   if(!el.lastChild){
    myTextNode = document.createTextNode("At least one Specialty must be selected!");
    el.appendChild(myTextNode);
    el.style.color = "rgb(255,0,0)";
    //isOk = false;
   }
  }

  el = document.getElementById('available_to_td');
  if(document.formSignup.men.checked ||
     document.formSignup.women.checked ||
     document.formSignup.couples.checked ||
     document.formSignup.groups.checked){
     if(el.lastChild) el.removeChild(el.lastChild);
  }else{
    isOk = false;
    if(!el.lastChild){
     my2TextNode = document.createTextNode("At least one Available To must be selected!");
     el.appendChild(my2TextNode);
     el.style.color = "rgb(255,0,0)";
     //isOk = false;
    }
  }

  el = document.getElementById('availability_td');
  if(document.formSignup.incall.checked ||
     document.formSignup.outcall.checked){
     if(el.lastChild) el.removeChild(el.lastChild);
  }
  else{
   isOk = false;
   if(!el.lastChild){
    my3TextNode = document.createTextNode("At least one Availability must be selected!");
    el.appendChild(my3TextNode);
    el.style.color = "rgb(255,0,0)";
    //isOk = false;
   }
  }

  ///
  chkIt('shortdesc_td', 'shortDesc', 'Short Description');
  chkIt('longdesc_td', 'longDesc', 'Long Description');
  chkIt('img_td', 'img', 'Small image path');

  c = 3;
  if(document.getElementById('img2').value == '')c--;
  if(document.getElementById('img3').value == '')c--;
  if(document.getElementById('img4').value == '')c--;

  el = document.getElementById('imgB_td');
  if(c < 3){
   isOk = false;
   if(!el.lastChild){
    myTextNode = document.createTextNode('At least 3 Big Images must be selected.');
    el.appendChild(myTextNode);
    el.style.color = "rgb(255,0,0)";
    //isOk = false;
   }
  }else if(el.lastChild) el.removeChild(el.lastChild);

  ///////////
  //if(!isOk)alert("Please, correct the red lines.");

  el = document.getElementById('error_td');
  if(!isOk){
     if(!el.lastChild){
        myTextNode = document.createTextNode('Error! Please, correct red lines.');
        boldEl = document.createElement("b");
        boldEl.style.color = "rgb(255,0,0)";
        boldEl.appendChild(myTextNode);
        boldEl.style.fontSize='24';
        el.appendChild(boldEl);
     }
  }else if(el.lastChild) el.removeChild(el.lastChild);


  //anisochronous check of reciprocal... (last step) 
  if(document.getElementById('recip').value != ''){
  	var recipURL = document.getElementById('recip').value;
    var url = root + 'signup_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;
}

///////////////////////////
var us_states = ['Alabama','Alaska','American Samoa','Arizona','Arkansas',
      'California','Colorado','Connecticut','Delaware','District of Columbia',
      'Florida','Georgia','Guam','Hawaii','Idaho','Illinois','Indiana','Iowa',
      'Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts',
      'Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska',
      'Nevada','New Hampshire','New Jersey','New Mexico','New York',
      'North Carolina','North Dakota','Northern Mariana Islands','Ohio',
      'Oklahoma','Oregon','Pennsylvania','Puerto Rico','Rhode Island',
      'South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont',
      'Virgin Islands','Virginia','Washington','West Virginia','Wisconsin',
      'Wyoming'];
var uk_ctrs = ['England','Isle of Man','N. Ireland','Scotland','Wales'];

function setStates(){

  var elSel = document.getElementById('state');
  for (i = elSel.length - 1; i>=0; i--) elSel.remove(i);

  el = document.getElementById('stateTitle');
  el.removeChild(el.lastChild);
  boldEl = document.createElement("b");

  var inx = document.getElementById('country').selectedIndex;
  var cntry = document.getElementById('country').options[inx].text;
  if(cntry=='United States'){
    //document.getElementById('zipcode').disabled=false;
    eval("document.getElementById('zipcode').value=''");

    //document.getElementById('state').disabled=false;
      for (var i=0; i < us_states.length; i++) {
      eval("document.getElementById('state').options[i]=new Option(us_states[i])");
    }
    boldEl.appendChild(document.createTextNode("State/Province: \u00a0"));
    el.appendChild(boldEl);
  }else if(cntry=='United Kingdom'){
    //document.getElementById('zipcode').disabled=true;
    eval("document.getElementById('zipcode').value='n/a'");

    //document.getElementById('state').disabled=false;
    for (var i=0; i < uk_ctrs.length; i++) {
      eval("document.getElementById('state').options[i]=new Option(uk_ctrs[i])");
    }
    boldEl.appendChild(document.createTextNode("UK country: \u00a0"));
    el.appendChild(boldEl);
  }else{
    //document.getElementById('zipcode').disabled=true;
    eval("document.getElementById('zipcode').value='n/a'");

    //document.getElementById('state').disabled=true;
    eval("document.getElementById('state').options[0]=new Option('n/a')");

    boldEl.appendChild(document.createTextNode("State/Province: \u00a0"));
    el.appendChild(boldEl);
  }
  //setCities(); //temp commented
}


   ////////////////////////////////////////////////////
   //////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.formSignup.submit();
      }
	  
   }

  function runDataAjax() {
    //alert(document.getElementById('recip'));
    var url = 'http://tiv:82/_func/ajax_data.php?'
              + 'recip=' + document.getElementById('recip').value
              + '&escaName=' + document.getElementById('escaName').value
              + '&escaEmail=' + document.getElementById('escaEmail').value
              + '&website=' + document.getElementById('website').value
              + '&country=' + document.getElementById('country').value
              + '&state=' + document.getElementById('state').value
              + '&zipcode=' + document.getElementById('zipcode').value
              + '&city=' + document.getElementById('city').value
              + '&phone=' + document.getElementById('phone').value
              + '&gender=' + document.getElementById('gender').value
              + '&hairColor=' + document.getElementById('hairColor').value
              + '&hairStyle=' + document.getElementById('hairStyle').value
              + '&age=' + document.getElementById('age').value
              + '&height1=' + document.getElementById('height1').value
              + '&height2=' + document.getElementById('height2').value
              + '&heightUnit=' + document.getElementById('heightUnit').value
              + '&weight=' + document.getElementById('weight').value
              + '&weightUnit=' + document.getElementById('weightUnit').value
              + '&cupSize=' + document.getElementById('cupSize').value
              + '&chest=' + document.getElementById('chest').value
              + '&chestUnit=' + document.getElementById('chestUnit').value
              + '&waist=' + document.getElementById('waist').value
              + '&waistUnit=' + document.getElementById('waistUnit').value
              + '&hip=' + document.getElementById('hip').value
              + '&hipUnit=' + document.getElementById('hipUnit').value
              + '&body=' + document.getElementById('body').value
              + '&ethnicity=' + document.getElementById('ethnicity').value
              + '&straight=' + document.getElementById('straight').value
              + '&masseuse=' + document.getElementById('masseuse').value
              + '&girlfriend=' + document.getElementById('girlfriend').value
              + '&dominatrix=' + document.getElementById('dominatrix').value
              + '&submissive=' + document.getElementById('submissive').value
              + '&bisexual=' + document.getElementById('bisexual').value
              + '&lesbian=' + document.getElementById('lesbian').value
              + '&gay=' + document.getElementById('gay').value
              + '&dancer=' + document.getElementById('dancer').value
              + '&specialty=' + document.getElementById('specialty').value
              + '&men=' + document.getElementById('men').value
              + '&women=' + document.getElementById('women').value
              + '&couples=' + document.getElementById('couples').value
              + '&groups=' + document.getElementById('groups').value
              + '&available_to=' + document.getElementById('available_to').value
              + '&incall=' + document.getElementById('incall').value
              + '&outcall=' + document.getElementById('outcall').value
              + '&availability=' + document.getElementById('availability').value
              + '&affiliation=' + document.getElementById('affiliation').value
              + '&shortDesc=' + document.getElementById('shortDesc').value
              + '&longDesc=' + document.getElementById('longDesc').value
              + '&img=' + document.getElementById('img').value
              + '&img2=' + document.getElementById('img2').value
              + '&img3=' + document.getElementById('img3').value
              + '&img4=' + document.getElementById('img4').value
              + '&submitInput=' + document.getElementById('submitInput').value;
	
    runAjax(url);	  
	  
  }
  
  /*function runImgAjax(last_id) {
    //alert(document.getElementById('recip'));
    var url = 'http://tiv:82/_func/ajax_img.php?'
              + 'last_id=' + last_id
              + '&img=' + document.getElementById('img').value
              + '&img2=' + document.getElementById('img2').value
              + '&img3=' + document.getElementById('img3').value
              + '&img4=' + document.getElementById('img4').value;			  
	
    runAjax(url);	  
	  
  }*/
  
  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;
  }
