// --- EXTERNALS ROUTINE

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/**
 * jQuery BASE64 functions
 * 
 * 	<code>
 * 		Encodes the given data with base64. 
 * 		String $.base64Encode ( String str )
 *		<br />
 * 		Decodes a base64 encoded data.
 * 		String $.base64Decode ( String str )
 * 	</code>
 * 
 * Encodes and Decodes the given data in base64.
 * This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
 * Base64-encoded data takes about 33% more space than the original data. 
 * This javascript code is used to encode / decode data using base64 (this encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean). Script is fully compatible with UTF-8 encoding. You can use base64 encoded data as simple encryption mechanism.
 * If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
 * 
 * Example
 * 	Code
 * 		<code>
 * 			$.base64Encode("I'm Persian."); 
 * 		</code>
 * 	Result
 * 		<code>
 * 			"SSdtIFBlcnNpYW4u"
 * 		</code>
 * 	Code
 * 		<code>
 * 			$.base64Decode("SSdtIFBlcnNpYW4u");
 * 		</code>
 * 	Result
 * 		<code>
 * 			"I'm Persian."
 * 		</code>
 * 
 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
 * @link http://www.semnanweb.com/jquery-plugin/base64.html
 * @see http://www.webtoolkit.info/
 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
 * @param {jQuery} {base64Encode:function(input))
 * @param {jQuery} {base64Decode:function(input))
 * @return string
 */

(function($){
	
	var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
	var uTF8Encode = function(string) {
		string = string.replace(/\x0d\x0a/g, "\x0a");
		var output = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				output += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				output += String.fromCharCode((c >> 6) | 192);
				output += String.fromCharCode((c & 63) | 128);
			} else {
				output += String.fromCharCode((c >> 12) | 224);
				output += String.fromCharCode(((c >> 6) & 63) | 128);
				output += String.fromCharCode((c & 63) | 128);
			}
		}
		return output;
	};
	
	var uTF8Decode = function(input) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < input.length ) {
			c = input.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = input.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = input.charCodeAt(i+1);
				c3 = input.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
	
	$.extend({
		base64Encode: function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = uTF8Encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
			}
			return output;
		},
		base64Decode: function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = keyString.indexOf(input.charAt(i++));
				enc2 = keyString.indexOf(input.charAt(i++));
				enc3 = keyString.indexOf(input.charAt(i++));
				enc4 = keyString.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = uTF8Decode(output);
			return output;
		}
	});
})(jQuery);

// --- END OF EXTERNALS --- 

function aviasales_lb_hide_errors() {
	$("#lb-errors-wrapper").hide();
	$("#lb-content-wrapper").show();
	window.parent.$.fn.fancybox.recalcHeight();
	window.parent.$.fn.fancybox.scrollBox();	
}

function aviasales_lb_fancybox_fix(){
	window.parent.$.fn.fancybox.recalcHeight();
	window.parent.$.fn.fancybox.scrollBox();
}

function foo(deal_id) {
  elem = $("#hd-details-"+deal_id);
  btn = $("#hd-more-btn-"+deal_id);
  if (!elem.is(':visible')) {
    elem.show("fast");
    btn.color("#CC0000");
    btn.text("Скрыть");
  } else {
    elem.hide("fast");
    btn.color("#336699");
    btn.text("Подробнее");
  }
}

function fix_size() {
	if (typeof(GLOBAL_TEST) != "undefined")
		alert(GLOBAL_TEST);
//	alert($('#davs_frame').contentWindow.document.body.offsetHeight);
//	$('#davs_frame').style.height = $('#davs_frame').contentWindow.document.body.offsetHeight + 'px';	

}

function aviasales_davs_test() {
	// window.location.href = window.location.pathname+"#davs_frame_wrapper";			
//	alert($('#davs_frame').attr("src"));
	alert(parent.davs_frame.location.pathname);
}

function aviasales_validate_davs_form() {
	if ($("#edit-city-from").val() == "" || $("#edit-city-to").val() == "") {
		alert("Необходимо указать пункт отправления и прибытия.");
		return false;
	}
	return true;
}

function aviasales_refresh_davs_frame(url) {	
	if (!aviasales_validate_davs_form()) {
		return false;
	}
	//setTimeout('fix_size()',2000);
	//$('#davs_frame').attr('src', url);
	/*
  		DepartureDate: str_replace('.', '/', $form_state['date_1']);
  		ArrivalDate: str_replace('.', '/', $form_state['date_2']);
  		From: $iata1;
  		To: = $iata2;
  		date_type: = $form_state['date_mode'];
  		oneway: =$form_state['direction'];
 			ItineraryAirlineOption1: = "";
  		ItineraryCabinOption: = $form_state['class'];
			only_direct:'flight_mode'
  		ADT: = $form_state['adult'];
  		YTH: = $form_state['youth'];
  		CHD: = $form_state['child'];
  		INF: = $form_state['infant'];
  		site: 'aviasales.ru'  			
	 
	 */
	params = $("#aviasales-davs-buy-form").serialize();
// 	$("#davs_frame_wrapper").html('');
// 	$("#davs_frame_wrapper").append('<iframe style="width:100%;hright:1200px;" src="/davs_offers_list?'+params+'"></iframe>');
 	$.ajax({  
   type: "POST",  
   url: "/davs_offers_list",  
	 dataType: "html",
   data: params,  
   success: function(data) {  
	 	$("#davs_frame_wrapper").html('');
		$("#davs_frame_wrapper").append('<iframe name="davs_frame" id="davs_frame" style="width:100%;height:6200px;" src="'+data+'">Дождитесь загрузки</iframe>');
		window.location.href = window.location.pathname+"#davs_frame_wrapper";		
   }     
	});  	
}

function aviasales_davs_init_orders_list() {
	$.tablesorter.addParser({
		id: "date_range",
		is: function(s) {
			return false;
		},
		format: function(s,table) {
			var pp = s.substr(0, 5).split(".");
			var cd = new Date();
			var year = cd.getFullYear();
			if (pp[1] < cd.getMonth()) {
				year += 1;
			} 
			return $.tablesorter.formatFloat(new Date(year,pp[1],pp[0]).getTime());
		},
		type: "numeric"
	});
	$.tablesorter.addParser({
		id: "date_since",
		is: function(s) {
			return false;
		},
		format: function(s,table) {
			var r = /(\d+) /;
			if ((mathes = r.exec(s)) != null) {
				return mathes[1];
			} else {
				return 0;
			}
		},
		type: "numeric"
	});
	
  $("#orders-list").tablesorter(
  { headers: { 
      0: { sorter: "date_since" }, 	
      5: { sorter: false } 
  } }				
	).bind("sortStart",function() { 
			$(".tbiw_g").remove();    	
			$(".btns_g").show();	
			$(".btnc_g").hide();		
  });	
}

function aviasales_more_orders_close(rnum) {
	$("#tbiw_" + rnum).remove();
	$("#btns_" + rnum).show();	
	$("#btnc_" + rnum).hide();		
}

function aviasales_more_orders(rnum,iata1,iata2,bidirect) {
	$("#btns_" + rnum).hide();	
	$("#btns_" + rnum).after('<img id="indic_'+rnum+'" border="0" src="/misc/ac/indicator.gif">');	
 	$.ajax({  
   url: "/list_orders_by_iata/"+rnum+"/"+iata1+"/"+iata2+"/"+bidirect,  
   success: function(data) {
	 	$("#row_"+rnum).after("<tr class=\"tbiw_g\" id=\"tbiw_"+rnum+"\"><td></td><td colspan=\"5\">"+data+"</td></tr>");		
		$("#indic_" + rnum).remove();
		$("#btnc_" + rnum).show();
    $("#tbi_" + rnum).tablesorter(
			{ headers: { 
      	0: { sorter: "date_since" }, 	
      	1: { sorter: "date_range" }, 	
      	4: { sorter: false } 
  		} });
      $("a.iframe").fancybox(
        {
          'frameWidth': 670,
          'frameHeight': 520,
          'overlayOpacity': 0.8,
          'centerOnScroll': false
        }
      );			
		}     
	});	
}

function subscr_delete(id) {
	$("#row"+id).parent().parent().remove();
 	$.ajax({ url: "/delete_subscriber/"+id });
	$("#sbscr_counter").html(parseInt($("#sbscr_counter").html())-1);	
}

function subscr_search_delete() {
	var mail = $("#subscriber_email").val();
	if (!mail) {
		alert("Надо хоть кого-то указать.");
		return false;
	}
 	$.ajax({  
   url: "/delete_subscriber/"+mail,
	 success: function(data){
			$("#sbscr_counter").html(parseInt($("#sbscr_counter").html())-1);	
			$("#subscriber_email").val("");
		 	alert("Подписчик удален из рассылки.");
   }  
	});
	return true;		
}

function initialize_avianews_form() {
	$("#edit-field-ids-0-value-wrapper").remove();
	
	$("#edit-field-airport-0-0-value").autocomplete("/airport_ac", {matchSubset: 0});
	$("#edit-field-airline-0-value").autocomplete("/airline_ac", {matchSubset: 0});
	
	$("#node-form").submit(function(){
			return true;
  });	
}

function as_check_xml_search_form() {
	if ($("#edit-xml-adults").val() < 1) {
		alert("Должен быть указан минимум 1 взрослый.");
		return false;
	}
	
	if ($('#edit-xml-loc1').val() == "" || $('#edit-xml-loc2').val() == "") {
    		alert("Необходимо указать пункты отправления и назначения.");
    		return false;
    	}
    	var date1 = null;
			var date2 = null;
		
    	if ($('#edit-xml-date1').val() != "") {
    		date1 = $('#edit-xml-date1').val().split('.');
				if (date1.length != 3) {
					alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
					return false;
				}
			} else{
				alert("Необходимо указать дату вылета.");
				return false;
			}
			
			if ($('#edit-xml-date2').val() != "") {
				date2 = $('#edit-xml-date2').val().split('.');
				if (date2.length != 3) {
					alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
					return false;
				}
			} else {				
				if ($("input[@name=\'xml_oneway\']:checked").val() == 0) {
					alert("Необходимо указать дату возвращения.");
					return false;
				}				
			}
		      
      if ($("input[@name=\'xml_euroavia\']:checked").val() == 1) {
    	  window.open("/goto_lenturist?"+$("#aviasales-xml-search-form").serialize(), "EuroAvia"); 
      }
      
      return true;	
}

function as_check_xml_main_form() {
	if ($("#edit-adult").val() < 1) {
		alert("Должен быть указан минимум 1 взрослый.");
		return false;
	}
	
	if ($('#edit-city-from').val() == '' || $('#edit-city-to').val() == '') {
		alert('Необходимо указать пункт отправления и назначения.');
		return false;
	}    	
	
	var date1 = null;
	var date2 = null;
	if ($('#edit-date-1').val() != "") {
		date1 = $('#edit-date-1').val().split('.');
			if (date1.length != 3) {
				alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
				return false;
			}
		} else {
			alert('Не указана дата вылета.');
			return false;
		}
		
		var oneway = false;
		if ($("input[@name='oneway']:checked").val() == 0) {
			if ($('#edit-date-2').val() != "") {
				date2 = $('#edit-date-2').val().split('.');
				if (date2.length != 3) {
					alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
					return false;
				}
			} else {
				alert('Не указана дата возвращения.');
				return false;					
			}
		} else {
			oneway = true;
		}
			
    if ($("input[@name=\'euroavia\']:checked").val() == 1) {
          window.open("/goto_lenturist?"+$("#aviasales-davs-buy-form").serialize(), "EuroAvia");
        }
    
	return true;			
}

function as_check_offers_search_form() {
	var date1 = null;
	var date2 = null;
		
	if ($('#edit-date1').val() != "") {
		date1 = $('#edit-date1').val().split('.');
			if (date1.length != 3) {
				alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
				return false;
			}
		}
		
		if ($('#edit-date2').val() != "") {
			date2 = $('#edit-date2').val().split('.');
			if (date2.length != 3) {
				alert("Неверный формат даты, должно быть День.Месяц.Год, например: 25.08.2009");
				return false;
			}
		}
		
  if (date1.length == 3 && date2.length == 3) {
    var d1 = new Date();
    d1.setFullYear(date1[2], date1[1], date1[0]);
    var d2 = new Date();
    d2.setFullYear(date2[2], date2[1], date2[0]);
    if (d2 < d1) {
      alert('Дата возвращения раньше даты прибытия, выберите другую дату.');
      return false;
    }        
  }
  return true;	
}

function as_xml_get_default() {
	var default_params = $.cookie('as_xml_params')
	if (default_params) {
		default_params = $.base64Decode(default_params);
	    eval("default_params="+default_params); 		
	}	
	return default_params;
}

function as_setup_xml_main_form() {
	try {
		var defs = as_xml_get_default();
		if (defs && $("input[@name='city_to']").val() == '') {
			$("input[@name='date_1']").val(defs.date1);
			$("input[@name='date_2']").val(defs.date2);		
			$("input[@name='city_from']").val(decodeURIComponent(defs.from));
			$("input[@name='city_to']").val(decodeURIComponent(defs.to));
			if (defs.range == '1') {				
				$("input[@name='date_mode'][@value='1']").attr("checked", true);
			}
			$("input[@name='oneway'][@value='"+defs.oneway+"']").attr("checked", true);
			$("input[@name='class'][@value='"+defs.klass+"']").attr("checked", true);

			$("#edit-adult").val(defs.adults);
			$("#edit-child").val(defs.children);
			$("#edit-infant").val(defs.infants);			
		}	
	} catch (err) {}	
}

function as_setup_xml_sb_form() {
	try {
		var defs = as_xml_get_default();
		if (defs && $("input[@name='xml_loc2']").val() == '') {
			$("input[@name='xml_date1']").val(defs.date1);
			$("input[@name='xml_date2']").val(defs.date2);		
			$("input[@name='xml_loc1']").val(defs.from);
			$("input[@name='xml_loc2']").val(defs.to);
			if (defs.range == '1') {
				$("input[@name='xml_range']").attr("checked", true);
			}
			$("input[@name='xml_oneway'][@value='"+defs.oneway+"']").attr("checked", true);
			$("input[@name='xml_class'][@value='"+defs.klass+"']").attr("checked", true);
			
			$("#ts_form_more").show();
		}	
	} catch (err) {}
	var dp_days = ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'];
	var dp_months = ['Январь','Февраль','Март','Апрель','Маи','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'];
	$("input.xml_efd1,input.efd1,input.dfd1").datepicker({
		dateFormat: 'dd.mm.yy',
		dayNamesMin: dp_days,
		monthNames:dp_months,
		firstDay: 1,
		minDate: new Date(new Date().getTime() + 86400000*2),
		maxDate: new Date(new Date().getTime() + 86400000 * 365),
		changeYear: false,
		onSelect: function(dateText, inst) {
			var sel_date = dateText.split(".").reverse()
			var selected_date =new Date(sel_date[0], sel_date[1]-1, sel_date[2]);
			$('input.xml_efd2,input.efd2,input.dfd2').datepicker('option', 'minDate', selected_date );
			return true; 
		}
	}).attr("autocomplete", "OFF");

	$("input.xml_efd2,input.efd2,input.dfd2").datepicker({
		dateFormat: 'dd.mm.yy',
		dayNamesMin: dp_days,
		monthNames:dp_months,
		firstDay: 1,
		minDate: new Date(new Date().getTime() + 86400000*2),
		maxDate: new Date(new Date().getTime() + 86400000 * 365),
		changeYear: false,
		onSelect: function(dateText, inst) {
			var sel_date = dateText.split(".").reverse()
			var selected_date =new Date(sel_date[0], sel_date[1]-1, sel_date[2]);
			$('input.xml_efd1,input.efd1,input.dfd1').datepicker('option', 'maxDate', selected_date );
			return true; 
		}
	}).attr("autocomplete", "OFF");

	$("input.xml_efd1,input.efd1,input.dfd1").bind(
		"dpClosed",
		function(e, selectedDates)
		{
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				$("input.xml_efd2,input.efd2,input.dfd2").dpSetStartDate(d.addDays(0).asString());
			}
		}
	);
	$("input.xml_efd2,input.efd2,input.dfd2").bind(
		"dpClosed",
		function(e, selectedDates)
		{
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				$("input.xml_efd1,input.efd1,input.dfd1").dpSetEndDate(d.addDays(0).asString());
			}
		}
	);			
	$("input[@name=\'xml_oneway\']").change(function(){
		if ($("input[@name=\'xml_oneway\']:checked").val() == 1) {
			$("#edit-xml-date2").attr("disabled", true); 
		} else {
			$("#edit-xml-date2").removeAttr("disabled"); 
		}
	});
	
	$("input[@name=\'oneway\']").change(function(){
		 $("#edit-date-2").attr("disabled", $("input[@name=\'oneway\']:checked").val() == 1);
	});	
}

NiftyLoad = function() {
	Nifty("div.offer-dates,div.offer-dates-2,div#block-block-9,div#block-tagadelic-2 div,div#apinfo-box,div#apinfo-offer-link,div#fb-form","small");
};

$(document).ready(function(){
	Date.firstDayOfWeek = 1;
	Date.format = "dd.mm.yyyy";

	as_setup_xml_sb_form();
	as_setup_xml_main_form();
	
	$("#content").append('<a style="display:none;" id="synonym_add_link" class="iframe4" href="/locationaddsynonym">zhopa</a>');
	
	$(".lac_field").autocomplete("/lac", {matchSubset: 0});
	$(".ac_city_field").autocomplete("/lac", {matchSubset: 0});
	
	$("#latest_orders_filter_reset").click(function(){
		$("#orders_list_wrapper").html("");
		$("#orders_list_wrapper").append("<font color='green'>Загружаю...</font>");
		$("#orders_list_wrapper").load("davs_get_latest_orders_table", {}, function(){ aviasales_davs_init_orders_list(); });
  });
	
	$("#filter_latest_orders").click(function() {		
		if ($("#field_from").val() == "" && $("#field_to").val() == "") {
			alert("Укажите хотя бы один из пунктов.");
		}
		else {
			$("#orders_list_wrapper").html("");
			$("#orders_list_wrapper").append("<font color='green'>Загружаю...</font>");
			$("#orders_list_wrapper").load(
				"davs_get_latest_orders_table", 
				{
					from:$("#field_from").val(),
					to:$("#field_to").val()		
				}, 
				function(){
					aviasales_davs_init_orders_list();
				}
			);
		}
	});
});

function as_check_cities() {
	//alert(flag);
	var Cfrom=$("#routes_from_1").val();
	var Cto=$("#routes_to_1").val();
	var i=0;
	var fl=true;
	var getstr='?';
	while(fl){
		i++;
		if($("#routes_from_"+i).val()){
			if($("#routes_from_"+i).val()!=''){
				getstr+='from_'+i+'='+$("#routes_from_"+i).val()+'&';
			}
			if($("#routes_to_"+i).val()!=''){
				getstr+='to_'+i+'='+$("#routes_to_"+i).val()+'&';
			}
		}else{fl=false;}
	}
	getstr=getstr.substr(0,getstr.length-1);
	//alert(getstr);
	//alert('dd');
	$.ajax({  
		   //type: "GET",  
		   url: "/lck/"+getstr,
		   cache: false,
		   async: false,
		   timeout: 30000,
		   //dataType: "html",
		   //data: '?from='+Cfrom,  
		   success: function(data) { 
		   //alert(data);
		   		if(data!=''){
		   				//alert('<a style="display:none;" id="synonym_add_link" class="iframe4" href="/locationaddsynonym'+data+'">zhopa</a>');
		   				$("#synonym_add_link").attr("href","/locationaddsynonym"+data);
						$("a.iframe4").fancybox(
						          {
						            'frameWidth': 650,
						            'frameHeight': 300,
						            'overlayOpacity': 0.8,
									'centerOnScroll': false,
									'callbackOnClose': function(){ } 
						          }
						        );
						$("#synonym_add_link").click();		
		   		}else {flag=true;}
			return false;
		   }
		   		
			});
	return flag;
}

