(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;
    Event.onDOMReady(function() {
        icsLayout = new YAHOO.widget.Layout({
            units: [
                { position: 'top', height: (noLogin?89:120), body: 'header'},
                { position: 'bottom', height: 42, body: 'footer' },
                { position: 'left', width: 200, body: 'sideBar', scroll: true},                
                { position: 'center', body: 'centerContent', scroll:true}
                //{ position: 'right', width: 200, body: 'infoBar', scroll: true, collapse:'true'}                      
            ]
        });
        icsLayout.render();   
        document.getElementById('yui-gen7').style.backgroundImage='url(images/centerBack.jpg)';
        if (!noLogin) {
        	var urlVars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
         
            for(var i = 0; i < hashes.length; i++) {
            	hash = hashes[i].split('=');
                urlVars.push(hash[0]);
                urlVars[hash[0]] = hash[1];
                appData.urlClaimID = urlVars['id']
            }
            if (!urlVars['action'])	urlVars['action'] = 0;
            switch (urlVars['action']){
            	case 'claim':
            		if (userSession.utype == 127){
            			var sql = "SELECT tblClaims.LossID FROM tblClaims WHERE ClaimID="+appData.urlClaimID;
            		} else {
            			var sql = "SELECT tblClaims.LossID FROM tblClaims INNER JOIN mapCompaniesToLosses ON tblClaims.LossID=mapCompaniesToLosses.LossID WHERE ClaimID="+appData.urlClaimID+" AND CompanyID="+userSession.cid;
            		}
            		appData.runSQL(sql, catchLossID);
            		break;
            	case 'form':
            		switch (urlVars['form']){
            			case 'HHG':
            				var json=new Object();
            				json.id=urlVars['id'];
            				loadForm('rvwHHG','center', 0, json);
            				break;
            			case 'Salvage':
            				var json=new Object();
            				json.id=urlVars['id'];
            				loadForm('rvwSalvage','center', 0, json);
            				break;
            			default:
            				menu('home');
            				break;
            		}
            		break;
            	default:
            		menu('home');
            }
        }else{
        	loadForm('addContact');
        }
    });
})();

function externalWindow(URL,Handle){
	window.open(URL,Handle);
}

function menu(option){
	//Menu Items must be added here.
	var items=new Array('home','search','addClaim','reports');
	var item;
	for (var i=0;i<items.length;i++){
		item=document.getElementById(items[i]);
		item.setAttribute('class',((items[i]==option)?'curPage':''));
	}
	appData.thisSect=option;
	appData.prevSect='none';
	appData.clearLoss();
	if (option=='addClaim'){
		loadForm('claimSide','left');
		loadForm('addClaim');
	}
	else loadForm(option);
}

function loadForm(formName, unit, ID, json){
	var AjaxCall = {
		handleSuccess:function(o){
			this.processResult(o);
		},
		handleFailure:function(o){
			// Failure Handler
			//TODO: Add Error Handling
			alert(formName+' failed to load');
			if (unit=='center') loadingScreen.hide();
		},
		processResult:function(o){		
			switch (unit){
				case 'left':
					element='sideBar';
					break;
				case 'right':
					element='infoBar';
					break;
				case 'dialog':
					element=appData.dialog.id;
					break;
				default:			
					element='centerContent';
			}
			var returnSplit=o.responseText.split('~||~');
			var replace=document.getElementById(element);
			replace.innerHTML=returnSplit[0];
			myLayout=icsLayout.getUnitByPosition('center');
			myLayout.body.scrollTop = 0;
			//Run JavaScript from bottom of page as delineated by the double pipe
			if (returnSplit[1]) eval(returnSplit[1]);
			//Move scroll to top or bottom depending on form
			if (element=='centerContent'){
				if (appData[formName]){
					if (ID) 
						if (appData[formName].retrieve)
							appData[formName].retrieve(ID);
						else
							appData.retrieve(formName,ID)
					else if (appData[formName].preInsert) 
						appData[formName].preInsert();
				} else if (appData[formName])if(appData[formName].preInsert) appData[formName].preInsert(); {
					appData.show();
				}
			} else if (unit=='dialog') {
				appData.createDialog();
			}
		},
		startRequest:function(){
			if (unit=='dialog'){
				if (appData.dialog){
					delete appData.dialog;
					oldDiv=document.getElementById('dialog');
					oldDiv.parentNode.removeChild(oldDiv);
				}
				strName = "dlg"+Math.floor(Math.random()*1000000)
				newDiv = document.createElement('div');
				newDiv.id = 'dialog';
				document.getElementById('body').appendChild(newDiv);
				appData.dialog=new Object();
				appData.dialog.id=strName;
				subDiv = document.createElement('div');
				subDiv.id = strName;
				document.getElementById('dialog').appendChild(subDiv);				
			}
			if (!unit) unit='center';
			if(json){
				document.getElementById('txtJson').value=json_encode(json);
				YAHOO.util.Connect.setForm(document.getElementById('json'));
			}
			else document.getElementById('txtJson').value='';
			YAHOO.util.Connect.asyncRequest('POST', 'includes/forms/'+formName+'/'+formName+'.php',callback);			
		}
	};
	var callback =
	{
		success:AjaxCall.handleSuccess,
		failure:AjaxCall.handleFailure,
		scope:AjaxCall
	};
	AjaxCall.startRequest();
}

function loadData (lossID, claimID){
	var json=new Object;
	
	if (lossID) json.lossID=lossID;
	if (claimID) json.claimID=claimID;
	//save the value of json to a variable so it can be retrieved when dataload is opened from claimSide
	appData.json=json;
	loadForm('claimSide','left','','loadOnly=1;');	
}
function goSearch(criteria){
	var json=new Object;
	
	if (criteria=='GO'){
		if (!document.getElementById('txtClaimNumberSearch').value){
			alert('Please type in a claim number first');
			return;
		}
		json.where="tblClaims.ClaimNum Like '%"+document.getElementById('txtClaimNumberSearch').value+"%' AND ";
	}
	else json.where=criteria;
	
	loadForm('searchSide','left')
	loadForm('searchResults','','',json);
	document.getElementById('txtClaimNumberSearch').value='';
}

////////////////////////////////////////////////////////////////////////////////////////////////
//This function's sole purpose is to catch the LossID of the SQL statement that is run during 
//if (!noLogin) (near the top of the page) and then pass the result into loadData.
////////////////////////////////////////////////////////////////////////////////////////////////
function catchLossID(result) {
	if (result[2]) {
		var result = result[2][0]['LossID'];
		loadData(result, appData.urlClaimID);
	} else {
		document.getElementById('centerContent').innerHTML = "<div class='centerContent'><br><br><br><br>**** Sorry, but you are not able to view this claim. ****</div>";
	}
}
////////////////////////////////////////////////////////////////////////////////////////////////
//This function is designed to check and see if the enter key has been pressed and return true
//if it has been pressed.
////////////////////////////////////////////////////////////////////////////////////////////////
function checkEnter(e)
{
	var keynum;
	
		if (window.event) // IE
		{
			keynum = e.keyCode;
	
			if (keynum == 13)
				return true;
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which;
			
			if(keynum == 13)
				return true;
		}
}
function createAC(inputFieldID,container,txtHiddenFieldID,qry)
{
    var oDS = new YAHOO.util.DataSource("ajax/json_proxy.php?");
    oDS.responseType = YAHOO.util.DataSource.TYPE_JSON;
    oDS.responseSchema =
    {
        resultsList: "records",
        fields: ["Description", "ID"],
        metaFields: {totalRecords: "totalRecords"}
    };

    oAC = new YAHOO.widget.AutoComplete(inputFieldID, container, oDS);
    oAC.resultTypeList = false;
    oAC.queryDelay = .25;

    oAC.generateRequest = function(sQuery)
    {
        return "results=10&ac="+qry+"&query=" + sQuery ;
    };

    var idField = YAHOO.util.Dom.get(txtHiddenFieldID);
    var setId = function(sType, aArgs)
    {
        var myAC = aArgs[0]; // reference back to the AC instance
        var elLI = aArgs[1]; // reference to the selected LI element
        var oData = aArgs[2]; // object literal of selected item's result data
        idField.value = oData.ID;
    };

    oAC.itemSelectEvent.subscribe(setId);
    return { oDS: this.oDS, oAC: this.oAC};
}; 

loadingScreen = new YAHOO.widget.Panel("loading", {
	fixedcenter : true,
	visible : false, 
	constraintoviewport : true,
	draggable: true,
	modal: true,
	resize: true
});
loadingScreen.render();
