$(document).ready(function() {
	layout_fix();
	main_menu_init();
	booking_init();
	slides_init();
	fancybox_init();
	decode_mail_links();
	forms_funcs();

	check_clock();
	setInterval("check_clock()", 60 * 1000);
	clock_popup_init();
});

function layout_fix() {
	$lcol_h = $("#left_col_inner").height();
	$rcol_h = $("#right_col_inner").height();

	if ($rcol_h < $lcol_h) {
		$("#right_col_inner").height($lcol_h);
	}
}

function slides_init() {
	$('#slides_photo').slides({
		container: 'slides_photo_container',
		preload: true,
		preloadImage: hostname + '/img/slides/loading.gif',
		paginationClass: 'slides_photo_paging',
		effect: 'fade',
		crossfade: true,
		fadeSpeed: 1000,
		play: 5000,
		pause: 2500,
		slidesLoaded: function() {
			$("#slides_photo .prev, #slides_photo .next").fadeIn();

			if ($('#thumbnails_loader').length) {
				var x = 1;
				$("#slides_photo .slides_photo_paging li a").each(function() {
					$(this).html($('#thumbnails_loader div.thl' + x).html());
					x++;
				});

				$('#slides_photo .slides_photo_paging li.current a img').css('opacity', 1);
				$("#slides_photo .slides_photo_paging").fadeIn('slow');
			}
		},
		animationStart: function(next) {
			$('#slides_photo .slides_photo_paging li.current a img').animate({opacity: 0.7}, 1000);
			$('#slides_photo .slides_photo_paging li:eq('+ next +') a img').animate({opacity: 1}, 1000);
		}
	});

	$('#slides').slides({
		paginationClass: 'slides_paging',
		slideSpeed: 750,
		play: 7000,
		pause: 3000,
		hoverPause: true
	});
}

function check_clock() {
	$.get(hostname + "/get_clock.php", function(data) {
		var expl = data.split("|");
		var hours = parseInt(expl[0]);
		var minutes = parseInt(expl[1]);
		var hours_long = expl[2];
		var minutes_long = expl[3];
		var filename = hours;
		var src = '';

		if (minutes >= 20) {
			filename += '-30';
		}
		filename += '.gif';
		src = hostname + '/img/clock/' + filename;

		if ($('#clock').html() == '') {
			$('#clock').html('<img class="old" src="' + src + '" alt="" />');
			$('#clock img').show();
		}
		else if ($('#clock img.old').attr('src') != src) {
			$('#clock').append('<img class="new" src="' + src + '" alt="" />');

			setTimeout(function() {
				$('#clock img.old').fadeOut('slow');
				$('#clock img.new').fadeIn('slow', function() {
					$('#clock img.old').remove();
					$(this).removeClass('new').addClass('old');
				});
			}, 5000);
		}

		$("#clock_popup_inner span").text(hours_long + ':' + minutes_long);
	});
}

function clock_popup_init() {
	$("#clock").hoverIntent(
		function () {
			$("#clock_popup").fadeIn();
		},
		function () {
			$("#clock_popup").fadeOut();
		}
	);
}

function main_menu_init() {
	var timer;
	var hide_delay = 800;

	$("div#main_menu ul li ul").each(function() {
		var $this_elem = $(this);
		var $parent_elem = $(this).parent("li");
		var $arrow = $this_elem.find('span.arrow');
		var parent_w = $parent_elem.width();
		var item_w = $this_elem.width();
		var left_pos = Math.floor((parent_w - item_w) / 2);

		//if (!$parent_elem.is(':first-child')) {
			$this_elem.css('left', left_pos);
			$arrow.css('left', (item_w / 2) - 6);
		//}

		$this_elem.find('li:first a')
		.mouseover(function() {
            $arrow.addClass("arrow_over");
		})
		.mouseout(function() {
            $arrow.removeClass("arrow_over");
		})

		$parent_elem.hoverIntent(
			function () {
				clearTimeout(timer);
				$(this).siblings().each(function() {
					$(this).children("ul").hide();
				});
				$this_elem.fadeIn();
			},
			function () {
				timer = setTimeout(function() {$this_elem.hide();}, hide_delay);
			}
		);
	});
}

function fancybox_init() {
	$("a.fancybox").fancybox({
		'transitionIn' : 'elastic',
		'transitionOut' : 'elastic',
		'speedIn' : 400,
		'speedOut' : 400,
		'titlePosition' : 'over',
		'overlayColor' : '#5d4425',
		'overlayOpacity' : 0.25
	});
}

function booking_init() {
	var update_selects = false;
	var select_repl_sett = {
		'menuTransition' : 'slide',
		'menuSpeed' : 'fast'
	};

	$('div#booking select').selectBox(select_repl_sett);

	if (typeof(book_min_date) != 'undefined') {
		if(!$.browser.msie || $.browser.version >= 7) {
			$('a.date_picker')
			.datePicker({
					createButton : false,
					startDate : book_min_date,
					endDate : book_max_date
			})
			.dpSetOffset(-1, 29)

			.bind('click', function() {
				$(this).dpDisplay();
				return false;
			})
			// fce se spousti i pri externi zmene data v pickeru (ve fci update_booking_calendar)
			.bind('dateSelected', function(e, selectedDate, $td, state) {
				var expl = $(this).attr("id").split("_");
				var set = expl[3];

				if (update_selects == true) {
					update_booking_selects(set, selectedDate, select_repl_sett);
				}

				update_booking_link();
			})
			/*
			.bind('dpClosed', function(e, selected) {
				var d = selected[0];
				if (d) {
					d = new Date(d);

					if($(this).attr("id").indexOf("arrival") != -1) {
						$('#id_date_picker_departure').dpSetStartDate(d.addDays(1).asString());
					}
					else {
						$('#id_date_picker_arrival').dpSetEndDate(d.addDays(-1).asString());
					}
				}

				//update_booking_selects(selected[0]);
			})
			*/
			.each(function() {
				var $calendar = $(this);
				var expl = $(this).attr("id").split("_");
				var set = expl[3];
				var $m_select = $('#id_book_m_' + set);
				var $d_select = $('#id_book_d_' + set);

				$('#id_book_m_' + set + ',' + '#id_book_d_' + set).bind('change', function() {
					if($(this).attr("id").indexOf("id_book_m") != -1) {
						var $reload_selects = $('#id_book_d_' + set);
						$reload_selects.selectBox('destroy');

						update_days_in_month($m_select, $d_select, set, false);

						$reload_selects.selectBox();
					}

					update_selects = false;
					update_booking_calendar($calendar, $m_select, $d_select);
					update_selects = true;
				});
			});

			$('div#booking div.other select').bind('change', function() {
				update_booking_link();
			});

			update_booking_calendar($('#id_date_picker_arrival'), $('#id_book_m_arrival'), $('#id_book_d_arrival'));
			update_booking_calendar($('#id_date_picker_departure'), $('#id_book_m_departure'), $('#id_book_d_departure'));
			update_selects = true;
		}
	}
};

function update_booking_calendar($calendar, $m_select, $d_select) {
	var expl = $m_select.val().split("-");

	var d = new Date(
		expl[0],
		expl[1] - 1,
		$d_select.val()
	);

	$calendar.dpSetSelected(d.asString());
}

function update_booking_selects(set, selectedDate, select_repl_sett) {
	var $reload_selects = $('#id_book_m_' + set + ',' + '#id_book_d_' + set);
	$reload_selects.selectBox('destroy');

	var selectedDate = new Date(selectedDate);

	update_days_in_month($('#id_book_m_' + set), $('#id_book_d_' + set), set, selectedDate);

	$('#id_book_d_' + set + ' option, #id_book_m_' + set + ' option').removeAttr('selected');
	$('#id_book_d_' + set + ' option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
	$('#id_book_m_' + set + ' option[value=' + (selectedDate.getFullYear()) + '-' + (selectedDate.getMonth() + 1) + ']').attr('selected', 'selected');

	$reload_selects.selectBox();
};

function update_days_in_month($m_select, $d_select, set, selectedDate) {
	if (selectedDate != false) {
		var d = selectedDate;
	}
	else {
		var expl = $m_select.val().split("-");
		var d = new Date(
			expl[0],
			expl[1] - 1,
			1
		);
	}
	var selected_val = $d_select.val();
	var days_in_month = d.getDaysInMonth();

	if (selected_val > days_in_month) {
		selected_val = days_in_month;
	}

	$d_select.find('option').remove();
	for (var i = 1; i < days_in_month + 1; i++) {
		$d_select.append('<option value="' + i + '">' + i + '</option>');
	}

	$d_select.find(' option[value=' + selected_val + ']').attr('selected', 'selected');
}

function update_booking_link() {
	var url = booking_page_url + '?hotel_id=1994&guide_id=802';

	$('div#booking select').each(function() {
		url += '&' + $(this).attr('name') + '=' + $(this).val();
	});

	$('div#booking div.submit a').attr('href', url);
}

function decode_mail_links() {
	$("span[class^='mail_link_replace']").each(function() {
		var $html = Base64.decode($(this).attr("title"));
		$(this).replaceWith($html);
	});
}

function forms_funcs() {
	$('div#form form').append('<input type="hidden" name="js_checker" value="1" />');

	$("div#form a.send_form").click(function() {
		$(this).parents("form").submit();

		this.blur();
		return false;
	});
}

var Base64 = {
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(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 +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    decode : 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 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.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 = Base64._utf8_decode(output);

        return output;

    },

    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}
