<?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');
}

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

checkUserAndRedirectToLogin();

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

$cn = db_connect();
$url = getCurPageURL();
$avlble = array();
$default_date_period = getCookieForPage('date_period',0) ;
$contlngid = $_SESSION['user_idlanguagecontent'];
$lng_shot = db_getLanguageShortByID($cn, $contlngid);

$_SESSION['adminconsoletoken'] = createGuid(false);
$sstoken = $_SESSION['adminconsoletoken'];
$isGroup = (isset($_COOKIE['indicatorsisgroup']) ?  $_COOKIE['indicatorsisgroup'] : 0);

if ( getSetting('portal','useRights',0) == 0 || getSetting('page','showpage.indicators',0) != 1){
 	$url = getCurPageURLWO()."/personal.php";
	header("Location: ".$url); 
	ob_end_flush();
	exit;
}

$urlFromCookies = getCurPageURL();
if (getCookieForPage('date_period') !== NULL && !isset($_REQUEST['date_period'])) {
	$urlFromCookies = urlReplaceParam($urlFromCookies,'date_period', getCookieForPage('date_period'));
}
if (getCookieForPage('date_value') !== NULL && !isset($_REQUEST['date_value'])) {
	$urlFromCookies = urlReplaceParam($urlFromCookies,'date_value', getCookieForPage('date_value'));
}
if (getCookieForPage('pf') !== NULL && !isset($_REQUEST['pf'])) {
	$urlFromCookies = urlReplaceParam($urlFromCookies,'pf', getCookieForPage('pf'));
}
if( $urlFromCookies !== getCurPageURL() ){
	header("Location: ".$urlFromCookies);
	ob_end_flush();
	exit;
}

function fixDate( $date_value ) { //dirty month add - date_create() works incorrect with year-only value
	return substr_count( $date_value, "-" ) == 0 ? $date_value."-01" : $date_value;
}

// settings
if(!is_readable(realpath(dirname(__FILE__)).'/resources/input/dateperiods.inc')) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/resources/input/dateperiods.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/resources/input/dateperiods.inc');
}
$default_order_column = getCookieForPage('order_column','value'); 
$default_order_val = getCookieForPage('order_val','asc');

// url parse and build
$pf = ( isset($_REQUEST['pf']) ? $_REQUEST['pf'] : 0);
setCookieForPage("pf", $pf);
$date_period = isset( $_REQUEST[ "date_period" ] ) ? $_REQUEST[ "date_period" ] : $default_date_period;
setCookieForPage("date_period", $date_period);
$date_format = $date_periods[ $date_period ][ "date_format" ];
$date_format_internal = $date_periods[ $date_period ][ "date_format_internal" ];
$default_date_value = date( $date_format_internal );
$date_value = isset( $_REQUEST[ "date_value" ] ) ? $_REQUEST[ "date_value" ] : $default_date_value;
setCookieForPage("date_value", $date_value);
$order_column = isset( $_REQUEST[ "order_column" ] ) ? $_REQUEST[ "order_column" ] : $default_order_column;
$order_val = isset( $_REQUEST[ "order_val" ] ) ? $_REQUEST[ "order_val" ] : $default_order_val;
setCookieForPage("order_column", $order_column);
setCookieForPage("order_val", $order_val);
$page = isset( $_GET[ "page" ] ) ? $_GET[ "page" ] : 1;
$date = date_create( fixDate( $date_value ) );
if (isset ($_GET[ "IsGroup" ])) {
	$isGroup = ($_GET[ "IsGroup" ] == 1 ? 1 : 0);
	setCookieLong('indicatorsisgroup', $isGroup);
}

function saveInputData( $inputArr, $date_period, $date_value, $pf = 0){
	global $cn;
	sendInputSave($cn, $inputArr, $date_period, $date_value, $pf);
}

// setting factors array changes
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
	$factors_arr = array();
	while ( list( $key, $value ) = each( $_POST ) ) {
		$factors_arr[ $key ] = array( "Value" => $key, "Fact" => $value );
	}
	//записываем и перенаправляем
	saveInputData( $factors_arr, $date_period, $date_value, $pf );
    Header("Location: ".getCurPageURL());
    exit;
}

$usr_arr = GetUserIDs();

?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	renderCommonCSS(); 
	?>
	<link rel="stylesheet" href="css/zDater.css">
</head>
<body>
	<?php renderModalHourGlassDiv();?>
	<div id="container">
	<?php renderLoginBlock();?>
	<div id="main" role="main" class="ui-layout-center">
	<?php renderMainMenu(strtolower(pathinfo(__FILE__, PATHINFO_FILENAME))); ?>
		<div id="content" class="ui-layout-center">
			<section id="box-input" class="clearfix">
			<div id="box-input-container" name="box-input-container">
					<div id="loadingbox" name="loadingbox" style="font-weight: bolder;padding-top: 40px;padding-bottom: 40px;"></div>
			</div>		
			</section>
		</div>
	</div>
</div>
<script src="js/libs/jquery.js"></script>
<script src="js/libs/jquery-ui-1.8.20.custom.min.js"></script>
<script>
	var Glang = '<?php echo db_getLanguageShortByID($cn, $_SESSION['user_idlanguageinterface'], true); ?>';
</script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/libs/zDater.js"></script>
<script src="js/libs/date.js"></script>
<script src="js/script.js"></script>
<link rel="stylesheet" href='css/ui-lightness/jquery-ui-1.8.20.custom.css' />
<script src="js/input.js"></script>
<script src="js/dotloader.js"></script>
<script>
ShowModalWindow(true);

var checkInputValues = <?php echo getSetting('page','indicators.checkinputvalues',0); ?>;
var sstoken = '<?php echo $sstoken;?>';
var loadingtext = '<?php getResource("title.loading");?>';
var loadingtextForDatePicker = '<?php getResource("title.loading");?>';
var params = location.search;

$(function(){
	// 62750 startLoadAndSwohDotsRun(loadingtext, "#loadingbox");
	loadPage(params);

	function loadPage(urlParam) {
		$("body").css("cursor", "wait"); //62750
		ShowModalWindow(true);
		$.ajax({
	        type: "GET",
	        url: ("service/input.php" + urlParam),
	        success: function(arg){
	    		var msg = arg;
		     	if ( msg.toString().length > 0 ) {
					$("#box-input-container").empty();
					$("#box-input-container").append(msg);

					//save coockies
					$.ajax({
						type: "GET",
						url: ("input.php" + urlParam)});
					$( window ).resize();
					inputApp();
					$("a:not(.self-event)").unbind('click');
					$("a:not(.self-event)").click(
						function(event) {
							messageText = "<?php getResource("confirm.savelesValue"); //STU ?>";
							if( $(this).hasClass('input-action') ) {
								event.preventDefault();
								if (!hasChange || (hasChange && confirm(messageText))) {
									var link = $(this).attr("href");
									var searchParams = link.split('?')[1];
									loadPage('?' + searchParams);
								}
							} else {
								return (!hasChange ? true : confirm(messageText));
							}
						}
					);
				}
	        },
	        complete:function(arg){
				stopLoadAndSwohDotsRun();
				$("#loadingbox").remove();
				ShowModalWindow(false);
				$("body").css("cursor", "default");
	        }
	    });
	}

    //61766
    function unloadPage(){ 
        if(hasChange){
            return "<?php getResource("confirm.savelesValue"); //STU ?>";
        }
    }
    
    window.onbeforeunload = unloadPage;    
});	
</script>

<?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
unset($trSt);
session_write_close();
db_disconnect($cn);
ob_end_flush();
?>
