<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");


$tabId = $_POST['uniqueTabId'];
$projectId = $_POST['id_project'];
$projName = $_POST['project'];
$tableName = $projName;
$reqUrl = 'webcati/_ajax/buildQuestionare/ajax.buildQProperties.php';
//!!!!!!!!!!!!!!!!!!! the grid for the project properties !!!!!!!!!!!!!!!!!!!!!!!
	$propGrid = new MakeGrid($tableName.'_properties');
	$propGrid->setReqUrl($reqUrl);
	$propGrid->setMainTable('_Projects')
	//->addConfig('width','450')
	->addConfig('hideHeaders','true')
	//->setTitle('Questionaire options')
	->setEditable(false)
	->setGrouping('grp',"{showGroupName:false,hideGroupedColumn:true}")
	->region('east')
	->setWidth(255)
	->flex(1);

	$propGrid->addColumn('value','Value')->type('checkColumn')->width(30);
	$propGrid->addColumn('option','Option')->width(220);
	$propGrid->addColumn('field');
	$propGrid->addColumn('grpName');
	$propGrid->addColumn('grp','group')->setProperty('groupRenderer',"function(a,b,r){return r.data.grpName;}"   );

	//SQL FOR PROJECT PROPERTIES...each select will be shown as a checkColumn!!!
	//warning no new lines in string since ajax can't handle it!

	// isTemplate,stat_show_scaleborder,9 --> was taken out, I do not know what for was this (Borut 20.1.2013)
	//Marko 17.5.2015
	$propGrid->selectSQL = "SELECT print_jump,print_filter,print_condition,print_answfilter,stat_show_var,stat_show_val,stat_show_filter_in,stat_show_filter_out,stat_show_goto,stat_show_answer_filter,stat_show_question_type,stat_show_open_end_type,lock_app_to_user,back_delete,interview_show_variable,interview_show_ans_value,hide_back_button FROM _Projects as a LEFT JOIN _ProjectProperties as b ON a.id = b.id_project   WHERE a.id = $projectId";
	//!Marko 17.5.2015
	$propGridName = $propGrid->getName();
	//$propGrid->addConfig('applyTo',"'cont_$propGrid'");

	echo $propGrid->createGrid();

	//a special afteredit for project property grid...since it doesn't update lines in a table but columns in a row
	echo "$propGridName.on('afteredit',function(e){
		var data = e.record.data;
		$propGridName.RMconn.request({
				 params: {
				 id:$projectId,
				 action: 'update',
				 //each row in the grid represents a field...we sent which field we just changed
				 field: data.field,
				value : e.value
				},
				success : function(resp,opt){if(Ext.decode(resp.responseText).success){
				e.record.commit();
				 } else {e.record.reject();}},
				failure: function(){e.record.reject();}
				});
			}); ";
    $form2 = new MakeForm($tableName.'_properties3');
    $form2->padding(15)
    ->setAutoUpdate()
    ->setReqUrl('webcati/_ajax/buildQuestionare/ajax.buildQProperties.php')
    ->flex(1)
    ->region('east')
 //   ->setHeight(280)
    ->setMainTable('_ProjectProperties',DB_WARPIT_WEBCATI_BASE)
    ->addConfig('labelWidth',210)
    ->addConfig('border', 'false')
    //->addConfig('autoScroll',true)
    ->id = $projectId;
    
    $form2->addField('successful_interview_price','Euro for one succsseful interview','numberfield')->width(50);
    $form2->addField('unsuccessful_interview_price','Euro for one unsuccsseful call','numberfield')->width(50);
    $form2->addField('contacted_interview_price','Euro for contacted and unsuccsseful call','numberfield')->width(50);
    $form2->addField('payType','Salary type','combo')
        ->setAutoUpdate(false)
        ->addListener('select',"function(fld,val)
        {
            $form2.RMautoUpdate(fld);
            if(val.data.field1 == '1')
            {
                $form2.getForm().findField('payday_monthly').hide();
                $form2.getForm().findField('payday_weekly').show();
            }
            else
            {
                $form2.getForm().findField('payday_monthly').show();
                $form2.getForm().findField('payday_weekly').hide();
            }
            
        }")
        ->setProperty('store',json_encode(array(
            array('1','Weekly salary'),
            array('2','Monthly salary')
        )))
        ->setProperty('triggerAction',"'all'");
        
    $form2->addField('payday_weekly','Salary payday','combo')
        ->setProperty('store',json_encode(array(
            array('1','Monday'),
            array('2','Tuesday'),
            array('3','Wednesday'),
            array('4','Thursday'),
            array('5','Friday'),
            array('6','Saturday'),
            array('7','Sunday')
        )))->setProperty('triggerAction',"'all'");
        $form2->addField('payday_monthly','Salary payday','numberfield')->width(50);
    /*$form2->addItem("new Ext.slider.MultiSlider({
        //width   : 214,
        fieldLabel: 'Interval',
        minValue: 0,
        maxValue: 31,
        values  : [10, 20],
        plugins : new Ext.slider.Tip()})");*/
    
    /*$form->autoUpdateFunction = "function(fld,val){
                var rec = $grid.getStore().getById($formName.selectedRowId);
                new RMajax().request({
                url:'$ajaxUrl',
                params:{
                     action:'update',
                     RMtable:'$tableName',
                     database:'".DB_WARPIT_WEBCATI_BASE."',
                     field:fld.RMfieldName,
                     value:val,
                     id: $id_project
                     idField: 'id_project' 
                 },
                 success:function(resp){
                    r = Ext.decode(resp.responseText);
                    if(!r.success)
                    {
                        alert( r.error );
                    }
                    else
                    {

                        rec.data[fld.RMfieldName] = val;
                    }
                 }
                 });

                 }";*/
    
	$form = new MakeForm($tableName.'_properties2');
	$form->padding(15)
	->setAutoUpdate()
	->setReqUrl('webcati/_ajax/buildQuestionare/ajax.buildQProperties.php')
	->flex(1)
	->region('west')
	//->setHeight(280)
	->setMainTable('_Projects',DB_WARPIT_WEBCATI_BASE)
	->addConfig('labelWidth',160)
    ->addConfig('border', 'false')
	//->addConfig('autoScroll',true)
	->id = $projectId;

	$form->addField('naziv_proj','Long project name','textfield')->width(205);
	$form->addField('start_date','Questionnaire start date','datetimefield');
	$form->addField('end_date','Questionnaire end date','datetimefield');
	$form->addField('webPoints','Points','numberfield')->width(50);
	
	   /*new Ext.slider.MultiSlider({
        renderTo: 'multi-slider-horizontal',
        width   : 214,
        minValue: 0,
        maxValue: 100,
        values  : [10, 50, 90],
        plugins : new Ext.slider.Tip()
    });*/
	//Marko 15.4.2015
	//$form->addField('active','Permission for interviewing','checkbox');
	$form->addItem("{
		xtype:'checkbox',
		name: 'podatki[active]',
		fieldLabel: 'Permission for interviewing',
		id: '".$tableName."_activeCheckBox',
		RMfieldName: 'active',
		listeners: {
			render : function(c){
				c.el.on('click',function(){
					var b = function(fld,val){
						if(fld.getValue() == 0){
							Ext.getCmp('".$tableName."_removeAllWebLinks').show();
						}else{
							Ext.getCmp('".$tableName."_removeAllWebLinks').hide();
						}
						new RMajax().request({
							url: '".$reqUrl."',
							params: {
								RMcomp:'form',
								action:'update',
								RMtable:'_Projects',
								database:'Warpit_Webcati_base',
								field:fld.RMfieldName,
						 		value: fld.getValue(),
						 		id: " . $projectId . "
						 	}
						});
					}
					b(c,c.getValue());
				});
			}
		}
	}");
	/*
	$form->addItem("{
		xtype : 'label',
	  	fieldLabel:'Delete used Links',
	},{
		xtype: 'button',
		text: 'Delete',
		id: '".$tableName."_deleteLinksButton',
		fieldLabel:'&nbsp;',
	  	labelSeparator:'&nbsp;',
		handler:function(){
			new RMajax().request({
				url: 'webcati/_ajax/generateWwwIds/ajax.generateWwwIds.php',
				params: {
					deleteUsedLinks:true,
					projectName: '$tableName',
			 		id_project: ".$tableName."_properties2.selectedId
			 	}
			});
		}
	}");*/
	$form->addItem("{
		xtype: 'compositefield',
        fieldLabel: 'Remove all used web links',
        id: '".$tableName."_removeAllWebLinks',
        msgTarget : 'side',
        anchor    : '-20',
        items: [
            {
               	xtype: 'button',
				text: 'Remove',
				id: '".$tableName."_deleteLinksButton',
				fieldLabel:'&nbsp;',
			  	labelSeparator:'&nbsp;',
				handler:function(){
					new RMajax().request({
						url: 'webcati/_ajax/generateWwwIds/ajax.generateWwwIds.php',
						params: {
							deleteUsedLinks:true,
							projectName: '$tableName',
					 		id_project: ".$tableName."_properties2.selectedId
					 	},
					 	success: function(resp){
					 		var res = Ext.decode(resp.responseText);
					 		if(res.success){
					 			Ext.Msg.alert('Successfuly removed', res.msg);
					 		}
					 	}
					});
				}
            },
            {
                xtype: 'datefield',
                hidden:true
            }
        ]
	}");
	//Konec
	$form->addField('use_lowest','Equally distributed tel. number','checkbox');

	$sql = "SELECT distinct q_name,q_name FROM " . DB_WARPIT_WEBCATI_BASE . ".quota_layer a
	           left join " . DB_WARPIT_WEBCATI_BASE . ".quota_layer_addon b ON a.layer = b.id WHERE id_project = $projectId AND telSelect = 1";
    $res = $db->SQLexecute($sql);
    while ($row = $db->fetchRow($res))
        $layers[] = $row;

    $form->addField('use_lowest_layer','Select layer','combo')->setProperty('store',json_encode($layers));

	//$languages = $db->get('_LanguageCodepage','enable = 1','id as 0,cp_comment as 1',DB_WARPIT_WEBCATI_BASE);
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$res = $db->SQLexecute('SELECT id ,cp_comment FROM _LanguageCodepage WHERE enable = 1');
	while ($row = $db->fetchRow($res))
		$languages[] = $row;

	$form->addField('language','Default Language','combo')->setProperty('store',json_encode($languages))
	->setProperty('triggerAction',"'all'")
	->addListener('select',"function(fld,val){
			//lets check if the project is open!
			if(Ext.getCmp('buildQuestionnaire_$projName'))
			{
				Ext.Msg.confirm('Project opened!','Build questionnaire will be closed!<br>Continue?',function(btn){
					if(btn == 'yes')
					{
						$form.RMautoUpdate(fld);
						mainTabPanel.remove(Ext.getCmp('buildQuestionnaire_$projName'));
						addTabAuto('buildQuestionnaire_$projName','webcati/_forms/buildQuestionare/forms.buildQuestionnaire.php',{id_project:$projectId});
					}
					else
						this.setValue( this.oldValue || this.startValue );

						this.oldValue = this.getValue();
				},this)
			}
			else
			{
				$form.RMautoUpdate(fld);
					this.oldValue = this.getValue();
			}
			//save old value for reseting

	  }")->setAutoUpdate(false);
	  $form->addItem("{
	  	xtype : 'label',
	  	fieldLabel:'Extra fields',
	  	name : 'extraVars',
	  	id : 'extraVarLabel_$tabId'
	  },{
	  	xtype: 'button',
	  	text: 'Edit',
	  	fieldLabel:'&nbsp;',
	  	labelSeparator:'&nbsp;',
	  //iconCls:'RMicon_edit_record',
	  	handler: function(){
	  		CallScript('webcati/_forms/buildQuestionare/window.addOnVariables.php',{tableName : '$tableName', id_project : $projectId , id_label: 'extraVarLabel_$tabId' });

	  	}
	  }");

	  $form->addField('redirectActive','Allow redirection','checkbox');
	  $form->addField('nth','Redirection settings','button')->setProperty("text","'Settings'")
	  ->setProperty('handler',"function(){
			addTabAuto('_Project_redirectSettings_$tableName','webcati/_forms/buildQuestionare/forms.redirectSettings.php',
			{id_project: $projectId });
	   }");
	   
	   $form->addField('check_for_quota','Check for quota on','combo')
        ->setProperty('store',json_encode(array(
            array('1','System default'),
            array('2','Quota questions'),
            array('3','All questions')
        )))->setProperty('triggerAction',"'all'");


	  $formLinks = new MakeForm($tableName.'_links');
	  $formLinks ->addConfig('title',"'Interviewer links'")
	  ->region('center')
	  ->addConfig('labelAlign',"'top'");

	  $paths = ConfigLoader::loadConfig('paths');
	  $loginSid = $db->get('_www_externalLinks','id_project = '.$projectId,'loginSID,linkType',DB_WARPIT_WEBCATI_BASE);
	if($loginSid) {
		  foreach ($loginSid as $row) {

		  	$type = $row['linkType'];
		  	$lText = '';
		  	$link = '';
		  	switch ($type) {
		  		case 1:
		  			$lText = "<br><b>Statistics link</b>";
		  			$link = $paths['warpit_www']."survey/showHTMLstat.php?loginSID=".$row['loginSID'];
		  		break;
		  		case 2:
	  				$lText = "<br><br><b>Statistics link (confirmed records only)</b>";
		  			$link = $paths['warpit_www']."survey/showHTMLstat.php?loginSID=".$row['loginSID'];
	  			break;
		  		case 3:
		  			$lText = "<br><br><b>Print questionnaire</b>";
		  			$link = $paths['warpit_www']."survey/printQuestionnaire.php?loginSID=".$row['loginSID'];
		  		break;
		  	}
		    $linksHtml .= "$lText<br><font style=font-size:3px ><br></font>$link <a target=_new href=$link>Link</a>";
		  }
	}

	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$sql = "SELECT loginSID,user_type FROM _www_ids WHERE id_project =$projectId AND (user_type = 3)";
	$res = $db->SQLexecute($sql);
	while ($row = $db->fetchRow($res))
	{
		$linkLabel = "Pop up link";
		$link = $paths['warpit_www']."survey/index.php?loginSID=".$row[0];
		$formLinks->addField('statLink',$linkLabel,'label')
		 ->setProperty('text', "'".$paths['warpit_www']."survey/index.php?loginSID=".$row[0]."'");
	   	$linksHtml .= "<br><br><b>Pop up link</b><br><br>$link <a target=_new href=$link>Click</a>";
	}
	$formLinks->addTbarItem("{text:'Create Links',iconCls:'RMicon_weblink',toolTip:'Create unique popup links',
		handler: function(){
			Ext.Msg.prompt('Create unique links','Number of links',function(btn,text)
			{
				var num = parseInt(text);
				if(num)
				{
					new RMajax().request({
						url:'webcati/_ajax/generateWwwIds/ajax.generateWwwIds.php',
						params:{
							defineUniquePopup:true,
							numLinks: num,
							id_project: $projectId
						},
						success: function(resp)
						{
							var r = Ext.decode(resp.responseText);
							if(r.success)
							{
								CallScript('webcati/_forms/buildQuestionare/forms.previewQuestion.php',{tableName : '$tableName', projectId : $projectId , id_site : r.id_site - text - 1 });
							}
						}
					});
				}
				else
				{
					Ext.Msg.alert('Error','Please enter number!');
				}
			});
		}}");

	echo $form->createForm();
	echo $form2->createForm();
	//echo $formLinks->createForm();

/*
  Old button for creating links instead Unique Link management

  {text:'Create Links',iconCls:'RMicon_weblink',toolTip:'Create unique popup links',
		handler: function(){
			Ext.Msg.prompt('Create unique links','Number of links',function(btn,text)
			{
				var num = parseInt(text);
				if(num)
				{
					new RMajax().request({
						url:'webcati/_ajax/generateWwwIds/ajax.generateWwwIds.php',
						params:{
							defineUniquePopup:true,
							numLinks: num,
							id_project: $projectId
						},
						success: function(resp)
						{
							var r = Ext.decode(resp.responseText);
							if(r.success)
							{
								CallScript('webcati/_forms/buildQuestionare/forms.previewQuestion.php',{tableName : '$tableName', projectId : $projectId , id_site : r.id_site - text - 1 });
							}
						}
					});
				}
				else
				{
					Ext.Msg.alert('Error','Please enter number!');
				}
			});
		}},
 */
echo "
$form2.on('afterrender',function(){
$form2.getForm().on('actioncomplete',function(form,action){
    if(action.type == 'load')
    {
        if($form2.getForm().findField('payType').getValue() == 1)
        {
            $form2.getForm().findField('payday_monthly').hide();
            $form2.getForm().findField('payday_weekly').show();
        }
        else
        {
            $form2.getForm().findField('payday_monthly').show();
            $form2.getForm().findField('payday_weekly').hide();
        }
    }
});
});
$form.on('afterrender',function(){
$form.getForm().on('actioncomplete',function(form,action){
	if(action.type == 'load')
	{
		Ext.getCmp('extraVarLabel_$tabId').setText( action.result.data.extraVars);
		//Marko 15.4.2015
		if(Ext.getCmp('".$tableName."_activeCheckBox').getValue() == 0){
			Ext.getCmp('".$tableName."_removeAllWebLinks').show();
		}else{
			Ext.getCmp('".$tableName."_removeAllWebLinks').hide();
		}
		//Konec
	}
});
});
var $tabId = new Ext.Panel({
	id:'$tabId',
	title:'Project properties - ".$projName." [".$projectId."]',
	closable:true,
	iconCls:'icon-options-3',
	layoutConfig:{ align:'stretch' },
	layout:'border',
 	padding: '10 10',
 	items:[{layout:'border', region:'center',items:[{
 	    xtype:'panel',
 	    region: 'north',
 	    layout: 'hbox',
 	//    layoutConfig:{align:'stretch'},
 	    autoScroll: true,
 	    height:280,
 	    items: [$form, $form2]
 	},
 	{
 		xtype: 'panel',
 		padding: '15',
 		autoScroll: true,
 		region:'center',
 		html: '$linksHtml',
 		tbar: [{
			text:'Unique Link Management',
			iconCls:'RMicon_weblink',
			handler: function(){
				addTabAuto('uniqueLinks_$projectId','webcati/_forms/buildQuestionare/forms.manageLinks.php',
					{
						id_project: $projectId,
						projName: '$projName'
					}
				);
			}
		}]
 	}
 	] },$propGrid ]
 	//html:\"<table width='100%' height='100%'><tr><td width='50%'><td id='cont_$propGrid' width='50%'></tr></table> \"
});

	mainTabPanel.add($tabId)";
if(!$_POST['uniqueNotShow'])
		echo  ".show();";
?>