TRACKER_TICKER_SEARCH_INSTANCE = null;
ORDERBY_FOR_YOUR = 1;
ORDERBY_FOR_TOP50 = 2;
RESULT_ADMISSION_TRACKER_FORM = 3;	
REQUEST_TYPE_ALL = 1;
REQUEST_TYPE_CONTENT = 2;
SYNCHRONIZE_YES = "Y";
SYNCHRONIZE_NO = "N";
SYNCHRONIZE_RADIO_VALUE_IN_COOKIE = 'synchronizeRadioValue';

var TrackerTickerSearch = new Class({
	initialize: function() {
		this.top50Parameter = {};
		this.yourCollegeList = {};
	},
	bindTop50OrderEvent: function() {
		var top50Request = this.top50OrderByRequest.bindWithEvent(this);
		if($$('.top50_sort_columns')) {
			$$('.top50_sort_columns').each(function(ele) {
				if(!ele.hasClass('linkstyleth')) {
					ele.addClass('linkstyleth');
				}
				ele.removeEvents('click');
				ele.addEvent('click', top50Request);				
			});
		}
	},
	removeTop50OrderEvent: function() {
		if($$('.top50_sort_columns')) {
			$$('.top50_sort_columns').each(function(ele) {
				if(ele.hasClass('linkstyleth')) {
					ele.removeClass('linkstyleth');
				}
				ele.removeEvents('click');			
			});
		}
	},
	
	bindYourlistOrderEvent: function() {
		var youListRequest = this.yourListOrderByRequest.bindWithEvent(this);
		if($$('.yourlist_sort_columns')) {
			$$('.yourlist_sort_columns').each(function(ele) {
				if(!ele.hasClass('linkstyleth')) {
					ele.addClass('linkstyleth');
				}
				ele.removeEvents('click');
				ele.addEvent('click', youListRequest);			
			});
		}
	},
	removeYourlistOrderEvent: function() {
		var youListRequest = this.yourListOrderByRequest.bindWithEvent(this);
		if($$('.yourlist_sort_columns')) {
			$$('.yourlist_sort_columns').each(function(ele) {
				if(ele.hasClass('linkstyleth')) {
					ele.removeClass('linkstyleth');
				}
				ele.removeEvents('click');
			});	
		}
	},
	top50OrderByRequest: function(e) {
		e = new Event(e);
		var target = $(e.target);
		if(target.tagName == "DIV"){
			target = target.getParent();
		}
		else if(target.tagName == "IMG"){
			target = target.getParent().getParent();
		}		
		var orderByColumn = target.getProperty('id');
		if(orderByColumn.indexOf('ForTop50') != -1) {
			orderByColumn = orderByColumn.substring(0, orderByColumn.indexOf('ForTop50'));
		}
		if(this.top50Parameter.orderByColumn != null && 
				this.top50Parameter.orderByColumn == orderByColumn) {
			if(this.top50Parameter.ascending == true) { 
				this.top50Parameter.ascending = false;
			}
			else {
				this.top50Parameter.ascending = true;
			}
		}
		this.top50Parameter.requestType = REQUEST_TYPE_CONTENT;
		this.top50Parameter.orderByColumn = orderByColumn;
		this.top50Parameter.queryFromCache = true;		
		this.top50Find();
	},
	yourListOrderByRequest: function(e) {
		e = new Event(e);
		var target = $(e.target);
		if(target.tagName == "DIV"){
			target = target.getParent();
		}
		else if(target.tagName == "IMG"){
			target = target.getParent().getParent();
		}
		var orderByColumn = target.getProperty('id');
		if(orderByColumn.indexOf('ForYourList') != -1) {
			orderByColumn = orderByColumn.substring(0, orderByColumn.indexOf('ForYourList'));
		}
		if(this.yourCollegeList.orderByColumn != null && 
				this.yourCollegeList.orderByColumn == orderByColumn) {
			if(this.yourCollegeList.ascending == true) { 
				this.yourCollegeList.ascending = false;
			}
			else {
				this.yourCollegeList.ascending = true;
			}
		}
		this.yourCollegeList.requestType = REQUEST_TYPE_CONTENT;
		this.yourCollegeList.orderByColumn = orderByColumn;
		this.yourCollegeList.queryFromCache = true;
		this.yourlistFind();
	},
	find: function() {
		this.yourlistFind();
		this.top50Find();
	},
	top50Find: function() {
		this.top50Parameter.orderByOcasion = ORDERBY_FOR_TOP50;
		var wrapId = "";
		if(this.top50Parameter.requestType == REQUEST_TYPE_CONTENT) {			
			wrapId = 'top50collegescontent';
		}
		else {
			wrapId = 'top50colleges';
		}		
		if($(wrapId) == null)return;
		AJAX_LOADER.loading($(wrapId));	
		AdmissionTickerService.getTop50Colleges(this.top50Parameter, 
				dwrCallback($(wrapId), {callback: this.doTop50CallBack.bind(this)}));
	},
	importAdmissionsFromLocker: function() {
		AJAX_LOADER.loading($('yourcollegelistcontent'));
		this.yourCollegeList.orderByOcasion = ORDERBY_FOR_YOUR;
		this.yourCollegeList.orderByColumn = null;		
		this.yourCollegeList.requestType = REQUEST_TYPE_CONTENT;
		AdmissionTickerService.importAdmissionsFromLocker(this.yourCollegeList, 
				dwrCallback($('yourcollegelistcontent'), {callback: this.doYourlistCallBack.bind(this)})
		);
	},
	addNewCollegeToYourList: function(schoolId) {
		AJAX_LOADER.loading($('yourcollegelistcontent'));
		this.yourCollegeList.orderByOcasion = ORDERBY_FOR_YOUR;
		this.yourCollegeList.requestType = REQUEST_TYPE_CONTENT;
		this.yourCollegeList.orderByColumn = null;
		//_hbPageView('Add+College','/tracker/home/my_college_list');
		AdmissionTickerService.addNewCollegeToYourList(schoolId, this.yourCollegeList, 
			dwrCallback($('yourcollegelistcontent'), {callback: this.doYourlistCallBack.bind(this)})
		);		
	},
	deleteOperation: function(schoolId, isSynchronized) {
		AJAX_LOADER.loading($('yourcollegelistcontent'));
		this.yourCollegeList.orderByOcasion = ORDERBY_FOR_YOUR;
		this.yourCollegeList.requestType = REQUEST_TYPE_CONTENT;	
		//_hbPageView('Remove+College','/tracker/home/my_college_list');
		AdmissionTickerService.deleteOperation(schoolId, isSynchronized, this.yourCollegeList, 
			dwrCallback($('yourcollegelistcontent'), {callback: this.doYourlistCallBack.bind(this)})
		);		
	},
	yourlistFind: function() {
		this.yourCollegeList.orderByOcasion = ORDERBY_FOR_YOUR;
		var wrapId = "";	
		if(this.yourCollegeList.requestType == REQUEST_TYPE_CONTENT) {
			wrapId = 'yourcollegelistcontent';
		}
		else {			
			wrapId = 'yourcollegelisttable';
		}
		if($(wrapId) == null)return;
		AJAX_LOADER.loading($(wrapId));	
		AdmissionTickerService.getYourCollegeList(this.yourCollegeList, 
			dwrCallback($(wrapId), {callback: this.doYourlistCallBack.bind(this)})
		);
	},
	doTop50CallBack: function(result) {
		if(this.top50Parameter.requestType == REQUEST_TYPE_CONTENT) {
			AJAX_LOADER.complete($('top50collegescontent'));
		}
		else {
			AJAX_LOADER.complete($('top50colleges'));
		}
		
		if($('top50colleges')) {
			$('top50colleges').empty();
			$('top50colleges').setHTML(result);
		}
		if($('help_top50')){
			var helpPopup = getHelpPopupInstance();
	        helpPopup.start('help_top50',{
		        poptitle:'Top 50 Colleges',
		        popcont:'The <i>Top 50 Colleges</i> displays the latest Admissions Tracker activity for the 50 colleges with the highest number of Admissions Profiles.',
		        popwidth:370
	      	}); 
		}		
		
		this.setOrderByColumn();
		this.displayErrorMessage();
		if($('resultSizeForTop50') && $('resultSizeForTop50').getText().toInt() > 1) {
			this.bindTop50OrderEvent();		
		}
		else {
			this.removeTop50OrderEvent();
		}
	},
	doYourlistCallBack: function(result) {
		if(this.yourCollegeList.requestType == REQUEST_TYPE_CONTENT) {
			AJAX_LOADER.complete($('yourcollegelistcontent'));
		}
		else {
			AJAX_LOADER.complete($('yourcollegelisttable'));
		}
		
		if($('yourcollegelisttable')) {
			$('yourcollegelisttable').empty();
			$('yourcollegelisttable').setHTML(result);
		}
		this.setOrderByColumn();
		this.importFromProfileListCallBackProcess();
		
		if($('yourCollegeListSize') && $('yourCollegeListSize').getText().toInt() > 1) {
			this.bindYourlistOrderEvent();			
		}
		else {
			this.removeYourlistOrderEvent();
		}
		
		// display the error message for your college list.
		if($('selectedCollegeAlreadyInList') && $('selectedCollegeAlreadyInList').getText() != '') {
			if($('your_college_error')) {
				$('your_college_error').setHTML('You have already added this college to your college list.');
				$('your_college_error').setStyle("display", "block");		
			}
		}
		else {
			if($('your_college_error')) {
				$('your_college_error').setStyle("display", "none");
			}	
			if($('searchInputInYourList')){
				$('searchInputInYourList').setProperty("value", "Enter College Name to Add");
				$('searchInputInYourList').blur();
				$('searchInputInYourList').addClass("disablefont");
			}				
		}
		$$('.searchbox')[0].focus();			
		$$('.searchbox')[0].select();		
	},
	setOrderByColumn: function() {
		if(this.top50Parameter.orderByOcasion == ORDERBY_FOR_TOP50) {
			if($('orderByColumnForTop50')) {
				var orderByColumnNameForTop50 = $('orderByColumnForTop50').getText();
				$$('#top50TRElement th').each(function(ele) {
					if(ele.hasClass('ascendingsorttag')) {
						ele.removeClass('ascendingsorttag');
					}
					if(ele.hasClass('descendingsorttag')) {
						ele.removeClass('descendingsorttag');
					}
				});
				
				if($(orderByColumnNameForTop50 + 'ForTop50') && $('resultSizeForTop50') && $('resultSizeForTop50').getText().toInt() > 1) {
					if($(orderByColumnNameForTop50 + 'ForTop50').getProperty('id') == 'RecentlyUpdatedForTop50'){
						$(orderByColumnNameForTop50 + 'ForTop50').addClass('ascendingsorttag');
					}else{
						if($('isAscendingForTop50').getText() == 'true') {						
							$(orderByColumnNameForTop50 + 'ForTop50').addClass('ascendingsorttag');
						}
						else {
							$(orderByColumnNameForTop50 + 'ForTop50').addClass('descendingsorttag');
						}
					}
					if(orderByColumnNameForTop50 == "ProfileName"){
						$(orderByColumnNameForTop50 + 'ForTop50').setStyle("padding-left", "13px");
					}else{
						$('ProfileNameForTop50').setStyle("padding-left", "10px");
					}
				}
			}
		}
		if(this.yourCollegeList.orderByOcasion == ORDERBY_FOR_YOUR) {
			if($('orderByColumnForYourList')) {
				var orderByColumnNameForYourList = $('orderByColumnForYourList').getText();
				$$('#yourListTRElement th').each(function(ele) {
					if(ele.hasClass('ascendingsorttag')) {
						ele.removeClass('ascendingsorttag');
					}
					if(ele.hasClass('descendingsorttag')) {
						ele.removeClass('descendingsorttag');
					}
				});
						
				if($(orderByColumnNameForYourList + 'ForYourList') && $('yourCollegeListSize') && $('yourCollegeListSize').getText().toInt() > 1) {
					if($(orderByColumnNameForYourList + 'ForYourList').getProperty('id') == 'RecentlyUpdatedForYourList'){
						$(orderByColumnNameForYourList + 'ForYourList').addClass('ascendingsorttag');
					}else{
						if($('isAscendingForYourList').getText() == 'true') {
							$(orderByColumnNameForYourList + 'ForYourList').addClass('ascendingsorttag');
						}
						else {
							$(orderByColumnNameForYourList + 'ForYourList').addClass('descendingsorttag');
						}
					}
					if(orderByColumnNameForYourList == "ProfileName"){
						$(orderByColumnNameForYourList + 'ForYourList').setStyle("padding-left", "13px");
					}else{
						$('ProfileNameForYourList').setStyle("padding-left", "10px");
					}
				}
			}
		}
	},
	displayErrorMessage: function() {
		if($('isNoResultReturned') && $('isNoResultReturned').getText() == 'true') {
			if($('top50_college_error')) {
				$('top50_college_error').setText('There are no top 50 colleges for this college class year.');
				$('top50_college_error').setStyle('display', '');
			}
		}
		else {
			if($('top50_college_error')) {
				$('top50_college_error').setStyle('display', 'none');
			}
		}		
	},
	importFromProfileListCallBackProcess: function() {
		if($('doesImportFromProfileList') && $('doesImportFromProfileList').getText() == 'true') {
			if($('importFromProfileList')) {
				$('importFromProfileList').setStyle('display', '');
			}
		}
		else {
			if($('importFromProfileList')) {
				$('importFromProfileList').setStyle('display', 'none');
			}
		}
	}
});

function trackerTickerSearchLoad(selectedClassYear, isFirstTime) {
	setSelectedClassYear(selectedClassYear);
	
	if(TRACKER_TICKER_SEARCH_INSTANCE == null) {
		TRACKER_TICKER_SEARCH_INSTANCE = new TrackerTickerSearch();
	}
	TRACKER_TICKER_SEARCH_INSTANCE.top50Parameter.queryFromCache = false;
	TRACKER_TICKER_SEARCH_INSTANCE.top50Parameter.orderByOcasion = ORDERBY_FOR_TOP50;
	TRACKER_TICKER_SEARCH_INSTANCE.top50Parameter.orderByColumn = null;
	TRACKER_TICKER_SEARCH_INSTANCE.top50Parameter.classYear = selectedClassYear;
	TRACKER_TICKER_SEARCH_INSTANCE.top50Parameter.requestType = REQUEST_TYPE_ALL;
	
	TRACKER_TICKER_SEARCH_INSTANCE.yourCollegeList.queryFromCache = false;
	TRACKER_TICKER_SEARCH_INSTANCE.yourCollegeList.orderByOcasion = ORDERBY_FOR_YOUR;
	TRACKER_TICKER_SEARCH_INSTANCE.yourCollegeList.orderByColumn = null;
	TRACKER_TICKER_SEARCH_INSTANCE.yourCollegeList.classYear = selectedClassYear;
	TRACKER_TICKER_SEARCH_INSTANCE.yourCollegeList.requestType = REQUEST_TYPE_ALL;
	
	if(!isFirstTime){
		//_hbPageView('Ticker+'+selectedClassYear,'/tracker/home');
	}
	TRACKER_TICKER_SEARCH_INSTANCE.find();	
}

function setSelectedClassYear(selectedClassYear){
 	var trackerTickerSearchClassYears = $$("#tabyears li"); 	
	trackerTickerSearchClassYears.each(function(ele) {
		if(ele.hasClass('selected')) {
			ele.removeClass('selected');
		}
		if(ele.getText().trim() == selectedClassYear.trim()) {		
			ele.addClass('selected');
		}
	});	
}

function trackerTickerSearch(){      
	if(getCookie('NEWSFEED_POPUP') != 'YES') window.newsfeedInstance = new NewsFeed('trackerfeed');
	var selectedClassYear = null;
	if($('classYearForTicker') && $('classYearForTicker').value != '') {
		selectedClassYear = $('classYearForTicker').value;
	}
	if(selectedClassYear == null) {
		selectedClassYear = DEFAULT_YEAR;
	}

	var trackerTickerSearchClassYears = $$("#tabyears li");
	trackerTickerSearchClassYears.each(function(ele) {
		ele.addEvent('click', function() {		
			if(ele.hasClass('selected')){
				return;
			}
			
			trackerTickerSearchLoad(ele.getText(), false);

			ajaxRefreshAds();		
		});
	});
	trackerTickerSearchLoad(selectedClassYear, true);
	initTrackCollege();
	initializeSynchronizeRadio();
	bindYourlistSubmitEvent();
}

function bindYourlistSubmitEvent() {
	var importRequest = TRACKER_TICKER_SEARCH_INSTANCE.importAdmissionsFromLocker.bindWithEvent(TRACKER_TICKER_SEARCH_INSTANCE);
	if($('importAdmissionsFromLocker')) {
		$('importAdmissionsFromLocker').removeEvents('click');
		$('importAdmissionsFromLocker').addEvent('click', importRequest);
	}
}

function initializeSynchronizeRadio() {
	if($$(document.getElementsByName('synAdmProfile')) && $$(document.getElementsByName('synAdmProfile'))[0] && $$(document.getElementsByName('synAdmProfile'))[1]) {
		var synchronizeRadioValue = Cookie.get(SYNCHRONIZE_RADIO_VALUE_IN_COOKIE);
		if(!synchronizeRadioValue) {
			synchronizeRadioValue = SYNCHRONIZE_YES;
		}
		if(synchronizeRadioValue == SYNCHRONIZE_YES) {
			$$(document.getElementsByName('synAdmProfile'))[0].setProperty('checked', true);
		}
		else {
			$$(document.getElementsByName('synAdmProfile'))[1].setProperty('checked', true);
		}
		$$(document.getElementsByName('synAdmProfile'))[0].addEvent('click', function() {
			Cookie.set(SYNCHRONIZE_RADIO_VALUE_IN_COOKIE, SYNCHRONIZE_YES, {duration: 3600});
		});
		$$(document.getElementsByName('synAdmProfile'))[1].addEvent('click', function() {
			Cookie.set(SYNCHRONIZE_RADIO_VALUE_IN_COOKIE, SYNCHRONIZE_NO, {duration: 3600});
		});
	}
}

function initTrackCollege(){
	$$('.searchbox').each(function(ele){
		ele.focus();
		ele.select();
	   	var admissionSearchBox = new AdmissionsHomeSearchBox(ele,{enterSubmit: true, selectSubmit: true});
	   	admissionSearchBox.anchorElement = $$('.inputcollname')[0];
	    $('searchsubmit').onclick = function(){
			var schoolId = DWRUtil.getValue("trackCollegeId");
			var classYear = DWRUtil.getValue("classYear");
		 	AdmissionTickerService.trackCollege(schoolId, classYear, 
		          dwrCallback(null, {callback: function(result){
		                                          if(result != ""){
		                                            window.location.href = result;
		                                          }else{
		                                            admissionSearchBox.setErrorMesage("There are currently no Admissions Profiles for this college for the year you selected.");
		                                          }
		                                       }
		                            		})
		    );
	    	//fix removing previousPageSection issue
	    	setCookie('previousPageSection','page_admissions_tracker');
	    }
	   	admissionSearchBox.setTriggerElement('searchsubmit');
	   	admissionSearchBox.start();
   });

	if($('yourcollegesearchsubmit')) {
		$('yourcollegesearchsubmit').onclick = function() {
			var schoolId = DWRUtil.getValue("yourSchoolId");
			
			if($$(document.getElementsByName('synAdmProfile')) && $$(document.getElementsByName('synAdmProfile'))[0]) {
				this.yourCollegeList.synchronizedUpdate = ($$(document.getElementsByName('synAdmProfile'))[0]).getProperty('checked');
			}
			this.yourCollegeList.orderByColumn = null;
			this.addNewCollegeToYourList(schoolId);
		}.bind(TRACKER_TICKER_SEARCH_INSTANCE);
		
    	$$('.searchinput').each(function(ele) {
    		ele.addEvent('focus', function() {
                var value = ele.getProperty("value");
                if(value.trim() == "Enter College Name to Add"){
				  ele.setProperty('value', '');
				  ele.removeClass("disablefont");
                }
			});
	    	var yourCollegeSearchBox = new YourCollegeSearchBox(ele,{enterSubmit: true, selectSubmit: true});
	    	yourCollegeSearchBox.anchorElement = $$('.addcollegefield')[0];
	    	yourCollegeSearchBox.containerId = "secondsearchsuggestioncontainer";
	    	yourCollegeSearchBox.setTriggerElement('yourcollegesearchsubmit');
	    	yourCollegeSearchBox.setErrorMsgElement('your_college_error');
	    	yourCollegeSearchBox.start();
	    });	    
	}
}

window.addEvent('domready', trackerTickerSearch);
