var farematrix = null;
var isReturn = false;
var NUM_CENTYEAR=30;
var BUL_TIMECOMPONENT=false;
var BUL_YEARSCROLL=true;
var calendars=[];
var RE_NUM=/^\-?\d+$/;
var monthAry=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var ARR_MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];
var ARR_WEEKDAYS=["Sun","Mon","Tue","Wed","Thur","Fri","Sat"];
var NUM_WEEKSTART=0;
var currDate;
var dt_current;
var passedDate;
var depdate;
var dt_firstday;
var curday;
var curmon;
year_scroll=BUL_YEARSCROLL;
var sysDate='';
var targetDisplayCol='';
var targetDisplayColHidden='';
var mflag=0;
var ctflag=0;
var airlineCode = "ALL";
var sortedFareMatrix = null;
var lowestfaremonth = 0;
var rm=new Object();
  rm.tiptriptype="If you are facing problem to find your desider airport tou can use airport link to find nearest airport to your destination through maps.";
  rm.farecalanderoneway="The best fares found by MakeMyTrip users are for depatures are displayed for one year.You can change airline to find best fare found for that airline.";
  rm.farecalanderreturn="The best fares found by MakeMyTrip users are for depatures are displayed for one year.You can change airline to find best fare found for that airline.";
  rm.firstNameEmpty="First name of {paxdetails} cannot be empty";
  rm.lastNameEmpty="Last name of {paxdetails} cannot be empty";
  rm.email="Please enter valid email address";
  rm.phone="Please enter valid telephone number in the format of +91123456789";
  rm.title="Please select valid title of {paxdetails}";
  rm.bank="Please select valid title of {paxdetails}";
  rm.nameoncard="Name on card can not be empty";
  rm.cardtype="Name on card can not be empty";
  rm.cardnumber="Name on card can not be empty";
  rm.expirydate="Name on card can not be empty";
  rm.cvvnum="Name on card can not be empty";
  rm.billaddfname="Name on card can not be empty";
  rm.billaddmname="Name on card can not be empty";
  rm.billaddlname="Name on card can not be empty";
  rm.billaddr1="Name on card can not be empty";
  rm.billaddr2="Name on card can not be empty";
  rm.billaddrcity="Name on card can not be empty";
  rm.billaddrregion="Name on card can not be empty";
  rm.billaddrpincode="Name on card can not be empty";
  
function resetHeading(index){
                     $('.ui-accordion-content').hide();
                     var selector = '.ui-accordion-content:eq('+index+')';
                     $(selector).show();
                     var contents = $('.ui-accordion-content');
                     for(var i = 0;i<contents.length;i++){
                         var departure = document.getElementById("departure_"+i).value;
                         var arrival = document.getElementById("arrival_"+i).value;
                         var departureDate = document.getElementById("dFrom_"+i).value;
                              departureDate = $.datepicker.parseDate('mm/dd/yy',departureDate);
  					   departureDate = formatDate(new Date(departureDate),'dd NNN');
                         if(departure == ""||arrival==""||departureDate==""){
  		                     // do nothing;
  		                    }else{
  		                       var innerHTML = "<span>"+getAirportCode(departure)+"-"+getAirportCode(arrival)+"&nbsp;&nbsp;"+departureDate+"</span>";
  		                       document.getElementById('heading'+i).innerHTML = innerHTML;
  		                      
                           }
                         
                     }
        }
        
        function getAirportCode(aiportValue){
           var indexofComma = aiportValue.indexOf(",");
           var indexofhyphen = aiportValue.indexOf("-");
           var indexofcodestart = aiportValue.indexOf("(");
           var indexofcodeend = aiportValue.indexOf(")");
           return aiportValue.substr(indexofcodestart+1,3);
          
         }
       
  	function toggleAdditionOptions(){
  	          if($('#toggleAdditionOptions').hasClass('closedadditionaloptions')){
  		    $('#toggleAdditionOptions').removeClass('closedadditionaloptions');
  		    $('#toggleAdditionOptions').addClass('openedadditionaloptions');
  		    document.getElementById('additionoptions').style.display='block';
  		 }else{
  		    $('#toggleAdditionOptions').removeClass('openedadditionaloptions');
  		    $('#toggleAdditionOptions').addClass('closedadditionaloptions');
  		     document.getElementById('additionoptions').style.display='none';
  		 }
  	}
  	function selectAirport(field){
  	   document.forms[0].field.value=field;
  	   document.forms[0]._eventId.value='searchAirport';
  	   document.forms[0].submit();
  	}
  	function addflight(){
  	  document.forms[0]._eventId.value='addNewFlight';
  	  var url = document.forms[0].action;
  	  url = url+"&ajaxSource=true";
  	  var params = $("form").serialize();
  	  $.post(url, params,
                function(data){
                   $("form").parent().get(0).innerHTML=data;
                   eval($("#script").children("script").html());
                   
               });
  	  
  	  
  	}
  	function changeTripType(){
  	        $("#fareCalHeader").hide();
  	        $("#fareCalBody").hide();
  	        $("#farecalanderborder").hide();
  		$("#heroshot").show();
  		try{
  		getFareHistory();
  		}catch(e){}
  	       var val;
  	                               for(var i = 0 ; i <document.forms[0].tt.length;i++){
  	                                  if(document.forms[0].tt[i].checked){
  	                                     val = document.forms[0].tt[i].value;
  	                                  }
  	                               }
  	                               if(val=='O'){
  									   $('.itinerary').show();
  	                                  $('.ui-accordion-header').hide();
  	                                  $('.ui-accordion-content').hide();
  	                                  $('.returnSeg').hide();
  	                                  $('.ui-accordion-content:eq(0)').show();
  	                                  $('#depRangeCheck').show();
  	                                  $('.flexiOption').show();
  	                               }
  	                               if(val=='R'){
  	                                  $('.itinerary').show();
  	                                  $('.ui-accordion-header').hide();
  	                                  $('.ui-accordion-content').hide();
  	                                 $('.ui-accordion-content:eq(0)').show();
  	                                 $('.returnSeg').show();
  	                                 $('#depRangeCheck').show();
									  $('.flexiOption').show();
  	                               }
  	                               if(val=='M'){
  	                                   
  	                                    $('.itinerary').show();
  	                                    $('.ui-accordion-header').show();
  	                                    $('.returnSeg').hide();
  	                                    $('.ui-accordion-content').hide();
  	                                    $('#depRangeCheck').hide();
  	                                    $('.ui-accordion-content:eq(0)').show();
  	                                    $('#addFlight').show();
										$('.flexiOption').hide();
  	                                  document.getElementById('flexiSearchCheck').checked=false;setFlexiSearch();
  	                                    
                           }
      }
function Set_Cookie( name, value, expires, path, domain, secure ) 
	 {
	 	// set time, it's in milliseconds
		 var today = new Date();
		 today.setTime( today.getTime() );
	
		 /*
		 if the expires variable is set, make the correct 
		 expires time, the current script below will set 
		 it for x number of days, to make it for hours, 
		 delete * 24, for minutes, delete * 60 * 24
		 */
		 if ( expires )
		 {
		 expires = expires * 1000 * 60 * 60 * 24;
		 }
		 var expires_date = new Date( today.getTime() + (expires) );
	
		 document.cookie = name + "=" +escape( value ) +
		 ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		 ( ( path ) ? ";path=" + path : "" ) + 
		 ( ( domain ) ? ";domain=" + domain : "" ) +
		 ( ( secure ) ? ";secure" : "" );
	 }
	 // with this test document.cookie.indexOf( name + "=" );
	 function Get_Cookie( check_name ) {
	 	// first we'll split this cookie up into name/value pairs
	 	// note: document.cookie only returns name=value, not the other components
	 	var a_all_cookies = document.cookie.split( ';' );
	 	var a_temp_cookie = '';
	 	var cookie_name = '';
	 	var cookie_value = '';
	 	var b_cookie_found = false; // set boolean t/f default f
	 	
	 	for ( i = 0; i < a_all_cookies.length; i++ )
	 	{
	 		// now we'll split apart each name=value pair
	 		a_temp_cookie = a_all_cookies[i].split( '=' );
	 		
	 		
	 		// and trim left/right whitespace while we're at it
	 		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	 	
	 		// if the extracted name matches passed check_name
	 		if ( cookie_name == check_name )
	 		{
	 			b_cookie_found = true;
	 			// we need to handle case where cookie has no value but exists (no = sign, that is):
	 			if ( a_temp_cookie.length > 1 )
	 			{
	 				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
	 			}
	 			// note that in cases where cookie is initialized but no value, null is returned
	 			return cookie_value;
	 			break;
	 		}
	 		a_temp_cookie = null;
	 		cookie_name = '';
	 	}
	 	if ( !b_cookie_found )
	 	{
	 		return null;
	 	}
	 }
	 // this deletes the cookie when called
	 function Delete_Cookie( name, path, domain ) {
		 if ( Get_Cookie( name ) ) document.cookie = name + "=" +
		 ( ( path ) ? ";path=" + path : "") +
		 ( ( domain ) ? ";domain=" + domain : "" ) +
		 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	 }
function submitHomePage(){
      
      if(validateSearchCriteria()){
        
         document.forms[0].action='/international/international/direct';
         
         var formdata = document.forms[0].uniqueid.value;
         var today = new Date();
         today.setTime( today.getTime() );
 	if ( Get_Cookie( 'userbehavior') ){
 	       var string = Get_Cookie( 'userbehavior' ) ;
 	       string = "@Search."+today.getTime()+":"+formdata;
 	       Delete_Cookie('userbehavior','/', '');
 	       Set_Cookie('userbehavior', string, '30', '/', '', '' );
 	 }else{
 	    var string=today.getTime()+":"+formdata;
 	    Set_Cookie('userbehavior', string, '30', '/', '', '' );
 	}
 	Delete_Cookie('countdowntime', '/', '');
 	document.forms[0].submit();
 	}
 	
}

function submitHomePageIndia(){
       document.forms[0].action='http://cheapfaresindia.makemytrip.com/international/international/direct?RdCaPage=yes';
       document.forms[0].submit();
}

function findPosX(obj){
   var curleft=0;
    if(obj.offsetParent){
        while(obj.offsetParent){
	   curleft+=obj.offsetLeft;
	   obj=obj.offsetParent;
         }
     }else if(obj.x)
    curleft+=obj.x;
    return curleft;
}
function findPosY(obj){
    var curtop=0;
    if(obj.offsetParent){
       while(obj.offsetParent){
           curtop+=obj.offsetTop;
	   obj=obj.offsetParent;
	}
     }else if(obj.y)
     curtop+=obj.y;
     return curtop;
}
                                                        
                                                        
function initDate(strdtvalue){
   var noofdays = 0;
     var arr_date='';
     if(strdtvalue.indexOf('-')!=-1)
  	arr_date=strdtvalue.split('-');
  	else if(strdtvalue.indexOf('/')!=-1)
  	arr_date=strdtvalue.split('/');
  	var dtvalue=new Date(arr_date[2],Number(arr_date[1])-1,arr_date[0])
  	dtvalue=dtvalue.valueOf()+(noofdays>0?(60*60*(24*noofdays)*1000):0);
        var currentdatevalue = new Date().getTime();
        if(currentdatevalue>dtvalue){
        	noofdays = 2;
        	dtvalue=currentdatevalue+(noofdays>0?(60*60*(24*noofdays)*1000):0);
        }
        
  	sysDate=new Date(dtvalue);
        currDate=new Date(sysDate);
        var currDate1=currDate.valueOf()+((60*60*(24*0)*1000));
        currDate = new Date(currDate1);
        dt_current=new Date(currDate);
        dt_firstday=new Date(dt_current);
        dt_firstday.setDate(1);
        dt_firstday.setDate(1-(7+dt_firstday.getDay()-NUM_WEEKSTART)%7);
        curday=currDate.getDate();
        curmon=currDate.getMonth();
	dt_current=new Date(currDate);
	dt_firstday=new Date(dt_current);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-NUM_WEEKSTART)%7);
	curday=currDate.getDate();
	curmon=currDate.getMonth();
	passedDate=new Date(sysDate);
	
}
function getmontharray(){
     var CalToday=currDate;

     var montharray=new Array();

     var yeararray=new Array();

     var startmonth=CalToday.getMonth();

     var startyear=CalToday.getFullYear();

     var yearcount=0;

     for(var i=0;i<12;i++){
          montharray[i]=monthAry[startmonth++]
          yeararray[i]=startyear;

          if(startmonth>=12){
              startmonth=startmonth-12;

              if(yearcount==0){
                   startyear=startyear+1;
                   yearcount++;

              }
          }
     }
     var display="<ul class='cal-m'>";

     for(var j=0;j<12;j++){
          if(montharray[j]==monthAry[dt_current.getMonth()])
            display=display+'<li><a class="selected" href="javascript:changemonth(\''+montharray[j]+'\',\''+yeararray[j]+'\')">'+montharray[j]+'</a></li>';

          else display=display+'<li><a href="javascript:changemonth(\''+montharray[j]+'\',\''+yeararray[j]+'\')">'+montharray[j]+'</a></li>';

     }
     display=display+"</ul>"

     }
function displayCalendar(){
   var caldata='';
   caldata=caldata+"<div>Note:&nbsp;This calendar displays the best fares found by other MakeMyTrip users over the past. Due to rapidly changing airline prices & seat availability, these fares may no longer be available.</div>";
   caldata=caldata+"<div>&nbsp</div>";
   var dispdtmonyear=0;
   var columnDatevalue=0;
   lowestfaremonth = 0;
   var dispcurmonyear=currDate.getFullYear()+''+(Number(currDate.getMonth())<=9?'0'+currDate.getMonth():currDate.getMonth())+''+(Number(currDate.getDate())<=9?'0'+currDate.getDate():currDate.getDate());
   
   var monthheader="<a href=javascript:set_newdate('prev_month','limited')><img src='/international/img/international/page-prev.gif' width='12' height='15' align='absmiddle' alt='back' border='0'/></a>&nbsp;";
    monthheader=monthheader+ARR_MONTHS[dt_current.getMonth()]+' '+dt_current.getFullYear();
    monthheader=monthheader+"&nbsp;<a href=javascript:set_newdate('next_month','limited')><img src='/international/img/international/page-next.gif' width='12' height='15' align='absmiddle' alt='forward' border='0'/></a>";
    $('#months').html(monthheader);
    caldata=caldata+"<table class='cal-d' width='100%' class='fareCalander'  cellspacing='0' cellpadding='0' style='border:1px outset #A8C2FF'>";
    caldata=caldata+'<tr style="background-color: #EBF7FE;">';
     for(var n=0;n<7;n++){
       if(n==0||n==6){
         caldata=caldata+"<th scope='col' width=60 style='border:none;color:blue;background-color:#A8C2FF'>"+ARR_WEEKDAYS[(NUM_WEEKSTART+n)%7]+"</th>";
       }else{
         caldata=caldata+"<th scope='col' width=60 style='border:none;color:blue;background-color:#A8C2FF'>"+ARR_WEEKDAYS[(NUM_WEEKSTART+n)%7]+"</th>";
       }
     }
     caldata=caldata+'</tr>';
     
    var dt_current_day=new Date(dt_firstday);
    var selectedDate=passedDate.getFullYear()+''+(Number(passedDate.getMonth())<=9?'0'+passedDate.getMonth():passedDate.getMonth())+''+(Number(passedDate.getDate())<=9?'0'+passedDate.getDate():passedDate.getDate());
    var trindex = 0;
    while(dt_current_day.getMonth()==dt_current.getMonth()||dt_current_day.getMonth()==dt_firstday.getMonth())
    {
       caldata=caldata+'<tr style="background-color: #EBF7FE;">';
       for(var n_current_wday=0;n_current_wday<7;n_current_wday++){
         dispdtmonyear=dt_current_day.getFullYear()+''+(Number(dt_current_day.getMonth())<=9?'0'+dt_current_day.getMonth():dt_current_day.getMonth())+''+(Number(dt_current_day.getDate())<=9?'0'+dt_current_day.getDate():dt_current_day.getDate());
         if(n_current_wday==0){
          if(trindex==0){
             caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-bottom:1px solid gray;border-top:1px solid gray;background-color:#D9E4FF' valign='top'>";
           }else{
              caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-bottom:1px solid gray;background-color:#D9E4FF' valign='top'>";
           }
         }else if(n_current_wday==6){
		if(trindex==0){
		 caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-right:1px solid gray;border-bottom:1px solid gray;border-top:1px solid gray;background-color:#D9E4FF' valign='top'>";
		}else{
		  caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-right:1px solid gray;border-bottom:1px solid gray;background-color:#D9E4FF' valign='top'>";
		}
         }else{
                 if(trindex==0){
	 		 caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-bottom:1px solid gray;border-top:1px solid gray;background-color:white' valign='top'>";
	 		}else{
	 		  caldata=caldata+"<td width='60' height='50' style='border-left:1px solid gray;border-bottom:1px solid gray;background-color:white' valign='top'>";
		}
             
         }
         if(dt_current_day.getMonth()==curmon){
	      if(dispdtmonyear>dispcurmonyear){
	         if(dispdtmonyear==selectedDate){
		        caldata=caldata+"<a class='selected' title='"+ARR_MONTHS[passedDate.getMonth()]+" "+passedDate.getDate()+"'>";
		     }else{
		        caldata=caldata+"<a>";
	         }
	      }else if(dispdtmonyear==dispcurmonyear){
	         caldata=caldata+"<a class='today' title='"+ARR_MONTHS[currDate.getMonth()]+" "+currDate.getDate()+"'>";
	      }else
	         caldata=caldata+"<a class='n-a'>";
	    }else{
	     if(dispdtmonyear>dispcurmonyear){
	        if(dispdtmonyear==selectedDate){
			   caldata=caldata+"<a class='selected' title='"+ARR_MONTHS[passedDate.getMonth()]+" "+passedDate.getDate()+"'>";
	        }else{
			   caldata=caldata+"<a>";
	        }
	     }else
	       caldata=caldata+"<a class='n-a'>";
	    }
	    if(dt_current_day.getMonth()==dt_current.getMonth()){
	       var key = "";
	       if(dt_current_day.getDate()<10)
	         key = key+"0"+dt_current_day.getDate();
	       else
	         key = key+dt_current_day.getDate();
	       if((dt_current_day.getMonth()+1)<10){
	         key = key+"/0"+(dt_current_day.getMonth()+1);
	       }else{
	         key = key+"/"+(dt_current_day.getMonth()+1);
	       }
	       key = key+"/"+dt_current_day.getFullYear();
	       if(dispdtmonyear>dispcurmonyear){
	       }else{
	        key="";
	       }
	       if(airlineCode=='ALL'){
	          if(sortedFareMatrix[key]==null||sortedFareMatrix[key]["lowestfare"]==0){
	              caldata=caldata+"<span style='color:black'>"+dt_current_day.getDate()+"</span></a><br/>"+"</td>";
	           }else{
	             var created = sortedFareMatrix[key]["fareObject"]["created"];
	             var createdSec = created/1000;
	             
	             var createdHours = parseInt(createdSec/3600);
	              createdSec = createdSec-createdHours*3600;
	             var createdMinutes = parseInt(createdSec/60);
	             createdSec = createdSec-createdMinutes*60;
	             var returndate = "";
	             if(sortedFareMatrix[key]["fareObject"]["return"]==""){
	             }else{
	             var dateDate = $.datepicker.parseDate('dd/mm/yy',sortedFareMatrix[key]["fareObject"]["return"]);
	             returndate=$.datepicker.formatDate("dd M",dateDate);
	             }
	 	     caldata=caldata+"<span style='color:black' class='"+sortedFareMatrix[key]["lowestfare"]+"'>"+dt_current_day.getDate()+"</span></a><br/><br/>&nbsp;&nbsp;<a href='javascript:selectDate("+'"'+key+'","'+sortedFareMatrix[key]["fareObject"]["return"]+'"'+")'><span style='font-size:9px;font-family:Arial'>"+formatCurrency(sortedFareMatrix[key]["lowestfare"])+"</span></a>";
	 	     if(returndate==""){
		     		   	  caldata=caldata+"</td>"
		     		   	}else{
		     		   	  caldata=caldata+"<div align='right'>"+returndate+"</div></td>";
		   	}
		   	if(lowestfaremonth==0){
				 	      lowestfaremonth = sortedFareMatrix[key]["lowestfare"];
				 	   }else if(lowestfaremonth>sortedFareMatrix[key]["lowestfare"]){
				 	       lowestfaremonth = sortedFareMatrix[key]["lowestfare"];
	 	   }
	 	     
	 	   }
	 	   
	 	}else{
	 	     if(sortedFareMatrix[key]==null||sortedFareMatrix[key]["lowestfare"]==0){
	 	        caldata=caldata+"<span style='color:black'>"+dt_current_day.getDate()+"</span></a><br/>"+"</td>";
	 	     }else if(sortedFareMatrix[key]["fareObject"][airlineCode]==null){
	 	       caldata=caldata+"<span style='color:black'>"+dt_current_day.getDate()+"</span></a><br/>"+"</td>";
	 	     }else{
			var created = sortedFareMatrix[key]["fareObject"]["created"];
			     var createdSec = created/1000;
       		           var createdHours = parseInt(createdSec/3600);
			      createdSec = createdSec-createdHours*3600;
			     var createdMinutes = parseInt(createdSec/60);
			createdSec = createdSec-createdMinutes*60;
			var returndate = "";
			if(sortedFareMatrix[key]["fareObject"]["return"]==""){
			}else{
			var dateDate = $.datepicker.parseDate('dd/mm/yy',sortedFareMatrix[key]["fareObject"]["return"]);
			returndate=$.datepicker.formatDate("dd M",dateDate);
			}
		   	caldata=caldata+"<span style='color:black' class='"+sortedFareMatrix[key]["fareObject"][airlineCode]+"'>"+dt_current_day.getDate()+"</span></a><br/><br/>&nbsp;&nbsp;<a href='javascript:selectDate("+'"'+key+'","'+sortedFareMatrix[key]["fareObject"]["return"]+'"'+")'><span style='font-size:9px;font-family:Arial'>"+formatCurrency(sortedFareMatrix[key]["fareObject"][airlineCode])+"</span></a>";
		   	if(returndate==""){
		   	  caldata=caldata+"</td>"
		   	}else{
		   	  caldata=caldata+"<div align='right'>"+returndate+"</div></td>";
		   	}
		   	if(lowestfaremonth==0){
				 lowestfaremonth = sortedFareMatrix[key]["fareObject"][airlineCode];
		         }else if(lowestfaremonth>sortedFareMatrix[key]["fareObject"][airlineCode]){
				  lowestfaremonth = sortedFareMatrix[key]["fareObject"][airlineCode];
	 	        } 
		     }
	 	}
	    }else{
		   if(dispdtmonyear>dispcurmonyear){

				caldata=caldata+"<font style='color:#cccccc;'>"+dt_current_day.getDate()+"</font></a></td>";
		   }
	    }
	 	dt_current_day.setDate(dt_current_day.getDate()+1);
	 }
	 caldata=caldata+'</tr>';
	 trindex++;
   }
   caldata=caldata+"</table>";
   caldata=caldata+'<div align="left"><table><tr><td width="5px" style="background-color:#FFFF66;border:1px outset gray;"></td><td style="font-size:10px;font-family:Arial">Shows lowest fare for the month.</td></tr></table></div>';
   caldata=caldata+'<div align="right"><span  id="farecalanderhelp">Help<img src="/international/img/international/icon-question.gif" width="15" height="15"/></span></div>';
   $("#fareCalBody").html(caldata);
   var selector = "span."+lowestfaremonth;
   $(selector).each(function(){
                        var parent = $(this).parent().get(0);
                            parent = $(parent).parent().get(0);
                            $(parent).css("background-color","#FFFF66");
                            
                          }
                        );
   


}

function set_newdate(dtchangeflag,yearrest){
            var curmonyear=currDate.getFullYear()+''+(Number(currDate.getMonth())<=9?'0'+currDate.getMonth():currDate.getMonth());
            var dtmonyear=0;
           if(dtchangeflag=="next_month")
              dtmonyear=dt_current.getFullYear()+''+((Number(dt_current.getMonth())+1)<=9?'0'+(dt_current.getMonth()+1):(dt_current.getMonth()+1));
           else if(dtchangeflag=="next_year")
               dtmonyear=(dt_current.getFullYear()+1)+''+(Number(dt_current.getMonth())<=9?'0'+dt_current.getMonth():dt_current.getMonth());
           else if(dtchangeflag=="next_5year")
               dtmonyear=(dt_current.getFullYear()+5)+''+(Number(dt_current.getMonth())<=9?'0'+dt_current.getMonth():dt_current.getMonth());
           if(dtchangeflag=="prev_month")
                 dtmonyear=dt_current.getFullYear()+''+((Number(dt_current.getMonth())-1)<=9?'0'+(dt_current.getMonth()-1):(dt_current.getMonth()-1));
           else if(dtchangeflag=="prev_year")
                 dtmonyear=(dt_current.getFullYear()-1)+''+(Number(dt_current.getMonth())<=9?'0'+dt_current.getMonth():dt_current.getMonth());
           else if(dtchangeflag=="prev_5year")
                dtmonyear=(dt_current.getFullYear()-5)+''+(Number(dt_current.getMonth())<=9?'0'+dt_current.getMonth():dt_current.getMonth());
           if((ctflag==0)||((ctflag==1)&&(dtmonyear<=curmonyear))||((ctflag==2)&&(dtmonyear>=curmonyear))){
                 var changedDate=new Date(dt_current);
                 var tempdate=new Date(currDate);
                if(yearrest=="limited")
                    tempdate.setMonth(tempdate.getMonth()+11);
                if(dtchangeflag=="prev_month"){
                     if(yearrest=="limited"){
                        changedDate.setMonth(changedDate.getMonth()-1);
                        if(Number(changedDate.getFullYear()+''+(changedDate.getMonth()<=9?'0'+changedDate.getMonth():changedDate.getMonth()))<curmonyear)
                            changedDate=new Date(tempdate);
                     }else{
                       changedDate.setMonth(changedDate.getMonth()-1);
               }
               
               
               }else if(dtchangeflag=="prev_5year"){
                   changedDate.setFullYear(changedDate.getFullYear()-5);
               }else if(dtchangeflag=="prev_year"){
                   changedDate.setFullYear(changedDate.getFullYear()-1);
               }
               else if(dtchangeflag=="next_month"){
                    if(yearrest=="limited"){
                         changedDate.setMonth(changedDate.getMonth()+1);
                         if(Number(changedDate.getFullYear()+''+(changedDate.getMonth()<=9?'0'+changedDate.getMonth():changedDate.getMonth()))>Number(tempdate.getFullYear()+''+(tempdate.getMonth()<=9?'0'+tempdate.getMonth():tempdate.getMonth())))
                                changedDate=new Date(currDate);
                          }else
                                changedDate.setMonth(changedDate.getMonth()+1);
                          }
                 
               }else if(dtchangeflag=="next_5year"){
                         changedDate.setFullYear(changedDate.getFullYear()+5);
               }
               else if(dtchangeflag=="next_year"){
                     changedDate.setFullYear(changedDate.getFullYear()+1);
               }
             setnewDate(changedDate);
         
    }
    function setnewDate(dt_changed_date){var CalToday=new Date(dt_changed_date);
                dt_current=CalToday;
                dt_firstday=new Date(dt_current);
                dt_firstday.setDate(1);
                dt_firstday.setDate(1-(7+dt_firstday.getDay()-NUM_WEEKSTART)%7);
                curday=currDate.getDate();
                curmon=currDate.getMonth();
                set_datetime(CalToday.valueOf());
    }
   function set_datetime(n_datetime,b_close){
          var dt_datetime=new Date(n_datetime);
           displayCalendar();
   }
   function formatCurrency(num,symbol) {
   	num = num.toString().replace(/\$|\,/g,'');
   	if(isNaN(num))
   	   num = "0";
   	   sign = (num == (num = Math.abs(num)));
   	   num = Math.floor(num*100+0.50000000001);
   	   cents = num%100;
   	   num = Math.floor(num/100).toString();
   	   if(cents<10)
   	       cents = "0" + cents;
   	       for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
   	       num = num.substring(0,num.length-(4*i+3))+','+
   	       num.substring(num.length-(4*i+3));
   	   if(symbol==null)
   	     return (((sign)?'':'-') + 'Rs.' + num);
   	   else
   	      return (((sign)?'':'-') + symbol+' '+ num);
  }
  function selectDate(date1,date2){
     var triptype='O';
            for(var i = 0 ; i <document.forms[0].tripType.length;i++){
            	      if(document.forms[0].tripType[i].checked){
            	          triptype = document.forms[0].tripType[i].value;
            	      }
     	}
     	
     document.getElementById('departure_0').value = document.getElementById("from").value;
     document.getElementById('arrival_0').value = document.getElementById("to").value;
     document.getElementById('dFrom_0').value = date1;
     if(triptype=='R'){
     document.getElementById('dTo_0').value = date2;
     document.forms[0].tripType[0].checked=true;
          document.forms[0].tripType[1].checked=false;
     document.forms[0].tripType[2].checked=false;
     }else if(triptype=='O'){
     document.forms[0].tripType[0].checked=false;
     document.forms[0].tripType[1].checked=true;
     document.forms[0].tripType[2].checked=false;
     }
     submitHomePage();
     
  }
  function changeAirline(sel){
     var selectedIndex = sel.selectedIndex;
     var airlinecode = sel.options[sel.selectedIndex].value;
     airlineCode = airlinecode;
     displayCalendar();
    
  }
  function validateSearchCriteria(){
        var isValid=true;
	var triptype='O';
	for(var i = 0 ; i <document.forms[0].tt.length;i++){
	      if(document.forms[0].tt[i].checked){
		  triptype = document.forms[0].tt[i].value;
	      }
	}
	if(triptype=='O'||triptype=='R'){
	  var from = document.getElementById('departure_0').value;
	   var to = document.getElementById('arrival_0').value;
	   var countryfrom = getCountry(from);
	   var countryto = getCountry(to);
	   if(countryfrom=="Not Valid"){
	      isValid=false;
	      alert("Please select valid from city or airport code");
	   }else if(countryto=="Not Valid"){
	      isValid=false;
	      alert("Please select valid to city or airport code");
	   } else if(countryfrom=='India'&&countryto=='India'){
	     alert("Please visit www.makemytrip.com  or select India site from top right, to search for  Indian domestic flights.");
		 //turnOnModalAlert("<table height='100px'><tr><td style='padding-left:50px'>You are trying to book tickets within India if yes please click on continue else click on cancel to change you journey details.</td></tr></table>","http://www.makemytrip.co.in/makemytrip/flights.do");
	     isValid=false;
	   }else if((countryfrom!='India' && countryfrom!='US' && countryfrom!='Canada')||(countryto!='India' && countryto!='US' && countryto!='Canada')){
				if (confirm("This sector is not supported on our Canada site. However you can book tickets for this sector on our International site. Please notice that there you will be charged in Indian Rupees for your ticket. Press OK to continue to our International site.")){
					 //window.location='http://www.makemytrip.com/international-flights/';
					 submitHomePageIndia();
					 return false;
					}
			isValid=false;
	   }
	   
	}else if(triptype=='M'){
	     var contents = $('.ui-accordion-content');
	     var allSegmentsInIndia = true;
	     var allSegmentsEmpty = true;
	     var SegementsInvalid = true;
	     for(var i = 0;i<contents.length;i++)
			{
	        var departure = document.getElementById("departure_"+i).value;
                 var arrival = document.getElementById("arrival_"+i).value;
                 if(departure==""&&arrival==""){
                     
                 }else{
                     allSegmentsEmpty= false;
                     var countryfrom = getCountry(departure);
                     var countryto = getCountry(arrival);
						if(countryfrom=='India'&&countryto=='India'){
							}
						else{
							allSegmentsInIndia = false;
							
								if(countryfrom=='Not Valid'||countryto=='Not Valid'){
								}
								else{
								SegementsInvalid=false;
								break;
								}
							}
						}
            }
	     
	     if(allSegmentsEmpty){
	        isValid=false;
	        alert("Please enter valid from and to city.");
	        return isValid;
	     }
	     if((SegementsInvalid)&&(!allSegmentsInIndia)){
	        isValid=false;
	        alert("Please enter valid from and to city."); 
	     }
	     if(allSegmentsInIndia){
	        alert("Please visit www.makemytrip.com  or select India site from top right, to search for  Indian domestic flights.");
			//turnOnModalAlert("<table height='100px'><tr><td style='padding-left:50px'>You are trying to book tickets within India if yes please click on continue to go to www.makemytip.com else click on cancel to modify and search international flights.</td></tr></table>","http://www.makemytrip.co.in/makemytrip/flights.do");
	        isValid=false;
	     }
	       var from = document.getElementById('departure_0').value;
		   var to = document.getElementById('arrival_0').value;
		   var countryfrom = getCountry(from);
		   var countryto = getCountry(to);
	       var from2 = document.getElementById('departure_1').value;
		   var to2 = document.getElementById('arrival_1').value;
		   var countryfrom2 = getCountry(from2);
		   var countryto2 = getCountry(to2);
		   var from3 = document.getElementById('departure_2').value;
		   var to3 = document.getElementById('arrival_2').value;
		   var countryfrom3 = getCountry(from3);
		   var countryto3 = getCountry(to3);
		   if((countryfrom!='India' && countryfrom!='US' && countryfrom!='Canada')||(countryto!='India' && countryto!='US' && countryto!='Canada')||
			  (countryfrom2!='Not Valid' && countryfrom2!='India' && countryfrom2!='US' && countryfrom2!='Canada')||(countryto2!='Not Valid' && countryto2!='India' && countryto2!='US' && countryto2!='Canada')||
			  (countryfrom3!='Not Valid' && countryfrom3!='India' && countryfrom3!='US' && countryfrom3!='Canada')||(countryto3!='Not Valid' && countryto3!='India' && countryto3!='US' && countryto3!='Canada')){
					   if (confirm("This sector is not supported on our Canada site. However you can book tickets for this sector on our International site. Please notice that there you will be charged in Indian Rupees for your ticket. Press OK to continue to our International site.")){
							 //window.location='http://www.makemytrip.com/international-flights/';
							 submitHomePageIndia();
							 return false;
							 
						}else{
							 isValid = false;
							}
				   }
	}
	if(isValid){
	  var adults = parseInt(document.forms[0].adt.value,10);
	  var children = parseInt(document.forms[0].chd.value,10);
	  var infants = parseInt(document.forms[0].inf.value,10);
	  var totalnumofpass = adults+children+infants;
	   if(totalnumofpass>6){
	    isValid = false;
	    alert("Total number of travelers can not be more than 6.");
	 }else if(infants>adults){
	    isValid = false;
	    alert("Number of infants can not be greater than adults");
	 }
	 else if(infants>2){
	    isValid = false;
	    alert("Number of infants can not be greater than 2");
	 }
	}
	
	return isValid;
  }
  function getCountry(selectedcity){
      var index = selectedcity.indexOf(",");
      var indexofdash=selectedcity.indexOf("-");
      if(index<0||indexofdash<0)return "Not Valid";
      var country = selectedcity.substr(index+1,(indexofdash-index)-1);
      return country;
  }
  function turnOnModalAlert(text,url) {
     createModalBox(text,url);
  }
  function createModalBox(text,url) {
         if($('#alertcontent>*').length==0){
          $("#alertcontent").append(text);
            var ul = document.createElement("ul");
            ul.appendChild(createLi("Continue", "continue", url, function() {turnOffModal();return true; } ));
            ul.appendChild(createLi("Cancel", "cancel", "#", function() { turnOffModal();return false; }));
            $('#buttonrow').append(ul);
          }
         $('#confirm').jqm({overlay: 80, modal: true, trigger: false});
         $('#confirm').jqmShow();
  }
  function createLi(text, id, url, onclick) {
     var li = document.createElement("li");
     var a = li.appendChild(document.createElement("a"));
     a.appendChild(document.createTextNode(text));
     a.className = "hrefbuttons";
     a.onclick = onclick;
     a.href = url;
     a.id = id;
    return li;
  }
  
  function turnOffModal() {
       $('#confirm').jqmHide();
  }
  
  ;(function($) {
      function Logger(){
               this.linenum =0;
              }
      $.extend(Logger.prototype, {
               init:function(){
                  this.linenum=0;
  		var loggerelemnt= document.createElement("div");
  		var jquerylogele = $(loggerelemnt);
  		jquerylogele.attr("id","weblogger");
  		jquerylogele.addClass("logger");
  		$('#loggertext').append(jquerylogele);
  		$('#weblogger').addClass("logger");
               },
               debug:function(text){
                    $('div.logger').append(this.linenum+":"+text+"<br/>");
                    this.linenum++;
                    
               },
               postweblog:function(){
                   
                    var logtext = $('div.logger').html();
                    var trackid = document.forms[0].uniqueid.value;
                    jQuery.ajax({
                         type: "POST",
                         url: "/international/weblogger",
                         data: "trackid="+trackid+"&weblog="+logtext
                         }
                        );
                   
               }
               
        });
    $.fn.logger = function(){
                             $.logger.init();
         
                           };
    $.logger = new Logger(); // singleton instance
         
})(jQuery);
var persistclose=0 //set to 0 or 1. 1 means once the bar is manually closed, it will remain closed for browser session
var startX=1000;
if(screen.width==1152)
 startX= 947 //set x offset of bar in pixels
 else if(screen.width==1024)
 startX=883
 else if(screen.width==800)
 startX=720
else if(screen.width==1280)
startX=1011
var startY = 250 //set y offset of bar in pixels
var verticalpos="fromtop" //enter "fromtop" or "frombottom"

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function closebar(){
if (persistclose)
document.cookie="remainclosed=1"
document.getElementById("topbar").style.visibility="hidden"
}

function staticbar(){
barheight=document.getElementById("topbar").offsetHeight
var ns = (navigator.appName.indexOf("Netscape") != -1) || window.opera;
var d = document;
function ml(id){
var el=d.getElementById(id);
if (!persistclose || persistclose && get_cookie("remainclosed")=="")
el.style.visibility="visible"
if(d.layers)el.style=el;
el.sP=function(x,y){this.style.left=x+"px";this.style.top=y+"px";};
el.x = startX;
if (verticalpos=="fromtop")
el.y = startY;
else{
el.y = ns ? pageYOffset + innerHeight : iecompattest().scrollTop + iecompattest().clientHeight;
el.y -= startY;
}
return el;
}
window.stayTopLeft=function(){
if (verticalpos=="fromtop"){
var pY = ns ? pageYOffset : iecompattest().scrollTop;
ftlObj.y += (pY + startY - ftlObj.y)/8;
}
else{
var pY = ns ? pageYOffset + innerHeight - barheight: iecompattest().scrollTop + iecompattest().clientHeight - barheight;
ftlObj.y += (pY - startY - ftlObj.y)/8;
}
ftlObj.sP(ftlObj.x, ftlObj.y);
setTimeout("stayTopLeft()", 10);
}
ftlObj = ml("topbar");
stayTopLeft();
}
function submitFeedback(){
        var emailid = document.getElementById("feedback_email").value;
        var phoneno = document.getElementById("feedback_mobile").value;
        var query = document.getElementById("feedback_query").value;
        var formdata=$("form").serialize();
        var sourceofpage = source;
        var postdata ={from:emailid,phoneno:phoneno,message:query,formparameters:formdata,source:sourceofpage};
        $.post('/international/feedback', postdata);
        alert('Thank you for submitting your query. We will get back to you as soon as possible.');
        
}



/*pic01= new Image(466,206);
pic01.src="/international/resources/img/international/466x206-SEAsia-081208-1.jpg";
pic02= new Image(466,206);
pic02.src="/international/resources/img/international/466x206-InternationalFlight-AMEX-031208.jpg";

function initArray() 
{
 if(document.getElementById('Hero_shot'))
 {
  var core = Math.floor((2-0)*Math.random()) + 0;
  //alert(core);  
  ranlink  = linkme[core];
  ranimage = images[core];
  rantext  = texts[core];
  rantarg  = targ[core];
  document.getElementById('Hero_shot').innerHTML = "<a href='"+ranlink+"' target='"+rantarg+"'><img src='"+ranimage+"' border=0 alt='"+rantext+"' title='"+rantext+"'></a>"; 
 }
}
var linkme = new Array(
"",
"http://www.makemytrip.com/promotion/AMEX_promo/AMEX_promo.html"
);
var images = new Array(
"/international/img/international/466x206-SEAsia-081208-1.jpg",
"/international/img/international/466x206-InternationalFlight-AMEX-031208.jpg"
);
var texts = new Array(
"Flights to South-East Asia!",
"Book Cheap International Flights!"
);
var targ = new Array(
""
,
"_blank"
);

initArray();
setInterval('initArray()',5000);*/




