/**
 * @filename ExploreHandler.js
 * 
 * @description Handles events for explore
 * 
 * @author Yahui Jin
 * @email yahui.jin@garmin.com
 * 
 * @requires Prototype 1.6.0.3+
 * 
 * Copyright(c) 2008, Garmin International
 */
		    
if (Garmin == undefined) var Garmin = {};

/**
 * ExploreHandlerConstants provides id's and classes used for generated elements
 * created within the ExploreHandler object.
 */
var ExploreHandlerConstants = {
	// IDs
	PERMA_URL_FRAGMENT_ID: 'permaURLFragment'
};

/**
 * The ExploreHandler class
 * 
 * @constructor
 */
Garmin.ExploreHandler = Class.create({		    
    
    /**
     * Populate search fields based on url fragment.
     */
    populateSearchFields: function(urlFragment) {
		// Only do something when we have a urlFragment
    	if (urlFragment != "") {
            this.parseUrlFragment(urlFragment);

	    	// Search	    	
			searchBarHandler.clickCheck();
	    	searchBarHandler.showSearchProgress();    	
	    	$(SearchBarHandlerConstants.REAL_SEARCH_BUTTON).click();
			$(SearchBarHandlerConstants.REAL_SEARCH_BUTTON).disabled = true;
			searchBarHandler.resetFilters();
    	}
    	else {
			// Since there is no url fragment, we will simply add the current state to the history event.
			addHistoryEvent();
		}
    },

    parseUrlFragment: function(urlFragment) {
        	var isFilterVisible = false;
	    	// Reset all search fields
	    	searchBarHandler.resetAll();

	    	// Trim # and ? from the urlFragment if there is one.
	    	if (urlFragment.length > 0) {
				if ((urlFragment.charAt(0) == '#') || (urlFragment.charAt(0) == '?')) {
					urlFragment = urlFragment.substring(1, urlFragment.length);
				}
	    	}

	    	var exploreSearchForm = "exploreSearchForm:";
	    	// Split the parameters
	    	var parameters = new Array();
	    	parameters = urlFragment.split('&');

	    	// Iterate through each key value and try to find the element
	    	for (var i = 0; i < parameters.length; i++) {
	    		var keyValue = new Array();
	    		keyValue = parameters[i].split('=');

	    		// Key and value
	    		var key = exploreSearchForm + keyValue[0];
	    		// Decode the url fragment so we can process it correctly
	    		var value = decodeURIComponent(keyValue[1]);

	    		// TODO: Refactor this... some elements do not have consistent
	    		// id naming
	    		switch (key) {
		    		case "exploreSearchForm:timePeriod":
		    			key = SearchBarHandlerConstants.TIME_SELECT_ID;

		    			// We are handling custom dates differently.
		    			// Since customDates has a parameters of a paramter, the array
		    			// length will be 1 longer than just a regular key value pair.
		    			if (keyValue.length > 2) {
		    				value = value + decodeURIComponent(keyValue[2]);
		    			}

		    			if (value == "customTimestamp") {
		    				$(SearchBarHandlerConstants.CUSTOM_DATES_ID).show();
		    			}

		    			break;
		    		// For personalized dateFormat, we need to make sure the format is correct before setting the value
		    		case "exploreSearchForm:activitySummaryBeginTimestamp-min":
						var jsDate = this.javascriptDateFormat(value);
						var date = new Date(jsDate);
						value = date.format(DATE_FORMAT.toLowerCase());
		    			key = SearchBarHandlerConstants.START_ID;
		    			break;
		    		// For personalized dateFormat, we need to make sure the format is correct before setting the value
		    		case "exploreSearchForm:activitySummaryBeginTimestamp-max":
						var jsDate = this.javascriptDateFormat(value);
						var date = new Date(jsDate);
						value = date.format(DATE_FORMAT.toLowerCase());
		    			key = SearchBarHandlerConstants.END_ID;
		    			break;
		    		case "exploreSearchForm:currentPage":
		    			key = SearchBarHandlerConstants.CURRENT_PAGE_ID;
		    			break;
		    		case "exploreSearchForm:username":
		    			// When clicking on the username in the grid, we need to populate the username in the filter
		    			if (value == $('exploreUser').innerHTML) {
		    				key = SearchBarHandlerConstants.MY_ACTIVITIES_ID;
		    				value = true;
		    				searchBarHandler.disable($(SearchBarHandlerConstants.USERNAME_ID), $('usernameField'));
		    			} else {
		    				key = SearchBarHandlerConstants.USERNAME_ID;
		    			}

		    			break;
		    		case "exploreSearchForm:owner":
		    			key = SearchBarHandlerConstants.USERNAME_ID;
		    			break;
		    		default:
		    			break;
	    		}

	    		// Find element
	    		var element = document.getElementById(key);

	    		// Check to see if the element exists
	    		if ((element != "") && (element != null)) {
	    			var elementType = element.type;

	    			// Needed for the my activities checkbox
	    			if (elementType == "checkbox") {
	    				element.setValue(true);
	    			} else if (elementType ==  "hidden"){
						element.value = value;
					}else {
	    				element.setValue(value + "");
	    			}
	    		} else {
	    			// Field does not exist
	    			//alert("parameter does not exist: " + key);
	    		}
            }
    },
	
    // This is a pretty gimp solution to the personalized dateFormat issue
    // Since the activity search service can only take one type of date format 
    // (a format javascript dislikes), we need it to make it javascript friendly to set the value
    // The solution should really be modifying the service to take javascript friendly date format
	// This is to make the date javascript friendly
	javascriptDateFormat: function(date) {
		// First, break up the date of yyyy-mm-dd
		var dateArray = new Array();
	    dateArray = date.split('-');
		
		// Then, put it back together to something javascript likes mm/dd/yyyy
		var dateFormat = dateArray[1] + "/" + dateArray[2] + "/" + dateArray[0];
		
		return dateFormat;
	},
	
	changeSearchType: function(element, value){
        window.changeSearchType = true; // used to disable zoom handler
		$('exploreSearchForm:searchType').value=value;
		$('searchTypeActivity').className = $('searchTypeActivity').className.replace(" active", '');
		$('searchTypeCourse').className = $('searchTypeCourse').className.replace(" active", '');
		
		element.className+=' active';
		
		if(value == 'COURSE'){
			//Disable the Activity Type and Event Type controls
			$(SearchBarHandlerConstants.ACTIVITY_TYPE_SELECT_ID).disabled = true;
			$(SearchBarHandlerConstants.EVENT_TYPE_SELECT_ID).disabled = true;
			$(SearchBarHandlerConstants.TIME_SELECT_ID).disabled = true;
		}
		else{
			//Enable the Activity Type and Event Type controls
			$(SearchBarHandlerConstants.ACTIVITY_TYPE_SELECT_ID).disabled = false;
			$(SearchBarHandlerConstants.EVENT_TYPE_SELECT_ID).disabled = false;
			$(SearchBarHandlerConstants.TIME_SELECT_ID).disabled = false;
		}
	}
});
