jQuery.noConflict();

jQuery.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return jQuery(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

function crateCaptchaImage() {
	var img = new Image();
	jQuery(img).load(function () {
		
    	jQuery('#captcha').html(this);
        
    }).attr('src', '/captcha/image.php?'+Math.random()).attr('id', 'img');
}

jQuery(document).ready(
	function($)
	{
		//$("#window").show();
		//$("#window").animate({ height: 'show' }, 'slow');
		//$("#windowContent").load('/offers_comment_form.php');
		//$("#windowContent").html('asdf');
		
		$("#datepickerArrive").datepicker({ dateFormat: 'dd.mm.yy', 
			dayNamesMin: ['Н', 'П', 'В', 'С', 'Ч', 'П', 'С'],
			monthNames: ['Януари','Февруари','Март','Април','Май','Юни','Юли','Август','Септември','Октомври','Ноември','Декември'],
			firstDay: 1,
			maxDate: '+1y',
			minDate: ''
		  });
		$("#datepickerLeave").datepicker({ dateFormat: 'dd.mm.yy', 
			dayNamesMin: ['Н', 'П', 'В', 'С', 'Ч', 'П', 'С'],
			monthNames: ['Януари','Февруари','Март','Април','Май','Юни','Юли','Август','Септември','Октомври','Ноември','Декември'],
			firstDay: 1,
			maxDate: '+1y',
			minDate: ''
		  });
		
		crateCaptchaImage();
		
		$('.windowOpen').bind(
			'click',
			function() {
				//var targetOffset = $('#wrapper').offset().left;
				//alert(targetOffset);
				
				if($('#window').css('display') == 'none') {
					
					//$("#window").animate({ height: 'show' }, 'slow');
					$("#window").show();
					//$("#window").css({'left', '30px'});
					scroll(0,150);
				}
				this.blur();
				return false;
			}
		);

		$('#windowClose').bind(
			'click',
			function()
			{
				//alert('b');
				//window.location.reload( true ); // refresh the page
				$('#window').hide();
				//$("#window").animate({ height: 'hide' }, 'slow');
				
			}
		);
		$('.windowClose').bind(
				'click',
				function()
				{
					//alert('a');
					//window.location.reload( true ); // refresh the page
					$('#window').hide();
					//$("#window").animate({ height: 'hide' }, 'slow');
					
				}
			);
		$('#windowMin').bind(
			'click',
			function()
			{
				$('#windowContent').SlideToggleUp(300);
				$('#windowBottom, #windowBottomContent').animate({height: 10}, 300);
				$('#window').animate({height:40},300).get(0).isMinimized = true;
				$(this).hide();
				$('#windowResize').hide();
				$('#windowMax').show();
			}
		);
		$('#windowMax').bind(
			'click',
			function()
			{
				var windowSize = $.iUtil.getSize(document.getElementById('windowContent'));
				$('#windowContent').SlideToggleUp(300);
				$('#windowBottom, #windowBottomContent').animate({height: windowSize.hb + 13}, 300);
				$('#window').animate({height:windowSize.hb+43}, 300).get(0).isMinimized = false;
				$(this).hide();
				$('#windowMin, #windowResize').show();
			}
		);
		$('#window').Resizable(
			{
				minWidth: 200,
				minHeight: 60,
				maxWidth: 700,
				maxHeight: 400,
				dragHandle: '#windowTop',
				handlers: {
					se: '#windowResize'
				},
				onResize : function(size, position) {
					$('#windowBottom, #windowBottomContent').css('height', size.height-33 + 'px');
					var windowContentEl = $('#windowContent').css('width', size.width - 25 + 'px');
					if (!document.getElementById('window').isMinimized) {
						windowContentEl.css('height', size.height - 48 + 'px');
					}
				}
			}
		);
		$('.terms').bind(
			'click',
			function()
			{	
				var targetOffset = $('#terms').offset().top;
				scroll(0,targetOffset);
			}
		);
		$('.backToComment').bind(
			'click',
			function()
			{	
				//scroll(0,150);
				$("#termsContent").hide();
				$("#windowContent").show();
				
			}
		);
		$('#changeImage').bind(
			'click',
			function()
			{	
				crateCaptchaImage();
			}
		);
		$("#commentSubmit").bind(
			'click',
			function()
			{
				var hasError = false;
				//$(".error").hide();
				
				var status = 'The folowing errors appears:\n';
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
				$("#formMail").removeClass("error");
				var emailVal = $("#email").val();
				if(emailVal == '') {
					$("#formMail").addClass("error");
					status += ' - Please enter your e-mail.\n';
					hasError = true;
				} else if(!emailReg.test(emailVal)) {
					$("#formMail").addClass("error");
					status += ' - Enter a valid email address.\n';
					hasError = true;
				}
				
				$("#formName").removeClass("error");
				var nameVal = $("#name").val();
				if(nameVal == '') {
					$("#formName").addClass("error");
					status += ' - Please, enter your name.\n';
					hasError = true;
				}
				
				$("#formTravel").removeClass("error");
				var travelVal = $("#travel").val();
				if(travelVal == '') {
					$("#formTravel").addClass("error");
					status += ' - Please, choose travel with.\n';
					hasError = true;
				}
				
				$("#formMonth").removeClass("error");
				var monthVal = $("#month").val();
				var yearVal = $("#year").val();
				var d = new Date();
				var currentMonth = d.getMonth() + 1;
				var currentYear = d.getFullYear();
				if(monthVal == 0) {
					$("#formMonth").addClass("error");
					status += '- Choose date.\n';
					hasError = true;
				}
				if(currentYear == yearVal && monthVal > currentMonth ) {
					$("#formMonth").addClass("error");
					status += ' - Wrong date.\n';
					hasError = true;
				}
				
				for (i=0;i<document.fcomment.rateValue.length;i++) {	
				      if (document.fcomment.rateValue[i].checked) {
				    	  var rateValueVal = document.fcomment.rateValue[i].value;
				      }
				      if (document.fcomment.rateLocation[i].checked) {
				    	  var rateLocationVal = document.fcomment.rateLocation[i].value;
				      }
				      if (document.fcomment.rateService[i].checked) {
				    	  var rateServiceVal = document.fcomment.rateService[i].value;
				      }
				      if (document.fcomment.rateCleanliness[i].checked) {
				    	  var rateCleanlinessVal = document.fcomment.rateCleanliness[i].value;
				      }
				      if (document.fcomment.rateAmenities[i].checked) {
				    	  var rateAmenitiesVal = document.fcomment.rateAmenities[i].value;
				      }
				      if (document.fcomment.rating[i].checked) {
				    	  var ratingVal = document.fcomment.rating[i].value;
				      }
				}
				//alert(subjectVal);   
				$("#formRatingTable").removeClass("error");
				
				$("#formRateValue").removeClass("error");
				if(!rateValueVal) {
					$("#formRateValue").addClass("error");
					status += ' - Please, choose rating for value.\n';
					hasError = true;
				}
				
				$("#formRateLocation").removeClass("error");
				if(!rateLocationVal) {
					$("#formRateLocation").addClass("error");
					status += ' - Please, choose rating for location.\n';
					hasError = true;
				}
				
				$("#formRateService").removeClass("error");
				if(!rateServiceVal) {
					$("#formRateService").addClass("error");
					$("#formRatingTable").addClass("error");
					status += ' - Please, choose rating for service.\n';
					hasError = true;
				}
				
				$("#formRateClean").removeClass("error");
				if(!rateCleanlinessVal) {
					$("#formRateClean").addClass("error");
					$("#formRatingTable").addClass("error");
					status += ' - Please, choose rating for cleanliness.\n';
					hasError = true;
				}
				
				$("#formRateAmenities").removeClass("error");
				if(!rateAmenitiesVal) {
					$("#formRateAmenities").addClass("error");
					$("#formRatingTable").addClass("error");
					status += ' - Please, choose rating for amenities.\n';
					hasError = true;
				}
				
				$("#formRating").removeClass("error");
				$("#formOveralRatingTable").removeClass("error");
				if(!ratingVal) {
					$("#formRating").addClass("error");
					$("#formOveralRatingTable").addClass("error");
					status += ' - Please, choose overall rating for this offer.\n';
					hasError = true;
				}
				$("#formComment").removeClass("error");
				$("#formComment").hide();
				var commentVal = $("#comment").val();
				if(commentVal == '') {
					$("#formComment").addClass("error");
					$("#formComment").show();
					status += ' - Please, write your comment.\n';
					hasError = true;
				}
				
				var chbx_value = '';
				
				for (var i=0; i < document.fcomment.chbx.length; i++) {
				   if (document.fcomment.chbx[i].checked) {
				      chbx_value = chbx_value + document.fcomment.chbx[i].value;
				      
				   }
				   else {
					  chbx_value = chbx_value + '0';
				   }
				}
				$("#formRecommanded").removeClass("error");
				$("#formRecommanded").hide();
				if(parseInt(chbx_value) == 0) {
					$("#formRecommanded").addClass("error");
					$("#formRecommanded").show();
					status += ' - Please, choose at least one option.\n';
					hasError = true;
				}
				
				$("#termsagreelabel").removeClass("error");
				var termsagree = $("#termsagree").val();
				if(document.fcomment.termsagree.checked != true) {
					$("#termsagreelabel").addClass("error");
					status += ' - Please, choose rating for amenities.\n';
					hasError = true;
				}
				
				//var hasError = false;
				var bodgadincho = 'a';
				$("#captchaText").removeClass("error");
				var captchaVal = $("#captchaField").val();
				if(captchaVal == '') {
					$("#captchaText").addClass("error");
					status += ' - Please, enter captcha code.\n';
					hasError = true;
				}
				else {
					/*$.post("/captcha/check_captcha.php",
					   { 
						userCode: captchaVal
					   },
					   	function(result){

						  	if(result == 'true'){
						  		$('#captcha').html(document.getElementById('captchaSuccessMsg').innerHTML);
						  		$('#captchaText').hide();
						  		$('#changeImage').hide();
						  		$('#captchaField').hide();
						  		bodgadincho = bodgadincho+'Captcha';
							}
						  	else {
						  		hasError = true;
						  		crateCaptchaImage();
						  		status += ' - Wrong captcha code.\n';
						  		document.forms['fcomment'].captchaField.value = '';
						  		$("#captchaText").addClass("error");
							}
						}
					);*/
				}
				
				//$('#captchaText').addClass('error'); // tozi class go slaga winagi. Ako capchata e minata uspeshno element 'captchaText' ne se wijda na ekrana a ako ne e minala shte stane 4erwen
				
				//alert(status);
				//alert(hasError);
				
				if(hasError == true) {
					scroll(0,150);
					alert(document.getElementById('errorMsg').innerHTML);
				}
				
				if(hasError == false) {
					$(this).hide();
					
					//$("#sendEmail li.buttons").append('<img src="/images/load.gif" alt="Loading" id="loading" />');
					$.post("/captcha/check_captcha.php",
							   { 
								userCode: captchaVal
							   },
							   	function(result){

								  	if(result == 'true'){// captcha true start
								  		$('#captcha').html(document.getElementById('captchaSuccessMsg').innerHTML);
								  		$('#captchaText').hide();
								  		$('#changeImage').hide();
								  		$('#captchaField').hide();
								  		bodgadincho = bodgadincho+'Captcha';
								  		$.post("/offers_comment_save.php",
											   { 
												name: nameVal,
												email: emailVal,
												travel: travelVal,
												month: monthVal,
												year: yearVal,
												rvalue: rateValueVal,
												rlocation: rateLocationVal,
												rservice: rateServiceVal,
												rcleanliness: rateCleanlinessVal,
												ramenities: rateAmenitiesVal,
												rating: ratingVal,
												comment: commentVal,
												recommend: chbx_value,
												offername: document.getElementById('offerName').innerHTML,
												offerId: document.getElementById('offerId').innerHTML
											   },
											   	function(data){
												   result = data.split(":");
												   //alert('submit result:' + result[0]);
												   /*if(result[0] == 'test') {
													   alert(result);
												   }*/
												   //bodgadincho = bodgadincho+'Sent';
												   if(result[0] == 'true') {
													   $("#left").hide();
													   $("#right").hide();
													   $("#sent").show();
													   $("#windowContent").height(80);
													   $("#window").height(125);
													   $("#windowBottom").height(95);
													   $("#windowBottomContent").height(95);
													   //$("#windowContent").html(result[1]);
													   scroll(0,150);
													   //t=setTimeout('$("#window").hide()',5000);
												   }
												   else {
													   $("#commentSubmit").show();
													   alert(document.getElementById('errorMsg').innerHTML+'.');
												   }
												   //alert(bodgadincho);
												}
											);
									}// captcha true end
								  	else { // captcha false start
								  		hasError = true;
								  		crateCaptchaImage();
								  		status += ' - Wrong captcha code.\n';
								  		document.forms['fcomment'].captchaField.value = '';
								  		$("#captchaText").addClass("error");
									}
								}
							);
					
					
				}
				return false;
			}	
		);
	}
);