var currentDate = new Date();

var arrivalDate=null;
var celldate = null;
var updatedCellDate = null;
var nights = 0; 
var checkindate=null;
var prevflag="false";


var prevnextFlag="false";

//new
var chkoutDate=null;


//This is called on clicking of show calendar link
function showCal() {
    
      //alert("calendar visibility "+document.getElementById('calendar').style.visibility);
   	  prevnextFlag="false";
	  celldate = document.selectOccupancyForm.arrDate.value;
	  document.getElementById('calendar').style.visibility="visible";
	  document.getElementById('cal').style.visibility="visible";
	  document.getElementById('show').style.visibility="hidden";
	  document.getElementById('hide').style.visibility="visible";
	  
	  document.getElementById('hide').style.display='inline';
	  document.getElementById('show').style.display='none';
	  
	  document.getElementById('calendar').style.display='';
	  document.getElementById('cal').style.display='';
	  //NEW TO SET CHKOUTDATE and nights
	  var thisForm = document.selectOccupancyForm;
	  nights = thisForm.nights[thisForm.nights.selectedIndex].value;
	  setCheckOutDate();
	  getCalendarDetails();
}

function hideCal() {
  //alert("HIDECAl");
 
   document.getElementById('cal').style.visibility="hidden";
   document.getElementById('cal').innerHTML="";
    document.getElementById('calendar').style.visibility="hidden";
   document.getElementById('hide').style.visibility="hidden";
   document.getElementById('show').style.visibility="visible";
   
   document.getElementById('show').style.display='inline';
   document.getElementById('hide').style.display='none';
   //alert("hidecal "+document.getElementById('show').style.visibility);
}
//Called on click of updatebutton
function onUpdateClick(thisForm){
	  
         nights = thisForm.nights[thisForm.nights.selectedIndex].value;
         //arrivalDate = thisForm.arrDate.value;
         
         //Calendar cell is not clicked,but since same ajax call is needed
         //we can make the arrivaldate as cell date
         celldate=document.selectOccupancyForm.arrDate.value;
         prevnextFlag="false";
         //alert("onUpdateclick() cell nights "+nights);
         //setCheckOutDate();
         getCalendarDetails();
     
}

function previous(mon,year) {
    // Apr 11 -- not to go to prev page if the checkoutdate is  > 350 days from current
    if(checkdateOnPrevious() == false)
      return false;
    //alert("mon "+mon);	
    var mons=0;
	if(mon != 0) {
		 mons = mon-1;
		 currentDate.setYear(year);
	}	 
	else if(mon == 0) {
	    var mons=11;	
	    var year=year-1;
	    currentDate.setYear(year);
	   // alert("mon 0 setting months 11 year  "+year);
    }
    
    //var mons=mon-1;
             			
	//alert("get month before setting "+currentDate.getMonth() +" mons "+mons);
	
	currentDate.setMonth(mons);
	
	
	arrivalDate=currentDate;
	//new
	checkindate= document.selectOccupancyForm.arrDate.value;
	prevflag="true";	
	
	prevnextFlag="true";
	celldate=null;
	getCalendarDetails();
	
	

}

function next(mon,year) {
	
	//alert("mon "+mon +" year "+year);
	var mons = mon+1;
	//alert("get month before setting "+currentDate.getMonth() +" mon "+mon);
	currentDate.setMonth(mon);
	
	//set current year as year passed 
	currentDate.setYear(year);
	
	
	
	arrivalDate=currentDate;
	//new
	prevflag="false";
	checkindate= document.selectOccupancyForm.arrDate.value;
	
	//alert("NEXT fun mon "+mons+" nextmonth "+currentDate.getMonth());
	prevnextFlag="true";
	celldate=null;
	getCalendarDetails();
  

}


//called on cliking a cell in the calendar
//caldate1 is in mm/dd/yy format
function popCal(caldate,caldate1){
//alert("CLASS NAME OF " +caldate+" STYLE bk"+document.getElementById(caldate).style.fontFamily);
prevnextFlag="false";
document.selectOccupancyForm.arrDate.value=caldate1;
nights =document.selectOccupancyForm.nights[document.selectOccupancyForm.nights.selectedIndex].value;
//Apr 10
setCheckOutDate();
if(checkdate() == false){
	return false;
}

if(caldate != null){
	
	//alert("Arrivaldate changed to cell date "+document.forms[0].arrDate.value);
	//new to set checkout date
	//setCheckOutDate();
	
	celldate = caldate1;
	var datePassed = new Date(caldate1);
	var curdate = new Date();
	curdate.setHours(0);curdate.setMinutes(0);curdate.setSeconds(0);
	//alert("date passed "+datePassed +" currentdate "+curdate);
	if(datePassed > curdate)
		getCalendarDetails();
	else if(datePassed.getDate() == curdate.getDate())
	 getCalendarDetails();			
	else
		alert("date passed is less than currentdate");   		
}
}

function getCalendarDetails()
  { 
	
	  
	  var xmlHttp;
  try
    {    // Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest(); 
  }
  catch (e)
    {    // Internet Explorer    
  try
    {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");     
	}
    catch (e)
    { 
		try 
        {   
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");       
		}
      catch (e)
        {   
		  alert("Your browser does not support AJAX!");        return false;    
		} 
	} 
   }

    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
        
        	if(xmlHttp.status  == 200){
        	
			  //alert("ready to display calendar ");
			  var cal = document.getElementById('cal');
			  
			  
			  //NEW FOR CHECKING IF THE TEXT HAS WHOLE HTML
			  var respHtml=xmlHttp.responseText;
			  if(prevnextFlag == "true") {
			 	//alert("response has div only");
			  	 //alert("Responsetext  "+xmlHttp.responseText);
			 	cal.innerHTML=xmlHttp.responseText;
			 	
			 	showdate('range');
			  }
			  else {
			  	// alert("Responsetext has entire HTML "+xmlHttp.responseText);
			     var divElements=splitTextIntoDiv(respHtml);  
			     //alert("after splittext divelems "+divElements);
			     replaceExistingWithNewHtml(divElements);
			
			  }
			  //NEW
			  if(prevnextFlag=="true") 
			     checkdateOnPrevious();
			     
			 	highlight();
			  
			   //new for restriction  - ajax call Apr 9
			   if(prevnextFlag=="false")
			   	getRestrictionDetails();
			   //End new for restriction  - ajax call Apr 9
			   
	        }
	        else if(xmlHttp.status  == 404)
	       {
	       		alert('Unable to contact server. Please try again later.');
	       }
	       else{
		       	alert('An error occurred while connecting to server.\nPlease try again later.');
	       }
      }
    }
    
    if(celldate != null) {
    	//alert("CELLDATE NOT NULL BEFORE CALLING AJAX "+document.selectOccupancyForm.nights.value);
    	xmlHttp.open("GET","priceAvail.do?cellDate="+celldate+"&nights="+nights+"&chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);    
    }
    /*else if(updatedCellDate != null) {
    	xmlHttp.open("GET","priceAvail.do?updatedCellDate="+updatedCellDate
    }*/
   
    else if(arrivalDate != null) {
       //alert("arrivaldate not null calling calendar action "+arrivalDate.toLocaleString()); 
    	xmlHttp.open("GET","Calendar.do?Monthstart="+arrivalDate.toLocaleString()+"&checkindate="+checkindate+"&prevflag="+prevflag+"&chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);
    } 	
    else
    	xmlHttp.open("GET","Calendar.do?Monthstart="+currentDate.toLocaleString()+"&" + (new Date()).getTime(),true);
    xmlHttp.send(null); 
}


function splitTextIntoDiv(textToSplit){
 
  //Split the document
  var returnElements=textToSplit. 
            split("</div>")
        
  //Process each of the elements        
  for(var i=returnElements.length-1;i>=0;--i){
                
    //Remove everything before the 1st span
    var divPos = returnElements[i]. 
             indexOf("<div");               
                
    //if we find a match, take out 
    //everything before the span
    if(divPos>0){
          subString=returnElements[i].substring(divPos);
          returnElements[i]=subString;
    } 
  }
  return returnElements;
}

function replaceExistingWithNewHtml 
        (newTextElements){
 var elementFound = false;
  //loop through newTextElements
  for(var i=newTextElements.length-1;i>=0;--i){
  	
  	
    //check that this begins with <span
    if(newTextElements[i].indexOf("<div")>-1){
                        
          //get the div name - sits
      // between the 1st and 2nd quote mark
      //Make sure your spans are in the format 
      var startNamePos=newTextElements[i].indexOf('"')+1;
      var endNamePos=newTextElements[i].indexOf('"',startNamePos);
      var name=newTextElements[i].substring(startNamePos,endNamePos);
                        
      //get the content - everything 
      // after the first > mark
      var startContentPos=newTextElements[i].indexOf('>')+1; 
      var content=newTextElements[i].substring(startContentPos);
      //alert("ID OF DIV ELEMENT "+name);                  
     //Now update the existing Document 
     // with this element, checking that 
     // this element exists in the document
     if(name == "cal") {
     if(document.getElementById(name)){
         //alert("CONTENT "+content);
         document.getElementById(name).innerHTML = content;
         elementFound = true;
         
      }
     }
    }
    
  }//end of fn
  if(elementFound == false ){
    	alert('An Error Occured. Please Try Again Later.');
    }
  }
  
  function getRestrictionDetails() {
 
  var xmlHttp;
  try
    {    // Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest(); 
  }
  catch (e)
  {    // Internet Explorer    
  try
    {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");     
	}
  catch (e)
    { 
		try 
        {   
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");       
			 
		}
      catch (e)
        {   
		  alert("Your browser does not support AJAX!");        return false;    
		} 
	} 
   }
        //alert("chkoutdate "+document.selectOccupancyForm.depDate.value);
  		xmlHttp.open("GET","restriction.do?chkoutdate="+document.selectOccupancyForm.depDate.value+"&" + (new Date()).getTime(),true);    
        xmlHttp.send(null); 
        
        
   xmlHttp.onreadystatechange=function()
   {
      if(xmlHttp.readyState==4)
      {
        var responsetxt=xmlHttp.responseText;
        if(responsetxt !=  null) {
	        var msg=responsetxt.substring(0,responsetxt.indexOf('*'));
	        var caldate=responsetxt.substring(responsetxt.indexOf('*')+1);
	        //alert(msg +"caldate "+caldate);
	        popup(msg,'blue',caldate); 
        }
        
      }
      else{
           //alert("inside call "+xmlHttp.readyState);
      }  
  	}
  
}//end of fn
	
	

