// setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------
var global_valfield;

function setFocusDelayed(){
  try{
     global_valfield.focus();
  }
  catch(e){
  }
}

function setfocus(valfield){
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100);
 }

function ValidateText(tbox){
 var txtBx = document.getElementById(tbox);
 if ((txtBx.value == "")||(txtBx.value == null)||(txtBx.value.length ==0)){
    txtBx.value="";
    alert("Please enter some text.");
    setfocus(txtBx);
    return false;
 }
 else{
    return true;
 }
}

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        //Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) 
           return false;
    }
    // All characters are numbers.
    return true;
}

function checkNum(tbx){
  var tbxOb=document.getElementById(tbx);
  if ((tbxOb.value=="")||(tbxOb.value==null))
     tbxOb.value=0;
  if (isInteger(tbxOb.value)==false){
     tbxOb.value=0;
  }
}


function ValidateUsername(tbox){
 var txtBx = document.getElementById(tbox);
 if ((txtBx.value == "")||(txtBx.value == null)||(txtBx.value.length <5)||(txtBx.value.indexOf(" ")!=-1)) {
      txtBx.value="";
      alert("Please enter username. Should be atleast 5 characters, max 8 Characters. No spaces allowed.");
      setfocus(txtBx);
      return false;
 }
 return true;
}

function ValidatePassword(tbox){
 var txtBx = document.getElementById(tbox);
 if ((txtBx.value == "")||(txtBx.value == null)||(txtBx.value.length <5)||(txtBx.value.indexOf(" ")!=-1)) {
     txtBx.value="";
     alert("Please enter password. Should be atleast 5 characters. No spaces allowed.");
     setfocus(txtBx);
     return false;
 }
 return true;
}

function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert("Invalid E-mail ID");
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Invalid E-mail ID");
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert("Invalid E-mail ID");
	    return false;
	}

	if (str.indexOf(at,(lat+1))!=-1){
	    alert("Invalid E-mail ID");
	    return false;
        }

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert("Invalid E-mail ID");
	    return false;
	}

	if (str.indexOf(dot,(lat+2))==-1){
	    alert("Invalid E-mail ID");
	    return false;
        }
		
	if (str.indexOf(" ")!=-1){
	   alert("Invalid E-mail ID");
	   return false;
         }

 	return true;					
}

function ValidateEmail(emBxid){
	var emailID=document.getElementById(emBxid);
	
	if ((emailID.value==null)||(emailID.value=="")){
		alert("Please Enter your Email ID");
                setfocus(emailID);
		return false;
	}
	if (echeck(emailID.value)==false){
		emailID.value="";
                setfocus(emailID);
		return false;
	}
	return true
 }

function ValidateInteger(numBxId)
   {
   numBx=document.getElementById(numBxId);
   // parse the input as an integer
   var intValue = parseInt(numBx.value, 10);

   // if this is not an integer
   if (isNaN(intValue))
      {
      // clear text box
      numBx.value = "";
      alert('Please enter valid number.');
      setfocus(numBx);
      return false;
      }
   // if this is an integer
   else
      {
       return true;
      }     
}

function hasWhiteSpace(s)
{
var reWhiteSpace = new RegExp(/^\s+$/);
 // Check for white space
 if (reWhiteSpace.test(s)) {
  return true;
  }
 return false;
}

function validateCheckBox(cbxId,checkFor,what){
 var cbxs=document.getElementById(cbxId);
 //alert(cbxs.length);
/* alert(cbxs.length);
 var cbCnt;
 for (cb=0;cb=cbxs.length;cb++){
   if (cbxs[cb].checked){      
     cbCnt=cbCnt+1;
    }
  }
 if (cbCnt==checkFor){
  return true;
 }
 else{
  alert('Please select atleast '+checkFor+' option from '+what);
  return false;
 }*/
 return false;
}


//Simple form(search franchise) validation here
function validateSearchFranchise(){
  if (ValidateText('name'))
   if (ValidateText('address'))
    if (ValidateEmail('email'))
     if (ValidateInteger('phone'))
       if (ValidateText('details'))
          return true;
  return false;
}

function validateLocateForm(){
  if (ValidateText('locaterName'))
   if (ValidateText('locatingAdd'))
    if (ValidateEmail('locvaterEmail'))
     if (ValidateInteger('locaterPhone'))
      if (ValidateInteger('locaterSize'))
         return true;
  return false;
}

function validateFranchiseApplication(){
 married=document.getElementById('married');
 if (ValidateText('name'))
    return true;
 return false;
}


function validateTelFrnfFrm(){
  if (ValidateText('name'))
   if (ValidateEmail('email'))
    if (ValidateEmail('femail'))
     if (ValidateText('comments'))
        return true;
  return false;
}

function validateFeedBackForm(){
  if (ValidateText('name'))
   if (ValidateText('address'))
    if (ValidateEmail('uemail'))
       return true;
  return false;
}

function validateSendLinkForm(){
  if (ValidateEmail('send_to_address'))
   if (ValidateEmail('send_from_address'))
       return true;
  return false;
}

function validatePSPForm(){
   //if (validateCheckBox('preferredlocation:list',1,'Preferred Locations.'))
    if (ValidateInteger('length'))
     if (ValidateInteger('width'))
      if (ValidateInteger('height'))
       if (ValidateInteger('frontage'))
        if (ValidateInteger('totalcarpetarea'))
         if (ValidateInteger('totalarea'))
          if (ValidateText('whichbusiness'))
           if (ValidateInteger('expectedvalue'))
            if (ValidateText('name'))
             if (ValidateText('address'))
              if (ValidateInteger('phone'))
               if (ValidateEmail('email'))
                if (ValidateInteger('rentorinvreturn'))
                   return true;
  return false;
}


function validateOSBFormOfProperties(){
   if (ValidateText('propertyaddress'))
    if (ValidateInteger('length'))
     if (ValidateInteger('width'))
      if (ValidateInteger('height'))
       if (ValidateInteger('frontage'))
        if (ValidateInteger('totalcarpetarea'))
         if (ValidateInteger('totalarea'))
          if (ValidateText('neighborbrand'))
           if (ValidateText('propertydetails'))
            if (ValidateInteger('expectedvalue'))
             if (ValidateInteger('advance'))
              if (ValidateInteger('leaselmount'))
               if (ValidateInteger('expectedmg'))
                if (ValidateText('previousbs'))
                 if (ValidateInteger('averagebrandsale'))
                  if (ValidateInteger('paidrentwas'))
                   if (ValidateText('name'))
                    if (ValidateText('address'))
                     if (ValidateInteger('phone'))
                      if (ValidateEmail('email1'))
                          return true;
   return false;
}

function validateOSBForm(){
   if (ValidateText('name'))
    if (ValidateText('address'))
     if (ValidateInteger('phone'))
      if (ValidateEmail('email1'))
       if (ValidateText('mallname'))
        if (ValidateText('location'))
         if (ValidateText('averagefootfall'))
          if (ValidateText('expecteddepositrate'))
           if (ValidateText('expecteddepositrate'))
            if (ValidateText('proximitytoother'))
             if (ValidateText('proximitytocolonies'))
              if (ValidateText('highlights'))
                  return true;
   return false;
}

function validateOtherForms(){
 if (ValidateText('name'))
  if (ValidateText('raddress'))
   if (ValidateText('education'))
    if (ValidateInteger('hphone'))
     if (ValidateInteger('wphone'))
      if (ValidateInteger('mobile'))
       if (ValidateEmail('email1'))
        if (ValidateText('workedatfranchise'))
         if (ValidateText('native'))
          if (ValidateText('nativeaddress'))
           if (ValidateText('pastachivements'))
            if (ValidateText('compname'))
             if (ValidateText('compaddress'))
              if (ValidateText('binterest'))
               if (ValidateText('othercompanies'))
                if (ValidateText('locaddress'))
                 if (ValidateInteger('dimension'))
                  if (ValidateText('neighborbrand'))
                   if (ValidateText('neighborbrand'))
                    if (ValidateInteger('parkingspace'))
                     if (ValidateText('timeframe'))
                      if (ValidateText('anyothercompany'))
                       if (ValidateText('referencedetails'))
                        if (ValidateText('suggestion'))
                           return true; 
 
 return false;
}

function validateEXFRForm(){
   if (ValidateText('name'))
    if (ValidateText('raddress'))
     if (ValidateInteger('hphone'))
      if (ValidateInteger('wphone'))
       if (ValidateInteger('mobile'))
        if (ValidateEmail('email1'))
         if (ValidateText('companies'))
            return true;
   return false;
}

function validateFranchisorForm(){
 if (ValidateText('name'))
  if (ValidateText('address'))
   if (ValidateInteger('hphone'))
    if (ValidateInteger('mobile'))
     if (ValidateInteger('mobile'))
      if (ValidateEmail('email1'))
       if (ValidateText('position'))
         if (ValidateText('compname'))
          if (ValidateText('compaddress'))
           if (ValidateText('city'))
            if (ValidateText('country'))
             if (ValidateInteger('contactnum'))
              if (ValidateInteger('officenum'))
               if (ValidateText('btype'))
                if (ValidateText('brandname'))
                 if (ValidateInteger('franchiseecnt'))
                  if (ValidateText('othercountries'))
                   if (ValidateText('bvolume'))
                    if (ValidateText('invprofile'))
                     if (ValidateInteger('totalcost'))
                      if (ValidateInteger('franchisefee'))
                       if (ValidateText('royalty'))
                        if (ValidateText('advertisements'))
                         if (ValidateText('training'))
                          if (ValidateText('infrastructure'))
                           if (ValidateText('staff'))
                            if (ValidateText('territories'))
                             if (ValidateText('specificreq'))
                              if (ValidateText('remarks'))
                                 return true; 
 
 return false;
}

function validateMallOwnerForm(){
   if (ValidateText('mallname'))
    if (ValidateText('franchisein'))
     if (ValidateInteger('totalsqft'))
      if (ValidateText('contact'))
       if (ValidateInteger('phonenum'))
          return true;
   return false;
}

function validateDetailedMallOwnerForm(){
   if (ValidateText('mallname'))
    if (ValidateText('promoters'))
     if (ValidateText('location'))
      if (ValidateText('details'))
       if (ValidateText('anchors'))
        if (ValidateText('obrands'))
         if (ValidateInteger('totalsqft'))
          if (ValidateText('sentby'))
           if (ValidateText('designation'))
            if (ValidateInteger('phone'))
             if (ValidateText('incharge'))
                return true;
   return false;
}

function validateAddWithUsForm(){
   if (ValidateText('name'))
    if (ValidateEmail('email1'))
     if (ValidateInteger('phone'))
      if (ValidateText('compname'))
       if (ValidateText('compurl'))
        if (ValidateText('comment'))
           return true;
   return false;
}


function validateFantasticFranchise(){
   if (ValidateText('name'))
    if (ValidateText('address'))
     if (ValidateInteger('phone'))
      if (ValidateEmail('email1'))
       if (ValidateText('position'))
        if (ValidateText('cmpname'))
         if (ValidateText('cmpadd'))
          if (ValidateInteger('pincode'))
           if (ValidateText('city'))
            if (ValidateText('country'))
             if (ValidateInteger('officephone'))
              if (ValidateText('btyp'))
               if (ValidateText('bname'))
                  return true;
   return false;
}

function validateGoodFranchise(){
   if (ValidateText('name'))
    if (ValidateText('address'))
     if (ValidateInteger('phone'))
      if (ValidateEmail('email1'))
       if (ValidateText('position'))
        if (ValidateText('cmpname'))
         if (ValidateText('cmpadd'))
          if (ValidateInteger('pincode'))
           if (ValidateText('city'))
            if (ValidateText('country'))
             if (ValidateInteger('officephone'))
              if (ValidateText('btyp'))
               if (ValidateText('bname'))
                if (ValidateText('bvolume'))
                 if (ValidateText('tpcost'))
                  if (ValidateText('training'))
                   if (ValidateText('infra'))
                    if (ValidateText('territories'))              
                       return true;
   return false;
}



//Tabbed validations (franchisor from)

function SelectCount(thefield) {
  for( var i=0,count=0; i<thefield.length; i++ ) {
	count += ( thefield.options[i].selected ? 1 : 0 )
  }	
  return count;
}

function SelectDefault(thefield){
 thefield.options[0].selected = true;
 }

function DeSelect(thefield){
  for( var i=0;i<thefield.length; i++ ) {
     thefield.options[i].selected=false;
  }
}

function validateCities(state,citiid){
 var citiLst=document.getElementById(citiid);
 if (state.checked){
    if (SelectCount(citiLst)==0){
        SelectDefault(citiLst);
    }
    return 1; 
 }
 else{
    DeSelect(citiLst); 
    return 1;
 } 
}

var zones=new Array("north","south","east","west","central");

function validateStates(prefix,under){
 var zcount=0;
 //alert('Zonal prefix is : '+prefix);
 for (var z=0;z<zones.length;z++){
    var zbxid=prefix+zones[z]+'_main';
        //alert(zbxid);
    var sbxLstid=prefix+zones[z]+':list';
        //alert(sbxLstid);        
    var zbx=document.getElementById(zbxid);
        //alert(zbx);
    var sbxLst=document.getElementsByName(sbxLstid);
        //alert(sbxLst);
    zcount+=(zbx.checked ? 1 : 0); //If any zone is selected or not 
    //alert('Zone - '+zones[z]);
    if (zbx.checked){
       var scount=0;
       for (s=0;s<sbxLst.length;s++){
           //alert('State - '+scount);
           scount+=(sbxLst[s].checked ? 1 : 0);  
       }
       if (scount==0){//No states selected
          alert(under+'\nPlease select the state in '+zones[z]+' zone.');
          return 0;
          break;
       } 
    } 
 }
 if (zcount==0){//No states selected
     alert(under+'\nPlease select a zone.');
     return 0;
 }

}

function validateModel(modelNum){
  var flds=new Array('fitoutcharge','franchisefee','nonrefunds','securitydeposit','workingcapital','otherinvestment'); 
  var total=0;
  var total_per=0;
  for (k=0;k<flds.length;k++){
      var fbx=document.getElementById(flds[k]+'_'+modelNum);
      if ((fbx.value=="")||(fbx.value==null))
         fbx.value=0;
      if (isInteger(fbx.value)==false)
         fbx.value=0;
      total+=parseInt(fbx.value);   
      var fpbx=document.getElementById(flds[k]+'_per_'+modelNum);
      if ((fpbx.value=="")||(fpbx.value==null))
         fpbx.value=0;
      if (isInteger(fpbx.value)==false)
         fpbx.value=0;
      total_per+=parseInt(fpbx.value);
  }
  var tbx=document.getElementById('totalinvestment_'+modelNum);
  var tbhx=document.getElementById('totalinvestment_hid_'+modelNum);
  var tpx=document.getElementById('totalinvestment_per_'+modelNum);
  var tphx=document.getElementById('totalinvestment_per_hid_'+modelNum);
  var cumplsbx=document.getElementById('compulsionval_'+modelNum);
  var cumplspbx=document.getElementById('compulsionval_per_'+modelNum);
  var cumplsphbx=document.getElementById('compulsionval_per_hid_'+modelNum);
  tbx.value=total;
  tbhx.value=total;
  tpx.value=total_per;
  tphx.value=total_per;
  if ((cumplsbx.value=="")||(cumplsbx.value==null))
     cumplsbx.value=0;
  if (total==0){ 
     cumplspbx.value=0;
     cumplsphbx.value=0;     
  }
  else{
     cumplspbx.value=(parseInt(cumplsbx.value)*100)/parseInt(total);
     cumplsphbx.value=(parseInt(cumplsbx.value)*100)/parseInt(total);
  }
}

function validateUsername(){
  xmlhttpPost('scripts/validateUsername','uname');
}


function validateWnd(divId){
 //alert('Requested to validate '+divId);
 if (divId==1){
    //Check for is already a member
    var ism=document.getElementById('isMem');
    if (ism.value==0){ 
       if (ValidateUsername('uname'))
          if (ValidatePassword('pword'))
             return 1;
       //hightlight(divId);
       return 0;
    }
    else{
       return 1;
    } 
 }
 if (divId==2){
    var bseg=document.getElementById('bsegment');     
    var obseg=document.getElementById('bsegmentother');  
    if (ValidateText('companyname'))
       if (ValidateText('brand'))
          if (ValidateText('address'))
             if (ValidateText('city'))
                if (ValidateText('state'))
                   if (ValidateInteger('pincode'))
                      if (ValidateInteger('landphone'))
                         if (ValidateInteger('mobile'))
                            if (ValidateEmail('email1'))
                               if (ValidateText('ceo'))
                                  if (ValidateText('managername'))
                                      return 1;
                                           
    //hightlight(divId);
    return 0;
 }

 if (divId==3){
    var unitfr=document.getElementById('unit');
    var unitfrrole=document.getElementById('unitrole');
    var masterfr=document.getElementById('master');
    var masterfrrole=document.getElementById('masterrole');
    var demarcation=document.getElementById('demarcation');
    //alert(document.getElementById('geographicrights').checked); 
    if ((unitfr.checked==0) && (masterfr.checked==0)){
       alert('Please select the franchise type you are seeking.');
       return 0; 
    }

    if (unitfr.checked==true){
        if ((unitfrrole.value=="")||(unitfrrole.value.length<20)){ 
           alert('Define the Unit /Single franchisees role. (Atleast 20 characters.)');           
           setfocus(unitfrrole);
           return 0;
        } 
    }

    if (masterfr.checked==true){
        if ((masterfrrole.value=="")||(masterfrrole.value.length<20)){ 
           alert('Define the master franchisees role. (Atleast 20 characters.)');           
           setfocus(masterfrrole);
           return 0;
        } 
    }

    if (document.getElementById('geographicrights').checked==true){
        if ((demarcation.value=="")||(demarcation.value.length<20)){ 
           alert('Define the demarcation we follow. (Atleast 20 characters.)');           
           setfocus(demarcation);
           return 0;
        } 
    }

    if (validateStates('ex','No Of Own Centers/Outlets Currently Operational')==0){
       return 0;  
    }

    if (validateStates('sk','No Of Franchisee Centers/Outlets You are Seeking')==0){
       return 0;  
    }

   return 1;           
 }

 if (divId==4){
    var modelObj=document.getElementById('modelcount');
    var modelNum=modelObj.options[modelObj.selectedIndex].value;
    for (m=1;m<=modelNum;m++){ //Referesh the totals
        validateModel(m);
    }
    return 1;    
 }

 if (divId==5){
    var preq=document.getElementById('prototyperequired'); 
    if ((preq.value=="")||(preq.value.length<20)){ 
        alert('What type of property is required for this franchise opportunity? (Atleast 20 characters.)');           
        setfocus(preq);
        return 0;
    } 
    return 1;    
 }

 if (divId==6){
    return 1;    
 }

 if (divId==7){
    var profile=document.getElementById('idealprofile'); 
    var skill=document.getElementById('requiredskill'); 
    var edu=document.getElementById('education'); 
    if ((profile.value=="")||(profile.value.length<20)){ 
        alert('What would be the ideal profile you are seeking as your franchisee? (Atleast 20 characters.)');           
        setfocus(profile);
        return 0;
    } 
    return 1;    
 }

 if (divId==8){
    return 1;    
 }
 return 0; //Shud be zero
}

//Tabbed actions

function hightlight(divEle){
  for(i=1;i<=8;i++){
    oDiv=document.getElementById(i);
    oFrmDiv=document.getElementById('form'+i);
    if (divEle!=i){
       oDiv.className='';
       oFrmDiv.style.display='none';
    }
    else{
       oDiv.className='active';       
       oFrmDiv.style.display='block';
       if (i==4){//Investment tab (Enable models)
          var modelObj=document.getElementById('modelcount');
          var modelNum=modelObj.options[modelObj.selectedIndex].value;
          for(k=1;k<6;k++){
             mObj=document.getElementById('model_'+k);
             if (k<=modelNum){
                mObj.style.display='block';
             }
             else{
                mObj.style.display='none';
             }             
          }  
       }
    }
  } 
}

function makeActive(divEle){
 //Validate previous window brfore navigating
 //alert('Clcked on tab - '+divEle);
 for(a=1;a<=divEle;a++){
     //alert('Validating tab - '+a);
     var vs=validateWnd(a);
     //alert('Validation of tab - '+a+' is '+vs); 
     if (vs==1){
        //alert('Validated tab - '+a); 
        hightlight(divEle);
     }
     else{
      //alert('Hilighting tab - '+a);        
      hightlight(a);
      break; 
     }
 }
}

function validateAllTabs(){
  for(t=1;t<9;t++){
     //alert('Form - '+t); 
     var s=validateWnd(t);
     if (s==0){          
        hightlight(t);         
        return false;
        break; 
     }
     else{
        hightlight(t);
     }
  }
 return true;
}

/*
    if (divEle!=a){  //Dont validate the currently clicked window   
       if (validateWnd(a)){
          //alert('validated '+a);
          hightlight(divEle);
       }
    }
*/

function nxt(){
  var sDiv=1;
  for(i=1;i<=8;i++){
    oDiv=document.getElementById(i);
    if (oDiv.className=='active'){
       sDiv=i;
       break;  
    }
  }
  if (i!=8){
       makeActive(sDiv+1);
  } 
}

function prv(){
  var sDiv=1;
  for(i=1;i<=8;i++){
    oDiv=document.getElementById(i);
    if (oDiv.className=='active'){
       sDiv=i;
       break;  
    }
  }
  if (i!=1){
       makeActive(sDiv-1);
  }  
}

//Ajax call


function xmlhttpPost(strURL,tbox) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            var resp=self.xmlHttpReq.responseText;             
            var resp=resp.split(':');
            var tbx=document.getElementById(tbox);
            if (resp[0]==1){  
               document.getElementById('userMsg').innerHTML='<b style="color:green;">'+resp[1]+'</b>';               
            } 
            else{
               tbx.value="";
               document.getElementById('userMsg').innerHTML='<b style="color:red;">'+resp[1]+'</b>';               
               setfocus(tbx);
            }

        }
        else{
            document.getElementById('userMsg').innerHTML='<b style="color:yellow;">Cheking the username..please wait.</b>';
            setfocus(tbx);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var word = document.getElementById('uname').value;
    qstr = 'uname=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}