/* -----Global items--------------------------------------------------------------------------------------------------------------------------------------------*/ 

var settings = {
	'viewFilters':true,    // view filters when open
	'positionWidthMin':180, // position width when filters open
	'positionWidthMax':300, // position width when filters close
	'onSiteLocationMin':100, // Location width when filters open
	'onSiteLocationMax':120, // Location width when filters close
	'gridWidthMin':618,     // grid width when filters open
	'gridWidthMax':740      // grid width when filters close
};

var columns = [
		{id:'reqID', header:'reqID', width:60, sortable: true,  dataIndex: 'reqID', hidden:true, hideable:false}, 
        {id:'positionTitle', header:'position', width:(settings['viewFilters']?settings['positionWidthMin']:settings['positionWidthMax']), sortable: true,  dataIndex: 'positionTitle', css: 'white-space:normal;'}, 
        {id:'maxRate', header:'salary', width:90, sortable: true,  dataIndex: 'maxRate'}, 
        {id:'maxRate2', header:'salary', width:60, sortable: true,  dataIndex: 'maxRate2', hidden:true, hideable:false}, 
        {id:'onSiteLocation', header:'location', width:(settings['viewFilters']?settings['onSiteLocationMin']:settings['onSiteLocationMax']), sortable: true,  dataIndex: 'onSiteLocation'},
        {id:'onSiteLocationRadius', header:'location', width:60, sortable: true,  dataIndex: 'onSiteLocationRadius', hidden:true, hideable:false}, 
        {id:'addedON', header:'active since', width:100, sortable: true,  dataIndex: 'addedON'},
        {id:'contractLength', header:'duration', width:70, sortable: true,  dataIndex: 'contractLength'},
        {id:'referralFee', header:'referral fee', width:77, sortable: true,  dataIndex: 'referralFee'},
        {id:'contractOrFT', header:'contract or Full Time', width:72, sortable: true,  dataIndex: 'contractOrFT', hidden:true},
        {id:'views', header:'Popularity', width:70, sortable: true,  dataIndex: 'views', hidden:true}
];

var dataStore = null;
var dataFilters = null;

/* ------------------------------------------------------------------------------------------------------------------------------------------------------------*/


// getElementById
function getById(id)
{
	return document.getElementById(id);
}

Ext.onReady(function(){
	
	

// active since filter calendar
var activeSince = new Ext.DatePicker({
		startDay: 1, 
		listeners:{
			'select':function (activeSince,date){getById('active-since').value=date.format('m/d/Y');activeSince.hide();setFilter('active-since');}
		}
});
activeSince.render('active-since-calendar');
activeSince.hide();
//Ext.EventManager.on('active-since', 'click',  function(e) {if (isDate(getById('active-since').value))activeSince.setValue(new Date(getById('active-since').value));activeSince.show();if (!e) var e = window.event;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation();});
Ext.EventManager.on('active-since-img', 'click',  function(e) {activeSince.show();if (!e) var e = window.event;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation();});
Ext.EventManager.on('body', 'click',  function() {activeSince.hide();});

	
Ext.state.Manager.setProvider(new Ext.state.Provider());
		
var ds = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({
		url:'grid.php'
	}),
	reader: new Ext.data.JsonReader({
		totalProperty: 'data.total',
		root: 'data.results'
	}, Ext.data.Record.create([
		{name: 'positionTitle'},
		{name: 'maxRate'},
		{name: 'maxRate2'},
		{name: 'onSiteLocation'},
		{name: 'addedON'},
		{name: 'contractLength'},
		{name: 'referralFee'},
		{name: 'contractOrFT'},
		{name: 'views'}])),
	sortInfo: {field: 'addedON', direction: 'DESC'},
	remoteSort: true
});
		
var filters = new Ext.ux.grid.GridFilters({filters:[
		{type: 'numeric', dataIndex: 'maxRate'},
		{type: 'numeric', dataIndex: 'maxRate2'},
		{type: 'string',  dataIndex: 'onSiteLocation'},
		{type: 'numeric',  dataIndex: 'onSiteLocationRadius'},
		{type: 'date',  dataIndex: 'addedON'},
		{type: 'list',  dataIndex: 'contractLength', options: ['Full Time', '3-6 months', '6-12 months', '12 months'], phpMode: true},
		{type: 'string',  dataIndex: 'contractOrFT'},
		{type: 'numeric',  dataIndex: 'views'}
]});
//console.log(filters)
filters.addFilter({type:'date', dataIndex:'addedON'}); // , value:{'after':new Date('<?php echo date('m/d/Y', time() - (30 * 24 * 60 * 60));?>')}

var cm = new Ext.grid.ColumnModel(columns);
cm.defaultSortable = true;

// paging bar
var paging = new Ext.PagingToolbar({
	  pageSize: 20,
	  store: ds,
	  displayInfo: true,
	  displayMsg: '{2} live jobs | {0}-{1} displayed ',
	  emptyMsg: "No jobs to display",
	  prependButtons: true
});
// paging 2
var paging2 = new Ext.PagingToolbar({
	  pageSize: 20,
	  store: ds,
	  displayInfo: true,
	  displayMsg: '{2} live jobs | {0}-{1} displayed ',
	  emptyMsg: "No jobs to display",
	  prependButtons: true
});

 var grid = new Ext.grid.GridPanel({
 	id: 'jobs',
 	el: 'searchResultsGrid',
	ds: ds,
    store: ds,
    cm: cm,
	plugins: filters,
   // height:'auto',
    height:750,
    width:(settings['viewFilters']?settings['gridWidthMin']:settings['gridWidthMax']),
    autoExpandMax:true,
   // frame: true,
    stripeRows: true,
    disableSelection:true,
    tbar:paging,
    bbar:paging2
});

// click row open win
grid.on('rowclick', function(grid, rowIndex, e){
	
//	 if (!e) 
//    var e = window.event;
//    e.cancelBubble = true;
//    if (e.stopPropagation) 
//    	e.stopPropagation();         
    	
      var rec = grid.store.getAt(rowIndex);
      rec.set('status', !rec.get('status'));
      //console.log(rec.json['reqID'])
	 var pageTitle = rec.get('positionTitle');
	 var jobId = rec.json['reqID'];
	 showJob(jobId, pageTitle);
	 
});

grid.render();
paging.add(' <a id="btn-filter" href="#"><b>open filter menu</b></a>');
grid.doLayout();

// btn to open filters
if (settings['viewFilters'])
	document.getElementById('btn-filter').style.display='none';
else
	document.getElementById('table-filter').style.display='none';

// filters
Ext.EventManager.on('close-filter', 'click',  function() {
	document.getElementById('table-filter').style.display='none';
	document.getElementById('btn-filter').style.display='';
	grid.setWidth(settings['gridWidthMax']);
	grid.getColumnModel().setColumnWidth(0, settings['positionWidthMax']);
	grid.getColumnModel().setColumnWidth(3, 100);
	return false;
});

// filters
Ext.EventManager.on('btn-filter', 'click',  function() {
	document.getElementById('btn-filter').style.display='none';
	document.getElementById('table-filter').style.display='';
	grid.setWidth(settings['gridWidthMin']);
	grid.getColumnModel().setColumnWidth(0, settings['positionWidthMin']);
	grid.getColumnModel().setColumnWidth(3, 80);
	return false;
});


ds.load({params:{start: 0, limit: 20}});
dataStore = ds;
dataFilters = filters;



});

function loadGrid()
{
	var s = getById('desc').value;
	if (dataStore)
	{
		var filterParams = dataFilters.buildQuery(dataFilters.getFilterData());
		//console.log(dataFilters);
		dataStore.load({params:Ext.apply(filterParams, {search:s, start: 0, limit: 20})});
	}
}

function intval (mixed_var, base) 
{
    var tmp;
    var type = typeof( mixed_var );
 
    if (type === 'boolean') {
        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var) ) {
        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}

function setFilter(id)
{
	switch(id)
	{
		case 'location':
			var location = getById('location').value;					
	    	dataFilters.addFilter({type:'string', dataIndex:'onSiteLocation', "value":location});
	    	dataStore.reload({params:{start: 0, limit: 20}});			
			break;		
		case 'location-radius':
			var locationRadius = intval(getById('location-radius').value);					
			if (locationRadius>=0)
			{
				dataFilters.addFilter({type:'numeric', dataIndex:'onSiteLocationRadius', "value":{lt:locationRadius}});
	    		dataStore.reload({params:{start: 0, limit: 20}});			
			}
			break;		
		case 'salary':
			var salaryFrom = intval(getById('salary-from').value);
			var salaryTo = intval(getById('salary-to').value);
			if (salaryFrom > 0 && salaryTo > 0 && salaryFrom <= salaryTo)
			{
		    	dataFilters.addFilter({type:'numeric', dataIndex:'maxRate', "value":{gt:salaryFrom, lt:salaryTo}});
		    	dataStore.reload({params:{start: 0, limit: 20}});
			}
			else if (salaryFrom > 0)
			{
				dataFilters.addFilter({type:'numeric', dataIndex:'maxRate', "value":{gt:salaryFrom}});
				dataStore.reload({params:{start: 0, limit: 20}});
			}
			else if (salaryTo > 0)
			{
				dataFilters.addFilter({type:'numeric', dataIndex:'maxRate', "value":{lt:salaryTo}});
				dataStore.reload({params:{start: 0, limit: 20}});
			}		
			
			if (getById('salary-from').value == "" && getById('salary-to').value == "")
			{
				dataFilters.getFilter('maxRate').setActive(false);
			}	
			break;
		case 'hourly-rate':
			var salaryFrom = intval(getById('hourly-rate-from').value);
			var salaryTo = intval(getById('hourly-rate-to').value);
		
			if (salaryFrom > 0 && salaryTo > 0 && salaryFrom <= salaryTo)
			{
		    	dataFilters.addFilter({type:'numeric', dataIndex:'maxRate2', "value":{gt:salaryFrom, lt:salaryTo}});
		    	dataStore.reload({params:{start: 0, limit: 20}});
			}
			else if (salaryFrom > 0)
			{
				dataFilters.addFilter({type:'numeric', dataIndex:'maxRate2', "value":{gt:salaryFrom}});
				dataStore.reload({params:{start: 0, limit: 20}});
			}
			else if (salaryTo > 0)
			{
				dataFilters.addFilter({type:'numeric', dataIndex:'maxRate2', "value":{lt:salaryTo}});
				dataStore.reload({params:{start: 0, limit: 20}});
			}
			
			
			if (getById('hourly-rate-from').value == "" && getById('hourly-rate-to').value == "")
			{
				dataFilters.getFilter('maxRate2').setActive(false);
			}
			
			
			break;
		case 'Full Time':
		case '3-6 months':
		case '6-12 months':
		case '12+ months':
			if (!getById('Full Time').checked || !getById('3-6 months').checked || !getById('6-12 months').checked || !getById('12+ months').checked)
			{
				var checked = [];
				if (getById('Full Time').checked) checked[checked.length] = 'Full Time';
				if (getById('3-6 months').checked) checked[checked.length] = '3-6 months';
				if (getById('6-12 months').checked) checked[checked.length] = '6-12 months';
				if (getById('12+ months').checked) checked[checked.length] = '12+ months';
		   		dataFilters.addFilter({type: 'list',  dataIndex: 'contractLength', options: ['Full Time', '3-6 months', '6-12 months', '12 months'], phpMode: true, 
		   			value:checked.join(',')});
				dataStore.reload({params:{start: 0, limit: 20}});				
			}
			else
			{
				dataFilters.getFilter('contractLength').setActive(false);
			}
			break;
		case 'active-since':
			if (getById('active-since').value == "")
			{
				dataFilters.getFilter('addedON').setActive(false);
				//dataStore.reload({params:{start: 0, limit: 20}});
				
			}
			else
			{
				dataFilters.addFilter({type:'date', dataIndex:'addedON', value:{'after':new Date(getById('active-since').value)}});
				dataStore.reload({params:{start: 0, limit: 20}});
			}
			break;
	}
	
}

function clearFiler(id)
{
	switch(id)
	{
		case 'active-since':
			getById('active-since').value = '';
			dataFilters.getFilter('addedON').setActive(false);
			break;
	}
	
}

var pressTime = 0;
var timer = null;
function setFilterDelay(type)
{
	var elapsed = new Date().getTime() - pressTime;
	if (elapsed < 1000 && timer)
	{
		clearTimeout(t);
		var t=setTimeout(function(){setFilter(type)},1000);
		return;
	}
	
	pressTime = new Date().getTime();
}

function isDate(sDate) {
   var re = /^\d{2}\/\d{2}\/\d{4}$/
   if (re.test(sDate)) {
      var dArr = sDate.split("/");
      var d = new Date(sDate);
      return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
   }
   else {
      return false;
   }
}


var winJob = null;
var jobid = 0;

function showJob(reqID, pageTitle, e)
{
	  winJob = new Ext.Window({
            autoLoad:{url:'applyjobwin.php?id='+reqID,scripts:true},
            title: pageTitle,
            width:800,
            height:600,
            draggable:false,
            closable:true,            
            plain:true,
            modal:true,
            autoScroll:true,
            border:false
        });
		jobid = reqID;
        winJob.show();
        if (!e) var e = window.event;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation();
}

function shareThis(sTitle, sUrl)
{
	//if (SHARETHIS)
	{
		SHARETHIS.addEntry({title:sTitle,url:sUrl},{button:false,popup:true}).attachButton(document.getElementById("share"));
	}
}

function showNotifyWin()
{
	window.open("emailnotification.php","emailnotification","menubar=no,width=450,height=300,toolbar=no");
	return;
	var win = new Ext.Window({
            autoLoad:'',
            width:450,
            height:300,
            draggable:false,
            closable:true,            
            plain:true,
            modal:true,
           // resizable:false,
            autoScroll:true,
            border:false
        }).show();

}

// facebook share
function fbs_click() 
{
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}