$(document).ready(function() {

  if($("#section_select option:selected").length>1){
    restoreSelectedValues();
  }

	changeSelectFields();
  
	$('tr.search_more').hide();
	
    $.post("/index/getlotcountforallcities/", {} ,function(data){
            $('#lot_count_div cite').html(data);
    }, 'text');
 
    $.post("/index/getlotcount/", {} ,function(data){
           $('#search_lot_count_div cite').html(data); 
            //$('#search_lot_count_div').load('search/getlotscounthtml');
            //setTimeout(function(){
          	//	  $('#search_lot_count_div cite').html(data);				
          	//},1000);            
    }, 'text'); 

	//hide all dialogs
	
	$('#dialog').css('display','none');
	$('#pass_reminder').css('display','none');
	$('#pass_reminder').css('display','none');
	$('#pass_reminder_msg_ok').css('display','none');
	$('#registration_confirmation').css('display','none');
	$('#registration_confirmation').css('display','none');
	$('#delete_confirm').css('display','none');
	$('#lot_reg_finish').css('display','none');
	
	//login dialog
	
	$('#dialog').dialog({
		autoOpen: false,
		width: 470,
		modal: true,
		buttons: {}
	});
	
     $('#dialog a.gray_s').click(function(){
    	 $('#dialog').dialog('close');
    	 $('#dialog').css('display','none');
    	 return false;
     });
     
	$('#user_login_link').click(function(){
		 $('#dialog').dialog('open');
		 $('#dialog').css('display','block');
		 return false;
	});  
	
	//pass remind dialog
	$('#pass_reminder').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
		
	
	//cancel button
	$('#pass_reminder a.gray_s').click(function(){
    	 $('#pass_reminder').dialog('close');
    	 $('#pass_reminder').css('display','none');
    	 return false;
    });
    
	//submit button
	$('#pass_reminder a.gray_b').click(function(){
		$('#forgot_msg').html('Kraunasi...').css('color','#9aa0a5');
		checkMail();		
   	 	return false;
   });
	
	
	$('#pass_reminder_link').click(function(){
		 $('#dialog').dialog('close');
		 $('#dialog').css('display','none');
		 $('#pass_reminder').dialog('open');
		 $('#pass_reminder').css('display','block');
		 return false;
	});
	
	//pass remind dialog msg ok
	$('#pass_reminder_msg_ok').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
	
	//close button
	$('#pass_reminder_msg_ok a.gray_b').click(function(){
    	 $('#pass_reminder_msg_ok').dialog('close');
    	 $('#pass_reminder_msg_ok').css('display','none');
    	 return false;
    });
	
	//registration confirmation
	
	$('#registration_confirmation').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
	
	$('#registration_confirmation a.gray_b').click(function(){
		$('#registration_confirmation').dialog('close');
		$('#registration_confirmation').css('display','none');
		window.location = '/';
		return false;
	});
	
	//delete confirm
	 $('#delete_confirm').dialog({
			autoOpen: false,
			width: 340,
			modal: true,
			buttons: {}
		});
	 $('#delete_lot_no').click(function(){
		 $('#delete_confirm').dialog('close');
		 $('#delete_confirm').css('display','none');
		 return false;
	 });	
	 
	 //lot finish popup
	 $('#lot_reg_finish').dialog({
			autoOpen: false,
			width: 600,
			modal: true,
			buttons: {}
		});
	 $('#lot_reg_finish a.gray_s').click(function(){
		 $('#lot_reg_finish').css('display','none');
		 window.location = '/user/home';		 
		 return false;
	 });
	 //step3 congrats
	 $('#activate_congrats').dialog({
			autoOpen: false,
			width: 650,
			modal: true,
			buttons: {}
		});
  
});

function restoreSelectedValues(){
  
  if($("#section_select option:selected").length){
      $("#section_select option:eq(0)").attr("selected",false);
    	catList =$('#section_select').val();
    	getCategories( catList );
  }
     
  setTimeout(function(){
		  if($("#category_select option:selected").length>0){
			   showLotCount();	
			}
      if( $("#duration_select option:eq(0)").attr("selected")!= true || $("#containment_select option:eq(0)").attr("selected") != true 
          || $("#lang_select option:eq(0)").attr("selected") != true || $("#day_period option:eq(0)").attr("selected") != true
          || $("#period option:eq(0)").attr("selected") != true || $("#payment_select option:eq(0)").attr("selected") != true
          || $("#place_select option:eq(0)").attr("selected") != true){
      
        moreSearchOptions(); 
        return false;
      }				
	},3000); 
}

function cleanSearchOptions(){

   $("#section_select").val($('option:first', '#section_select').val());
   $("#section_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#section_select").trigger("change");
    
   $("#category_select").val($('option:first', '#category_select').val());
   $("#category_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#category_select").trigger("change");
    
   $("#employment_place").val($('option:first', '#employment_place').val());
   $("#employment_place").bind('change',function(event) {
     changeSelectFields();
   });
   $("#employment_place").trigger("change");
    
   $("#age_select").val($('option:first', '#age_select').val());
   $("#age_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#age_select").trigger("change");
    
   $("#price_select").val($('option:first', '#price_select').val());
   $("#price_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#price_select").trigger("change");
    
   $("#duration_select").val($('option:first', '#duration_select').val());
   $("#duration_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#duration_select").trigger("change");
    
   $("#containment_select").val($('option:first', '#containment_select').val());
   $("#containment_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#containment_select").trigger("change");
    
   $("#lang_select").val($('option:first', '#lang_select').val()); 
   $("#lang_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#lang_select").trigger("change");
    
   $("#day_period").val($('option:first', '#day_period').val());
   $("#day_period").bind('change',function(event) {
     changeSelectFields();
   });
   $("#day_period").trigger("change");
     
   $("#period").val($('option:first', '#period').val()); 
   $("#period").bind('change',function(event) {
     changeSelectFields();
   });
   $("#period").trigger("change");
        
   $("#payment_select").val($('option:first', '#payment_select').val());
   $("#payment_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#payment_select").trigger("change");
         
   $("#place_select").val($('option:first', '#place_select').val());  
   $("#place_select").bind('change',function(event) {
     changeSelectFields();
   });
   $("#place_select").trigger("change");
       
  
   catList =$('#section_select').val();
   getCategories( catList, '1' );

   $.post("/index/getlotcount/", {} ,function(data){
            $('#search_lot_count_div cite').html(data);
            //$('#search_lot_count_div').load('search/getlotscounthtml');
            //setTimeout(function(){
          	//	  $('#search_lot_count_div cite').html(data);				
          	//},500);    
   }, 'text');   
}

function showLotCount(){

    $sectionsList = $('#section_select').val();
    $categoriesList = $('#category_select').val();
    $employmentPlacesList = $('#employment_place').val();
    $agesList = $('#age_select').val();
    $pricesList = $('#price_select').val();
    $durationList =$('#duration_select').val();
    $containmentsList =$('#containment_select').val();
    $languagesList =$('#lang_select').val();
    $dayPeriodsList =$('#day_period').val();
    $periodsList =$('#period').val();
    $paymentsList =$('#payment_select').val();
    $placesList = $('#place_select').val();

    $.post("/search/getlotscount/", {"section[]":$sectionsList,"categories[]":$categoriesList,"employment_place[]":$employmentPlacesList,"age[]":$agesList,"price[]":$pricesList,"duration[]":$durationList,"containment[]":$containmentsList,"language[]":$languagesList,"day_period[]":$dayPeriodsList,"period[]":$periodsList,"payment[]":$paymentsList,"place[]":$placesList} ,function(data){
            $('#search_lot_count_div cite').html(data);
            //$('#search_lot_count_div').load('search/getlotscounthtml');
            //setTimeout(function(){
          	//	  $('#search_lot_count_div cite').html(data);				
          	//},1000);     
     }, 'text');
}

/*----------------------------------*/
function openCongratsDialog(){
	alert('hi');
	
	//$('#activate_congrats').css('display','block');
	//$('#activate_congrats').dialog('open');
}
/*----------------------------------*/

$(function(){
    $("#section_select").change(function(){
    	catList =$('#section_select').val();
    	getCategories( catList );
    }); 
});

$(function(){
    $("#employment_place").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#age_select").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#price_select").change(function(){
        showLotCount();
    }); 
}); 
$(function(){
    $("#duration_select").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#containment_select").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#lang_select").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#day_period").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#period").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#payment_select").change(function(){
        showLotCount();
    }); 
});
$(function(){
    $("#place_select").change(function(){
        showLotCount();
    }); 
});

function getCategories( catList, resetSess ){
	if( catList != null ){
		$(function(){
    		$.post("/search/getcategories/", {"catList[]" : catList, "resetSess" : resetSess} ,function(data){
    			$('#cat_select_div').html(data);
    			changeSelectFields();
    	    }, 'text')
    	});
	}
}

function changeSelectFields(){
	$("#section_select").dropdownchecklist({ firstItemChecksAll: true, width:142, maxDropHeight: 415 });
	$("#price_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#age_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#duration_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#containment_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#place_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#payment_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#category_select").dropdownchecklist({ firstItemChecksAll: true,width:142, maxDropHeight: 415 });
	$("#employment_place").dropdownchecklist({ firstItemChecksAll: true,width:142, maxDropHeight: 415 });
	$("#lang_select").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#day_period").dropdownchecklist({ firstItemChecksAll: true,width:142 });
	$("#period").dropdownchecklist({ firstItemChecksAll: true,width:142 });
}

function checkSelectivity(){

	sectionVal = $("#section_select").val();
	catVal = $("#category_select").val();
  
	isOk = true;

	if(sectionVal == 0 || sectionVal == null){
		$("#section_label").css('color','#ff0000');
		isOk = false;
	}
	else{
		$("#section_label").css('color','#29abe2');
	}
	
	if(catVal == 0 || catVal == null){
		$("#category_label").css('color','#ff0000');
		isOk = false;
	}
	else{
		$("#category_label").css('color','#29abe2');
	}
	 
	if( isOk ){
		$('#lot_search_form').submit();	
	}
	
}

function checkLogin(){
	email = $('#login_email').val();
	pass  = $('#login_password').val();
	
	$(function(){
		$.post("/user/checklogin/", {"email" : email, "pass" : pass} ,function(data){
			if( data == 0 ){
				$('#login_form p').html('Neteisingi prisijungimo duomenys. Bandykite dar kartą.').css('color','#ff0000');
			}
			else if( data == 1 ){
				$('#login_form p').html('');
				$('#login_form').submit();				
			}
	    }, 'text')
	});
	
	
}

function checkMail(){
	email = $('#forgot_email').val();
	isOk = true;
	
	//email
	reg = /^.*@.*\..*$/
		
	if( !reg.test(email)){
		isOk = false; 
		$("#forgot_msg").html('Blogai įvestas el. pašto adresas.').css('color','#ff0000');
	}
	
	if( isOk ){				
		
		$(function(){
			$.post("/user/forgotpass/", {"email" : email} ,function(data){
				if( data == 0 ){					
					$('#forgot_msg').html('Toks el. pašto adresas sistemoje nerastas.').css('color','#ff0000');			
					return;
				}
				else if( data == 1 ){
					$('#pass_reminder').dialog('close');
					$('#pass_reminder').css('display','none');
					
					//clean fields
					$('#forgot_email').val('');
					$('#forgot_msg').html('');					
					
					//open new dialog
					$('#pass_reminder_msg_ok').css('display','block');
					$('#pass_reminder_msg_ok').dialog('open');
					
				}
			}, 'text')
		});
	}	
	
}
function confirmRegistration(){
	$(document).ready(function() {
		$('#registration_confirmation').css('display','block');
		$('#registration_confirmation').dialog('open');	
	});	
}

function deleteConfirm( lotId ){

	$(document).ready(function() {
		$('#delete_lot_yes').bind('click', function() {
			if( lotId ){
				window.location = '/lot/deletelot/id/' + lotId;
			}		
			return false;
		});
		$('#delete_confirm').css('display','block');	
		$('#delete_confirm').dialog('open');		
	});
	
	return false;
}

/*----------------------------*/
function uploadButton( buttonDiv ){
	$("#photoButtonsBlock").fadeOut("slow");
	$("#upload_photo").fadeOut("slow");
	$("#form_container").fadeIn("slow");	
	$('#form_container p').text('Nuotrauka ne didesnė negu 2MB, formatas - jpg, gif, png').css('color','#888888').fadeIn('slow');	
	
	setTimeout(function(){
		hideUploadField();			
	},45000);
	
}
/*----------------------------*/
function hideUploadField(){
	$("#upload_photo").fadeIn("slow");
	$("#photoButtonsBlock").fadeIn("slow");
	$("#form_container").fadeOut("slow");	
}
/*----------------------------*/
function uploadFile( uploadField, userId ){

	var extReg = /\.gif|\.jpg|\.jpeg|\.png/i;
	var filename = uploadField.value;
	
	
	
	if (filename.search(extReg) == -1){			
		$('#form_container p').text('Negalimas failo plėtinys. Gali būti - *.jpg, *.pgn, *.gif')
		.css('color','#ff0000').fadeIn("slow");					
		
		setTimeout(function(){
			$('#form_container p').fadeOut("slow");					
		},10000);
		
    	uploadField.form.reset();
    	return false;
	}
	
	imageId = $('#file_id').val();
	
	if( imageId ){
		deletePhoto();
	}
	
	uploadField.form.submit();
	uploadField.disabled = true;
	
	$('#form_container p').text('Kraunasi...').css('color','#888888');
	
	return true;
	
}
/*----------------------------*/
function stopUpload( output ){
	
	eval("var obj=" + output);
	
	if(obj.status == 'ok'){
		photoUrl =obj.photo;

		photoUrl = photoUrl.replace(/amp;/gi,'');	
	
		$('#photo').attr('src',photoUrl);
		$('#form_container p').text( obj.msg ).fadeIn('slow');
		$('#photo_file').attr('disabled',false);
		
		$('#file_id').val(obj.fileId);
		$('#file_name').val(obj.fileName);
		$('#folder').val(obj.folder);
		
	}
	if(obj.status == 'error'){
		$('#form_container p').text( obj.msg ).css('color','#ff0000').fadeIn('slow');
		$('#photo_file').attr('disabled',false);	
	}
	
	
	
}
/*----------------------------*/
function deletePhoto(){
	
	imageId = $('#file_id').val();
		
	if( imageId ){
		$(function(){
			$.post("/image/removeuserphoto/", {"imageId" : imageId} ,function(data){
				$('#photo').attr('src',data);
				$('#file_id').val("");
				$('#file_name').val("");
				$('#folder').val("");
			 	$('#form_container p').text('Nuotrauka sėkmingai ištrinta').css('color','#888888');
			}, 'text')
		});
	}
	
}
/*----------------------------*/
function lotRegFinish(){
	$(document).ready(function() {
		$('#lot_reg_finish').css('display','block');
		$('#lot_reg_finish').dialog('open');	
	});	
}
/*---------------------------*/
$(document).ready(function() {

	//changeSelectFields();
	
	$('tr.search_more').hide();

    //$.post("/index/getlotcountforallcities/", {} ,function(data){
	//		$('#lot_count_div cite').html(data);
	//}, 'text');	
	

	//hide all dialogs
	
	$('#dialog').css('display','none');
	$('#pass_reminder').css('display','none');
	$('#pass_reminder').css('display','none');
	$('#pass_reminder_msg_ok').css('display','none');
	$('#registration_confirmation').css('display','none');
	$('#registration_confirmation').css('display','none');
	$('#delete_confirm').css('display','none');
	$('#lot_reg_finish').css('display','none');
	
	//login dialog
	
	$('#dialog').dialog({
		autoOpen: false,
		width: 470,
		modal: true,
		buttons: {}
	});
	
     $('#dialog a.gray_s').click(function(){
    	 $('#dialog').dialog('close');
    	 $('#dialog').css('display','none');
    	 return false;
     });
     
	$('#user_login_link').click(function(){
		 $('#dialog').dialog('open');
		 $('#dialog').css('display','block');
		 return false;
	});  
	
	//pass remind dialog
	$('#pass_reminder').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
		
	
	//cancel button
	$('#pass_reminder a.gray_s').click(function(){
    	 $('#pass_reminder').dialog('close');
    	 $('#pass_reminder').css('display','none');
    	 return false;
    });
    
	//submit button
	/*$('#pass_reminder a.gray_b').click(function(){
		$('#forgot_msg').html('Kraunasi...').css('color','#9aa0a5');
		checkMail();		
   	 	return false;
   });*/
	
	
	$('#pass_reminder_link').click(function(){
		 $('#dialog').dialog('close');
		 $('#dialog').css('display','none');
		 $('#pass_reminder').dialog('open');
		 $('#pass_reminder').css('display','block');
		 return false;
	});
	
	//pass remind dialog msg ok
	$('#pass_reminder_msg_ok').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
	
	//close button
	$('#pass_reminder_msg_ok a.gray_b').click(function(){
    	 $('#pass_reminder_msg_ok').dialog('close');
    	 $('#pass_reminder_msg_ok').css('display','none');
    	 return false;
    });
	
	//registration confirmation
	
	$('#registration_confirmation').dialog({
		autoOpen: false,
		width: 650,
		modal: true,
		buttons: {}
	});
	
	$('#registration_confirmation a.gray_b').click(function(){
		$('#registration_confirmation').dialog('close');
		$('#registration_confirmation').css('display','none');
		window.location = '/';
		return false;
	});
	
	//delete confirm
	 $('#delete_confirm').dialog({
			autoOpen: false,
			width: 340,
			modal: true,
			buttons: {}
		});
	 $('#delete_lot_no').click(function(){
		 $('#delete_confirm').dialog('close');
		 $('#delete_confirm').css('display','none');
		 return false;
	 });	
	 
	 //lot finish popup
	 $('#lot_reg_finish').dialog({
			autoOpen: false,
			width: 600,
			modal: true,
			buttons: {}
		});
	 $('#lot_reg_finish a.gray_s').click(function(){
		 $('#lot_reg_finish').css('display','none');
		 window.location = '/user/home';		 
		 return false;
	 });

});

function moreSearchOptions(){
	
	var elem = $('tr.search_more')[0];

	
	if(elem.style.display == 'none'){
		$('tr.search_more').show();
		$('#search_less_btn').toggle();
		$('#search_more_btn').toggle();
	}     
	else{
		$('tr.search_more').hide();   
		$('#search_less_btn').toggle();
		$('#search_more_btn').toggle();
	}

	
}

function checkGeneralSearch(){
	
	wLen = $('#general_search_query').val().length;
	
	if(wLen < 2){
		$('#general_search_query').val('Min. 2 simboliai!').css('color','#ff0000');
		
		setTimeout(function(){
			$('#general_search_query').val('').css('color','#000000');	
		},2000);
		
		return;
	}
	
	$('#general_search').submit();
}
