/* City changing vars*/
var keykode = -1;
var textsaved = null;
var blockvisible = false;
var firstFocus = true;
var lockblock = false;
var saving_in_process = false;

/* Var to store New city */
var newCity = null;

function cityClass (id, countryCode, cityName, longitude, latitude, timeZone, gmt, swtime, shabatAdj, galut, ampm) {
	this.id = id;
	this.countryCode = countryCode;
	this.cityName = cityName;
	this.longitude = longitude;
	this.latitude = latitude;
	this.gmt = gmt;
	this.shabatAdj = shabatAdj;
	this.timeZone = timeZone;
	this.swtime = swtime;
	this.galut = galut;
	this.ampm = ampm;
}

/*Function to get new clocks values */
function cityClass_getCurrentTime () {
	var hours = 0;
	var minutes = 0;
	var date = 0;
	var month = 0;
	var year = 0;
	$.ajax({
		url : '/ajax/city_time.php',
		cache: false,
		async: false,
		success: function(data){
			var arr = data.split(":");
			minutes = arr[0];
			hours = arr[1];
			date = arr[2];
			month = arr[3];
			year = arr[4];
		}
	});
	
	return {'hours': hours, 'minutes': minutes, 'date': date, 'month': month, 'year': year};
}
cityClass.prototype.getCurrentTime = cityClass_getCurrentTime;

function custom_city_i_focusin (el, cclass) {
	if (firstFocus == true) {
		el.value = '';
		firstFocus = false;
		$('#' + cclass + '_cities_block').width($(el).outerWidth() - 4);
		$('#' + cclass + '_cities_block_wrapper').offset({
			top: $(el).offset().top + $('#' + cclass + '_custom_city_i').outerHeight(), 
			left: $(el).offset().left
		});
	}
}

function custom_city_i_focusout (el, cclass) {
	if (lockblock == false) {
		$('#' + cclass + '_cities_block').hide();
		blockvisible = false;
	}
}

function cities_block_div_click (el, cclass) {
	textsaved = null;
	$('#' + cclass + '_custom_city_i').val($(el).attr('cityname'));
	$('#' + cclass + '_cities_block > div').each(
		function () {
			$(el).css('background-color', '#ffffff');
			$(el).attr('select', 0);
			$(el).attr('filtered', 0);
		}
	);
	$('#' + cclass + '_cities_block').hide();
	blockvisible = false;
	$('#' + cclass + '_custom_city_i').focus();
}

function custom_city_i_keypress (event, cclass) {
	if ( event.which == 13 ) {
		event.preventDefault();
		if (blockvisible) {
			$('#' + cclass + '_cities_block > div').filter(':visible').each(
				function() {
					cur = $(this);
					if (cur.attr('select') == 1) {
						cur.attr('select') == 0;
					}
				}
			);
			
			$('#' + cclass + '_cities_block').hide();
			blockvisible = false;
		} else {
			$('#' + cclass + '_custom_city_ok').focus();
			$('#' + cclass + '_custom_city_ok').click();
		}
	} 
	keykode = event.which;
}

function custom_city_i_keyup (event, cclass) {
	if ((keykode < 1072 || keykode > 1105) && keykode != 0 && event.which != 32 && event.which != 109 && event.which != 18 &&								event.which != 16 && event.which != 17 && event.which != 116 && event.which != 27 && event.which != 8 && event.which != 46 && event.which != 37 && event.which != 38 && event.which != 13 && event.which != 39 && event.which != 40 && event.which != 35 && event.which != 36 && event.which != 45) {
		return;
	} else {
		var cur = null;
		var prev = null;
		var next = null;
		switch (event.which) {
			/* Esc handler*/
			case 27:
				$('#' + cclass + '_cities_block').hide();
				blockvisible = false;
				return;
			case 116:
				event.preventDefault();
				return;
			case 13:
				event.preventDefault();
				if (blockvisible) {
				$('#' + cclass + '_cities_block > div').filter(':visible').each(
					function() {
						cur = $(this);
						if (cur.attr('select') == 1) {
							cur.attr('select') == 0;
						}
					}
				);
				$('#' + cclass + '_cities_block').hide();
					blockvisible = false;
				} else {
					$('#' + cclass + '_custom_city_ok').focus();
					$('#' + cclass + '_custom_city_ok').click();
				}
				return;
			default:
				break;										
		}

		/*UP ARROW Handler*/
		if (event.which == 38) {
			var setup = false;
			$('#' + cclass + '_cities_block > div').filter(':visible').each(
				function() {
					cur = $(this);
					if (cur.attr('select') == 1) {
						prev = cur.prevAll('div').filter(':visible').first();
						cur.attr('select', 0);
						cur.css('background-color', '#ffffff');
						if (prev.attr('cityname')) {
							prev.css('background-color', '#aaaaff');
							prev.attr('select', 1);
							if (textsaved == null) {
								textsaved = $('#' + cclass + '_custom_city_i').val();
							}
							$('#' + cclass + '_custom_city_i').val(prev.attr('cityname'));
						} else {
							if (textsaved == null)
								textsaved = '';
								$('#' + cclass + '_custom_city_i').val(textsaved);
								textsaved = null;
						}
						setup = true;
					}
				}
			);
									
			if (setup == false) {
				$('#' + cclass + '_cities_block > div').filter(':visible').last().css('background-color', '#aaaaff');
				$('#' + cclass + '_cities_block > div').filter(':visible').last().attr('select', 1);
				if (textsaved == null) {
					textsaved = $('#' + cclass + '_custom_city_i').val();
				}
				$('#' + cclass + '_custom_city_i').val($('#' + cclass + '_cities_block div').filter(':visible').last().attr('cityname'));
			}
		}
								
		/*DOWN ARROW Handler*/
		if (event.which == 40) {
			var setup = false;
			$('#' + cclass + '_cities_block > div').filter(':visible').each(
				function() {
					cur = $(this);
					if (cur.attr('select') == 1 && setup == false) {
						next = cur.nextAll('div').filter(':visible').first();
						cur.attr('select', 0);
						cur.css('background-color', '#ffffff');
						if (next.attr('cityname') != undefined) {
							next.css('background-color', '#aaaaff');
							next.attr('select', 1);
							if (!textsaved) {
								textsaved = $('#' + cclass + '_custom_city_i').val();
							}
							$('#' + cclass + '_custom_city_i').val(next.attr('cityname'));
						} else {
							if (textsaved == null)
								textsaved = '';
								$('#' + cclass + '_custom_city_i').val(textsaved);
								textsaved = null;
						}
						setup = true;
					}
				}
			);
									
			if (setup == false) {
					var firstcity = $('#' + cclass + '_cities_block > div').filter(':visible').first();
					firstcity.css('background-color', '#aaaaff');
					firstcity.attr('select', 1);
					if (textsaved == null) {
						textsaved = $('#' + cclass + '_custom_city_i').val();
					}
					$('#' + cclass + '_custom_city_i').val(firstcity.attr('cityname'));
			}
		}
		
		// city filtering while user input
		if ((keykode > 1039 && keykode < 1105) || keykode == 1025 || event.which == 8 || event.which == 32 || event.which == 46) {
			keykode = -1;
			textsaved = null;
			$('#' + cclass + '_cities_block > div').each(
				function () {
					var part = $('#' + cclass + '_custom_city_i').val();
					$(this).attr('select', 0);
					$(this).css('background-color', '#ffffff');
					if (part.length < 1) {
						$(this).show();
						$(this).attr('filtered', 0);
					} else {
						part = part.toLowerCase();
						var cname = $(this).attr('cityname').toLowerCase();
						if (cname.indexOf(part) == 0) {
							$(this).show();
							$(this).attr('filtered', 1);
						} else {
							$(this).hide();
							$(this).attr('filtered', 0);
						}
					}
				}
			);										
		}
								
		if ($('#' + cclass + '_cities_block > div[filtered="1"]').length > 0) {
			$('#' + cclass + '_cities_block').show();
			blockvisible = true;
		} else {
			$('#' + cclass + '_cities_block').hide();
			blockvisible = false;
		}
	}
}

function adjust_dclocks (date, month, year) {
	$('#dclocks_d').text(format_2digits(date));
	$('#dclocks_mon').text(env.CivMonthNamesRp[parseInt(month, 10)]);
	$('#dclocks_y').text(parseInt(year, 10).toString());
	
	var	hDate = getHebFromCiv(date, month, year);
	var dhdate = hDate.date;
	var dhmonth = hDate.month;
	var dhyear = hDate.year;
	var hmonth_length = hDate.hmonthlength;
			
	var ndDate = new Date (year, month - 1, date, 1, 1, 1);
	var ndStamp = ndDate.getTime();
	
	var nextNdCDate = new Date (ndStamp + 24*60*60*1000);
	
	var	nexthDate = getHebFromCiv(nextNdCDate.getDate(), nextNdCDate.getMonth() + 1, nextNdCDate.getFullYear());
	var dnexthdate = nexthDate.date;
	var dnexthmonth = nexthDate.month;
	var dnexthyear = nexthDate.year;
	var nexthmonth_length = nexthDate.hmonthlength;
	
	var newHebDate = "";
	if (dhmonth == dnexthmonth) {
		newHebDate += dhdate + " - " + dnexthdate + " " + env.HebMonthNamesRp[dhmonth] + " " + dhyear;
	} else if (dhyear == dnexthyear) {
		newHebDate +=  dhdate + " " + env.HebMonthNamesRp[dhmonth] + " - " + dnexthdate + " " + env.HebMonthNamesRp[dnexthmonth] + " " + dhyear;
	} else {
		newHebDate +=  dhdate + " " + env.HebMonthNamesRp[dhmonth] + " " + dhyear + " - " + dnexthdate + " " + env.HebMonthNamesRp[dnexthmonth] + " " + dnexthyear;
	}
	$('#dclocks_hdate').text(newHebDate);
}

function update_citiesStack_controls () {
	for (i in currentCity_stack) {
		$('.custom_city' + i + '_name').each(function () { $(this).text(currentCity_stack[i].cityName);});
	}
}

function custom_city_history_click (cclass, num_in_stack) {
	cname =  $('#' + cclass + '_custom_city' + num_in_stack + '_name').text();
	custom_city_ok_click (cclass, cname);
}

function custom_city_ok_click (cclass, cname) {
	if (saving_in_process == true) {
		$('#' + cclass + '_custom_city_save_status').html('Сохраняется... Пожалуйста подождите...');
		$('#' + cclass + '_custom_city_save_status').toggle().delay(2000).fadeOut(2000);
	}
	
	saving_in_process = true;
	var cname_fromHistory = false;
	if (cname == null) {
		cname =  $('#' + cclass + '_custom_city_i').val();
	} else {
		cname_fromHistory = true;
	}
	var notfound = true;
	for (id in userCities) {
		var city = userCities[id];
		if (city.cityName == cname) {
			newCity = city;
			$('.custom_city_name').each(function () { $(this).text(cname);});
			
			var notInStack = true;
			for(i in currentCity_stack) {
				if(city.id == currentCity_stack[i].id) {
					currentCity_stack.splice(i, 1);
					currentCity_stack.unshift(city);
					notInStack = false;
				}
			}
			
			if (notInStack == true) {
				currentCity_stack.unshift(city);
				if (currentCity_stack.length > 10) {
					currentCity_stack = currentCity_stack.slice(0,10);
				} else if (typeof (MedTerm) != 'undefined') {
					mt_city_history_add_blank ();
				}  else if (typeof (CLuach) != 'undefined') {
					tc_city_history_add_blank ();
				}
			}
			
			update_citiesStack_controls ();
			
			var cityIdsToSaveStr = "";
			for(i in currentCity_stack) {
				cityIdsToSaveStr += currentCity_stack[i].id + ",";
			}
			
			$.ajax({
				url : '/ajax/save_user_settings_stack.php',
				data: { cityids: cityIdsToSaveStr},
				cache: false,
				async: false,
				success: function(data) {
					$('#' + cclass + '_custom_city_save_status').html('Сохранено');
					$('#' + cclass + '_custom_city_save_status').toggle().delay(2000).fadeOut(2000);
				}
			});
			
			var newClockVal = newCity.getCurrentTime();
			stopClock();
			var TermHourAdj = 0;
			var newDate = true;
			if (clockDate < newClockVal.date) {
				TermHourAdj = 24 - clockHour + parseInt(newClockVal.hours, 10);
			} else if (clockDate > newClockVal.date) {
				TermHourAdj = parseInt(newClockVal.hours, 10) - clockHour - 24;
			} else {
				newDate = false;
				TermHourAdj = parseInt(newClockVal.hours, 10) - clockHour;
			}
			clockHour = newClockVal.hours;
			clockMin = newClockVal.minutes;
			clockDate = newClockVal.date;
			clockMonth = newClockVal.month;
			clockYear = newClockVal.year;
			if (typeof (MedTerm) != 'undefined') {
				$('#clocks_h').text(format_2digits(clockHour));
				$('#clocks_m').text(format_2digits(clockMin));
				$('#clocks_d').text(format_2digits(clockDate));
				$('#clocks_mon').text(format_2digits(clockMonth));
				$('#clocks_y').text(parseInt(clockYear, 10).toString().substr(2,2));
			}
			
			if (typeof (SmallTerm) != 'undefined') {
				$('#stclocks_h').text(format_2digits(clockHour));
				$('#stclocks_m').text(format_2digits(clockMin));
				$('#stclocks_d').text(format_2digits(clockDate));
				$('#stclocks_mon').text(format_2digits(clockMonth));
				$('#stclocks_y').text(parseInt(clockYear, 10).toString().substr(2,2));
			}
			
			if (newDate == true) {
					adjust_dclocks (clockDate, clockMonth, clockYear);
			}
								
			startClock();
			
			notfound = false;
			//alert($('#' + cclass + '_custom_city').css('display'));
			if (cname_fromHistory == false || $('#' + cclass + '_custom_city').css('display') != 'none') {
				$('#' + cclass + '_custom_city').toggle();
				$('#' + cclass + '_custom_city_i').val('Введите город...');
				$('#' + cclass + '_custom_city_a').toggle();
			}
			
			if (typeof (MedTerm) != 'undefined') {
				MedTerm.term_hour += TermHourAdj;
				RenewTerm (newCity, MedTerm.term_date, MedTerm.term_month, MedTerm.term_year);
				mt_city_history_rewind ();
			}
			
			if (typeof (CLuach) != 'undefined') {
				tc_city_history_rewind ();
			}
			
			if (typeof (SmallTerm) != 'undefined') {
				SmallTerm.term_hour += TermHourAdj;
				RenewSmTerm (newCity, SmallTerm.term_date, SmallTerm.term_month, SmallTerm.term_year);
			}
			
			currentCity = newCity;
		}
	}
							
	if (notfound == true) {
		$('#' + cclass + '_custom_city_save_status').html('Вашего города нет в базе, для ввода координат и временной зоны, перейдите, пожалуйста, по ссылке:<br><a href=\"/calendar/#profile\">расширенные настройки</a>');
		$('#' + cclass + '_custom_city_save_status').toggle().delay(2000).fadeOut(2000);
		$('#' + cclass + '_custom_city').delay(2000).fadeOut(2000);
		$('#' + cclass + '_custom_city_i').delay(4000).val('Введите город...');
		$('#' + cclass + '_custom_city_a').delay(4000).fadeIn(100);
	}
	firstFocus = true;
	saving_in_process = false;
}

	
