<?php
ob_start();

if(!(is_readable(realpath(dirname(__FILE__)).'/include/includesroutines.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/include/includesroutines.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/include/includesroutines.inc');
}

checkUserAndRedirectToLogin();

if(!(is_readable(realpath(dirname(__FILE__)).'/classes/tree.php'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/classes/tree.php');
} else {
	include_once(realpath(dirname(__FILE__)).'/classes/tree.php');
}

$cn = db_connect();
$lng = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
$lngid = db_getLanguageID($cn, getLanguage());
$contlng = $lng;
$contlngid = $lngid;
if (getSetting('portal','useRights',0) == 1){
	$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
	$contlngid = $_SESSION['user_idlanguagecontent'];
}else{
	$contlng = 'lang='.db_getDefaultLangShortName($cn);
	$contlngid = db_getDefaultLangID($cn);//$_SESSION['user_idlanguageinterface'];
}


$url = getCurPageURL();
$urlWO = getCurPageURLWO();
mb_internal_encoding('UTF-8');
//Task 61628 - only main branch
$skbranch = db_getMainSKBranch($cn);
$idbranch = db_getMainIDBranch($cn);	
$usr_arr = GetUserIDs();
?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	renderCommonCSS(); 
	?>
</head>
<body>
	<?php renderModalHourGlassDiv();?>
	<div id="container">
	<?php renderLoginBlock();?>
	<div id="main" role="main" class="ui-layout-center">
		<?php renderMainMenu(); ?>
		<div id="content" class="ui-layout-center">
			<section id="box-search" class="clearfix">

                <form name="selfform" id="selfform" action="" method="post">
				<section id="box-search-form">
					<label for="text-search-full"><?php getResource("button.search");?>:</label><input type="text" id="text-search-full"  name="search" value="" placeholder="<?php getResource("message.enterText");?>"><span><button id="goSearch" class="btn-top btn-top-text" title="<?php getResource("button.search");?>"><span><?php getResource("button.search");?></span></button></span>
				</section>


				<section id="box-search-form-extended-title" class="clearfix">
					<h2><?php getResource("title.addParams");?></h2>
					<div id="btn-toggle-title" title="<?php getResource("button.hideshow");?>" <?php if(!isset($_REQUEST['hidepanel']) || $_REQUEST['hidepanel'] == '1') { print 'class="closed"';}  ?>>&uarr;&darr;</div> <!--STU -->
				</section>

				<section id="box-search-form-extended-form-container" <?php if(!isset($_REQUEST['hidepanel']) || $_REQUEST['hidepanel'] == '1') { print 'style="display:none"';}  ?> >

					<div id="box-search-form-extended-form" class="clearfix">
                 		<div id="fieldset-left-container">
                 		<fieldset id="fieldset-placement">
							<legend>&nbsp;<?php getResource("field.wordPlaced");?>:&nbsp;</legend>
							<input type="radio" id="searchin"  name="searchin" value="s_all" <?php if (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_all') { echo 'checked="checked"'; }?> ><label for="placement-all"><?php getResource("field.placement-all");?></label><br />
							<input type="radio" id="searchin" name="searchin" value="s_body" <?php if (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_body') { echo 'checked="checked"'; }?> ><label for="placement-body"><?php getResource("field.placement-body");?></label><br />
							<input type="radio" id="searchin" name="searchin" value="s_title" <?php if (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_title') { echo 'checked="checked"'; }?> ><label for="placement-subject"><?php getResource("field.placement-subject");?></label>
						</fieldset>
						<fieldset id="fieldset-words">
							<legend>&nbsp;<?php getResource("button.search");?>:&nbsp;</legend>
							<input type="radio" id="searchop" name="searchop" value="so_all" <?php if (isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_all') { echo 'checked="checked"'; }?>><label for="words-all"><?php getResource("field.words-all");?></label><br />
							<input type="radio" id="searchop" name="searchop" value="so_any"  <?php if (isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_any') { echo 'checked="checked"'; }?>><label for="words-any"><?php getResource("field.words-any");?></label><br />
							<input type="radio" id="searchop" name="searchop" value="so_full"  <?php if (isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_full') { echo 'checked="checked"'; }?>><label for="words-exact"><?php getResource("field.words-exact");?></label>
						</fieldset>
						<?php if (db_getLangsCountFromResources($cn) > 1  && getSetting('portal','useRights',0) == 1 /* 75638 */ )/*Îäèí ÿçûê áóäåò âñåãäà*/ { ?>
						<fieldset id="fieldset-words">
							<legend>&nbsp;<?php getResource("field.language");?>:&nbsp;</legend>
							<input type="checkbox" id="searchinalllanguages" name="searchinalllanguages" value="searchinalllanguages" <?php if (isset($_REQUEST['searchinalllanguages'])) { echo 'checked="checked"'; }?>><label for="searchinalllanguages"><?php getResource("field.searchinalllanguages");?></label><br />
						</fieldset>						
						<?php } ?>
                        </div>

						<fieldset id="fieldset-place">
							<legend>&nbsp;<?php getResource("field.searchPlace");?>:&nbsp;</legend>
							<div id="box-tree-search">
							<ul id="mixed">
								<?php
								//61628
								$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid, $skbranch);
								foreach ($tr_arr as $node) {
									echo '<li id="'.$node['idobject'].'" name="'.$node['o_guid'].'" class="hasChildren"><nobr><span><img  src="'.$urlWO.'/'.getImgIcon($node['o_icon']).'" /><input type="checkbox" name="searchinobj[]" id="'.$node['idobject'].'" class="searchinobj" value="'.$node['idobject'].'" />'.$node['o_name'].'</span></nobr>';
									if (sizeof(db_getObjectTreetoSearchtoUser($cn, $node['idobject'], GetUserIDs(), $contlngid, $skbranch)) > 0){
										echo '<ul>';
										echo '	<li><span class="placeholder">&nbsp;</span></li>';
										echo '</ul>';
									}
									echo '</li>';
								}
								?>
							</ul>
							</div>
						</fieldset>

						<fieldset id="fieldset-reports">
							<legend>&nbsp;<?php getResource("field.searchReports");?>:&nbsp;</legend>
							<div id="box-tree-search-reports">
								<ul id="mixed_searchreports">
								<?php
								 		$tr_arr = db_getPreparedObjectReportTreetoUser_Search($cn, $usr_arr, $contlngid, NULL);
								 		$size = sizeof($tr_arr);
										$tree = new Tree();
										for($i=0; $i<$size; $i++){
											if ($tree->itemExists($tr_arr[$i]['parent_idobject']."_".$tr_arr[$i]['parent_idreport'])) {
												$tree->addItem($tr_arr[$i]['idobject']."_".$tr_arr[$i]['idreport'], $tr_arr[$i]['parent_idobject']."_".$tr_arr[$i]['parent_idreport'], $tr_arr[$i]);
											} else {
												$tree->addItem($tr_arr[$i]['idobject']."_".$tr_arr[$i]['idreport'], "0", $tr_arr[$i]);
											}

										}
										echo $tree->createHtmlSearch(0);
								 		unset($tr_arr);
								?>
								</ul>
							</div>
						</fieldset>
          		</div>

				</section>
  		        <input type="hidden" name="page" id="page" value="1"/>
  		        <input type="hidden" name="lang" id="lang" value="<?php echo getLanguage()?>"/>
				</form>

				<section id="box-search-results">
				</section>
		</div>
	</div>
</div>
<script src="js/script.js"></script>
<script src="js/tree.js"></script>
<script src="js/libs/jquery.treeview.js"></script>
<script src="js/libs/jquery.treeview.edit.js"></script>
<script src="js/libs/jquery.treeview.async.search.js"></script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/search.js"></script>
<script src="js/libs/jquery.highlight.js" ></script>
<script>

//	Task 65712 var searchString = "<?php echo str_replace('"', "&quot;", (isset($_REQUEST['search']) ? $_REQUEST['search'] : '')); ;?>";
	var searchString = "<?php echo htmlentities(isset($_REQUEST['search']) ? $_REQUEST['search'] : ''); ;?>";

	function clickPage(page){
    	$("#page").val(page);
    	$("#goSearch").click();
    }

	function clickSeflLink(){
	    ShowModalWindow(true);
	    document.location = "search.php<?php echo '?'.$lng ?>&searchop=so_all&searchin=s_all&hidepanel=0";
	}

	$(document).ready(function(){
		//	Task 65712 $( "#text-search-full").attr("value", searchString.split("&quot;").join('"'));
	    $( "#text-search-full").attr("value", $('<textarea />').html(searchString.split("&quot;").join('"')).text() );
		initTrees("service/treeStructServiceSearch.php<?php echo '?'.$lng ?>", true);
		setSearchObjectTreeEvents();
		initReportsTree('',true);

		$( "#goSearch" ).click(function() {
			$('#selfform').submit(function (){
		        return false;
		    });

			ShowGlassWindow(true);
			$('#mixed').find('.searchinobj').each(function() {
	   			if (!$(this).parent().parent().parent().find( 'li' ).length || $(this).parent().parent().parent().find('li').first().hasClass('last') ){
	   				$(this).attr('name', 'searchinobjlast[]');
	   			} else {
	   				$(this).attr('name', 'searchinobj[]');
	   			}
  			});
  			var post_data = $('#selfform').serialize();
  			$.ajax({
			  type: "POST",
			  url: "service/searchService.php",
			  data: post_data,
			  dataType: "html",
			  success: function( data ) {
			     $( "#box-search-results" ).html( data );
			      ShowGlassWindow(false);
			      var settings = {};
			      settings.remove = false;
			      settings.caseSensitive = false;
			      settings.strictly = true;
				  settings.full = false;
				  try{
					var searchpattern = $.trim($("#text-search-full").val());
					var htmlEntities = [
								{regex:/>/g,entity:'&gt;'},
								{regex:/</g,entity:'&lt;'},
								{regex:/"/g,entity:'&quot;'},
								{regex:/á/g,entity:'&aacute;'},
								{regex:/é/g,entity:'&eacute;'},
								{regex:/í/g,entity:'&iacute;'},
								{regex:/ó/g,entity:'&oacute;'},
								{regex:/ú/g,entity:'&uacute;'}
							];

					for(v in htmlEntities){
						searchpattern = searchpattern.replace(htmlEntities[v].regex, htmlEntities[v].entity);
					}
					if ($('input[name=searchop]:checked', '#selfform').val() == 'so_full'){
					//	settings.full = true;
						$(".highlight-plugin").highlight(searchpattern, settings);
					} else {
						searchpattern = searchpattern.replace('.',' ').trim();
						var arr = $.trim(searchpattern).split(' ');
						for (var i=0,len=arr.length;i<len;i++) {
							$(".highlight-plugin").highlight(arr[i], settings);
						}
					}
				  }catch (err){

				  }
				  $("#page").val(1);
		      },
			  error: function() {
			  	 alert('inernal error!');
			     $("#box-search-results").html("");
			      ShowGlassWindow(false);
			  }
			});
		});

		$("#goSearchMin").click(function() {
			$("#text-search-full").val($("#text-search-min").val());
			$("#text-search-min").val('');
			$("#goSearch").click();
		});

		$("#text-search-min").keyup(function(e){
    		if(e.keyCode == 13)
    		{
    			$("#goSearchMin").click();
            }
        });

		$("input#checkbox_reptree_root").change(function() {
			var clname = $(this).attr("class").split(" ")[0];
			if ( clname ) {
				var selector = '#checkbox_reptree_node.'+clname;
		        $(this).parent().parent().parent().parent().parent().find(selector).prop('checked',this.checked);
		        delete selector;
		        delete clname;
			}
	    });

	    $('input#checkbox_reptree_node').change(function() {
	    	var clname = $(this).attr('class').split(' ')[0];
			if ( clname ) {
				var selector = '#checkbox_reptree_root.'+clname;
				$(this).parent().parent().parent().parent().parent().find(selector).prop('checked',false);
		        delete selector;
		        delete clname;
			}
	    });

	    $("#goSearch" ).click();
	});

	</script>
<!-- <link rel="stylesheet" href='css/jquery-ui.css' /> -->
<link rel="stylesheet" href='css/ui-lightness/jquery-ui-1.8.20.custom.css' />

<?php
	if(!(is_readable(realpath(dirname(__FILE__)).'/templates/languagesbox.template'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	} else {
		include_once(realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	}
?>

<?php renderFooterTemplate(); ?>
</body>
</html>
<?php
db_disconnect($cn);
ob_end_flush();
?>