$(document).ready(function(){
	//clicking submit class elements
   $(".news_search_subm_btn").click(function(event){
	event.preventDefault();
	var sWord = jQuery.trim($("input#newsSearchWord").val());
	if(chckNewsSearchInput(sWord)){
		createActionAndSubmit();
	}
   });
   
   //pressing Enter in text field
   $("#newsSearchWord").keypress(function(event){
		if (event.keyCode == 13) {
			var sWord = jQuery.trim($("input#newsSearchWord").val());
			if(chckNewsSearchInput(sWord)){
				createActionAndSubmit();
			}
			return false;
		}
   });
})

function createActionAndSubmit(){
		
	   var selectedCats = '';
	   //getting selected categories
	   $('div.panel input').each(function() {   
		   if($(this).attr('checked')==true){
				if(selectedCats == ''){
					selectedCats = $(this).val();
				}else{
					selectedCats = selectedCats + ',' + $(this).val();
				}
			}
	   });
	   //adding categories to url if entered
	   if(selectedCats != ''){
			var actionVal = $("#news_search_form").attr('action');
			$("#news_search_form").attr('action', actionVal + 'c/' + selectedCats + '/');
		}
		//adding search word to url if entered
		var searchWord = jQuery.trim($("input#newsSearchWord").val());
		if(searchWord != ''){
			var actionVal = $("#news_search_form").attr('action');
			$("#news_search_form").attr('action', actionVal + 's/' + searchWord + '/');
		}
		
		$('#news_search_form').submit();
}

//checks if search phrase or categories are input, search phrase length
function chckNewsSearchInput(inpStr){
	inpStr = jQuery.trim(inpStr);
	if(inpStr.length > 0){//is prase entered, only check it's lengt, no cat check
		if(inpStr.length < 3){
			alert(sPhraseTooShort);
			return false;
		}else{
			return true;
		}
	}else{//no phrase entered, check if any cat is entred
		var atLeastOneChecked = false;
		$('div.panel input').each(function() {   
		   if($(this).attr('checked')==true){
				atLeastOneChecked = true;
			}
		});
		if(!atLeastOneChecked){
			alert(inputPhraseOrCat);
			return false;
		}else{
			return true;
		}
	}
}
   
function clearCheckboxes(){
    $('div.panel input').each(function() {   
		   if($(this).attr('checked')==true){
				$(this).attr('checked', false);
			}
	   });
}
   

