var DestinationsXML = null;
var CitiesXML=null;
var global_activeRows=2;
var _site_path = path;
var reg_destinations_path = "/shared/CharterAndRegularCities.HE.xml"
var langOps="EN";
var tlvText = "";
var tlvCode = "TLV";

var currRegSeId = "";
var currRegSeIndex = "";
var currRegSeObjName = "";


function InitRegularSearchEngine(id,lang)
{
    var tempLength = 1;
	
    reg_destinations_path = "/shared/CharterAndRegularCities."+lang+".xml"
    
    
	langOps = (lang=="HE"?"EN":"HE");
	
	try
	{
	    tlvText = dic['TEL_AVIV'].split(",")[0];
	}
	catch(e){}
	
      
    if(!DestinationsXML){
        DestinationsXML = $.ajax({
	        type: "GET",
	        url: reg_destinations_path,
	        dataType: "xml",
	        contentType: "text/xml",
	        async: false
        }).responseXML;
    }
    

	
	var xpath = "cities > city";
	var citiesNodes = $(DestinationsXML).find(xpath)
	
	
	if(citiesNodes)
	{
	    
	    //alert("global_activeRows : " + global_activeRows)
	    // go over active destinations rows 
	    for (var i=1;i<=global_activeRows;i++)
	    {	
		    
		    var selectListObjFrom	= document.getElementById("RegDestinationFrom"+i+id);
		    var selectListObjTo		= document.getElementById("RegDestinationTo"+i+id);
		    if (selectListObjFrom && selectListObjTo)
		    {	
			    // reset select lists 
			    //selectListObjFrom.selectedIndex = 0;
			    selectListObjFrom[0].text	= dic["DEFAULT_SELECT"];
			    selectListObjFrom[0].value	= "";
			    selectListObjFrom[0].selected = true;
    			
			    //selectListObjTo.selectedIndex = 0;
			    selectListObjTo[0].text	= dic["DEFAULT_SELECT"];
			    selectListObjTo[0].value	= "";
			    selectListObjTo[0].selected = true;
			    
			    selectListObjFrom.length = citiesNodes.length+1;	
			    selectListObjTo.length = citiesNodes.length+1; 
			    
			    for(var k=0;k<citiesNodes.length;k++)
	            {
	                var cityText=$(citiesNodes[k]).attr(lang);
			        var countryText=$(citiesNodes[k]).attr("country_"+lang);
			        var cityCode=$(citiesNodes[k]).attr("code");
			        if(cityText=="")
			        {
			            cityText=$(citiesNodes[k]).attr(langOps);
			        }
			        if(countryText=="")
			        {
			            countryText=$(citiesNodes[k]).attr("country_"+langOps);
			        }
			        
			        selectListObjFrom[(k+1)].text	= cityText+", "+countryText;
				    selectListObjFrom[(k+1)].value	= cityCode;
					
				    selectListObjTo[(k+1)].text  = cityText+", "+countryText;
				    selectListObjTo[(k+1)].value = cityCode;
        	        
		            
	            }
    			
			    	
			    
		    }
	    } // end going over destinations rows
	    
	    
	    $(".rse_dest_date input").val("");
	    
	    // after filling select lists, set Tel Aviv in From1 and To2 rows 
        // when flight type is CHARTER or if trip type is ROUNDTRIP
        //var roundTrip	= document.all["RegDirectionTypeRoundTrip"+ID].checked;
        var tripType = $('div.rse_radio_list input:radio:checked').val()
        //alert(tripType)
        if (tripType=="ROUNDTRIP")
        {
	        // Set row 1, destination FROM
	        var selectListObjFrom1	= document.getElementById("RegDestinationFrom1"+id);		
	        var index = findItemInSelectList(selectListObjFrom1, tlvCode);
	        if (index>0)
	        {
		        selectListObjFrom1.selectedIndex = index;
	        } else {
		        selectListObjFrom1.length = selectListObjFrom1.length+1;
		        var len = selectListObjFrom1.length-1;
		        selectListObjFrom1[len].text		= tlvText;
		        selectListObjFrom1[len].value		= tlvCode;
		        selectListObjFrom1[len].selected	= true;	
	        }
	        // Set row 2, destination TO 
	        var selectListObjTo2	= document.getElementById("RegDestinationTo2"+id);
	        var index = findItemInSelectList(selectListObjTo2, tlvCode);
	        if (index>0)
	        {
		        selectListObjTo2.selectedIndex = index;
	        } else {
		        selectListObjTo2.length = selectListObjTo2.length+1;
		        var len = selectListObjTo2.length-1;
		        selectListObjTo2[len].text		= tlvText;
		        selectListObjTo2[len].value		= tlvCode;
		        selectListObjTo2[len].selected	= true;	
	        }
        }	
	}
    
    
}






function findItemInSelectList(selectList, itemValue)
{	
	for (var k=0;k<selectList.length;k++)
	{
		if (selectList[k].value == itemValue)
		{
			return k;
		}
	}
	return 0;
}

function findItemInArray(arr, itemName)
{	
	for (var k=0;k<arr.length;k++)
	{
		if (arr[k].key == itemName)
		{
			return k;
		}
	}




	return 0;
}




/*
---------------------------------------------------------------------------
POP-UPS
---------------------------------------------------------------------------
*/

function showDetailsPopup(field_name,folder_id)
{
    $(".rse_result").html("");
    $(".rse_popup").dialog("destroy");
    $(".rse_popup").dialog({
        autoOpen: true,
        modal: true,
        //title: $(obj).html(),
        width: 500,
        height: 300,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_loading").css("display","none");
        }
    });
    $(".rse_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/REGULAR/popup.asp",
		cache: true,
		data: "pi="+node_pi+"&sitePath="+_site_path+"&lang="+lang+"&folder="+folder_id+"&field="+field_name,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(data);
		}
	})
}


function ShowPrices(cache_id)
{
	$(".rse_result").html("");
    $(".rse_popup").dialog("destroy");
    $(".rse_popup").dialog({
        autoOpen: true,
        modal: true,
        title: dic["PRICE_POPUP_TITLE"],
        width: 500,
        height: 200,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_loading").css("display","none");
        }
    });
    $(".rse_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/REGULAR/Price.asp",
		cache: true,
		data: "stcss="+css+"&pi="+node_pi+"&sitePath="+_site_path+"&CacheID="+cache_id,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(data);
		}
	})
}

function ShowRules(cache_id)
{
    //<div class='rse_rules_popup'><div class='rse_rules_loading'></div><div class='rse_rules_result'></div></div>
	$(".rse_rules_result").html("");
    $(".rse_rules_popup").dialog("destroy");
    $(".rse_rules_popup").dialog({
        autoOpen: true,
        modal: true,
        title: dic["FLIGHT_RULES"],
        width: 500,
        height: 550,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_rules_loading").css("display","none");
        }
    });
    $(".rse_rules_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/REGULAR/Rules.asp",
		cache: true,
		data: "pi="+node_pi+"&sitePath="+_site_path+"&lang="+lang+"&stcss="+css+"&CacheID="+cache_id,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_rules_loading").css("display","none");
		    $(".rse_rules_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_rules_loading").css("display","none");
		    $(".rse_rules_result").html(data);
		}
	})
}
function ShowRule(qs)
{
    $(".rse_rules").html('');
    $(".rse_rules_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/regular/ShowRule.asp",
		cache: true,
		data: qs,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_rules_loading").css("display","none");
		    $(".rse_rules").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_rules_loading").css("display","none");
		    $(".rse_rules").html(data);
		}
	})
}





function setRoundTripReturnValues(code, text, callingField, ind, id)
{
	$("#RegDate"+ind+id).val('');
	
	if ($('div.rse_radio_list input:radio:checked').val()=="ROUNDTRIP")
	{
		
		ind = 3-ind; // ind = 1 or 2 
		// reset second destination row date input field
		if (callingField=="DestinationFrom")
		{
		    //alert("x-" + callingField + " : " + ind + " : " + id)
			var targetObj	= document.getElementById("RegDestinationTo"+ind+id);
			var textObj		= document.getElementById("TextDestinationTo"+ind+id);
		} 
		else 
		{
			//alert("y-" + callingField + " : " + ind + " : " + id)
			var targetObj	= document.getElementById("RegDestinationFrom"+ind+id);
			var textObj		= document.getElementById("TextDestinationFrom"+ind+id);
		}
		if (targetObj)
		{
			var index = findItemInSelectList(targetObj, code);
			if (index>0)
			{
				targetObj.selectedIndex = index;
			} 
			else 
			{
				targetObj.length = targetObj.length+1;
				var len = targetObj.length-1;
				targetObj[len].text		= text;
				targetObj[len].value	= code;
				targetObj[len].selected = true;
			}
		}
	}
}

function setRoundTripReturnValuesOnchange(obj, callingField, ind, id)
{
    setRoundTripReturnValues(obj[obj.selectedIndex].value, obj[obj.selectedIndex].text, callingField, ind, id)
	
}





// FOR EXTENDED SEARCH ENGINE
// hide/display the destination rows.
// each destination has two TRs: one for the select lists and the calendar
// and another one above it for the text labels and the "additional destinations" links.
// Handled document objects :
//	1.	destinations select lists :	DestinationFrom, DestinationTo  
//	2.	destinations texts & links:	RowLinks, RowLinksAlter 
//	3.	calendar image & Input field: openCalButt, RegDate	
	


function setDestinationFields(tripType, flightType, ID, lang) 
{
	var activeRows=1;
	switch (tripType) {
		case 'ONEWAY':
			activeRows = 1;
			break;
		case 'ROUNDTRIP':	
			activeRows = 2;
			break;
		case 'MULTITRIP':
			activeRows = 5;			
			break;
	}
	if (global_activeRows<activeRows) global_activeRows = activeRows;
	
	for (var i=1;i<=global_activeRows;i++)
	{
		try 
		{
			if (i<=activeRows)
			{
				// ADDITIONAL DESTINATIONS
				// disable additional destinations in Charter or in Round Trip (disable second row) 
				$("#LinksRowFrom"+i+ID).show();
				$("#LinksRowTo"+i+ID).show();
				$("#LinksRowAlterFrom"+i+ID).hide();
				$("#LinksRowAlterTo"+i+ID).hide();
				// DESTINATION & CALENDAR
				$("#DestinationRow"+i+ID).show();
			} else {
				// additional destinations
				$("#LinksRowFrom"+i+ID).hide();
				$("#LinksRowTo"+i+ID).hide();
				$("#LinksRowAlterFrom"+i+ID).hide();
				$("#LinksRowAlterTo"+i+ID).hide();
				// Destination & Calendar
				$("#DestinationRow"+i+ID).hide();
			}
		} catch(e){}
	}
	global_activeRows = activeRows;
	if (tripType=="ONEWAY")
	{
		$("#FillSecondRow2"+ID).show();
	} 
	else 
	{
		$("#FillSecondRow2"+ID).hide();
	}
	// fill destinations select lists
	InitRegularSearchEngine(ID,lang)
}




////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS FOR SEARCH RESULTS PAGE 
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// set an item as selected on an existing select list
// used in the Search Results page.
function SetDefaultsRegularSearchEngine()
{
	if("dest" in urlParams)
	{
		if(urlParams["dest"] != "")
		{
			SetSelectValueFromRequest($(".rse_destination_to_1").attr("id"),urlParams["dest"],urlParams["dest"])
			SetSelectValueFromRequest($(".rse_destination_from_2").attr("id"),urlParams["dest"],urlParams["dest"])
		}
	}
}
function setSelectedItems(requestArray, ID)
{

	
	
	
	for (var i=0;i<requestArray.length;i++)
	{
	    if (isnull(requestArray[i].value) || requestArray[i].value=="ALL" || requestArray[i].value=="0")
	    {
	        continue;
	    }
	    else if(requestArray[i].key == "DirectionType")
	    {
	        switch(requestArray[i].value)
	        {
	            case "ROUNDTRIP":
	                $("#RegDirectionTypeRoundTrip"+ID).click();
	                break;
	            case "ONEWAY":
	                $("#RegDirectionTypeOneWay"+ID).click();
	                break;
	            case "MULTITRIP":
	                $("#RegDirectionTypeMultiTrip"+ID).click();
	                break;
	        }
	    }
	}
	
	for (var i=0;i<requestArray.length;i++)
	{
	    if (isnull(requestArray[i].value) || requestArray[i].value=="ALL" || requestArray[i].value=="0")
	    {
	        continue;
	    }
	    
	    switch(requestArray[i].key)
	    {
	        case "ChildsAges":
	            $("#ChildsAges").val(requestArray[i].value)
	            break;
	        case "TextClass":
	            $("#TextClass"+ID).val(requestArray[i].value)
	            break;
	        case "TextAirline":
	            $("#TextAirline"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationFrom1":
	            SetSelectValueFromRequest("RegDestinationFrom1"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationFrom1"))
	            break;
	        case "TextDestinationFrom1":
	            $("#TextDestinationFrom1"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationTo1":
	            SetSelectValueFromRequest("RegDestinationTo1"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationTo1"))
	            break;
	        case "TextDestinationTo1":
	            $("#TextDestinationTo1"+ID).val(requestArray[i].value)
	            break;
	        case "RegDate1":
	            $("#RegDate1"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationFrom2":
	            SetSelectValueFromRequest("RegDestinationFrom2"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationFrom2"))
	            break;
	        case "TextDestinationFrom2":
	            $("#TextDestinationFrom2"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationTo2":
	            SetSelectValueFromRequest("RegDestinationTo2"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationTo2"))
	            break;
	        case "TextDestinationTo2":
	            $("#TextDestinationTo2"+ID).val(requestArray[i].value)
	            break;
	        case "RegDate2":
	            $("#RegDate2"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationFrom3":
	            SetSelectValueFromRequest("RegDestinationFrom3"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationFrom3"))
	            break;
	        case "TextDestinationFrom3":
	            $("#TextDestinationFrom3"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationTo3":
	            SetSelectValueFromRequest("RegDestinationTo3"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationTo3"))
	            break;
	        case "TextDestinationTo3":
	            $("#TextDestinationTo3"+ID).val(requestArray[i].value)
	            break;
	        case "RegDate3":
	            $("#RegDate3"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationFrom4":
	            SetSelectValueFromRequest("RegDestinationFrom4"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationFrom4"))
	            break;
	        case "TextDestinationFrom4":
	            $("#TextDestinationFrom4"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationTo4":
	            SetSelectValueFromRequest("RegDestinationTo4"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationTo4"))
	            break;
	        case "TextDestinationTo4":
	            $("#TextDestinationTo4"+ID).val(requestArray[i].value)
	            break;
	        case "RegDate4":
	            $("#RegDate4"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationFrom5":
	            SetSelectValueFromRequest("RegDestinationFrom5"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationFrom5"))
	            break;
	        case "TextDestinationFrom5":
	            $("#TextDestinationFrom5"+ID).val(requestArray[i].value)
	            break;
	        case "DestinationTo5":
	            SetSelectValueFromRequest("RegDestinationTo5"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextDestinationTo5"))
	            break;
	        case "TextDestinationTo5":
	            $("#TextDestinationTo5"+ID).val(requestArray[i].value)
	            break;
	        case "RegDate5":
	            $("#RegDate5"+ID).val(requestArray[i].value)
	            break;
	        case "Airline":
	            SetSelectValueFromRequest("RegAirline"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextAirline"))
	            break;
	        case "Class":
	            SetSelectValueFromRequest("RegClass"+ID,requestArray[i].value,GetValueFromRequestArray(requestArray,"TextClass"))
	            break;
	        case "AdultNumber":
	            SetSelectValueFromRequest("RegAdultNumber"+ID,requestArray[i].value)
	            break;
	        case "YouthNumber":
	            SetSelectValueFromRequest("RegYouthNumber"+ID,requestArray[i].value)
	            break;
	        case "ChildNumber":
	            SetSelectValueFromRequest("RegChildNumber"+ID,requestArray[i].value)
	            break;
	        case "SeniorNumber":
	            SetSelectValueFromRequest("RegSeniorNumber"+ID,requestArray[i].value)
	            break;
	        case "InfantNumber":
	            SetSelectValueFromRequest("RegInfantNumber"+ID,requestArray[i].value)
	            break;
        }
	}

}

function GetValueFromRequestArray(arr,key)
{
    var res = "";
    for (var i=0;i<arr.length;i++)
	{
	    if (isnull(arr[i].value) || arr[i].value=="ALL" || arr[i].value=="0")
	    {
	        continue;
	    }
	    if(arr[i].key == key)
	    {
	        res = arr[i].value;
	        break;
	    }
	}
	return res; 
}

function SetSelectValueFromRequest(selName,vCode,vText)
{
    try{
        var selectListObjFrom1	= document.getElementById(selName);		
        var index = findItemInSelectList(selectListObjFrom1, vCode);
        if (index>0)
        {
            selectListObjFrom1.selectedIndex = index;
        } else {
            selectListObjFrom1.length = selectListObjFrom1.length+1;
            var len = selectListObjFrom1.length-1;
            if(vText)
            {
                selectListObjFrom1[len].text		= vText;
            }
            selectListObjFrom1[len].value		= vCode;
            selectListObjFrom1[len].selected	= true;	
        }
    }
    catch(e)
    {
    }
}

// AIRLINES LOGOS 
//------------------------------------------------------------------
// in case an airline logo image has failed to load,
// hide the image and display the airline's name
function ImageLoadFailed(imgObj) 
{
    $(imgObj).parent().html($(imgObj).parent().parent().attr("airline"))
}

//------------------------------------------------------------------













//----------------------------------------------------------------------
//	SUBMIT	EXTENDED SERACH ENGINE
//----------------------------------------------------------------------
function SubmitRegularFlightsExtendedEngine(id) 
{
	var flightType	= "REGULAR"
	var roundTrip	= false;
	var onewayTrip	= false;
	var multiTrip	= false;
	
	
	var tripType = $('div.rse_radio_list input:radio:checked').val()
    if (tripType=="ROUNDTRIP") roundTrip = true
    else if (tripType=="ONEWAY") onewayTrip = true
    else multiTrip = true
    
	// ROUNDTRIP -------------------------------------------------
	if (roundTrip)
	{
		for (var i=1;i<=2;i++)
		{
			if (isnull(document.getElementById('RegDestinationFrom'+i+id).value) || isnull(document.getElementById('RegDestinationTo'+i+id).value))
			{
				alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
				return;	
			}
			if (isnull(document.getElementById('RegDate'+i+id).value)) 		
			{
				alert(dic.REGULAR_FLIGHTS_DATES_ERROR);
				return;
			}
		}
	}
	// ONEWAY ---------------------------------------------------
	else if (onewayTrip)
	{
		if (isnull(document.getElementById('RegDestinationFrom1'+id).value) || isnull(document.getElementById('RegDestinationTo1'+id).value))
		{
			alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
			return;	
		}
		if (isnull(document.getElementById('RegDate1'+id).value))  		
		{
			alert(dic.REGULAR_FLIGHTS_DATES_ERROR);
			return;
		} 
	}
	// MULTITRIP -------------------------------------------------
	else if (multiTrip)
	{
		var destinations = 0;
		for (var i=1;i<=5;i++)
		{
		    if (!isnull(document.getElementById('RegDestinationFrom'+i+id).value) && !isnull(document.getElementById('RegDestinationTo'+i+id).value) && !isnull(document.getElementById('RegDate'+i+id).value))
			{
				destinations++;
			} 
			else 
			{
			    if (!isnull(document.getElementById('RegDestinationFrom'+i+id).value) || !isnull(document.getElementById('RegDestinationTo'+i+id).value) || !isnull(document.getElementById('RegDate'+i+id).value))
				{
					if (isnull(document.getElementById('RegDate'+i+id).value))
					{
						alert(dic.REGULAR_FLIGHTS_DATES_ERROR);
					}
					else 
					{
						alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
					}
					return;
				}
			}			
		}	 
	}	
	// submit
	if (destinations<2)
	{
		alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
		return;	
	}
	if (preventUNN(id))
	{ 

		$("#RegExtendedSearchForm"+id).attr("action",regular_action);
		
		//$("#RegExtendedSearchForm"+id).attr("target","_parent");


		// set destination text descriptions as values in hidden text fields 
		setHiddenTexts(id);

		if(top.location != self.location && (document.location.href.indexOf("component.asp")>-1 || document.location.href.indexOf("yad2Regular.asp")>-1))
		{
			$("#RegExtendedSearchForm"+id).attr("target","_top");
		}		
		
		$("#RegExtendedSearchForm"+id).submit();
	}
}

// UNN = Unaccompanied Child
// prevent the selection of a Child/Infant without Senior/Adult 
function preventUNN(id) {
	var snn = document.getElementById('RegSeniorNumber'+id);
	var adt = document.getElementById('RegAdultNumber'+id);
	var yth = document.getElementById('RegYouthNumber'+id);
	var cnn = document.getElementById('RegChildNumber'+id);
	var inf = document.getElementById('RegInfantNumber'+id);

	var totalAdults = adt.value*1 + snn.value*1;
	if (inf.value > totalAdults)
	{	
		alert(dic.REGULAR_FLIGHTS_INFANT_ERROR);
		return false;
	}
	if (yth.value==0 && adt.value==0 && snn.value==0) 
	{
		alert(dic.REGULAR_FLIGHTS_SELECT_PASSENGER_ERROR);
		return false;
	}
	return true;
}

function setHiddenTexts(id)
{
	// destinations
	for (var i=1;i<=5;i++)
	{
		var destFrom = document.getElementById("RegDestinationFrom"+i+id);
		if (destFrom.selectedIndex>0)
		{
			document.getElementById("TextDestinationFrom"+i+id).value	= destFrom[destFrom.selectedIndex].text;
		}
		var destTo = document.getElementById("RegDestinationTo"+i+id);
		if (destTo.selectedIndex>0)
		{
			document.getElementById("TextDestinationTo"+i+id).value	= destTo[destTo.selectedIndex].text;
		}
	}
	// airline 
	var airline = document.getElementById("RegAirline"+id);
	if (airline.selectedIndex>0)
	{
		document.getElementById("TextAirline"+id).value = airline[airline.selectedIndex].text;
	}
	// flight class
	var flightClass = document.getElementById("RegClass"+id);
	if (flightClass.selectedIndex>0)
	{
		document.getElementById("TextClass"+id).value = flightClass[flightClass.selectedIndex].text;
	}
}


function OpenCalendarPopUp(ind, id, mode) 
{	
	if (!fillingDatesRules(ind, id)) return;

	
	
	


    var previousDate = '';
    //alert(parseInt(ind))
	if (parseInt(ind)>1)
	{
		var previousDate = document.getElementById("RegDate"+(parseInt(ind)-1)+id).value;
	}  
	
	
	$(".rse_calendar").datepicker("destroy");
    $(".rse_calendar").html("");
    $(".rse_calendar_popup").dialog("destroy");
    $(".rse_calendar_popup").dialog({
        autoOpen: true,
        modal: true,
        title: (mode=='exit' ? dic.CHOOSE_EXIT_DATE :  dic.CHOOSE_RETURN_DATE ),
        width: 530,
        height: 380,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_calendar_loading").css("display","none");
        }
    });
    
    $(".rse_calendar_text1").html("<div class='rse_calendar_text'>"+dic["CALENDAR_EXPLAINATION_1"]+"</div>");
    if(mode=='exit')
    {
        $(".rse_calendar_text2").html('');
        $(".rse_calendar_text3").html('');
    }
    else
    {
        $(".rse_calendar_text2").html("<div class='rse_calendar_text'><div class='rse_special_date'></div>"+dic["CALENDAR_EXPLAINATION_3"]+"</div>");
        $(".rse_calendar_text3").html("<div class='rse_calendar_text'>"+dic["CALENDAR_EXPLAINATION_4"]+"</div>");
    }
    //$(".rse_calendar_loading").css("display","block");
    
    
    $('.rse_calendar').datepicker({
        minDate: ind > 1 ?  $.datepicker.parseDate('yy-mm-dd', $('#RegDate'+(ind-1)+id).val()) : '+1d',
        maxDate: '+12m',
        numberOfMonths: 2,
        onSelect: function(dateText, inst){
            $('#RegDate'+ind+id).val(dateText);
            $(".rse_calendar_popup").dialog("close");
        },
        beforeShowDay: function(date) { 
            if(mode=='exit')
            {
                return [true]
            }
            else if(isCheapDate(date,$.datepicker.parseDate('yy-mm-dd', $('#RegDate'+(ind-1)+id).val())))
            {
                return [true,'rse_special_date']
            }
            else
            {
                return [true]
            }
            
            //show only available dates
            /*try{
                if (FlightOutboundDate[$.datepicker.formatDate('yy-mm-dd', date)]) { 
                    return [true]; 
                } else { 
                    return [false]; 
                } 
            }
            catch(e){}
            
            return [false];*/
            
        }
    });
	
	
}

function isCheapDate(d, start)
{
    return ((d-start)/(1000*60*60*24) == 5 || (d-start)/(1000*60*60*24) == 19);
    
}



function fillingDatesRules(ind, id)
{
	
	var destFromObj = document.getElementById('RegDestinationFrom'+ind+id);
	var destToObj	= document.getElementById('RegDestinationTo'+ind+id);
	var oneway = ($('div.rse_radio_list input:radio:checked').val() == "ONEWAY")
	
	if (destFromObj)
	{
		if (isnull(destFromObj.value)) 
		{
			alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
			return false;	
		}
	}
	if (destToObj)
	{
		if (isnull(destToObj.value)) 
		{
			alert(dic.REGULAR_FLIGHTS_DESTINATIONS_ERROR);
			return false;	
		}
	}
	if (ind>1 || oneway)
	{
		var dateObj	= document.getElementById('RegDate'+(ind-1)+id);
		if (dateObj)
		{
			if (isnull(dateObj.value)) 
			{
				alert(dic.REGULAR_FLIGHTS_FILL_DATES_BY_ORDER_ERROR);
				return false;	
			}
		}
	}
	return true;
}
































function OpenChildsAgesPopup(id){
    currRegSeId = id;
    var o = document.getElementById("RegChildNumber"+id);
    var ca = document.getElementById("ChildsAges");
    
    if(o.value == "0")
    {
        ca.value="";
        //return;
    }
    
    
    childsNumber = o.value;
    var ages = ca.value;
    if(ages != ""){
        agesArr = ages.split(",");
    }
    
    $(".rse_result").html("");
    $(".rse_popup").dialog("destroy");
    $(".rse_popup").dialog({
        autoOpen: true,
        modal: true,
        title: dic["CHOOSE_CHILD_AGE"],
        width: 500,
        height: 200,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_loading").css("display","none");
        }
    });
    $(".rse_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/regular/ChildAges.asp",
		cache: true,
		data: "lang="+lang+"&Childs="+o.value+"&Ages="+ca.value,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(data);
		    
		    
		    try{
		        
		        var o = document.getElementById("NumberOfChilds");
		        o.value = childsNumber;
    		    RefreshSelects();
    		    InitAges();
		    }
		    catch(e){alert(e.description);}
		}
	})
    
    /*
	var features = "dialogHeight:120px;dialogWidth:420px;scroll:no;"
	var childsUrl = "/site/windows/regular/ChildAges.asp?lang="+lang+"&Childs="+o.value+"&Ages="+ca.value ;
	var result = showModalDialog(childsUrl, self, features);
	if(!isnull(result))
	{
		var resArr = result.split("___");
		SetChildAges(resArr[0],resArr[1]);
	}
	*/
}
var childsNumber = 0;
var agesArr = [];


function ClearRegularFlightsExtendedEngine(id)
{
    $(".rse_dest_date input").val("");
    $(".rse_dest_from select").val("");
    $(".rse_dest_to select").val("");
    $(".rse_type_number select").val("0");
    $(".rse_type_adult select").val("1");
    $(".rse_classes select").val("Y");
    $(".rse_airlines select").val("ALL");
}



function RefreshSelects()
{
    var o = document.getElementById("line1Tit")
    if(childsNumber > 0)
    {
        o.style.visibility = "visible";
    }
    else
    {
        o.style.visibility = "hidden";
    }
    for(var i=1; i<=10; i++){
        if(i>childsNumber){
            document.getElementById("Child"+i).disabled = true;
            document.getElementById("dChild"+i).style.visibility = "hidden";
        }
        else{
            document.getElementById("Child"+i).disabled = false;
            document.getElementById("dChild"+i).style.visibility = "visible";
        }
    }
}
function InitAges()
{
    for(var i=0; i<agesArr.length; i++){
        document.getElementById("Child"+(i+1)).value = agesArr[i].length == 1 ? "0" + agesArr[i] : agesArr[i];
    }
}
function SetChildsNumber()
{
    var o = document.getElementById("NumberOfChilds");
    childsNumber = o.value;
    
    RefreshSelects();
}
function SetChildAges()
{
    var res = "";
    for(var i=1; i<=childsNumber; i++){
        if(res != "")
            res += ",";
        res += document.getElementById("Child"+i).value
    }
    //parent.SetChildAges(res,childsNumber);
    var result = res + "___" + childsNumber;
    
    if(!isnull(result))
	{
		var resArr = result.split("___");
		SetChildAgesCallback(resArr[0],resArr[1]);
	}
	
	$(".rse_popup").dialog("close");
}

function SetChildAgesCallback(res,val){
    var o = document.getElementById("RegChildNumber"+currRegSeId);
    var ca = document.getElementById("ChildsAges");
    
    o.value = val;
    ca.value=res;
    //chIframe.style.display="none";
}

/*************** AIRLINES POPUP *****************************************/


function OpenAirlinesPopUp(id) 
{	
    currRegSeId = id;
    $(".rse_result").html("");
    $(".rse_popup").dialog("destroy");
    $(".rse_popup").dialog({
        autoOpen: true,
        modal: true,
        title: dic["ADDITIONAL_AIRLINES"],
        width: 500,
        height: 300,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_loading").css("display","none");
        }
    });
    $(".rse_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/regular/AirlinesPopup.asp",
		cache: true,
		data: "stcss="+css+"&lang="+lang+"&sitePath="+_site_path+"&id="+id + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(data);
		    
		    $(".rse_airlines_popup:first").show();
		}
	})
}
function getAirlines(l)
{
    $(".rse_airlines_popup").css("display","none");
    $("#airlines_"+l).show()
}
function SetResultFromAirlinesPopUp(resultCode,resultName) 
{	
    //alert(resultCode + " : "+ resultName + " : " + currRegSeId)
	if(!isnull(resultCode) && !isnull(resultName)){	
		var selectListObj = document.getElementById(currRegSeId);
		if (selectListObj)
		{
		    var index = findItemInSelectList(selectListObj, resultCode);
			if (index>0)
			{
				selectListObj.selectedIndex = index;
			}
			else 
			{
				var len = selectListObj.length
				selectListObj.length = selectListObj.length+1;
				selectListObj[len].text			= resultName;
				selectListObj[len].value		= resultCode;
				selectListObj[len].selected	= true;	
			}
		}
	}
	
	$(".rse_popup").dialog("close");
}



function OpenDestinationsPopUp(objName, ind, id) 
{	
    currRegSeId = id;
    currRegSeIndex = ind;
    currRegSeObjName = objName;


    $(".rse_result").html("");
    $(".rse_popup").dialog("destroy");
    $(".rse_popup").dialog({
        autoOpen: true,
        modal: true,
        title: dic["ADDITIONAL_DESTINATIONS"],
        width: 500,
        height: 300,
        resizable: false,
        draggable: false,
        onClose: function(){
            $(".rse_loading").css("display","none");
        }
    });
    $(".rse_loading").css("display","block");

    $.ajax({
		type: "GET",
		url: "/site/windows/REGULAR/DestinationsPopup.asp",
		cache: true,
		data: "stcss="+css+"&lang="+lang+"&sitePath="+_site_path+"&objName="+objName+"&ind="+ind+"&id="+id,// + "&r=" + Math.random(),
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(dic['LOADING_DATA_ERROR']);
			//alert('error : ' + textStatus + " : " + errorThrown);
		},
		success: function(data, textStatus){
		    $(".rse_loading").css("display","none");
		    $(".rse_result").html(data);
		    
		    $(".rse_destinations_popup:first").show();
		}
	})
}
function getDestinations(l)
{
    $(".rse_destinations_popup").css("display","none");
    $("#destinations_"+l).show()
}
function SetResultFromDestinationsPopUp(resultCode, resultName) 
{	
	//alert(objName+"\n"+ind+"\n"+id)
	
	var id = currRegSeId;
    var ind = currRegSeIndex;
	var objName = currRegSeObjName;
	//alert(id + " : " + ind + " : " + objName + " : " + resultCode + " : " + resultName)
	if(!isnull(resultCode) && !isnull(resultName)){	
	    //alert(123)
		var selectListObj = document.getElementById("Reg"+objName+ind+id);	
		if (selectListObj)
		{
		//alert(123)
			var index = findItemInSelectList(selectListObj, resultCode);
			if (index>0)
			{
				selectListObj.selectedIndex = index;
			} 
			else 
			{	
				var len = selectListObj.length
				selectListObj.length = selectListObj.length+1;
				selectListObj[len].text		= resultName;
				selectListObj[len].value	= resultCode;
				selectListObj[len].selected = true;
			}
			
			// reset date input field
	        $("#RegDate"+ind+id).val('');
	        
        	var tripType = $('div.rse_radio_list input:radio:checked').val()
            if (tripType=="ROUNDTRIP")
	        { 
		        
        			
		        ind = 3-ind; // ind = 1 or 2 
		        // reset second destination row date input field
		        $("#RegDate"+ind+id).val('')
		        var targetObj	= null;
		        var textObj		= null;
		        
		        if (objName=="DestinationFrom")
		        {
			        targetObj	= document.getElementById("RegDestinationTo"+ind+id);
			        textObj		= document.getElementById("TextDestinationTo"+ind+id);
		        } 
		        else 
		        {
		            targetObj	= document.getElementById("RegDestinationFrom"+ind+id);
			        textObj		= document.getElementById("TextDestinationFrom"+ind+id);
			    }
		        if (targetObj)
		        {
			        var index = findItemInSelectList(targetObj, resultCode);
			        if (index>0)
			        {
				        targetObj.selectedIndex = index;
			        } 
			        else 
			        {
				        targetObj.length = targetObj.length+1;
				        var len = targetObj.length-1;
				        targetObj[len].text		= resultName;
				        targetObj[len].value	= resultCode;
				        targetObj[len].selected = true;
			        }
			        //setRoundTripReturnValues(resultCode, resultName, objName, ind, id);
		        }
		        
	        }
		}
	}
	
	$(".rse_popup").dialog("close");
}
function ContinueToRegularFlightsDetail(id)
{
    document.getElementById('detailsForm_'+id).submit();
}











/***********************************************************************************************************************/

function submitPassengersDetailsForm(count,bCheckRules){
    if(!checkPassengerDetailsConditions()) return;
	//AGENTS_BY_AREA
	var agentByAreaObj = document.getElementById("agentByArea");
	if(agentByAreaObj && agentByAreaObj.value == "")
	{
		alert(dic.BAD_AGENT_BY_AREA);
		agentByAreaObj.focus();
		return;
    }
    
    if(bCheckRules && !$("#confirmTerms").attr("checked")){
		alert(dic.REGULAR_FLIGHTS_RULES_ERROR)
		document.getElementById("confirmTerms").focus()
		return
	}
	
	var oForm=document.getElementById('passengersDetailsForm')
	oForm.action=purchase_action
	oForm.submit();
}

function submitRegularFlightFormToPhoneAsk(agentID){
    
	
		var oForm=document.getElementById('passengersDetailsForm')
		$('#passengersDetailsForm_step').val("_PhoneRequest");
		oForm.action=purchase_action
		oForm.submit();
	

}

function checkPassengerDetailsConditions(){
	var oTodayDate = new Date(sTodayDate)
	var res = $('tr.pdPassengerData').length>0;
	$('tr.pdPassengerData').each(function() {
	    var l = $(this).find('input.pdLastName')
	    var f = $(this).find('input.pdFirsName')
	    var y = $(this).find('select.pdBirthYear')
	    var m = $(this).find('select.pdBirthMonth')
	    var d = $(this).find('select.pdBirthDay')
	    var b = $(this).find('input.pdBirthDate')
	    var mina = $(this).find('input.pdMinAge')
	    var maxa = $(this).find('input.pdMaxAge')

	    if (res && isnull(l.val())) {
	        alert(dic.MUST_TO_FILLED_LAST_NAME);
	        l.focus()
	        res = false
	    }
	    if (res && isnull(f.val())) {
	        alert(dic.MUST_TO_FILLED_FIRST_NAME);
	        f.focus()
	        res = false
	    }
	    if (res && isnull(y.val())) {
	        alert(dic.FILL_BIRTH_DATE);
	        y.focus()
	        res = false
	    }
	    if (res && isnull(m.val())) {
	        alert(dic.FILL_BIRTH_DATE);
	        m.focus()
	        res = false
	    }
	    if (res && isnull(d.val())) {
	        alert(dic.FILL_BIRTH_DATE);
	        d.focus()
	        res = false
	    }

	    if (res) {
	        var yv = y.val()
	        var mv = zeroPad(m.val(), 2, true)
	        var dv = zeroPad(d.val(), 2, true)
	        b.val(yv + "-" + mv + "-" + dv)
	        var minAge = mina.val()
	        var maxAge = maxa.val()

	        var tempDateForCheck1 = new Date(yv + "/" + mv + "/" + dv)
	        var tempDateForCheck2 = new Date(yv + "/" + mv + "/" + dv)

	        tempDateForCheck1.setFullYear(parseInt(tempDateForCheck1.getFullYear()) + parseInt(minAge))
	        tempDateForCheck2.setFullYear(parseInt(tempDateForCheck2.getFullYear()) + parseInt(maxAge))


	        if (oTodayDate < tempDateForCheck1 || oTodayDate > tempDateForCheck2 ||
		        (parseInt(maxAge) == "2" && (oTodayDate < tempDateForCheck1 || oTodayDate >= tempDateForCheck2))) {
	            alert(dic.INVALID_BIRTH_DATE);
	            y.focus()
	            res = false;
	        }

	    }
	})
	
	return res;
	
}
