/**
 * @filename GridHandler.js
 * 
 * @description Handles events for a data grid, like expanding items, and connection with 
 * the maps class. 
 * 
 * @author Diana Chow
 * @email diana.chow@garmin.com
 *
 * @requires Prototype 1.6.0.2+
 * 
 * Copyright(c) 2008, Garmin International
 */

if(Garmin == undefined) var Garmin = {};

/**
 * GridHandlerConstants provides id's and classes used for generated elements created
 * within the GridHandler object.
 * 
 */
var GridHandlerConstants = {
    // IDs
	LOADING_MASK: 'gridLoadingMask',
    RESULT_ENTRY_ID_PREFIX: 'entry-',
    RESULT_ENTRY_EXPANDED_ID_PREFIX: 'entryExpanded-',
    FORMATTED_LOCATION_NAME_ID: 'formattedLocationName',
    
    // Class
	RESULT_DATE_CLASS: 'resultsDate',
	RESULT_ENTRY_CLASS: 'resultsEntry',
	RESULT_ENTRY_EXPANDED_CLASS: 'resultsEntryExpanded',
	RESULT_TITLE_CLASS: 'resultsTitle',
	HIGHLIGHT_CLASS: 'highlight'
};

/**
 * The GridHandler class generates the view and provides functions for altering the
 * view.
 * 
 * @constructor
 * @param {Object} config
 * 
 */
Garmin.GridHandler = Class.create({
	
    initialize: function() {
        this.linkClicked = false;
        
        this.setEntryHandlers();
    },
    
    /**
     * Function to set the event handlers for the collapsed and expanded
     * entries
     */
    setEntryHandlers: function() {
        // Set handlers for collapsing and expanding
        var collapsedEntries = $$('.'+GridHandlerConstants.RESULT_ENTRY_CLASS);
        var expandedEntries = $$('.'+GridHandlerConstants.RESULT_ENTRY_EXPANDED_CLASS);
        
        for(var i=0; i < collapsedEntries.length; i++){
            var collapsedEntry = collapsedEntries[i];
            var expandedEntry = expandedEntries[i];
            entryId = expandedEntry.id.split('-')
            var activityId = entryId[1];
            
            collapsedEntry.onclick = function(collapsedEntry, expandedEntry) {
                if( !this.linkClicked ) {
                    this.expandEntry(collapsedEntry);
                    this.highlightEntry(expandedEntry);
                    this.resetOtherEntries(collapsedEntry);
                } else {
                    this.linkClicked = false;
                }
            }.bind(this, collapsedEntry, expandedEntry);
            
            expandedEntry.onclick = function(expandedEntry) {
                if( !this.linkClicked ) {
                    this.collapseEntry(expandedEntry);
                } else {
                    this.linkClicked = false;
                }
            }.bind(this, expandedEntry);   
            
        }
        
        // Set handlers for links so that they don't conflict with entry handlers
        var resultTitles = $$('.'+GridHandlerConstants.RESULT_TITLE_CLASS);
        var resultDates = $$('.'+GridHandlerConstants.RESULT_DATE_CLASS);
        
        for(var i=0; i < resultTitles.length; i++) {
            var titleLink = resultTitles[i].down('a'); // There shall be only one
            
            titleLink.onclick = function() {
                this.linkClicked = true;
            }.bind(this);
        }
        
        for(var i=0; i< resultDates.length; i++) {
            var dateLink = resultDates[i].down('span'); // There shall be only one
            if (dateLink != undefined){
	            dateLink.onclick = function(event) {
	                this.linkClicked = true;
	                var element;
	                if(window.event){
	                	element = window.event.srcElement;
	                }else if (event.target){
	                	element = event.target;
	                }
	                searchBarHandler.searchUser(element);
	            }.bind(this);
            }
        }
        
        //Sets the invisible value in the form for sort option, if its null, its
        //relevance.  If the user has selected a value, itsthat value
        if ($('exploreSearchForm:sortField').value != ""){
        	$('sortSelect').setValue($('exploreSearchForm:sortField').value);
        } else {
        	$('exploreSearchForm:sortField').setValue("relevance");
        }
        
        $('sortSelect').onchange = function(){
        	$('exploreSearchForm:sortField').setValue($('sortSelect').value);
			searchBarHandler.clickSearch();        
        }
        
		//changes the display for location search to the formatted location
		//name from the service when the location is not "current search area" in map
		if ($(SearchBarHandlerConstants.LOCATION_ID).value != "" 
			&& $(SearchBarHandlerConstants.LOCATION_ID).value != null
			&& $(SearchBarHandlerConstants.LOCATION_ID).value != bundle_activitysearch_api.current_map_search) {			
			if ($(GridHandlerConstants.FORMATTED_LOCATION_NAME_ID).innerHTML != "") {
				var formattedLocationName = $(GridHandlerConstants.FORMATTED_LOCATION_NAME_ID).innerHTML;
				var decodeFormattedLocationName = decodeURIComponent(formattedLocationName);
				$(SearchBarHandlerConstants.LOCATION_ID).setValue(decodeFormattedLocationName);
				//this.setLastSearchedLocationCookie(decodeFormattedLocationName);
			}			
		}
    },
    
    /**
     * Sets the cookie of the location name
     * 
     * @param locationName the formatted location name displayed in the location box
     */
    setLastSearchedLocationCookie: function(locationName){
		var date = new Date();
		//days for the cookie to last * hours in a day * minutes in an hour * seconds in a minute 
		date.setTime(date.getTime()+(365*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = "lastSearchedLocation="+locationName+expires;
    },
    
    /**
     * Gets the entry (collapsed) DOM element for a given activityId
     */
    getEntryForId: function(activityId) {
        return $(GridHandlerConstants.RESULT_ENTRY_ID_PREFIX + activityId); 
    },
    
    /**
     * Gets the entry (expanded) DOM element for a given activityId
     */
    getEntryExpandedForId: function(activityId) {
        return $(GridHandlerConstants.RESULT_ENTRY_EXPANDED_ID_PREFIX + activityId);
    },
    
    /**
     * Highlights and expands the activity in the grid
     */
    highlightAndExpandActivity: function(activityId) {
        // Check to see if it's already expanded
        var expandedEntry = this.getEntryExpandedForId(activityId);
        
        // Expand it if collapsed
        if( !expandedEntry.visible() ) {
           this.expandActivity(activityId);
        }
        
        this.highlightEntry(expandedEntry);
        
        var collapsedEntry = this.getEntryForId(activityId);
        this.resetOtherEntries(collapsedEntry);        
    },
    
    /**
     * Just highlight an activity, without expanding it.
     * Works for collapsed and expanded entries.
     */
    highlightActivity: function(activityId) {
        // Check to see if it's already expanded
        var expandedEntry = this.getEntryExpandedForId(activityId);
        var collapsedEntry = this.getEntryForId(activityId);
        
        // Highlight it
        this.highlightEntry(expandedEntry);
        this.highlightEntry(collapsedEntry);
    },
    
    /**
     * Unhighlight an activity, without collapsing it.
     * Works for collapsed and expanded entries.
     */
    unhighlightActivity: function(activityId) {
        // Check to see if it's already expanded
        var expandedEntry = this.getEntryExpandedForId(activityId);
        var collapsedEntry = this.getEntryForId(activityId);
        
        // Highlight it
        this.unhighlightEntry(expandedEntry);
        this.unhighlightEntry(collapsedEntry);
    },
    
    /**
     * Collapses the activity in the grid. 
     * Handles activities that are already collapsed.
     */
    collapseActivity: function(activityId) {
        var expandedEntry = this.getEntryExpandedForId(activityId);
        var collapsedEntry = this.getEntryForId(activityId);
        
        if( expandedEntry.visible() && !collapsedEntry.visible()) {
            this.collapseEntry(expandedEntry);
        }
    },
    
    /**
     * Expands the activity in the grid without highlighting. 
     * Handles activities that are already expanded.
     */
    expandActivity: function(activityId) {
        var expandedEntry = this.getEntryExpandedForId(activityId);
        var collapsedEntry = this.getEntryForId(activityId);
        
        if( !expandedEntry.visible() && collapsedEntry.visible()) {
            this.expandEntry(collapsedEntry);
        }
    },
    
    /**
     * Hides the result entry passed in and displays the expanded result entry 
     * 
     * @private
     * 
     * @param collapsedEntry {Element}
     */
    expandEntry: function(collapsedEntry) {
    	Element.extend(collapsedEntry);
    	
        var slideTimeInSeconds = 0.5;
        var scaleFromPercentage = 38;
        
        // TODO Make sure it's a collapsed entry we're dealing with
        var expandedEntry = collapsedEntry.next('.'+GridHandlerConstants.RESULT_ENTRY_EXPANDED_CLASS);
        
        expandedEntry.show();
        collapsedEntry.hide();
    },
    
    /**
     * Hides the expanded result entry passed in and displays the collapsed result entry
     * 
     * @private
     * 
     * @param expandedEntry {Element} 
     */
    collapseEntry: function(expandedEntry) {
    	Element.extend(expandedEntry);
        var slideTimeInSeconds = 0.3;
        var slideTimeInMs = slideTimeInSeconds * 100;
        var scaleToPercentage = 38;
        
        // TODO Make sure it's an expanded entry we're dealing with   
        var collapsedEntry = expandedEntry.previous('.'+GridHandlerConstants.RESULT_ENTRY_CLASS);
        collapsedEntry.show();
        expandedEntry.hide();
//        setTimeout(function(){collapsedEntry.show();}.bind(this), slideTimeInMs);
    },
    
    /**
     * Collapses other entries besides the one passed in to ensure only
     * one entry is expanded at a time. Also ensures that other entries
     * are not highlighted.
     */
    resetOtherEntries: function(collapsedEntry) {
        collapsedId = this.splitForActivityId(collapsedEntry);
        
        var expandedEntries = $$('.'+GridHandlerConstants.RESULT_ENTRY_EXPANDED_CLASS);
        /*
         * Collapse any visible expanded entries
         */
        for(var i=0; i < expandedEntries.length; i++) {
            var entry = expandedEntries[i];
        	expandedId = this.splitForActivityId(entry);
            if( entry.visible() && collapsedId != expandedId) {
                this.collapseEntry(entry);
            }
        }
        
        /*
         * Unhighlight any highlighted entries
         */
        var collapsedEntries = $$('.'+GridHandlerConstants.RESULT_ENTRY_CLASS);
        for(var i=0; i < collapsedEntries.length; i++) {
            var entry = collapsedEntries[i];
            expandedId = this.splitForActivityId(entry);
            if( entry.visible() && collapsedId != expandedId) {
                this.unhighlightEntry(entry);
            }
        }
    },
    
    /**
     * Helper function used for splitting off the activity id
     * 
     * @param entry the entry in question
     */
    splitForActivityId: function(entry) {
    	id = entry.id;
    	splitId = id.split("-");
    	activityId = splitId[1];
    	return activityId;
    },
    
    /**
     * Adds a classname to the entry to highlight it
     * @private
     */
    highlightEntry: function(entry) {
        entry.addClassName(GridHandlerConstants.HIGHLIGHT_CLASS);
    },
    
    /**
     * Removes the classname that highlights the entry
     * @private
     */
    unhighlightEntry: function(entry) {
        entry.removeClassName(GridHandlerConstants.HIGHLIGHT_CLASS);
    },
    
    /**
     * Shows loading mask
     */
    showLoadingMask: function() {
    	$(GridHandlerConstants.LOADING_MASK).show();
    },
    
    /**
     * Hides loading mask
     */
    hideLoadingMask: function() {
    	$(GridHandlerConstants.LOADING_MASK).hide();  	
    }
});