// editor
var myEditor = new Array;
var ButtonGroups;
var gblId;
var userGrid;
var userRow;
// global vars
var pClass;
var pId;
var _pClass;
var _ai_pclass;
var _ai_pid;
/* activity variables */
var act;
var lastfetch=0;
var actref=new Array;
/* contracts variables */
var contract_pClass;
var contract_pId;
// used by Gantt
var ganttUrl;
var ganttDiv;

var sys = {
	init:function() {
		this.writeTo='';
		this.url=_siteurl+'/service.php';
		this.error=false;
	},

	connect:function(aform, request, writeOn) {
		var crit;
		if (writeOn) {
			this.writeTo = writeOn;
		}
		else
			this.writeTo = 'defaultDiv';
		if (aform) {
			this.error=false;
			if (document.getElementById('warning')) {
				document.getElementById('warning').style.display='none';
			}
			
			// use jquery to do this FAST
			var inputs = $('#'+aform+' :input');
			inputs.each(function() {
				//$(this).attr.("class")className = $(this).className.replace('errorNode', '');
				if ($(this).attr('c')) {
					crit = $(this).attr('c').split(',');
					switch(crit[0]) {
						case "s":
							if ($(this).val().length < crit[1] || $(this).val().length > crit[2])
								this.seterror($(this));
						break;
						case "sc":
							if ($(this).val() != document.getElementById(crit[3]).value) {
								this.seterror($(this));
							}
					}
				}
			});
			if (this.error) {
				if (document.getElementById('warning')) {
					document.getElementById('warning').style.display='block';
					document.getElementById('warning').innerHTML = 'Please update the highlighted fields';
				}
				else {
					alert("ERROR: Please update the highlighted fields");
				}
			}
			else {
				$.ajax({
					type:'POST',
					url:this.url, 
					data: $('#'+aform).serialize(), 
					success: function(data) { sys.callback(1, data); },
					error: function(data) { sys.callback(0, data); }
				});
			}
		}
		else {
			request = '&request='+request;
			$.ajax({
				type:'POST',
				url:this.url, 
				data: request, 
				success: function(data) { sys.callback(1, data); },
				error: function(data) { sys.callback(0, data); }
			});
		}
	},
	
	callback:function(stat, responseData) {
		if (stat ==1 ) {
			var split = responseData.split('//endmessage');
			if (split.length > 1) {
				div = document.getElementById(sys.writeTo);
				div.innerHTML = split[1];
				eval(split[0]);
			}
			else {
				div = document.getElementById(sys.writeTo);
				div.innerHTML = responseData;
			}
		}
		else {
			Ext.MessageBox.show({
			title: 'Network Error',
			msg: 'There is a problem with the network connection. Please ensure your computer is currently connected or contact the system administrator.',
			width:300,
			buttons: Ext.MessageBox.OK
			});
		}
		cnfjs();
		sys.processMessage();
	},
	switchView:function(req) {
		Ext.getCmp('main-panel').getUpdater().update({url:'service.php', callback: cnfjs, params:'&request='+req});
	},
	switchAdmin:function(req) {
		Ext.getCmp('main-panel').getUpdater().update({url:'service.php', callback: cnfjs, params:'&request=admin.default'});
	},
	seterror:function(item,mesg) {
		this.error = true;
		item.className = item.className + ' errorNode';
	},
	openHelp:function(module) {
		Ext.MessageBox.show({
			title: 'Help Dialog',
			msg: 'Help is under development',
			width:300,
			buttons: Ext.MessageBox.OK
		});
	},
	processMessage:function() {
		setTimeout("$('.qMessage').fadeOut('slow')", 5000);
	},
	print:function(div,t) {
		if (document.getElementById(div)) {
			var fi =document.createElement('iframe');
			fi.id = 'ifrmPrint';
			fi.style.position='absolute';
			fi.style.top = '-500px';
			document.body.appendChild(fi);
			var oIframe = document.getElementById('ifrmPrint');
			var oContent = document.getElementById(div).innerHTML;
			var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
			if (oDoc.document) oDoc = oDoc.document;
			oDoc.write("<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"js/ext-3.0.3/resources/css/ext-all.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"css/extjs/ColumnNodeUI.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"css/extjs.ext.css\"><title>"+t+"</title></head>");
			oDoc.write("<body onload='this.focus(); this.print();'>");
			oDoc.write(oContent + "</body></html>");
			oDoc.close();
		}
		else {
			Ext.MessageBox.show({
			    title: 'Error Printing',
			    msg: 'Security settings do not allow this item to be printed.',
			    width:300,
			    buttons: Ext.MessageBox.OK
			});
		}
	}
};

function loadDown() {
	Ext.getCmp('quick-panel').destroy();
	Ext.getCmp('header_ext_menu').destroy();
	Ext.getCmp('header').destroy();
	Ext.getCmp('main-panel').destroy();
	Ext.getCmp('portal').destroy();
}

function loadUp() {
    // create some portlet tools using built in Ext tool ids
    
    var toolgear = {id:'gear',handler: function(){Ext.Msg.alert('Message', 'The Settings tool was clicked.');}};
    var toolclose= {id:'close',handler: function(e, target, panel){panel.ownerCt.remove(panel, true);}}
   
    function loadAccordianData(item) {
    	item.getUpdater().update({url:item.url, callback: cnfjs, params:item.params});
    }
    function resetExtPanels() {
    	if ($('#programbook-grid').length) {
    		Ext.getCmp('programbook-grid').setHeight($(window).height()-150);
    		Ext.getCmp('programbook-grid').setWidth($(window).width()-Ext.getCmp('quick-panel').getWidth()-50);
    		Ext.getCmp('programbook-grid').getView().scrollOffset = 0;
    	}
    }
    function convert() {
    	var grid = new Ext.ux.grid.TableGrid("activity_table", {border:false});
    	grid.render();
    }
    var viewport = new Ext.Viewport({
        layout:'border',
        id:'portal',
        items:[{
            border:false,
            autoLoad:{url:'service.php',callback:cnfjs,params:'&request=common.get.header'},
            layout:'anchor',
            cls:'page-header',
            region:'north',
            id:'header',
            height:45
        },{
            region:'west',
            id:'quick-panel',
            title:'My Items',
            split:true,
            width: 250,
            collapsible: true,
            margins:'0 0 0 0',
            cmargins:'0 0 0 0',
            layout:'accordion',
			listeners: {'bodyresize': resetExtPanels},
            layoutConfig:{
                animate:true
            },
            items: [{
                title:'TimeSheet',
                autoScroll:true,
                listeners: {'beforeexpand': loadAccordianData},
                url: 'service.php',
                params: '&request=timesheet.default',
                autoLoad:{url:'service.php', callback:cnfjs, params:'&request=timesheet.default'},
                border:false,
                iconCls:'icon-extjs-ts-weekview'
            },{
                title:'Search',
                autoScroll:true,
                listeners: {'beforeexpand': loadAccordianData},
                url: 'service.php',
                params: '&request=common.search.action',
                autoLoad:{url:'service.php', callback:cnfjs, params:'&request=common.search.action'},
                border:false,
                iconCls:'icon-extjs-ts-search'
            },{
                title:'Documents',
                autoScroll:true,
                listeners: {'beforeexpand': loadAccordianData},
                url: 'service.php',
                params: '&request=common.documents.mini',
                autoLoad:{url:'service.php', callback:cnfjs, params:'&request=common.documents.mini'},
                border:false,
                iconCls:'icon-extjs-ts-document'
            }]
        },{
        	xtype:'portal',
            region:'center',
            id:'main-panel',
            border:false,
            margins:'0 0  0',
            items:[{
                columnWidth:1,
                autoScroll: false,
                items:[{
                    title: 'My Items',
                    layout:'fit',
                    autoLoad:{url:'service.php', callback:cnfjs, params:'&request=home.myitems'}
                }]
            }]
        }]
	});
}
   
function showLogin(res) {
	var addon='';
	if (res) {
		if (res.length>0 && res != 'ok'){
			addon = '<div style="padding:5px;font-size:11px;background-color:#ffffcc;">'+res+'</div>';
		}
	}
	Ext.MessageBox.show({
		closable:false,
	    title: 'Sign On ',
	    msg: addon+'Username:<br/><input type="text" id="username" name="username" value="" style="width:200px;"/><br/>Password:<br/><input type="password" id="password" name="password" value="" style="width:200px;"/><div><a href="#" onclick="passwordReset();">Forget your Password?</a></div>',
	    width:300,
	    buttons: {ok:'Sign On', cancel:'Register'},
	    fn: showLoginResults
	});
	
}

function getSiteName(id) {
	$.getJSON(_siteurl+'/license.php', {"site":id}, 
		function(data) {
			if (data.length > 0) {
				document.getElementById('sitename').innerHTML=data[0].label;
			}
			else {
				document.getElementById('sitename').innerHTML='Invalid Site Id';
			}
		}
	);
}
function getSitedata() {
	$.getJSON(_siteurl+'/license.php',{"id":$(this).val()},
		function(data) {
			$.each(data,function(i,item) {         
				$('#siteSelect').append('<option value="'+item.id+'">'+item.value+'</option>');      
			});
		});
}

function passwordReset() {
	Ext.MessageBox.hide();
	Ext.MessageBox.show({
		closable:false,
	    title: 'Reset Password',
	    msg: 'Email Address:<br/><input type="text" id="accountemail" name="accountemail" value="" style="width:200px;"/>',
	    width:300,
	    buttons: Ext.MessageBox.OKCANCEL,
	    fn: showPasswordReset
	});
}

function showConfirm(res) {
	var addon='';
	if (res) {
		if (res.length>0){
			addon = '<div style="line-height:24px;background-color:#ffffcc;">'+res+'</div>';
		}
	}
	Ext.MessageBox.show({
		closable:false,
	    title: 'Confirm Account',
	    msg: addon+'<div style="line-height:20px;">Username:&nbsp;<span style="font-weight:bold;">'+document.getElementById('simplelook').value+'</span></div>Choose Password (min 8 chars):<br/><input type="password" id="cfrmpass" name="cfrmpass" value="" style="width:200px;"/><br/>Retype Password (must match Password):<br/><input type="password" id="cfrmpass2" name="cfrmpass2" value="" style="width:200px;"/>',
	    width:300,
	    buttons: Ext.MessageBox.OK,
	    fn: showConfirmResult
	});
}

function showLoginResults(btn) {
	if (btn=='ok') {
		sys.connect(null, 'login.default&username='+document.getElementById('username').value+'&password='+document.getElementById('password').value, 'nowrite');
	}
	else if (btn=='cancel') {
		showRegister();
	}
}

function showRegister(res) {
	var addon='';
	if (res) {
		if (res.length>0){
			addon = '<div style="line-height:24px;background-color:#ffffcc;">'+res+'</div>';
		}
	}
	var str = addon + '<div style="margin-bottom:3px;">First Name:<br/><input type="text" id="register_fname" name="register_fname" style="width:200px;"/></div>';
		str +='<div style="margin-bottom:3px;">Last Name:<br/><input type="text" id="register_lname" name="register_lname" value="" style="width:200px;"/></div>';
		str +='<div style="margin-bottom:3px;">Email Address:<br/><input type="text" id="register_email" name="register_email" style="width:200px;"/></div>';
		str +='<div style="padding:5px;text-align:center;background-color:#98B4D1;border:1px solid #7F9DB9;margin-top:3px;">Please ensure you have access to the email account you entered. You must confirm your account before accessing this site.</div>';
		
	Ext.MessageBox.show({
		closable:false,
	    title: 'Site Registration (all fields are required)',
	    msg: str,
	    width:300,
	    buttons: {ok:'Register', cancel:'Cancel'},
	    fn: showRegisterResults
	});
}

function showRegisterResults(btn) {
	if (btn=='cancel') {
		showLogin();
	}
	else {
		sys.connect(null, 'login.register&fname='+document.getElementById('register_fname').value+'&lname='+document.getElementById('register_lname').value+'&email='+document.getElementById('register_email').value, 'nowrite');
	}
}

function showPasswordReset(btn) {
	if (btn=='ok') {
		sys.connect(null, 'login.reset&lookup='+document.getElementById('accountemail').value, 'nowrite');
	}
	else {
		showLogin();
	}
}

function showConfirmResult(btn) {
	if (btn=='ok') {
		if (document.getElementById('cfrmpass').value.length > 7) {
			if (document.getElementById('cfrmpass').value == document.getElementById('cfrmpass2').value)
				sys.connect(null, 'login.confirm&cfrmpass='+document.getElementById('cfrmpass').value+'&validate='+document.getElementById('validate').value, 'nowrite');
			else
				showConfirm('Error: Please make sure passwords match');
		}
		else {
			showConfirm('Error: Password must be 8 characters');
		}
	}
}

function showConfirmRegister() {
	Ext.MessageBox.show({
		closable:true,
	    title: 'Registration Successful',
	    msg: '<span style="color:#7F9DB9;font-weight:bold;">Thank you for registering.</span> The registration system just sent a confirmation email to you. Please read the email and follow the directions it contains to confirm this account.',
	    width:300
	});
}

function cnfjs() {
	var v = document.getElementById('jsscript');
	if (v) {
		eval(v.innerHTML);
		if (v.parentNode)
			v.parentNode.removeChild(v);
	}
}

function openItem(tab) {
	tab.getUpdater().update({url:tab.url, callback: cnfjs, params:tab.params+'&pid='+gblId});
}

function updatefcal(id,title,start,end) {
	var calEvent = $('#calendar').fullCalendar('clientEvents', id);
	calEvent[0].title = title;
	calEvent[0].start = start;
	calEvent[0].end = end;
	$('#calendar').fullCalendar('updateEvent', calEvent[0]);
}

function in_array( n, h ){
	var a=false;
	for(var i=0;i<h.length;i++){
	  if(n == h[i]){
	    a=true;
        break;
	  }
	}
	return a;
}

 // autocomplete variables
function findValue() {
	var sValue = li.extra[0];
}

function getPocs(li) {
	sys.connect(null, 'common.team.default&addcompany='+li.extra[0], 'teams');
}

function setCompany(li) {
	 document.getElementById('form_company').value = li.extra[0];
}

function setContact(li) {
	 document.getElementById('form_contact').value = li.extra[0];
}

function setLead(li) {
	 document.getElementById('form_task_lead').value = li.extra[0];
}

function setLaborCats(li) {
	 document.getElementById('form_laborcat').value = li.extra[0];
}

function formatItem(row) {
	return row[0];
}

function lookupAjax(){
	var oSuggest = $("#phpAjax")[0].autocompleter;
	oSuggest.findValue();
	return false;
}

sys.init();
