// JavaScript Document
var ID_gPlatform = 2;

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

$(document).ready(function() {
		
	var IDt = setTimeout("reloadTopBanner();",5000); 
	assignBannerBtn(IDt);	
	
	$("a.roundBtn", $("form#maillistForm")).click(function() {signupEmail($(this));});
	
	hs.graphicsDir = '/images/hs/';
	hs.outlineType = 'rounded-white';
	hs.wrapperClassName = 'draggable-header';
	hs.showCredits = false;
	
	//$('#filterForm').attr('action','/script/action/getBBoards.php').ajaxForm({ dataType: 'json', type: 'post', clearForm: false, beforeSubmit: showAjaxLoader, success: showResponse });
	
	//$('#filterForm').attr('action','/script/action/getBBoards.php').ajaxForm({ type: 'post', clearForm: false, beforeSubmit: showAjaxLoader, success: showResponse });
	
	$('.roundBtn', $('#commentForm')).click(function () {
		$('#commentForm').submit();
		return false;
	});
	
	$('#commentForm').attr('action','/script/action/commentAdd.php').ajaxForm({ dataType: 'json', type: 'post', clearForm: false, beforeSubmit: function () {}, success: commentFormSuccess });
	
	$('.roundBtn', $('#filterSortForm')).click(function () {
		$('#filterSortForm').submit();
		return false;
	});

	
	//---------------------------------------------	
	// **** search by destination code - START ****
	//---------------------------------------------
	
	$('#searchDestBtn').click(function(){		
		  	$('#searchDest').submit(); 
	});	
		
	$("#location, #arrivalDate, #departureDate").keyup(function(event){  
		if(event.keyCode == 13) { 		
			$('#searchDest').submit(); 
		}  
	});  	
		
	$("#searchDest").validate({
		onsubmit: true,
		
		submitHandler: function() {
			$('#searchDest').ajaxSubmit(function(data) {						
				if (data.substr(0,4) == "[OK]") {
					window.parent.location = data.substr(4);						 
				} else {
					$('#searchDestError').html(data).show();
				}	
			});
		}
	});

	//---------------------------------------------		
	// **** search by destination code - END ****
	//---------------------------------------------
	
	// **** Client Filter Form
	$('#filterForm').attr('action','/script/action/getClients.php').ajaxForm({ dataType: 'json', type: 'post', clearForm: false, beforeSubmit: clientCatSerialize, success: getClients });
		
	//---------------------------------------------	
	// **** search by activities code - START ****
	//---------------------------------------------
	
	$('#searchActBtn').click(function(){		
	 	$('#searchAct').submit(); 
	});	
		
	$("#searchAct").validate({
		onsubmit: true,
		
		submitHandler: function() {
			$('#searchAct').ajaxSubmit(function(data) {		
				if (data.substr(0,4) == "[OK]") {
					window.parent.location = data.substr(4);
				} else {
					$('#searchActError').html(data).show();
				}	
			});
		}
	});
		
	$("#aktivnosti").change(function () { 
		$.ajax({
		  type: 'POST',
		  url: '/script/action/getActivities.php',
		  data: $("#searchAct").serialize(),
		  success: function(data) {
		 		// če je na začetku "[redir]" --> naredi document.location "link" drugače ...
		  	if (data.substr(0,7) == "[redir]") {
		  			$("#urlGo").val(data.substr(7));
						$('#searchAct').submit();					
						//document.location = data.substr(7);				
				} else {
					$("#acti").html(data);
		  	}
		  }
		});					
 	})
	
	//---------------------------------------------	
	// **** search by activities code - END ****
	//---------------------------------------------

	//---------------------------------------------	
	// **** reservation form - START ****
	//---------------------------------------------
			
	$('#reservationForm').validate({
		focusInvalid: true,
		event: 'blur',
		rules: 
		{
			'arrivalDate':		{ required: true },
			'departureDate':	{ required: true },
			'nights':					{ required: true },
			'adults':					{ required: true },
			'children':				{ required: true },
			'ID_oUnit[]':			{ required: true },
			'purpose':				{ required: true },
			'name':						{ required: true },					
			'email': 					{ required: true, email: true }
		},
		messages:
		{
			required: 'We need your email address to contact you'
		},
		_onsubmit: true,			
		_submitHandler: function(form) { form.submit(); },				
		errorElement: 'span'
	});			
	
	//---------------------------------------------	
	// **** reservation form - END ****
	//---------------------------------------------
		
		
});

function commentFormSuccess(a)
{
	//alert("pred ="+a["message"]);
	if (a["message"].substr(0,4) == "[OK]") {
		alert(a["message"].substr(4));
		
		$(':input','#commentForm')
	  .not(':button, :submit, :reset, :hidden, #country')
	  .val('')
	  .removeAttr('checked')
	  .removeAttr('selected');

		location.reload();
		window.scrollTo(0,0)
		//$('html, body').animate({scrollTop:0}, 'slow');
	  //return false;
	} else {
		alert(a["message"]);
	}
}

function refreshCaptcha() 
{
	var rndCode = Math.random();
	$('#captchaImage').attr('src',$('#captchaImage').attr('src')+'&r='+rndCode);
}

$(function() {
	$("#arrivalDate, #departureDate").datepicker({
		showOn: 'both',
		buttonImage: '/images/date_icon_green.gif',
		buttonImageOnly: true,
		defaultDate: "+1d",
		minDate: 0,
		maxDate: '+1Y',
		showAnim: 'slideDown',
		onSelect: function(selectedDate)
		{
			var option = this.id == "arrivalDate" ? "minDate" : "maxDate";
			var instance = $(this).data("datepicker");
			var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
			if (option == "minDate")
				$("#departureDate").datepicker("option", option, date);
			else
				$("#arrivalDate").datepicker("option", option, date);
		}
	});
	$("#arrivalDate2, #departureDate2").datepicker({
		showOn: 'both',
		buttonImage: '/images/date_icon_green.gif',
		buttonImageOnly: true,
		defaultDate: "+1d",
		minDate: 0,
		maxDate: '+1Y',
		showAnim: 'slideDown',
		onSelect: function(selectedDate)
		{
			var option = this.id == "arrivalDate2" ? "minDate" : "maxDate";
			var instance = $(this).data("datepicker");
			var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
			if (option == "minDate")
				$("#departureDate2").datepicker("option", option, date);
			else
				$("#arrivalDate2").datepicker("option", option, date);
		}
	});
	/*$("#arrivalDate2").datepicker({
		showOn: 'both',
		buttonImage: '/images/date_icon_green.gif',
		buttonImageOnly: true,
		defaultDate: "+1d",
		minDate: 0,
		maxDate: '+1Y',
		showAnim: 'slideDown'
	});
	$("#departureDate2").datepicker({
		showOn: 'both',
		buttonImage: '/images/date_icon_green.gif',
		buttonImageOnly: true,
		defaultDate: "+1w",
		minDate: 0,
		maxDate: '+1Y',
		showAnim: 'slideDown'
	});*/
	
	$("#location").autocomplete({
		source: "/script/action/autoLocation.php",
		minLength: 2
	});

});


function assignBannerBtn(IDt)
{	
	$('a.prev', $('.newsBannerModule')).click(function(a) { 
		reloadTopBanner();
		clearTimeout(IDt);
	});
	
	$('a.next', $('.newsBannerModule')).click(function(a) { 	
		reloadTopBanner();
		clearTimeout(IDt);
	});
}


function reloadTopBanner()
{

	var IDt = setTimeout("reloadTopBanner();",5000);	
	
	var ID_gPlatform = $('#ID_gPlatform').val();
	var bannerID = $('#bannerID').val();
	$(".newsBannerModule").fadeOut("normal", function() {
			$(".newsBannerWrapper").load("/script/action/getTopAd.php", {idpl: ID_gPlatform, idb: bannerID}, function() {
					assignBannerBtn(IDt);
				$(".newsBannerModule").fadeIn("normal", function() {});
			});
		});	
		
	
}

function showAjaxLoader()
{
	$('#ajaxLoader').show();
}

function clientCatSerialize()
{
	$('#sortFormField').val($('#sortForm').serialize());
	showAjaxLoader();
}

function getbBoards(data) {
	$('.specialOffersList').html(data);
	//$('#filterList').html(data.filters);
	$('#ajaxLoader').hide();
}
function showResponse(responseText, statusText, xhr, $form)  { 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
} 

function filter2() {

	if ($('#sortOption').val() == 586) {
		
				$('#sortOption2').val('1');
			
			
			} else if ($('#sortOption').val() == 589) {
			
				$('#sortOption2').val('2');
			
			} else {
			
				$('#sortOption2').val('');
			
			}
		
	filter();		

}


function filter() {	
	clientCatSerialize();
	$('#filterForm').submit();
}

function getClients(data) {
	
	//alert(data.html);
	
	$('.list').html(data.html);
	
	if (data.filterList != undefined) { 
		
		//alert(data.filterList);
					
		$('#filterList').html(data.filterList);
		
	} else {
		
		
		
		if (data.starFilterList != '') {
			$('#starFilterList').html(data.starFilterList);
		} else {
			$('.f1').hide();
		}
		
		if (data.subTabsTags != '') {
			$('#subTabsTags').html(data.subTabsTags);
		} else {
			$('.f2').hide();
		}
		
		if (data.addOfferFilter != '') {
			$('#addOfferFilter').html(data.addOfferFilter);
		} else {
			$('.f3').hide();
		}
	
	}
			
	$('#ajaxLoader').hide();
}


function ErrFunct(XMLHttpRequest, textStatus, errorThrown) {
	
	console.log(XMLHttpRequest, textStatus, errorThrown);
	
}

function showPhoto(src,title,link,author,alt) 
{
	$('#photoBig').fadeOut("fast", function() {
		$('#photoBig').attr('src',src);
		$('#photoBig').attr('alt',alt);
	});
	if (link != '') {			
		$('#photoBigTitle').html('<a href="'+link+'">'+title+'</a>');
	}
	else {
		$('#photoBigTitle').html(title);
	}			
	if (author != '') {
		$('#photoBigTitle').append(author);
	}
	$('#photoBig').fadeIn();
}

function clientAppFilter()
{
	$('#clientAppFilter').submit();
}

/* --- LOGIN 2 CMS --- */

function login(qlmsg)
{				
	$.ajax({
	  type: 'POST',
	  url: '/script/action/login.php',
	  data: 'ID_gPLanguage='+$('#langg').val()+'&username='+$('#username').val()+'&pass='+$('#pass').val()
	  	+'&remember='+( $('#remember').is(':checked') ? 1 : 0 ),
	  success: function(msg){
			if (msg!=qlmsg){				
				if (msg.indexOf('&remember=1') > 0) {
					var expires=new Date();
					expires.setDate(expires.getDate()+365);
					document.cookie='cms_already_logged_in=1;path=/;expires='+expires.toGMTString();
				}
				window.location = msg;
			} else {
				document.getElementById('err').innerHTML=msg+'<br>';
				document.getElementById('err').style.display='';
			}		
	  }
	});	
}

/* --- CONTACT --- */

function writeContact() 
{		
	$.ajax({
	  type: 'POST',
	  url: '/script/action/contact.php',
	  data: $("#contactForm").serialize(),
	  dataType: "json",
	  success: function(msg){
			if (msg.status != -1) { 
				if (msg.url) {
					document.location = msg.url;
				}
				$("div#dobra").show(); $("div#slaba").hide(); 
			} 
			else { $("div#dobra").hide(); $("div#slaba").html(msg.message).show(); }
	  }
	});	
}

function goTo(url) {
	$("#urlGo").val(url);
	$('#searchAct').submit();
}

function reloadImage(img, path)   {
  img = document.getElementById(img);
  img.src = path+'?' + Math.random();
} 


/* --- REZERVATION FORM --- */

function RF_clearErrors() 
{	
	$('#RF_statusMsg').hide();
		
	var valid = $("#reservationForm").validate().form();	
	if (valid) $('#RF_ajaxLoader').show();
	
	return valid;
}

function RF_formResponse(data) 
{
	var status = data.status;
	var message = data.message;	
	
	if (status == 1) {
		if (data.url) {
			document.location = data.url;
		}
		document.getElementById('reservationForm').reset();
		$('#RF_statusMsg').addClass('ok');
	}
	
	$('#RF_statusMsg').show();		
	$('#RF_statusMsg').html(data.message);
	$('#RF_ajaxLoader').hide();
	
	//tb_init("a.thickbox");
	refreshCaptcha();
}

function refreshCaptcha() 
{
	var rndCode = Math.random();
	$('#captchaImage').attr('src',$('#captchaImage').attr('src')+'&r='+rndCode);
	$('#CF_captchaImage').attr('src',$('#CF_captchaImage').attr('src')+'&r='+rndCode);
	$('#RF_captchaImage').attr('src',$('#RF_captchaImage').attr('src')+'&r='+rndCode);
}

/* --- CONTACT FORM --- */

function showCForm(show) {
	if (show) { 
		$('.contactForm p').show();	
		$('#CF_statusMsg').hide(); 
		$('#RF_statusMsg').hide(); 
	}
	else { 
		$('.contactForm p').hide(); 
	}
}

function CF_clearErrors() 
{
	$('#CF_statusMsg').hide();
	$('#CF_ajaxLoader').show();
}

function CF_formResponse(data) 
{	
	var status = data.status;
	var message = data.message;	
				
	if (status == 1) {
		if (data.url) {
			document.location = data.url;
		}
		document.getElementById('contactForm').reset();
		$('.contactForm p').hide();			
		$('#CF_statusMsg').addClass('ok');		
	}
	
	$('#CF_statusMsg').show();	
	$('#CF_statusMsg').html(message);			
	$('#CF_ajaxLoader').hide();

	//tb_init("a.thickbox");	
	refreshCaptcha();
}

function popUp(URL,w,h) 
{
	window.open(URL,'view', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=' + w + ',height=' + h + ',left = 312,top = 184');
}

function signupEmail(a) {
	var frm = $(a).parent().parent();
	var email = $("input#email", frm).val();
	
	if (!isValidEmailAddress(email))
	{
		alert(alert_297);
		return false;
	}
	var anyChecked = false;
	$("input[type=checkbox]:checked", frm).each(function() { anyChecked = true; });
	if (!anyChecked)
	{
		alert(alert_732);
		return false;
	}
	
	$.post("/script/action/signupEmail.php", frm.serialize(), function(data) {
		if (data.substr(0,3) == "OK:") {
			var spl = data.indexOf(":",3); 
			//alert(data.substr(spl+1));
			document.location=data.substr(3,spl-3);
		}
		else if (data != "")
	   alert(data);
	});
}

// **** AdThis Button *****
addthis.button("#atbutton");
var addthis_config =
{
	//seznam service-ov http://www.addthis.com/services/list			   
	services_compact: 'facebook, twitter, more, digg, google, delicious, netlog, blogger',
	services_exclude: 'print',
	ui_click: true
}	

function PriceDateCheck() {	
	alert(alert_1018);
}
