var SearchBarBetaAjax = Class.create();
SearchBarBetaAjax.prototype = {
	preDisambigChoices: new Array,
	currentPreDisambigCheck: 0, 

	initialize: function(context) {
        this.colorSelector='Simple';

		this.tagHint = new IS_TagHint({
			textHintBoxID: 'SearchBarTextHintBox',
			textHintLoadingBoxID: 'SearchBarTextHintLoadingBox',
			textFieldID: 'SearchBarText',
			languageFieldID: 'SearchBarLanguage'
		});
	},
	
	/**
	 * add observers to html elements
	 */
	loadEvents: function() {
		this.searchBarTextObserver();
		
		// checkboxes
		var fileTypes = new Array('Image','Illustration [Vector]','Flash','Video','Audio');
		fileTypes.each(function(type, index) {
			$("SearchBarFileType"+type).observe('click', function() {
				this.toggleFileType(type);
			}.bind(this));
		}.bind(this));
		
		$('SearchBarForm').observe('submit', this.searchBarFormOnSubmit.bind(this));
		
		$('SearchBarSubmitImage').observe('click', function() {
			return this.searchBarFormOnSubmit();
		}.bind(this));
		
		$('SearchBarAdvancedToggle').observe('click', function() {		
			this.toggleSearchBar(false);
		}.bind(this));
		
		$('SearchBarHelpToggle').observe('click', function() {
			window.open('popup_search_tips.php#basic','Popup','scrollbars=yes,width=700,height=470');
		});
		
		// If a search has been performed, changing the sort option will automatically
		// re-sort the results by submitting the form immediately with the "Search Within" option checked.
		// Else, changing the sort option simply saves the new filter value to the server using AJAX.
		if( $('SearchWithin') ) {

			// On change, automatically check the "within" checkbox, and then re-submit the form.
			$('SearchBarSortBy').observe('change', function() {

                // true to skip ajax since we're ready to refreshing the page
				this.setSortBy($F('SearchBarSortBy'), true); 
				if ( $('SearchWithinCheckbox') ){ 
					$('SearchWithinCheckbox').checked = true; 
					this.setSearchWithin('');
				} else if ($('FO_SearchWithInCheckbox')){
					$('FO_SearchWithinCheckbox').checked = true; 
					this.setSearchWithin('FO_');
				}
				return this.searchBarFormOnSubmit();
			}.bind(this));
		}
		else{
			$('SearchBarSortBy').observe('change', function() {
				this.setSortBy($F('SearchBarSortBy'), false);
			}.bind(this));
		}
		
		if($('SearchWithin')){
			$('SearchWithinCheckbox').observe('click', function(){
				this.setSearchWithin('');
			}.bind(this));
		} else if($('FO_SearchWithin')){
			$('SearchWithinCheckbox').observe('click', function(){
				this.setSearchWithin('FO_');
			}.bind(this));
		}
		
		
	},
	
	searchBarFormOnSubmit: function(event) { 
        // only stop the event if the event exists (or it causes really hard-to-find bugs in IE6&7)
        if (typeof event != 'undefined') event.stop();

        var searchText = this.getTextValue($('SearchBarText'), $('SearchBarTipText'));
        SearchParams.text = (searchText == SearchParamsDefault.text ? null : searchText);
        SearchSubmit();
		return false;
	},
	
	// add observers to the search box
	searchBarTextObserver: function() {
        
		if ($('SearchBarText')) {
		
			// turn off autocomplete
			$('SearchBarText').setAttribute('autocomplete', 'off');
			
			// add the 'Enter Keyword(s)' text - if the field is not already in use
			if ($F('SearchBarText') == '') $('SearchBarText').value = $F('SearchBarTipText');
			
			Event.observe('SearchBarText', 'keydown', function(e) {
				if ($F('SearchBarText').length >= 3) searchBarAjax.tagHint.getHintsFromPartialTagOnKeydown(e);
			});
			
			Event.observe('SearchBarText', 'keyup', function(e) {
				if ($F('SearchBarText').length >= 3) searchBarAjax.tagHint.getHintsFromPartialTagOnKeyup(e);
				else searchBarAjax.tagHint.resetHintBox();
			});
			
			Event.observe('SearchBarText', 'focus', function(e) {
				if ($F('SearchBarText') == $F('SearchBarTipText')) {
					$('SearchBarText').value = '';
					$('SearchBarText').style.color = '#000';
				} else searchBarAjax.tagHint.getHintsFromPartialTag();
			});

			Event.observe('SearchBarText', 'blur', function(e) {
				if ($F('SearchBarText') == '') {
					$('SearchBarText').value = $F('SearchBarTipText');
					$('SearchBarText').style.color = '#999';
				}
				searchBarAjax.tagHint.resetHintBox(250);
			});
		}
	},

	
	toggleFileType: function(selectedFileType) {
		// to ensure we have at least one file type selected.
		if(!$("SearchBarFileTypeImage").checked && !$("SearchBarFileTypeFlash").checked && !$("SearchBarFileTypeIllustration [Vector]").checked && !$("SearchBarFileTypeVideo").checked && !$("SearchBarFileTypeAudio").checked) {
			$("SearchBarFileType"+selectedFileType).checked = true;
			return;
		}
		
		// Update sort options
		this.ToggleSortOptions();
		
		// initially selected file types
		// an array of json objects which holds info about each file type selection.
		var fileTypeSizePrice = (typeof SearchParams.fileTypeSizePrice === "undefined" ? SearchParamsDefault.fileTypeSizePrice : SearchParams.fileTypeSizePrice);
		
		// this array will hold the final selection file types.
		var newFileTypeSizePrice = new Array();
		
		// video can appear more than once (because we have 2 aspect ratios)
		// this will hold the count of the number of video there are in the fileTypeSizePrice
		var hasVideo = 0;
		var resetAudio = 0;

		// loop through the fileTypeSizePrice array
		fileTypeSizePrice.each(function(fileType){
			// this is the current selection
			if(fileType.type == selectedFileType){
				if(fileType.type=='Image'){
					fileType.size = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
				// because video may appear twice
				else if(fileType.type=='Video') {
					hasVideo++;
					fileType.size = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
				else{
					fileType.priceOption = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
			}
			
			if(selectedFileType == 'Audio' && (fileType.type=='Standard Audio' || fileType.type=='Pump Audio')){
				fileType.size = ($('SearchBarFileTypeAudio').checked ? 'All' : 'None');
				resetAudio = 1;
				SearchParams.tempo = null;
				SearchParams.audioKey = null;
				SearchParams.timeSignature1 = null;
				SearchParams.timeSignature2 = null;
			}
			// we only want video to appear once in the new file type size array
			if(fileType.type != 'Video' || (hasVideo <= 1 && fileType.type == 'Video')){
				newFileTypeSizePrice.push(fileType);
			}
		});
		
		var fileTypeSizePriceJsonString = Object.toJSON(newFileTypeSizePrice);

		// update the member's search param
        SearchParams.fileTypeSizePrice = newFileTypeSizePrice;

		// If the advanced search window is initialized, we change the settings in the form when the basic settings are changed
		if(typeof(filtersAndOptions) != "undefined") {
			
			if($("SearchBarFileTypeAudio").checked){
				$("AdvancedAudioOptions").style.display = 'block';
			}
			else{
				$("AdvancedAudioOptions").style.display = 'none';
			}
			fileTypeSizePrice.each(function(fileType){
				switch(fileType.type) {
					
					
					case 'Image':
						var type = "FO_Image"
						$(type).value = fileType.size;
						filtersAndOptions.imageOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
						break;
						
					case 'Flash':
						var type = "FO_Flash";
						$(type).value = fileType.priceOption;
						filtersAndOptions.flashOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.priceOption;
						break;
						
					case 'Illustration [Vector]':
						var type = "FO_Illustration";
						$(type).value = fileType.priceOption;
						filtersAndOptions.illustrationOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.priceOption;
						break;
						
					case 'Video':	
						switch (fileType.size) {
							case 'All 4_3':
							case 'None 4_3':
							case 'PAL':
							case 'DV':
							case 'NTSC':
								var type = "FO_Video4_3";
								$(type).value = fileType.size;
								filtersAndOptions.video43OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
								break;	
							case 'All 16_9':
							case 'None 16_9':
							case 'HD 720':
							case 'HD 1080':
								var type = "FO_Video16_9";
								$(type).value = fileType.size;
								filtersAndOptions.video169OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
								break;	
							case 'All':
							case 'None':
							
								var type = "FO_Video4_3";
								$(type).value = fileType.size+' 4_3';
								filtersAndOptions.video43OnChange();							
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size+' 4_3';
								
								var type = "FO_Video16_9";
								$(type).value = fileType.size+' 16_9';
								filtersAndOptions.video169OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size+' 16_9';
								break;
						}
						break;
						
					case 'Standard Audio':
						var type = "FO_Audio_Standard";
						$(type).value = fileType.size;
						filtersAndOptions.audioStandardOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
						break;
						
					case 'Pump Audio':
						var type = "FO_Audio_Premium";
						$(type).value = fileType.size;
						filtersAndOptions.audioPremiumOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;		
						break;

					default:
						var type = "";
						break;
				}
			});
			
		}

        this.updateSearchURL("fileTypeSizePrice", fileTypeSizePriceJsonString);

		
		//saves the current search options into the session
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveFileType&ajax_class=searchbarbeta&fileTypeSizePrice="+fileTypeSizePriceJsonString+'&resetAudio='+resetAudio;
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.toggleFileTypeCompleted.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
	},

    updateSearchURL: function(filter, filterValue) {
        if (!filter) return;

        // On the user_view page, There is a link to view the selected user's portfolio.  This link needs
        // to change when the user changes their search options.
        if($("toolPortfolioLink")) {
            // if you know of a better way, by all means, FIXME!!
            // first test to see if there is an & after the filter name
            var rExp = new RegExp("(.*)"+filter+"=(.*?)&(.*)", "i");
            var o = $("toolPortfolioLink")
            var matches = o.href.match(rExp);

            // this could mean that there aren't any more parameters following the filter name and value
            if (matches == null) {
                rExp = new RegExp("(.*)"+filter+"=(.*)", "i");
                matches = o.href.match(rExp);
            }

            if (matches != null) {
                o.href=matches[1]+filter+"="+encodeURI(filterValue)+(matches[3] ? "&"+matches[3] : "");
            }
        }
    },
	
	toggleFileTypeCompleted: function(req) {
			
		var data = req.responseText;
	}, 

	toggleBestMatchMix: function(orderValue) {
	    if ($('FO_BestMatchMix')) {    
    	    if (orderValue == 6) {
    	        $('FO_BestMatchMix').setOpacity(1);
    	        $('BestMatchRankingHandle').show();
    	    } else {
    	        $('FO_BestMatchMix').setOpacity(0.4);
    	        $('BestMatchRankingHandle').hide();
    	    }	  
	    }  
	},	
	
	setSortBy: function(val, skipAJAX) {

		if ( !skipAJAX ){
			skipAJAX = false;
		}

        // the new value is the default value, set the user value to null
        SearchParams.order = (val == SearchParamsDefault.order ? null : val);

        // Set the visual select menu on the search bar.
		$('SearchBarSortBy').value = val;
		
		// Try and set the advanced search sort value.
		try{
		    filtersAndOptions.params.FO_Sort.value = val;
		} catch(exception) {
		    // This just means that advanced search has not been initialized yet.
		}
		
		this.toggleBestMatchMix(val);

		if ( skipAJAX == false ){
			var url = "ajax_class_creator.php";
			var params = "ajax_action=SetSortBy&ajax_class=searchbarbeta&sortBy="+val;
			var myAjax = new Ajax.Request
				(
					url, 
					{ 
						method: "get", 
						parameters: params,
						onComplete: this.setSortByCompleted.bind(this),
						onFailure: this.failed.bind(this)
					}
				);	
		}
	},
	
	setSortByCompleted: function(req) {
		var data = parseInt(req.responseText);
		
		if($("FO_Sort")) {
			$("FO_Sort").value = data;
		}

        this.updateSearchURL("order", data);
	},
	
	failed: function(req) {
		//alert('Failed' + req.status);
		return false;
	},

	getTextValue: function(obj, tipObj){
		if ( obj.value == tipObj.value ){
			return '';
		} else {
			return obj.value;
		}
	},
	
	toggleSearchBar: function(toSimple) {
		var containerBasic = $('SearchBarContainerBasic');
		var containerAdvanced = $('SearchBarContainerAdvanced');
		var advancedSearchLoading = $('AdvancedSearchLoading');
	
		if(toSimple) {
			containerBasic.show();
			togglePopup(containerAdvanced, 'none');
			advancedSearchLoading.hide();
			
		} else {
			advancedSearchLoading.show();
			containerBasic.hide(); 
			
			// lazy load the js
			if(typeof(filtersAndOptions) === "undefined") {
				LazyLoad.loadJS("/js/ajax_searchfiltersandoptionsbeta.js", this.initAdvancedSearch.bind(this), "advancedSearch:loaded");
			}
			else {
				advancedSearchLoading.hide();
				togglePopup(containerAdvanced);
			}			
		}
	},
	
	initAdvancedSearch:function() {
		filtersAndOptions = new SearchFiltersAndOptionsBetaAjax('FileSearch');
	},
	
	setSearchWithin:function(prefix) {
		if(prefix=="FO_") {
			var isWithin = $("FO_SearchWithinCheckbox").checked;
			$("SearchWithinCheckbox").checked = isWithin;
		} else {
			var isWithin = $("SearchWithinCheckbox").checked;
			// certain filters that trigger "search within" on the basic
			// form are ignored on the adavanced form, so the search within
			// may not exist in the advanced bar
			if($("FO_SearchWithinCheckbox")) {
				$("FO_SearchWithinCheckbox").checked = isWithin;
			}
		}

        // load SearchParamWithin Parameters into SearchParams when within is true,
        // otherwise set SearchParams to null
        // this will force it to use the default value and not be submitted as a search param
        for (i in SearchParamsWithin){
            // convert to string for comparison
            if (isWithin && Object.toJSON(SearchParamsDefault[i]) != Object.toJSON(SearchParamsWithin[i])) {
                SearchParams[i] = SearchParamsWithin[i];
            }
            else {
                SearchParams[i] = null;
            }
        }
	},
	
	ToggleSortOptions: function() {
		/* Hiding audio sort options if audio is enabled 
		and sort options.
		Gets all of the translated sort options from a hidden
		field that contains all of the values in a JSON string
		*/
		var foAudio = $("SearchBarFileTypeAudio");
		var sortBy = $("SearchBarSortBy");
        var defaultSortValue = sortBy.value;
		var OptionLength = 0;
		if(!foAudio.checked || $("SearchBarFileTypeImage").checked || $("SearchBarFileTypeIllustration [Vector]").checked || $("SearchBarFileTypeFlash").checked || $("SearchBarFileTypeVideo").checked){
			if(sortBy.value == 8 || sortBy.value == 9){
				sortBy.value = SearchParamsDefault.order;
			}
			OptionLength = 7;
		}
		else{
			OptionLength = 9;
		}
		
		if(sortBy.options.length != OptionLength && OptionLength != 0){
			//Clearing and populating the sortBy option box
			sortBy.options.length = 0;
            counter = 0;
            for (var sortValue in SearchSortOptions) {
                if (counter >= OptionLength) break;
                sortBy.options[counter] = new Option(SearchSortOptions[sortValue], sortValue, defaultSortValue == sortValue);
                counter++;
            }
		}
	}
};

// load after dom exists
document.observe('dom:loaded', function() {
	searchBarAjax = new SearchBarBetaAjax();
    searchBarAjax.loadEvents();
});

// holds the user's search param values, default search param values and sort by option values & labels,
var SearchParams = SearchParamsDefault = SearchParamsWithin = SearchSortOptions = {};

/**
 * Global function for generating and redirecting to the search URL
 */
function SearchSubmit() {
    var url = "file_search.php?action=file";

    // compile the url with params that are not default values
    for (var property in SearchParams) {

        // skip the page parameter, let the
        // page navigator handle this
        if (property == 'page') continue;

        var val = SearchParams[property];
        if (val === null) continue;
        url += "&" + property + "=" + (typeof val == "object" ? Object.toJSON(val) : val);
    }
    location.href = url;
    return false;
}