HJ.App = Class.create();

HJ.App.prototype = {

	initialize: function() {
		this.db = null;
	},
	
	initialize1: function() {
		this.enableBrowserHistory = true;
		var myModuleBookmarkedState = YAHOO.util.History.getBookmarkedState(HJ.YUI_HISTORY_MANAGER_MODULE_DASHBOARD);
		this.currentTabInYUIHistoryManager = myModuleBookmarkedState || HJ.DESTINATION_PAGE_HOME;
		YAHOO.util.History.register(HJ.YUI_HISTORY_MANAGER_MODULE_DASHBOARD, this.currentTabInYUIHistoryManager, this.backButtonPressHandler.bind(this));
		YAHOO.util.History.onReady(function () {
			var currentTab;
			
			// This is the tricky part... The onLoad event is fired when the user
			// comes back to the page using the back button. In this case, the
			// actual tab that needs to be selected corresponds to the last tab
			// selected before leaving the page, and not the initially selected tab.
			// This can be retrieved using getCurrentState:
			currentTab = YAHOO.util.History.getCurrentState(HJ.YUI_HISTORY_MANAGER_MODULE_DASHBOARD);
		});
		YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		
		document.onkeypress = this.keyPressHandler.bindAsEventListener(this);
		this.tabLinkClicked = false;
		this.templateLinkClicked = false;
		
		//  Main Navigation..
		this.mainTab = null;
		this.homePageUI = new HJ.HomePageUI();
		this.SIHP = new HJ.SIHP();
		this.db = new HJ.Dashboard();
		this.db.init();
	},
	
	initialize2: function() {
		restrictBack();

		this.colorPicker = new Af.ColorPicker();

		this.dndMgrScribble = new Af.DndMgr2(this);

		this.dndMgrMyLists = new Af.DndMgr2(this);

		this.scribble = new HJ.Scribble();

		this.schedule = new HJ.Schedule();

		this.invitation = new HJ.Invitation();
		
		this.calenderTop = document.getElementById("calenderTop");		

		this.myLists = new HJ.MyLists();
		this.myGroups = new HJ.MyGroup();
		this.myPeople = new HJ.MyPeople();
		this.myResources = new HJ.MyResources();
		this.myLovedOne = new HJ.MyLovedOne();

		this.communityCalendar = new HJ.CommunityCalendar();
		this.holiday = new HJ.holiday();
		this.resource = new HJ.Resource();
		this.question = new HJ.Question();
		
		this.summerCamps = new HJ.SummerCamps();

		//  This is the shell page for Signups and Invites Tab..  
		//  Don't confuse with signin or signup..
		this.signups = new HJ.Signups();

		/*
			Classes moved to below function;
		*/

		this.currentView = null;

		return;	
	},

	initialize3: function() {

		// Moved classes from upper function		
		//this.about = new HJ.About();

		this.formatPhone = new Af.PhoneFormatter();
		this.emailValidator = new HJ.EmailValidator();
		this.validator = new HJ.Validator();

		this.myMHM = new HJ.MyMHM();
		this.myInfo = new HJ.MyInfo();
		this.publicProfile = new HJ.MyPublicProfile();
		this.commResProfile = new HJ.MyCommResourcesProfile();		

		this.seeingStar = new HJ.SeeingStar();
		this.seeingStarMHM = new HJ.SeeingStarMHM();
		this.seeingStarComRes = new HJ.SeeingStarCommResources();
		this.memberProfile = new HJ.SeeingStarMemberProfile();

		this.thankYouNote = new HJ.ThankYouNote();

		return;
	},
	
	cleanup: function() {
	   if (this.db != null) {
	       this.dndMgrScribble.clearAll();
		   this.dndMgrMyLists.clearAll();
		   if (login != null) {
		   		login.cleanup();
		   }
		   this.db.cleanup();
		   this.scribble.cleanup();
		   this.schedule.cleanup();
		   this.invitation.cleanup();
		   this.communityCalendar.cleanup();
		   this.myLists.cleanup();
		   this.myGroups.cleanup();
		   this.myPeople.cleanup();
		   this.myResources.cleanup();
		   this.myLovedOne.cleanup();
		   this.myResources.cleanup();
		   var e = document.getElementById("MainArea");
		   e.appendChild(this.dndMgrScribble.draggableElement);
		   e.appendChild(this.dndMgrMyLists.draggableElement);

			// SETTING REFERENCE TO NULL , PREVENTS MEMORY LEAK

		    this.colorPicker = null;
			this.dndMgrScribble = null;
			this.dndMgrMyLists = null;
			this.scribble = null;
			this.schedule = null;
			this.invitation = null;
			this.myLists = null;
			this.myGroups = null;
			this.myPeople = null;
			this.myResources = null;
			this.myLovedOne = null;
			this.communityCalendar = null;
			this.holiday = null;
			this.camp = null;
      	this.resource = null;
			this.question = null;			

			this.formatPhone = null;
			this.emailValidator = null;
			this.validator = null;
			this.myInfo = null;
			this.myMHM = null;
			this.publicProfile = null;
			this.commResProfile = null;
			this.seeingStar = null;
			this.seeingStarMHM = null;
			this.seeingStarComRes = null;
			this.memberProfile = null;
			this.thankYouNote = null;
	   }
	   
	},
	
	setCurrentView: function(v) {
	   if (this.currentView == v) {
	      return;
	   }
       document.getElementById("content").style.backgroundColor = "white"; 
	   this.dndMgrScribble.clearDropZones();
	   this.dndMgrMyLists.clearDropZones();
	   if (this.currentView != null && this.currentView.setVisible) {
	      this.currentView.setVisible(false);
	   }
	   
	   this.currentView = v;
	   
	   if (this.currentView != null && this.currentView.setVisible) {
	      this.currentView.setVisible(true);
	   }
		   
	   this.db.QATitle.src="img/buttons/Moms_helping_moms01.jpg";				   	
	   this.db.communityResourcesTitle.src="img/buttons/Community_Resources01.gif";	
	   //this.db.seeingStarTitle.src="img/buttons/Seeing_Stars.jpg";	
	   
	},
	
	groupUpdated: function(group, allPeople) {
	   var l = group["people"];
	   var excludes = new Array();
	   var includes = new Array();
	   
	   for (var i=0; i<allPeople.length; i++) {
	      var p = allPeople[i];
	      if (findObjIndex(l, p) < 0) {
	         excludes.push(p);
	      } else {
	         includes.push(p);
	      }
	   }
	   
	   // add group in includes if not present
	   
	   for (var i=0; i<includes.length; i++) {
	     var gl = includes[i]["group"];
	     if (gl == null) {
	        createOneToManyAssoc(includes[i], "group", "Group");
	        gl = includes[i]["group"];
	     }
	     if (findObjIndex(gl, group) < 0) {
	        gl.push(group);
	     }
	   }
	   
	   for (var i=0; i<excludes.length; i++) {
	     var gl = excludes[i]["group"];
	     if (gl == null) {
	        continue;
	     }
	     var idx = findObjIndex(gl, group);
	     if (idx >= 0) {
	        deleteFromArray(gl, gl[idx]);
	     }
	   }
	
	},
	
	groupDeleted: function(group, allPeople) {
	   for (var i=0; i<allPeople.length; i++) {
	     var gl = allPeople[i]["group"];
	     if (gl == null) {
	        continue;
	     }
	     var idx = findObjIndex(gl, group);
	     if (idx >= 0) {
	        deleteFromArray(gl, gl[idx]);
	     }
	   }
	
	},
	
	peopleUpdated: function(people, allGroup) {
	   var l = people["group"];
	   var excludes = new Array();
	   var includes = new Array();
	   
	   for (var i=0; i<allGroup.length; i++) {
	      var g = allGroup[i];
	      if (findObjIndex(l, g) < 0) {
	         excludes.push(g);
	      } else {
	         includes.push(g);
	      }
	   }
	   
	   // add group in includes if not present
	   
	   for (var i=0; i<includes.length; i++) {
	     var pl = includes[i]["people"];
	     if (pl == null) {
	        createOneToManyAssoc(includes[i], "people", "Person");
	        pl = includes[i]["people"];
	     }
	     if (findObjIndex(pl, people) < 0) {
	        pl.push(people);
	     }
	   }
	   
	   for (var i=0; i<excludes.length; i++) {
	     var pl = excludes[i]["people"];
	     if (pl == null) {
	        continue;
	     }
	     var idx = findObjIndex(pl, people);
	     if (findObjIndex(pl, people) >= 0) {
	        deleteFromArray(pl, pl[idx]);
	     }
	   }
	   
	
	},
	
	peopleDeleted: function(people, allGroup) {
	   for (var i=0; i<allGroup.length; i++) {
	     var pl = allGroup[i]["people"];
	     if (pl == null) {
	        continue;
	     }
	     var idx = findObjIndex(pl, people);
	     if (idx >= 0) {
	        deleteFromArray(pl, pl[idx]);
	     }
	   }
	   	
	},
	
	keyPressHandler: function(e) {
	   var eventTarget = e.target ? e.target : e.srcElement;
       var c = e.keyCode ? e.keyCode : e.which;
	   if ((eventTarget.tagName != "TEXTAREA" && eventTarget.tagName != "INPUT") && (c == 8)) {
	        consumeEvent(e);
		    return false;
	   }
	},
	
	updateEventReferences: function(parentSchedule, event) {
	   var schedules = this.workspace["schedule"];
	   o = event["addnlSchedules"];
	   var sl;
       if (o != null) {
          var sl = o.split(",");
       } else {
          sl = new Array();
       }
       
      var s = trim(event.driver1);
      if (s != "") {
         sl.push(s);
      }
      s = trim(event.driver2);
      if (s != "") {
         sl.push(s);
      }
      for (var i=0; i<sl.length; i++) {
         var s = trim(sl[i]);
         var sch = findObjById(schedules, s);
         if (parentSchedule == sch || sch == null) {
            continue;
         }
         var el = sch["event"];
         if (el == null) {
            createOneToManyAssoc(sch, "event", "Event");
            el = sch["event"];
         }
         if (findObjById(el, event.UUID) == null) {
            el.push(event);
         }
      }
	},
	
	deleteEventReferences: function(sl, parentSchedule, event) {
	   var schedules = this.workspace["schedule"];
	   for (var i=0; i<sl.length; i++) {
         var s = trim(sl[i]);
         var sch = findObjById(schedules, s);
         if (parentSchedule == sch || sch == null) {
            continue;
         }
         var el = sch["event"];
         deleteFromArray(el, event);
       }
	},
	
	setCurrentTab: function(tab, calledFromBackButtonPressHandler) {
		this.mainTab = tab;
	},
	
	setCurrentTabInYUIHistoryMgr: function(tab, skipTabLinkClicked) {
		if (skipTabLinkClicked == null || !skipTabLinkClicked) {
			this.tabLinkClicked = true;
		}
		if (this.currentTabInYUIHistoryManager != null && this.currentTabInYUIHistoryManager == tab) { // avoid duplicate
			return;
		}
		try {
			YAHOO.util.History.navigate(HJ.YUI_HISTORY_MANAGER_MODULE_DASHBOARD, tab);
			this.currentTabInYUIHistoryManager = tab;
		} catch (ex) {
			// noop
		}
	},
	
	getCurrentTab: function() {
		return this.mainTab;
	},
		
	backButtonPressHandler: function(destTab) {
		if (!this.enableBrowserHistory) {
			return false;
		}
		
		if (this.tabLinkClicked) {
			// reset the trigger so that event generated when back button of the browser 
			// is clicked is consumed correctly
			this.tabLinkClicked = false; // avoid infinite loop
			
			if (this.templateLinkClicked) {
				this.templateLinkClicked = false;
			}
			return false;
		}
		
		if (this.templateLinkClicked) {
			this.templateLinkClicked = false;
			return false;
		}
		if (this.currentTabInYUIHistoryManager == destTab) {
			return false;
		}
		
		if (destTab == HJ.DESTINATION_PAGE_FRIENDS ||
				destTab == HJ.DESTINATION_PAGE_HOME ||
				destTab == HJ.DESTINATION_PAGE_INAROUND ||
				destTab == HJ.DESTINATION_PAGE_OUR_CAL) {
			/*			
			*/
		} else {
			destTab = HJ.DESTINATION_PAGE_HOME;
		}
		this.setCurrentTabInYUIHistoryMgr(destTab, true);
		this.setCurrentTab(destTab);
		this.db.displayCurrentTab();
		return false;
	}, 

    /**
     * Show the user that we are busy doing something
     */
    showBusy: function() {
        showModalMessageDialog("Processing ... please wait", 300, 40);
    },

    /**
     * End busy display
     */
    endBusy: function() {
        hideModalMessageDialog();
    }

}

	function getGroupsPeople(groupList) {
	   var l = groupList; 
	   var peopleNames = "";
       if (l == null) {		 	   
	       l = new Array();
	   }	  
	   if (l != null) {		   		   
		   for (var i=0; i<l.length; i++) {
		      var g = l[i];
			  g = findObjById(app.workspace["myGroup"], g.UUID);
			  if (g == null) {
			     continue;
			  }
			   if (peopleNames == "") {
				peopleNames = '<strong>'+ "GROUPS" + "<br/>" + g.name + '</strong>' +"<br/>";
			  } else {
				peopleNames += " <br/>" + '<strong>'+ g.name+ '</strong>' +" <br/>";
			  }	
			  
			   var gPeopleList = g["people"];	 
			   if(gPeopleList != null) {
				   for(pId = 0; pId < gPeopleList.length; pId++ ) {		
				        var p = gPeopleList[pId];
					    p = findObjById(app.workspace["myPeople"], p.UUID);
					    if (p == null) {
						  continue;
					    }			
						peopleNames +=  (""==trim(getFullName(p)) ? p["email"] : getFullName(p))+ "<br/>";
				   }
			   }
		   }
	   }

	   return peopleNames;

	}

	function getPeopleNames(peopleList) {
	   var l = peopleList; 
	   var groupsPeople = "";

       if (l == null) {
		   l = new Array();
	   }
	   for (var i=0; i<l.length; i++) {
	      var p = l[i];
	      p = findObjById(app.workspace["myPeople"], p.UUID);
	      if (p == null) {
	         continue;
	      }
		  if (groupsPeople == "") {						
				groupsPeople =  '<strong>'+ "INDIVIDUALS" + '</strong>' + "<br/>" +(""==trim(getFullName(p))?p["email"]:getFullName(p));			
		  } else {
			groupsPeople += "<br/>" + (""==trim(getFullName(p)) ? p["email"] : getFullName(p));
		  }
	   }

	   return groupsPeople;
       
	}

	function getNewGroupsPeople(groupList, originalGL) {
	   var l = groupList; 
	   var peopleNames = "";
       if (l == null) {		 	   
	       l = new Array();
	   }	  
	   if (l != null) {		   		   
		   for (var i=0; i<l.length; i++) {
		      var g = l[i];
			  g = findObjById(app.workspace["myGroup"], g.UUID);
			  if (g == null) {
			     continue;
			  }
			  if(originalGL != null && originalGL.length > 0){
				   var o = findObjIndex(originalGL, g);			 
				   if( o != -1){
					   o = null;
					   continue;
				   }
			  }
			   if (peopleNames == "") {
				peopleNames = '<strong>'+ "GROUPS" + "<br/>" + g.name + '</strong>' +"<br/>";
			  } else {
				peopleNames += " <br/>" + '<strong>'+ g.name+ '</strong>' +" <br/>";
			  }	
			  
			   var gPeopleList = g["people"];	 
			   if(gPeopleList != null) {
				   for(pId = 0; pId < gPeopleList.length; pId++ ) {		
				        var p = gPeopleList[pId];
					    p = findObjById(app.workspace["myPeople"], p.UUID);
					    if (p == null) {
						  continue;
					    }			
						peopleNames +=  (""==trim(getFullName(p)) ? p["email"] : getFullName(p))+ "<br/>";
				   }
			   }
		   }
	   }

	   return peopleNames;

	}

	function getNewPeopleNames(peopleList, originalPL) {
	   var l = peopleList; 
	   var groupsPeople = "";

       if (l == null) {
		   l = new Array();
	   }
	   for (var i=0; i<l.length; i++) {
	      var p = l[i];
	      p = findObjById(app.workspace["myPeople"], p.UUID);
	      if (p == null) {
	         continue;
	      }
		  if(originalPL != null && originalPL.length > 0){
			  var o = findObjIndex(originalPL, p);			 
			  if( o != -1){
				  o = null;
				  continue;
			  }
		  }
		  if (groupsPeople == "") {		  
			groupsPeople =  '<strong>'+ "INDIVIDUALS 1 " + '</strong>' + "<br/>" +(""==trim(getFullName(p)) ? p["email"] : getFullName(p));
		  } else {
			groupsPeople += "<br/>" + (""==trim(getFullName(p)) ? p["email"] : getFullName(p));
		  }
	   }

	   return groupsPeople;
       
	}

	function refreshWidget() {
		 
		 if(app.schedule.target.style.backgroundColor != "white"){
			 app.schedule.target.style.backgroundColor = "white";

			 if(app.schedule.scheduleTable == null){
				 return false;
			 }

			 var row = app.schedule.scheduleTable.selectedRowNumber;
			 if(row != -1){
				  var selectedRow = app.schedule.scheduleTable.getSelectedRowData();
				  if(selectedRow == null) {
					 return false;
				  }
				  var bc = selectedRow["color"];
				  var c = getTextColor(bc);
				  var bc = getBackground(bc);				 
			      app.schedule.scheduleTable.unselectRow(row); 	
				  app.schedule.scheduleTable.tableElement.rows[row].cells[2].style.backgroundColor = bc;
				  app.schedule.scheduleTable.tableElement.rows[row].cells[2].style.color = c;
			 }
		 }
		 return false;
	}

	function openPopWindows(template){			
		window.open(template,"_blank","toolbar=yes, location=yes, directories=no, status=no, //menubar=yes, scrollbars=yes, resizable=yes, copyhistory=yes, width=800, height=600");	
		addLog("advClicked", template);
		return false;
	}
	
	function addLog(operation, source, description) {
		var req = new Af.DataRequest(svcURL, addLogSuccess, requestFailedCommon, null, requestTimedoutCommon);
		req.addService("AuditLogService", "addLog");
		req.addParameter("operation", operation);
		req.addParameter("source", source);
		if (description != null) {
			req.addParameter("description", description);
		}
		ajaxEngine.processRequest(req);
	}
	
	function addLogSuccess() {
	
	}
