	var startTab=0;
	var validLogin=false;
	var SCREEN_QUESTIONS=1;
	var SCREEN_LIST=2;
	var SCREEN_CATEGORY=3;
	var Screen=0;
	var isKiosk;
	var tdiv='';
	var changed=false;
	var curCat='';
	var curSys='';
	var api;
	var onLoadSys='';
	var resetSys='';
	var onLondCat='';
	var lastQuoteNum='';
	var lastQuoteJob='';
	var partAccordion;
	var partAccordion2;
	var loggingIn=false;
	var selectedHeaderIndex=0;
	var IE = document.all?true:false;
	var tempX = 0;
	var tempY = 0;
	var exp;
	var tempPart;
	var lastParts=new Array(0);
	var ticker;

	
	function showImpersonation(){
		showDiv('impModal');
	}

	function updateImpersonation(i){
		$.ajax({
			url: '/admin_changeImpersonationDo.php?i=' + i + '&refresh=' + randomString(),
			success: function(data) {

				if (typeof refreshPageUserInfo == 'function') {
					refreshUserInfo();
					refreshPageUserInfo();
					refreshAdminWarning();
				}else{
					window.location=window.location.href;
				}
			}
		});					
	}
	
	function updateShoppingCart(){
		var url= '/shoppingCartMenu.php?summary=true&refresh=' + randomString();
		setLoading('shoppingCart2',true,true,true);				
		$('#shoppingCart2').load(url);
	}
	function doSearch(v){
		var url= '/search.php?find=' + encodeURIComponent(v);
		window.location=url;
	}
	function doCheckStock(m, q){
		$("#stockStatus").hide();
		var qty = document.getElementById(q).value;
		var url= '/doCheckStock.php?m=' + encodeURIComponent(m) + '&q=' + qty + '&refresh=' + randomString();
		$("#stockStatus").load(url, function(){
			$("#stockStatus").show();
		});
	}

	function doAddPartToCart(m, q){
		var qty = document.getElementById(q).value;
		var url= '/addPartToCart.php?m=' + encodeURIComponent(m) + '&q=' + qty + '&refresh=' + randomString();
		$.ajax({
			url: url,
			success: function(data) {
				document.getElementById(q).value='0';
				updateShoppingCart();
			}
		});			
	}

	function refreshAdminWarning(){
		if (!$("#employeeWarning")) return;
		$('#employeeWarning').html('').hide();	
		var j=array2json(lastParts);
		var url= '/employeeWarning.php?refresh=' + randomString();
		$.ajax({
			url: url,
			success: function(data) {
				var a = data.replace(/^\s*/, "").replace(/\s*$/, "");
				if (a.length>0){
					$('#employeeWarning').animate({
						height: 'toggle'
					}, 500, function() {
						document.getElementById('employeeWarning').innerHTML=a;
					});					
				}
			}
		});	
	}

	function refreshUserInfo(){
		if (!$('#userInformation')) return;
		
		setLoading("userInformation",true,false,true);

		var j=array2json(lastParts);
		var url= '/getUserInfo.php?refresh=' + randomString();
		$.ajax({
			url: url,
			success: function(data) {
				var a = data.replace(/^\s*/, "").replace(/\s*$/, "");
				var ind=a.indexOf("@");
				$('#userInformation').html(a);					
				validLogin = (ind>=0);
				if (document.getElementById('sidemenu'))
					updateSideMenu();
				updateShoppingCart();
			}
		});		
	}


	function initializePage2(){
		//document.domain = "alphacommunications.com";
		refreshUserInfo();	
		autosizeIframe(false);		
	}		
	function initializePage(c,s,k){
		//document.domain = "alphacommunications.com";
		onLoadSys=s;
		onLoadCat=c;
		isKiosk=k;
		refreshUserInfo();	
		$.easing.drop = function (x, t, b, c, d) {
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
		};
		$.easing.easeInOutQuad= function (x, t, b, c, d) {
			if ((t/=d/2) < 1) {return (c/2*t*t + b);}
			return (-c/2 * ((--t)*(t-2) - 1) + b);
		};
		$.tools.overlay.addEffect("drop", function(css, done) { 
		   var conf = this.getConf(), overlay = this.getOverlay();           
		   if (conf.fixed)  {
		      css.position = 'fixed';
		   } else {
		      css.top += $(window).scrollTop();
		      css.left += $(window).scrollLeft();
		      css.position = 'absolute';
		   } 
		   overlay.css(css).show();
		   overlay.animate({ top: '+=100',  opacity: 1  }, 400, 'easeInOutQuad', done);
		   }, function(done) {
		      this.getOverlay().animate({top:'-=100', opacity:0}, 300, 'easeInOutQuad', function() {
		         $(this).hide();
		         done.call();      
		      });
		   }
		);	
		getSystemSelector(c,false);
		if ($('#buttons-expanded').length>0){
			$('#buttons-expanded').jsShare({
				maxwidth: 360, 
				yoursitetitle : $('title').html(),
				yoursiteurl : window.location.href,
				yoursitename : 'Alpha Communications&trade;' 
			});
		}

		
	}

	function refreshSys(v){
		setLoading("partLoading",true,false,true);
		$('#modlno').html('&nbsp');
		var url= '/alphaquote/sysDetails.php?c=' + encodeURIComponent(curCat) + '&s=' + encodeURIComponent(v) + '&refresh=' + randomString();
		
		$.ajax({
			url: url,
			success: function(data) {
				setLoading("partLoading",false,false,true);
				var ak = data.replace(/^\s*/, "").replace(/\s*$/, "");
				var a = ak.split("~JAG~");				
				$('#modlno').html(a[0]);
				$('#partDetails').html(a[1]);	
				partAccordion2 = $("#accordion2").accordion({
					autoHeight: false,
					collapsible:true,
					active:0,
					autoScrollToActive: false,
					autoScrollOffset: 0,
					navigation:true,
					icons: false,
					change: 
						function(event, ui) { 
							autosizeIframe(false);
						}
				});		
			    if (document.getElementById('mycarouselRel')) {
			    	var c=$('#mycarouselRel').roundabout({
			    		tilt: 3
			    	});

		    	}			
			}
		});		
	}

	function refreshPartModal(v){
		setLoading("partLoading",true,false,true);
		$('#modlno').html('&nbsp');
		var url= '/alphaquote/partDetails.php?m=' + encodeURIComponent(v) +'&recent=' + encodeURIComponent(j) +'&refresh=' + randomString();

		$.ajax({
			url: url,
			success: function(data) {
				setLoading("partLoading",false,false,true);
				var ak = data.replace(/^\s*/, "").replace(/\s*$/, "");
				var a = ak.split("~JAG~");				
				$('#modlno').html(a[0]);
				$('#partDetails').html(a[1]);	
				
				partAccordion2 = $("#accordion2").accordion({
					autoHeight: false,
					collapsible:true,
					active:0,
					autoScrollToActive: false,
					autoScrollOffset: 0,
					navigation:true,
					icons: false,
							change: 
								function(event, ui) { 
									autosizeIframe(false);
								}
				});		
			    if (document.getElementById('mycarouselRel')) {
			    	var c=$('#mycarouselRel').roundabout({
			    		tilt: 3
			    	});

		    	}
			}
		});


	}		
	function refreshPart(v){
		$('#modlno').html(v);
		lastParts.push(v);
		while (lastParts.length>6)
			lastParts.shift();
		setLoading("partLoading",true,false,true);
		var j=array2json(lastParts);
		var url= '/alphaquote/partDetails.php?m=' + encodeURIComponent(v) +'&recent=' + encodeURIComponent(j) +'&refresh=' + randomString();

		$.ajax({
			url: url,
			success: function(data) {
				setLoading("partLoading",false,false,true);
				var a = data.replace(/^\s*/, "").replace(/\s*$/, "");
				document.getElementById('partDetails').innerHTML=a;	
				partAccordion2 = $("#accordion2").accordion({
					autoHeight: false,
					collapsible:true,
					active:0,
					autoScrollToActive: false,
					autoScrollOffset: 0,
					navigation:true,
					icons: false
				});
			    if (document.getElementById('mycarouselRel')) $('#mycarouselRel').roundabout();			
			}
		});	
	}
	function makeList(){
		var json=JSON.stringify($('#mainForm').serializeObject());
		var url= '/alphaquote/makeList.php';
		var data = 'j=' + encodeURIComponent(json) + '&refresh=' + randomString();
		Screen = SCREEN_LIST;

		for (x=0; x<=200; x++){
			if (document.getElementById('Q' + x)){
				if (document.getElementById('Q' + x).className != 'select'){
					document.getElementById('Q' + x).className='select';
				}
			}
			if (document.getElementById('quesheader' + x)){
				if (document.getElementById('quesheader' + x).className != 'questionHeader'){
					document.getElementById('quesheader' + x).className='questionHeader';
				}
			}
		}			
		setLoading("submitLoading",true,false,true); 
		
		$.ajax({
			url: url,
			data: data,
			type: 'POST',
			success: function(data) {
				document.getElementById("submitLoading").innerHTML='<img src="images/submit.png" />'; 
				var a = new Array();
				a=data.replace(/^\s*/, "").replace(/\s*$/, "");
				var found=false;
				if (a.substring(0,5)=="Error"){
					var arr=a.split("|");
					var message=arr[1];
					var ay=arr[2].split(",");
					var ay2=arr[3].split(",");
					for (x=0; x<ay.length; x++) 
						if (document.getElementById(ay[x]))
							document.getElementById(ay[x]).className='selectError';
					for (x=0; x<ay2.length; x++) {
						if (document.getElementById('quesheader' + ay2[x])) document.getElementById('quesheader' + ay2[x]).className='questionHeaderError';
						if (selectedHeaderIndex == parseInt(ay2[x])) found=true;
					}
					if (!found) partAccordion.accordion( "activate", parseInt(ay2[0]) );	
					showError(message, "Error");	
				} else {
					window.scroll(0,0);
					$('#results').html(a);
					
											
					
					if (!changed && lastQuoteNum.length>0) {
						document.getElementById('quoteNumber').innerHTML= '<font class="bigReg"><b>Quote #</b>' + lastQuoteNum + '</font>';
						document.getElementById('quoteJob').innerHTML= '<font class="bigReg"><b>Project/Job:</b> ' + lastQuoteJob + '</font><hr>';

						
						setVisible('quoteJob',false);
						setVisible('quoteNumber',false);
						
						setVisible('quoteJob',true);
						setVisible('quoteNumber',true);
						
						document.getElementById('btnSaveQuote').innerHTML='Quote #' + lastQuoteNum +' Saved' ;
						document.getElementById('btnSaveQuote').disabled=true;					
						document.getElementById('btnSaveQuote2').innerHTML='Quote #' + lastQuoteNum +' Saved' ;
						document.getElementById('btnSaveQuote2').disabled=true;	
					}
					showParts();
					autosizeIframe(true);	
				}
			}
		});
	
	}
	
		
	
	
	function doLogin(){
		loggingIn=true;
		setLoading("loginLoading",true,false,true); 
		var u = document.getElementById('loginusername').value;
		var p = document.getElementById('loginpassword').value;
		var a = document.getElementById('loginaccount').value;
		var r = document.getElementById('loginremember').value;
		var url= '/login.php?username=' + encodeURIComponent(u) + '&remember=' + encodeURIComponent(r) + '&password=' + encodeURIComponent(p) + '&account=' + encodeURIComponent(a) + '&doecho=Y&refresh=' + randomString();

		$.ajax({
			url: url,
			success: function(data) {
				var a = data.replace(/^\s*/, "").replace(/\s*$/, "");

				if (a=="OK"){
					if (api) api.close();
					updateAllUserInfo();
				} else {
					showError(a,'Login Error');
				}
				setLoading("loginLoading",false,false,true);	
			}
		});
	}
	
	function checkLoginKeyPress(e){
			var keynum;
			if(window.event) // IE
				keynum = e.keyCode;

			else if(e.which) // Netscape/Firefox/Opera
				keynum = e.which;
	
			if (keynum==13) doLogin();

	}
	
	function updateAllUserInfo(){
		if (Screen == SCREEN_LIST){
			makeList();	
			updateSystemSelectBoxOnly(curCat);
			
		} else if (Screen == SCREEN_CATEGORY){
			updateSystems(curCat)
			
		} else if (Screen == SCREEN_QUESTIONS){
			
			updateSystemSelectBoxOnly(curCat);
			updateQuestions(curSys);
			
			
		}	else {
			if ($.isFunction(updateSystemSelectBoxOnly))
				updateSystemSelectBoxOnly(curCat);
		}
		refreshUserInfo();
		//refreshAdminWarning();
		if (typeof window.refreshPageUserInfo == 'function'){
			refreshPageUserInfo();
		}	
		
			
	}
	
	function logout(){
		loggingIn=false;
		if (confirm("Are you sure you want to logout?")){
			$.ajax({
				url: '/logout.php',
				success: function(data) {
					updateAllUserInfo();	
				}
			});
		}
	}

	
	function saveQuote(){
		var p = document.getElementById('partsForm');
		var f = document.getElementById('saveQuoteForm');
		p.sendvia.value=f.sendvia.value;
		p.quattn.value=f.quattn.value;
		p.jobname.value=f.jobname.value;
		
		var json=JSON.stringify($('#partsForm').serializeObject());
		var url= '/alphaquote/saveQuote.php';
		$.ajax({
			url: url,
			data: 'json=' + encodeURIComponent(json) + '&refresh=' + randomString(),
			type:'POST',
			success: function(data) {
				var a = data.replace(/^\s*/, "").replace(/\s*$/, "");
				if (a.length==0) return;
				var arr;
				if (a.substring(0,5)=="Error"){
					arr=a.split("|");
					var message=arr[1];
					showError(message,'Error');
			
				} else {
					arr=a.split("|");
					var qNum=arr[1];
					var p = document.getElementById('partsForm');				
					lastQuoteJob = p.jobname.value;
					lastQuoteNum=qNum;
					document.getElementById('quoteNumber').innerHTML= '<font class="bigReg"><b>Quote #</b>' + lastQuoteNum + '</font>';
					document.getElementById('quoteJob').innerHTML= '<font class="bigReg"><b>Project/Job:</b> ' + lastQuoteJob + '</font><hr>';				
					document.getElementById('btnSaveQuote').innerHTML='Quote #' + lastQuoteNum +' Saved' ;
					document.getElementById('btnSaveQuote').disabled=true;
					document.getElementById('btnSaveQuote2').innerHTML='Quote #' + lastQuoteNum +' Saved' ;
					document.getElementById('btnSaveQuote2').disabled=true;
					updateChanged(false);
					api.close();
					autosizeIframe(false);		
				}
			}
		});
	}
	

	
	function getSystemSelector(v, skipQuestions){
		
		resetSys = ((skipQuestions) ? document.getElementById('curSystem').value : "");
		var url = '/alphaquote/getSystemSelector.php?i=' +v;
		$.ajax({
			url: url,
			success: function(data) {
				var a = new Array();
				a=data.replace(/^\s*/, "").replace(/\s*$/, "");
				document.getElementById('systemSelector').innerHTML=a;	

				if (onLoadCat.length>0) {
					disableSystemSelector(true);
					updateSystems(onLoadCat);
					onLoadCat='';
				} else if (resetSys.length>0) {
					return;
				} else {
					onLoadSys='';
					getMain();
				}		
				autosizeIframe(false);		
			}
		});
	
	}
	
	function updateSideMenu(){
		var url = '/sidemenu.php';
		$('#sidemenu').load(url, function  () {
			initSideBar();
		});
	}	
	
	function initSideBar(){
	
		$(".sideTab_content").hide(); //Hide all content
		
		if (startTab > 0 && $('#sideMenuTab' + startTab)) {
			
			var s = '';
			if (startTab==0) s='menuTab';
			if (startTab==1) s='accountTab';
			if (startTab==2) s='adminTab';
			
			$("ul.sideTabs li").removeClass("active");
			$('#sideMenuTab' + startTab).addClass("active").show(); //Activate first tab
			$('#'+s).show();
			
		}else{	
			$("ul.sideTabs li:first").addClass("active").show(); //Activate first tab
			$(".sideTab_content:first").show();
		}
		//On Click Event
		$("ul.sideTabs li").click(function() {
	
			$("ul.sideTabs li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".sideTab_content").hide(); //Hide all tab content
	
			var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			return false;
		});	

		if ($("#accountTab").length==0 && $("#adminTab").length==0)
			$("#cont1").css("border","1px solid #999999");	

		//if (startTab > 0 && $('#sideMenuTab' + startTab)) 
		//	$('#sideMenuTab' + startTab).trigger('click');

		ticker = $("#ticker");

		if (ticker){
			
			ticker.children().filter("dt").each(function() {
			  var dt = $(this), container = $("<div>");
			  dt.next().appendTo(container);
			  dt.prependTo(container);
			  container.appendTo(ticker);
			});
	
			ticker.css("overflow", "hidden");
			
			
			var t=setTimeout("animator(ticker.children(':first'))",3000);
		
			ticker.mouseenter(function() {
				ticker.children().stop();
			});
			
			ticker.mouseleave(function() {
				animator(ticker.children(":first"));
			});				
		}		
	}
	
	function initializeTabs(){
		$(".mainTab_content").hide(); //Hide all content
		$(".mainTab_content:first").show(); //Show first tab content
		$(".sideTab_container").find("li").css('list-style', 'none');
		/*
		var arr = window.location.href.split('/');
		if (arr[arr.length-1] != "test.php" ) return;

		$('.mainTabs li').hover(function(){
			var id = $(this).attr('id');
			var dropId = id + 'Drop';
			
			$('.menuDrop[id!="' + dropId + '"]').hide();
			
			if($('#' + dropId).length==0){
				
				
				
				var x = $(this).position().left;
				var y = $(this).position().top + 32;
				
				var html="<div class='menuDrop' id='" + dropId + "'><img src='/alphaquote/images/loading.gif' /></div>";
				$('body').append(html);
				
				$('#' + dropId).css({
					top: y + 'px',
					left: x + 'px'
				});
				
				$('#' + dropId).load(id + '.php');
				
				
			}
			$('#' + dropId).fadeIn('fast');
						
		}, function(){

			
		});		
		*/
	}	
	
	
	//animator function
	function animator(currentItem) {
	  	//work out new anim duration
		var distance = currentItem.height();
		var speed =  0.015; //lower = slower
		var duration = (distance + parseInt(currentItem.css("marginTop"))) / speed;
		
		currentItem.animate({ marginTop: -distance }, duration, "linear", function() {
			currentItem.appendTo(currentItem.parent()).css("marginTop", 0);
			animator(currentItem.parent().children(":first"));
		}); 
	};

	
	function autosizeIframe(v){
		var nm= ((v) ? 'results' : 'content');
		var h = $('#' + nm).height()+250;
			
		try {
			$('#aqFrameSlider', window.parent.document).animate({"height": h}, 100);
		} catch(e) {
			try {
				parent.getElementById('aqFrameSlider').height=h;
			} catch(e2) {
				
				try {
					window.parent.adjust(h);
				} catch(e3) {
					try {
						window.parent.adjust(h);
					} catch(e4) {
						
					}					
				}				
			}			
		}
	}
	
	function updateSystemSelectBoxOnly(i){
		if (i.length == 0) return; 
		if (checkSaved()){
			hideParts();
			if (i=='-1'){
				$("#systems").html('');
				getMain();
				return;
			}
			
			
			disableSystemSelector(true);
			curCat=i;
			var url = '/alphaquote/getSystems.php?cat=' + i + '&r=' + resetSys;
			$.ajax({
				url: url,
				success: function(data) {
					var a = data.split('~JAG~');
					$('#systems').html(a[0]);
					$('#curSystem').val(curSys);		
					disableSystemSelector(false);		
				}
			});
		} else {
			$('#curCat').val(curCat);
		}	
	}	
	
	function updateSystems(i){
		
		if (checkSaved()){
			hideParts();
			if (i=='-1'){
				$("#systems").html('');
				getMain();
				return;
			}
			
			
			disableSystemSelector(true);
			curCat=i;

			var url = '/alphaquote/getSystems.php?cat=' + i + '&r=' + resetSys;	
			setLoading("systems",true,false,true);
			setLoadingWithText("questions",true,"[ Loading Category Systems ]<br /><br /></b>This may take a few moments.");
				 
			$.ajax({
				url: url,
				success: function(data) {
					var a = data.split('~JAG~');
					$('#systems').html(a[0]);
					Screen = SCREEN_CATEGORY;
					if (a[1]=="ERR"){
						$('#questions').html('<img src="images/main.png" />');
						disableSystemSelector (false);	
					}else if (onLoadSys.length>0){
						$('#curSystem').val(onLoadSys);
						updateQuestions(onLoadSys);
						onLoadSys='';
					} else {
						$('#questions').html(a[1]);
						disableSystemSelector (false);				
					}
					
					autosizeIframe(false);	
				}
			});			
		} else {
			document.getElementById('curCat').value=curCat;
		}	
	}

	function updateQuestions(i){
		
		if (checkSaved()){
			hideParts();
			if (i=='-1'){
				if (curCat>0)
					updateSystems(curCat);
				else
					document.getElementById("questions").innerHTML='';
				return;
			}			
			
		 	setLoadingWithText("questions",true,"[ Loading System Questions ]<br /><br /></b>This may take a few moments.");
			disableSystemSelector(true);
			curSys=i;
			var url = '/alphaquote/getQuestions.php?sys=' + i;
			$.ajax({
				url: url,
				success: function(data) {
					Screen = SCREEN_QUESTIONS;
					disableSystemSelector(false);	
					
					a=data.split("~JAG~");
					$('#questions').html(a[1]);
		
		
					if (a[0].length>5){
			 			var JSONCode=document.createElement("script");
			            JSONCode.setAttribute("type","text/javascript");
			            JSONCode.text=a[0];
			            
						var cell=document.getElementById("codeHolder");
						if ( cell.hasChildNodes() )
						    while ( cell.childNodes.length >= 1 )
						        cell.removeChild( cell.firstChild );
								       
						cell.appendChild(JSONCode);
					}
					partAccordion = $("#accordion").accordion({
						autoHeight: false,
						collapsible:true,
						active:0,
						autoScrollToActive: false,
						autoScrollOffset: 0,
						navigation:true,
						icons: false,
						change: 
							function(event, ui) { 
								selectedHeaderIndex= parseInt($(this).find("h3").index ( ui.newHeader[0] ));
								autosizeIframe(false);
							}
					});			
					if (a.length>2)
						if (a[2].length>0) 
							eval(a[2]);	
					autosizeIframe(false);		
				}
			});	
		} else {
			$('#curSystem').val(curSys);
		}
	}
	
	function getMain(){
		var url = '/alphaquote/main.php';
		$('#questions').load(url, function(){
			autosizeIframe(false);
		})			
	}

	function AddItem(objListBox, strText, strId) {
	  var newOpt;
	  newOpt = document.createElement("OPTION");
	  newOpt = new Option(strText,strText);
	  newOpt.id = strId;
	  newOpt.value = strId;
	  objListBox.add(newOpt);
	}
	
	function RemoveItem(objListBox, strId) {
	  var intIndex = GetItemIndex(objListBox, strId);
	  if (intIndex != -1)
	    objListBox.remove(intIndex);
	}
	
	function GetItemIndex(objListBox, strId) {
	  for (var i = 0; i < objListBox.children.length; i++)
	  {
	    var strCurrentValueId = objListBox.children[i].id;
	    if (strId == strCurrentValueId)
	    {
	      return i;
	    }
	  }
	  return -1;
	}
	
	function setVisible(div, vis){
		var cl='';
		var st=''		
		try{
			var i=(document.getElementById(div).className.indexOf('Ind')>=0);
		}catch (e){

		}
		cl = i ?'questionInd' : 'question';

		if (!vis){
			$('#'+div).hide();
		}else{
			$('#'+div).addClass(cl).slideDown('fast');
		}
	
	 	autosizeIframe(false);
		 	
	}
	function checkBlur(){
		//$('#curCat').focus();
	}	
	
	function togggleDesc(v){
		var d = document.getElementById('ldesc' + v);
		var d2 = document.getElementById('desc' + v);
		
		if (d.style.display=='none'){
			d.style.display='';
			d2.style.display='none';
		} else {
			d2.style.display='';
			d.style.display='none';		
		}
	}
	function changeSystem(v){
		$('#curSystem').val(v.toUpperCase());
		updateQuestions($('#curSystem').val());
	}
	function changeCat(v){
		$('#curCat').val(v);
		updateSystems($('#curCat').val());
	}	
	

	function showError(text,title){
		
		if ($('#errorText').length >0){
			$('#errorText').html(text);
			if (title.length==0)title='Error';
			$('#errorTitle').html(title);
			showDiv('genError');
		}else{
			alert(text);
		}	
		
	}
	
	function showParts(){
		
		$("#results").show();
		$('#divMenu').hide();
		$('#questions').hide();

		
		var p = $("#topleft").position();
		var h =  p.top + 3;
		var w =  $('#systemSelector').width();
		var l =  p.left;
		var h = $("#questions").height() + $("#systemSelector").height();
		var h2=$("#results").height();

		if (h2 < h)	$("#results").css( { "left":l+"px", "top":h+"px", "width":w+"px", "height":h+"px" } );
		
	}
	
	function hideParts(){
		$("#results").hide();
		$('#divMenu').show();
		$('#questions').show();
	}
	
	
	function checkLeaving(){
		if (changed)
			return "Changes have been made. Are you sure you want to leave this page?";
	}

	function checkSaved(){
		if (!changed || isKiosk==1) return true;
		if (confirm("Changes have been made. These changes will be lost.\r\n\r\nContinue?")){
			changed=false;
			return true;
		} else {
			return false;
		}
	}
	

	
	function disableSystemSelector(v){
		if (document.getElementById('curCat')) document.getElementById('curCat').disabled=v;
		if (document.getElementById('curSystem')) document.getElementById('curSystem').disabled=v;
	}
		
	function randomString(length) {
	    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
	    
	    if (! length) {
	        length = Math.floor(Math.random() * chars.length);
	    }
	    
	    var str = '';
	    for (var i = 0; i < length; i++) {
	        str += chars[Math.floor(Math.random() * chars.length)];
	    }
	    return str;
	}	
	
	
/////////////////////////////////////////////////////////////////////////////////	
	function setLoadingWithText(divName, isLoading, text){

		var r='';
		if (divName.length>0){
			tdiv=divName;
			var d=$("#" + divName);
			if (d.length > 0 ){
				if (isLoading){
					r=r+'<center>';
					if (isKiosk==1)
						r=r+'<img src="/kiosk/images/loading.gif" />';
					else						
						r=r+'<img src="/alphaquote/images/loading.gif" />';
					
					if (text.length==0)
						r=r+'<br /><br /><font class="reg"><b>[ Loading ]</b></font>';
					else
						r=r+'<br /><br /><font class="reg"><b>' + text + '</b></font>';
			
					r=r+'</center>';
				} else {
					r='';
				}
				d.html(r);		
			}
		}
	}
	function setLoading(divName, isLoading, isLarge, isCenter){

		var r='';
		if (divName.length>0){
			tdiv=divName;
			var d=$("#" + divName);
			if (d){
				if (isLoading){
					if (isCenter) r=r+'<center>';
					
					if (isLarge) {
						if (isKiosk==1)
							r=r+'<img src="/kiosk/images/loading.gif" />';
						else						
							r=r+'<img src="/alphaquote/images/loading.gif" />';
						
						r=r+'<br /><br /><font class="reg"><b>[ Loading ]</b></font>';
					} else {
							r=r+'<img src="/alphaquote/images/loadingSmall.gif" />';
					}					
					if (isCenter) r=r+'</center>';
				} else {
					r='';
				}
				d.html(r);
			} else {
				
			}
		}
	}	
/////////////////////////////////////////	

	try{
		$.fn.serializeObject = function()
		{
		    var o = {};
		    var a = this.serializeArray();
		    $.each(a, function() {
		        if (o[this.name]) {
		            if (!o[this.name].push) {
		                o[this.name] = [o[this.name]];
		            }
		            o[this.name].push(this.value || '');
		        } else {
		            o[this.name] = this.value || '';
		        }
		    });
		    return o;
		};	
	} catch (e){
		
	}
	function toggleDesc(v){
		var d1=document.getElementById('desc' + v);
		var d2=document.getElementById('ldesc' + v);
		
		if (d1.style.display==''){
			d1.style.display='none';
			d2.style.display='';
		} else {
			d1.style.display='';
			d2.style.display='none';			
		}
		
	}
	function showDiv(v){
		
		if (api)
			if (api.isOpened)
				api.close();
		
		if (!document.getElementById(v)) return;

		api=$('#'+v).overlay({
			mask: {
				color: '#000',
				loadSpeed: 200,
				closeOnClick: true,
				closeOnEsc: true,
				opacity: 0.75,
				maskId: v + '_Mask'
			},		
			top:'0px',
			api: true		
		}).load();
	
	}		
	
	function showDivAndLoadSys(v,t){
		
		if (api){
			if (api.isOpened){
				api.close()
			}
		}
		
		if (!document.getElementById(v)) return;
		refreshSys(t);	
		api=$('#'+v).overlay({
			mask: {color: '#000000'},	
			top:'0px',
			api: true,
			autoScrollToActive: false,
			autoScrollOffset: 0	
		}).load();

	}	
	
	function showDivAndLoad(v,t){
		
		if (api){
			if (api.isOpened){
				api.close()
			}
		}
		
		if (!document.getElementById(v)) return;
		refreshPart(t);	
		api=$('#'+v).overlay({
			mask: {color: '#000000'},	
			top:'0px',
			api: true,
			autoScrollToActive: false,
			autoScrollOffset: 0	
		}).load();

	}	
	
	function showDivAndFocus(v,t){
		
		if (api)
			if (api.isOpened)
				api.close();

		api = $('#'+v).overlay({
			mask: {color: '#000000'},	
			top:'0px',
			api: true,
			autoScrollToActive: false,
			autoScrollOffset: 0	
		}).load();
		
		$('#'+t).focus();
	}	

	function updateChanged(v){
		changed=v;
		//if (v) $.mask.close();
	}	
	
	function updateChanged2(v,n,i){
		changed=v;
		var s=document.getElementById('Q' + n).options[parseInt(i)].text;
		$('#QT' + n).val(s);
	}	
		
	function exposeItem(v, i){
		currItem=v;
		var bg;
		var bo;	
		if (i==1){
			bg='#fff';
			bo='1px solid #333';
			
			
		} else {
			bg='#fff';
			bo='1px solid #333';
						
		}
		exp=$('#'+v).expose({
			api: true,
			color:null,
			loadSpeed:'fast',
			closeSpeed:'fast',
			onLoad: function() {	
				$('#'+v).css({border: '1px solid #001975',background:'#fff url(images/questionhover.png) no-repeat	'});
			},
			onClose: function() {
				$('#'+v).css({border: bo,background:bg});
			}			
		}).load();


	}
	
	
	function array2json(arr) {
	    var parts = [];
	    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
	
	    for(var key in arr) {
	    	var value = arr[key];
	        if(typeof value == "object") { //Custom handling for arrays
	            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
	            else parts[key] = array2json(value); /* :RECURSION: */
	        } else {
	            var str = "";
	            if(!is_list) str = '"' + key + '":';
	
	            //Custom handling for multiple data types
	            if(typeof value == "number") str += value; //Numbers
	            else if(value === false) str += 'false'; //The booleans
	            else if(value === true) str += 'true';
	            else str += '"' + value + '"'; //All other things
	            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
	
	            parts.push(str);
	        }
	    }
	    var json = parts.join(",");
	    
	    if(is_list) return '[' + json + ']';//Return numerical JSON
	    return '{' + json + '}';//Return associative JSON
	}	
	function showPartData(v){
		$('#partDetails').html('');
		showDivAndLoad('partmodal',v);		 
	}
	function showSysData(v){
		
		if(typeof parent.refreshSys == 'function' && isKiosk){
			parent.refreshSys(v);
		}else{
			$('#partDetails').html('');
			showDivAndLoadSys('partmodal',v);			
		}	 
	}
	
	function gotoAQ(cat, sys){
		window.location.href='/alphaquote/' + encodeURIComponent(sys.trim());
	}
			
	function initializePageMain(){

		$.easing.drop = function (x, t, b, c, d) {
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
		};
		$.easing.easeInOutQuad= function (x, t, b, c, d) {
			if ((t/=d/2) < 1) {return (c/2*t*t + b);}
			return (-c/2 * ((--t)*(t-2) - 1) + b);
		};
		$.easing.elasout = function(x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;

		};		
		$.tools.overlay.addEffect("drop", function(css, done) { 
		   var conf = this.getConf(), overlay = this.getOverlay();           
		   if (conf.fixed)  {
		      css.position = 'fixed';
		   } else {
		      css.top += $(window).scrollTop();
		      css.left += $(window).scrollLeft();
		      css.position = 'absolute';
		   } 
		   overlay.css(css).show();
		   overlay.animate({ top: '+=100',  opacity: 1,  width: '+=50'}, 400, 'easeInOutQuad', done);
		   }, function(done) {
		      this.getOverlay().animate({top:'-=100', opacity:0, width:'-=50'}, 300, 'easeInOutQuad', function() {
		         $(this).hide();
		         done.call();      
		      });
		   }
		);	
		
		
		if ($('#letterSelector')) 
			$('#letterSelector').animate({right:'0'}, 1000, 'easeInOutQuad');
		
		
		initializeTabs();
		initSideBar();
        initSystemMenu();
		if ($("#accountTab").length==0 && $("#adminTab").length==0)
			$("#cont1").css("border","1px solid #999999");
		
		options = {  
		    reject : { // Rejection flags for specific browsers  
		        all: false, // Covers Everything (Nothing blocked)  
		        msie5: true,msie6: true // Covers MSIE 5-6 (Blocked by default)  
		    },  
		    display: ['firefox','chrome','msie'], // What browsers to display and their order  
		    browserInfo: { // Settings for which browsers to display  
		        firefox: {  
		            text: 'Firefox (Latest)', // Text below the icon  
		            url: 'http://www.mozilla.com/firefox/' // URL For icon/text link  
		        },  
		        msie: {  
		            text: 'MSIE (Latest)',  
		            url: 'http://www.microsoft.com/windows/Internet-explorer/'  
		        },  		        
		        chrome: {  
		            text: 'Chrome  (Latest)',  
		            url: 'http://www.google.com/chrome/'  
		        }
		    },  
		    header: 'Did you know that your Internet Browser is out of date?', // Header of pop-up window  
		    paragraph1: 'Your browser is out of date, and may not be compatible with our website. A list of the most popular web browsers can be found below.', // Paragraph 1  
		    paragraph2: 'Just click on the icons to get to the download page', // Paragraph 2  
		    close: true, // Allow closing of window  
		    closeMessage: 'By closing this window you acknowledge that your experience on this website may be degraded', // Message displayed below closing link  
		    closeLink: 'Close This Window', // Text for closing link  
		    closeURL: '#', // Close URL  
		    closeESC: true, // Allow closing of window with esc key  
		    closeCookie: true, // If cookies should be used to remmember if the window was closed (see cookieSettings for more options)  
		    // Cookie settings are only used if closeCookie is true  
		    cookieSettings: {  
		        path: '/', // Path for the cookie to be saved on (should be root domain in most cases)  
		        expires: 0 // Expiration Date (in seconds), 0 (default) means it ends with the current session  
		    },  
		    imagePath: '/images/', // Path where images are located  
		    overlayBgColor: '#000', // Background color for overlay  
		    overlayOpacity: 0.8, // Background transparency (0-1)  
		    fadeInTime: 'fast', // Fade in time on open ('slow','medium','fast' or integer in ms)  
		    fadeOutTime: 'fast' // Fade out time on close ('slow','medium','fast' or integer in ms)  
		}  		
		$.reject(options); 
		

		$('#buttons-expanded').jsShare({
			maxwidth: 360, 
			yoursitetitle : $('title').html(),
			yoursiteurl : window.location.href,
			yoursitename : 'Alpha Communications&trade;' 
		});
    	$('.newAccTitle').click(function(e){
    	   var target=$(this).next('.newAccContent');
           var vis = target.is(':visible');
           if (!vis) $('.newAccContent:visible').slideUp('medium');
           target.slideToggle('medium');
    	});	        
	}

	var lastPartTextBox='';
	var lastResultDiv='';
	var currentFocus='';
	
	function focusPartSuggest(textboxName, resultDivName){
		currentFocus=textboxName;
	}

	function lostFocusPartSuggest(textboxName, resultDivName){
		currentFocus='';
	}
	var searchAjaxObject=null;
	function searchSuggest(textboxName, resultDivName) {
				
	    var str = escape(document.getElementById(textboxName).value);
	    
	    if (str.length<1){
	    	clearSearchSuggest(textboxName);
	    	return;
	    } else {
	    	
			lastPartTextBox=textboxName;
			lastResultDiv=resultDivName;	    	
	    	currentFocus=textboxName;
 	    		
			var url = '/suggest.php?s=' + str;
			if (searchAjaxObject!=null) searchAjaxObject.abort();
			searchAjaxObject = $.ajax({
				url: url,
				success: function(data) {
					searchAjaxObject=null;
				    var i = $('#' + textboxName);
				    var p = i.position();
				    
			    	var ss = document.getElementById(resultDivName);
					ss.innerHTML = data.replace(/^\s*/, "").replace(/\s*$/, "");			    
				    
					$('#' + resultDivName).animate({
						height: '300px'
					}, 500, function() {
						// Animation complete.
					});	 	
				}
			});			
	    }
	}
	
	function clearSearchSuggest() {
		if (searchAjaxObject) searchAjaxObject.abort();
		if (currentFocus=='') return; 
		$('.partSuggest').animate({
			height: '0px'
		}, 500, function() {
			$('.partSuggest').html('');
		});	 		

	}
	
	function refreshPic(){
		document.getElementById('lg').src='/image.php?size=l&modlno=<?php echo urlencode($modlno); ?>';
		return;
	}		
	
    jQuery.extend({
        isOnScreen: function (box, container) {
            for (var i in box) {
                box[i] = parseFloat(box[i])
            };
            for (var i in container) {
                container[i] = parseFloat(container[i])
            };
            if (!container) {
                container = {
                    left: $(window).scrollLeft(),
                    top: $(window).scrollTop(),
                    width: $(window).width(),
                    height: $(window).height()
                }
            }
            if (box.left + box.width - container.left > 0 && box.left < container.width + container.left && box.top + box.height - container.top > 0 && box.top < container.height + container.top) return true;
            return false;
        }
    })
    jQuery.fn.isOnScreen = function (container) {
        for (var i in container) {
            container[i] = parseFloat(container[i])
        };
        if (!container) {
            container = {
                left: $(window).scrollLeft(),
                top: $(window).scrollTop(),
                width: $(window).width(),
                height: $(window).height()
            }
        }
        if ($(this).offset().left + $(this).width() - container.left > 0 && $(this).offset().left < container.width + container.left && $(this).offset().top + $(this).height() - container.top > 0 && $(this).offset().top < container.height + container.top) return true;
        return false;
    }	
	
	$.fn.preloader = function(options,images) {
	    var defaults = {
	        onDone:function(){ },
	        onEachLoad:function(img){},
	        fadeIn : 200,
	        delay : 100,
	        interval : 200,
	        parentWrap : 'a'
	    },
	    options = $.extend(defaults, options),
	    delayTime = 0;
	    images.css({
	            visibility : 'visible',
	            opacity : 0
	        }).each(function() {
	            var thisParent = $(this).parent(options.parentWrap)
	            if(thisParent.length)
	                thisParent.addClass('preloader');
	            else
	                $(this).wrap('<a class="preloader unwrap"/>');
	        });
	    var timer = setInterval(function() {
	            init()
	        }, options.interval);
	    init = function() {
	        images = images.filter(function() {
	                if(this.complete && this.naturalWidth !== 0) {
	                    delayTime = delayTime + options.delay;
	                    $(this).css({
	                            visibility : 'visible'
	                        }).delay(delayTime).animate({
	                            opacity : 1
	                        }, options.fadeIn, function() {
	                            $(this).parent().removeClass('preloader');
	                            if($(this).parent().hasClass('unwrap'))
	                                $(this).unwrap();
	                            options.onEachLoad($(this));
	                        });
	                } else {
	                    return this;
	                }
	            }
	        );
	        if(images.length == 0) {
	            clearInterval(timer);
	            options.onDone();
	        }
	    };
	}		
	
	


function doConfirm(container, text, onConfirmCallback, onCancelCallback){
    $('.addedConfirmDiv').remove();
    
    var html = '<div id="consoleModalConfirm" style="padding:10px;margin:10px;border-bottom:1px solid #999;" class="hide addedConfirmDiv"><strong>'+text+'</strong><br /><br />' + 
        '<button class="ok" id="confYes">Confirm</button>' +
        '<button class="cancel" id="confNo">Cancel</button>' + 
        '</div>';  

    container.prepend(html);
    
    $('#confYes').click(function(e){
        $('.addedConfirmDiv').slideUp('fast');
        if (onConfirmCallback) onConfirmCallback();
    });
    $('#confNo').click(function(e){
        $('.addedConfirmDiv').slideUp('fast');
        if (onCancelCallback) onCancelCallback();
    });    
    $('.addedConfirmDiv').slideDown('fast');
} 
            
var menuTimer=null;    
var f = function(){
    $('#systemMenu').slideUp('fast');         
};
function initSystemMenu(){
    $('#mtSystems').hover(function(){
        clearTimeout(menuTimer);
        if ($('#systemMenu:visible').length>0) return;
        

            $('#systemMenu').css({
                'top': ($('#mtSystems').position().top + $('#mtSystems').outerHeight()) + 'px' ,
                'left': ($('#mtSystems').position().left -10) + 'px'
            }).slideDown('fast');                

                
 
        clearTimeout(menuTimer); 
    },function(){
        menuTimer = setTimeout(f, 300);
    }).click(function(){
        f();
    });
    $('#systemMenu').hover(function(){
        clearTimeout(menuTimer);
    },function(){
        menuTimer = setTimeout(f, 300);
    }).click(function(e){
        e.stopPropagation();
    }); 
    $('body').click(function(){f();}); 
}            

function generateIIRF(callback, callbackFail){
    $.ajax({
        url: '/generateiirf.php',
        dataType: 'html', 
        success:function(obj){
            if (obj=='OK'){
                if (callback) callback();
            }else{
                if (callbackFail) callbackFail(obj);
            }
        }
    });    
}
