var SearchBarAjax = Class.create();
SearchBarAjax.prototype = {
	initialize: function(context) {
		this.colorSelector='Simple';
	},
	
	toggleFileType: function(fileType) {
		var url = "ajax_class_creator.html";
		var params = "ajax_action=toggleFileType&ajax_class=searchbar&fileType="+fileType;
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.toggleFileTypeCompleted.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
	},
	
	toggleFileTypeCompleted: function(req) {
		var data = AjaxUtil.receiveArray(req.responseText);	
		if(data['fileType'] == 8) {
			$("SearchBarFileType"+data['fileType']).src=data['src'];
			this.updateFileTypeRadio(data['fileType']+'4_3', 'SearchBarFileTypeOptions'+data['fileType']+"4_3_"+data['value']);
			this.updateFileTypeRadio(data['fileType']+'16_9', 'SearchBarFileTypeOptions'+data['fileType']+"16_9_"+data['value']);
			if($(data['advancedFileFilter']+'4_3') && $(data['advancedFileFilter']+'4_3').value !="" && $(data['advancedFileFilter']+'16_9') && $(data['advancedFileFilter']+'16_9').value !="")	{
				$(data['advancedFileFilter']+'4_3').value=data['value'];
				$(data['advancedFileFilter']+'4_3').onchange();
				$(data['advancedFileFilter']+'16_9').value=data['value'];
				$(data['advancedFileFilter']+'16_9').onchange()	;
			}
		} else {
			$("SearchBarFileType"+data['fileType']).src=data['src'];
			this.updateFileTypeRadio(data['fileType'], 'SearchBarFileTypeOptions'+data['fileType']+"_"+data['value']);
			if($(data['advancedFileFilter']) && $(data['advancedFileFilter']).value !="") {
				$(data['advancedFileFilter']).value=data['value'];
				$(data['advancedFileFilter']).onchange();
			}
		}
		$("TopSearchFileTypeSizePrice").value=data.jsonValue;
	}, 
	
	expandFileType: function(fileType) {
		var fileTypePopup = $("SearchBarFileTypeOptionsContainer"+fileType);
		buildPopupIFrame(fileTypePopup, false);
		positionPopup($("SearchBarFileTypeContainer"+fileType), fileTypePopup, 10, -1);
		togglePopup(fileTypePopup);
		$("SearchBarFileTypeExpand"+fileType).onclick=function() {
			togglePopup(fileTypePopup);
		}
		fileTypePopup.onmouseover=function() {
			togglePopup(fileTypePopup, "block");
		}
		fileTypePopup.onmouseout=function() {
			togglePopup(fileTypePopup, "none");
		}
		
	},
	
	toggleFileTypeRadio:function(fileType, checkedRadioID) {
		if(this.validateRadioSelection(fileType, checkedRadioID)){
			this.updateFileTypeRadio(fileType, checkedRadioID);
			
			var url = "ajax_class_creator.html";
			var params = "ajax_action=toggleFileTypeRadio&ajax_class=searchbar&fileType="+fileType+"&fileTypeRadio="+$(checkedRadioID).value;
			var myAjax = new Ajax.Request
				(
					url, 
					{ 
						method: "get", 
						parameters: params,
						onComplete: this.toggleFileTypeRadioCompleted.bind(this),
						onFailure: this.failed.bind(this)
					}
				);
		}
	},
	
	toggleFileTypeRadioCompleted:function(req) {
		var data = AjaxUtil.receiveArray(req.responseText);
		if(data['src'] && $("SearchBarFileType"+data['fileType'])) {
			$("SearchBarFileType"+data['fileType']).src=data['src'];
		}
		if(data['advancedFileFilter'] && $(data['advancedFileFilter']) && $(data['advancedFileFilter']).value!="") {
			$(data['advancedFileFilter']).value=data['advancedFileFilterValue'];
			$(data['advancedFileFilter']).onchange()
		}
		$("TopSearchFileTypeSizePrice").value=data.jsonValue;
	},
	
	updateFileTypeRadio:function(fileType, checkedRadioID) {
		var form = $("SearchBarFileTypeOptionsForm"+fileType);
		var checkedRadio=$(checkedRadioID);
		var radios = form.elements[checkedRadio.name];
		for(var i=0; i<radios.length; i++){
			radios[i].checked=(radios[i].id == checkedRadio.id ? true:false);
			$(radios[i].id+"_Label").className=(radios[i].checked? 'radioon' :'radiooff');
		}
	},
	
	validateRadioSelection: function(fileType, checkedRadioID) {
		if($(checkedRadioID).value!='None') {
			return true;
		} else {
			if(fileType!=1) {
				var form = $("SearchBarFileTypeOptionsForm1");
				var radios = form.elements['SearchBarFileTypeOptions1'];
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked && radios[i].value!='None') {
						return true;
					}
				}
			}
			if(fileType!=4) {
				var form = $("SearchBarFileTypeOptionsForm4");
				var radios = form.elements['SearchBarFileTypeOptions4'];
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked && radios[i].value!='None') {
						return true;
					}
				}
			}
			if(fileType!=7) {
				var form = $("SearchBarFileTypeOptionsForm7");
				var radios = form.elements['SearchBarFileTypeOptions7'];
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked && radios[i].value!='None') {
						return true;
					}
				}
			}
			if(fileType!='84_3') {
				var form = $("SearchBarFileTypeOptionsForm84_3");
				var radios = form.elements['SearchBarFileTypeOptions84_3'];
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked && radios[i].value!='None') {
						return true;
					}
				}
			}
			if(fileType!='816_9') {
				var form = $("SearchBarFileTypeOptionsForm816_9");
				var radios = form.elements['SearchBarFileTypeOptions816_9'];
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked && radios[i].value!='None') {
						return true;
					}
				}
			}
			return false;
		}
	},
		
	toggleColorSelector:function(selector) {
		if(this.colorSelector!=selector) {			
			if($("ColorSelector_"+selector).innerHTML=="") {
				var url = "ajax_class_creator.html";
				var params = "ajax_action=GetColorSelector&ajax_class=searchbar&color="+$('SearchBarColor').value+"&type="+selector;
				var myAjax = new Ajax.Request
					(
						url, 
						{ 
							method: "get", 
							parameters: params,
							onComplete: this.toggleColorSelectorCompleted.bind(this),
							onFailure: this.failed.bind(this)
						}
					);
			} else {
				this.switchColorSelector(selector);	
			}
		}
	},
	
	toggleColorSelectorCompleted:function(req) {
		var data = AjaxUtil.receiveArray(req.responseText);
		$('ColorSelector_'+data['selector']).innerHTML = data['content'];
		this.switchColorSelector(data['selector']);
	},
	
	switchColorSelector:function(selector) {			
		$("ColorSelector_"+this.colorSelector).style.display="none";
		$("ColorSelectorAnchor_"+this.colorSelector).style.fontWeight="normal";
		$("ColorSelector_"+selector).style.display="block";
		$("ColorSelectorAnchor_"+selector).style.fontWeight="bold";
		this.colorSelector=selector;
	},
	
	setMatrix:function() {
		var location=[];
		var value=[];
		CopySpace.syncSuffix();
		CopySpace.setSensitivity();
		for(var i=0; i<CopySpace.matrix.length; i++) {
			var spaceEle = $("cs_"+CopySpace.matrix[i]+"_button");
			if(spaceEle.className == 'cs_on' || spaceEle.className == 'cs_off') {
				var loc = (CopySpace.matrix[i] == "center" ? "Center" : CopySpace.matrix[i].toUpperCase());
				location.push(loc);
				value.push(spaceEle.className);
			}
		}
		var url = "ajax_class_creator.html";
		var params = "ajax_action=SetMatrix&ajax_class=searchbar&sensitivity="+CopySpace.currentSensitivity+"&location="+location.join(",")+"&value="+value.join(",");
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.setMatrixCompleted.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
		
	},
	
	setMatrixCompleted: function(req) {
		$('copyspaceContainer2').style.display='none';
		$('copySpace').value=req.responseText
	},
	
	resetMatrix: function() {
		CopySpace.resetBox();
	},
	
	closeMatrix: function() {
		CopySpace.syncBox();
		CopySpace.syncSensitivity();
		togglePopup($("copyspaceContainer2"));
	},
	
	toggleCopySpace:function() {
		var copyspacePopup = $("copyspaceContainer2");
		buildPopupIFrame(copyspacePopup, false);
		positionPopup($("SearchBarCopySpaceContainer"), copyspacePopup, 10, 10);
		togglePopup(copyspacePopup);
		$("SearchBarCopySpaceContainer2").onclick=function() {
			togglePopup($("copyspaceContainer2"));
		}
		copyspacePopup.onmouseover=function() {
			togglePopup($("copyspaceContainer2"), "block");
		}
		copyspacePopup.onmouseout=function() {
			togglePopup($("copyspaceContainer2"), "none");
		}
	},
	
	toggleSearchColor:function() {
		var divPopup = $('SearchBarColorSelector');
		buildPopupIFrame(divPopup, false);
		positionPopup($("SearchBarColorContainer"), divPopup, 10, 10);
		togglePopup(divPopup);
		$("SearchBarCurrentColorBox").onclick=function() {
			togglePopup($('SearchBarColorSelector'));
		}
		divPopup.onmouseover=function() {
			togglePopup($('SearchBarColorSelector'), 'block');
		}
		divPopup.onmouseout=function() {
			togglePopup($('SearchBarColorSelector'), 'none');
		}
	},
	
	setSearchColor: function() {
		ColorSelector.syncSearchBarColor();
		$('color').value=ColorSelector.initialRGB;
		$('SearchBarColorSelector').style.display='none';
	},
		
	clearSearchColor: function() {
		ColorSelector.clearColor();
	},
	
	closeSearchColor: function() {
		ColorSelector.syncPopupColor();
		togglePopup($('SearchBarColorSelector'));
	},
	
	setSortBy: function(value, skipAJAX) {

		if ( !skipAJAX ){
			skipAJAX = false;
		}

		$('order').value=value;

		if ( skipAJAX == false ){
			var url = "ajax_class_creator.html";
			var params = "ajax_action=SetSortBy&ajax_class=searchbar&sortBy="+value;
			var myAjax = new Ajax.Request
				(
					url, 
					{ 
						method: "get", 
						parameters: params,
						onComplete: this.setSortByCompleted.bind(this),
						onFailure: this.failed.bind(this)
					}
				);	
		}
	},
	
	setSortByCompleted: function(req) {
		if($("FO_Sort")) {
			$("FO_Sort").innerHTML = req.responseText;
		}
	},
	
	failed: function(req) {
		alert(req.responseText);
	},
	
	toggleAdvancedSearch: function(){
		//make sure it's initalized
		filtersAndOptions.initializeAdvanced();

		var container = $('AdvancedSearchFiltersAndOptionsContainer');
		var currentState = container.style.display;
		var newState = 'block';
		var sendState = $('advancedSearchState');
		
		if(currentState == newState){
			newState = 'none';
		}
		
		container.style.display = newState;
		sendState.value = newState;
	},
		
	toggleBrowseSearch: function(){
		var container = $('MajortermBrowserContainer');
		var currentState = container.style.display;
		var newState = 'block';
		var sendState = $('browserSearchState');
		
		if(currentState == newState){
			newState = 'none';
		}
		
		container.style.display = newState;
		sendState.value = newState;
   },
   
   toggleSearchTips: function(){
		var container = $('SearchTipsContainer');
		
		if(container.innerHTML=="") {
			this.loadSearchTips();
		} else {
			var currentState = container.style.display;
			var newState = 'block';
			//var sendState = $('tipsSearchState');
			
			if(currentState == newState){
				newState = 'none';
			}
			
			container.style.display = newState;
			//sendState.value = newState;
		}
   },
   
	loadSearchTips: function() {
		var url = "ajax_class_creator.html";
		var params = "ajax_action=LoadSearchTips&ajax_class=searchbar";
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.loadSearchTipsCompleted.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
	},
	loadSearchTipsCompleted:function(req) {
		$('SearchTipsContainer').innerHTML = req.responseText;
		this.toggleSearchTips();
	}
};

var CopySpace = {
	matrix: ['nw', 'n','ne','w','center', 'e', 'sw','s','se'],
	initialSensitivity: 'sensitivity3',
	currentSensitivity: 'sensitivity3',
	sensitivityInit:function(value){
		this.initialSensitivity=value;
		this.currentSensitivity=value;
	},
	changebox: function(ele) {
		if (ele.className == 'cs_xxx' || ele.className == 'xxx'){
			ele.className = 'cs_on';
		} else if (ele.className == 'cs_on'){
			ele.className = 'cs_off';
		} else if (ele.className == 'cs_off'){
			ele.className = 'cs_xxx';
		}
	},
	changeSensitivity: function(ele){
		for (i = 1; i <= 5; i++){
			$("sensitivity"+i).className = "sensitivity_off";
		}
		ele.className = "sensitivity_on";
		this.currentSensitivity = ele.id;
	},
	syncSuffix: function() {
		for(var i=0; i<this.matrix.length; i++) {
			$("cs_"+this.matrix[i]+"_button").className=$("cs_"+this.matrix[i]).className;
		}
	},
	syncBox: function() {
		for(var i=0; i<this.matrix.length; i++) {
			$("cs_"+this.matrix[i]).className=$("cs_"+this.matrix[i]+"_button").className;
		}
	},
	resetBox:function() {
		for(var i=0; i<this.matrix.length; i++) {
			$("cs_"+this.matrix[i]).className="cs_xxx";
		}
	},
	setSensitivity:function() {
		this.initialSensitivity=this.currentSensitivity;
	},
	syncSensitivity:function() {
		this.currentSensitivity=this.initialSensitivity;
		this.changeSensitivity($(this.currentSensitivity));
	}
};

function UpdateCurrentColorBox(rgb) {
	if (rgb == ""){
		ColorSelector.clearColor();
	} else {
		ColorSelector.setColor(rgb);
	}
}

var ColorSelector={
	initialRGB:"",
	rgbInit:function(value){
		this.initialRGB=value;		
	},
	clearColor:function() {
		$('SearchBarColor').value='';
		var thebox2 = $("SearchBarCurrentColorBox2");
		thebox2.title="";
		thebox2.setStyle({
  			backgroundColor: "",
  			backgroundImage: "url(/images/colourblock_bg.gif)"
		});
		$("ColorSelectorHex").value="";
		this.refreshColorSelectors('0,0,0');
	},
	setColor:function(rgb){
		rgb = this.formatRGB(rgb);
		var hex=this.rgbToHex(rgb);
		$("ColorSelectorHex").value=hex;
		var thebox2 = $("SearchBarCurrentColorBox2");
		thebox2.title=hex;
		thebox2.setStyle({
  			backgroundColor: "rgb("+rgb+")",
  			backgroundImage: "none"
		});
		this.refreshColorSelectors(rgb);
	},
	formatRGB: function(rgb) {
		var value_array = rgb.split(",");
		var newRGBArray = new Array(3);
		newRGBArray[0] = (value_array[0]-0);
		newRGBArray[1] = (value_array[1]-0);
		newRGBArray[2] = (value_array[2]-0);
		return newRGBArray.join(',');
	},
	refreshColorSelectors: function(value) {
		if($("ColorSelector_HSV").innerHTML=='' && $("ColorSelector_HSV").innerHTML=='') {
		} else {
			var url = "ajax_class_creator.html";
			var params = "ajax_action=RefreshColorSelectors&ajax_class=searchbar&color="+value;
			var myAjax = new Ajax.Request
				(
					url, 
					{ 
						method: "get", 
						parameters: params,
						onComplete: this.refreshColorSelectorsCompleted.bind(this)
					}
				);
		}
	},
	refreshColorSelectorsCompleted: function(req) {
		var data=AjaxUtil.receiveArray(req.responseText);
		
		if($("ColorSelector_HSV").innerHTML!='') {
			$("ColorSelector_HSV").innerHTML = data.HSV;
		}
		if($("ColorSelector_RGB").innerHTML!='') {
			$("ColorSelector_RGB").innerHTML = data.RGB;
		}
	},
	
	hexToDec:function(hex){ 
		return parseInt(hex,16); 
	},
	
	trimHex:function(str){
		return str.replace(/^\#/g, '');
	},
	
	splitHex:function(hex){
		var hex = this.trimHex(hex);
		if(hex.length==6) {
			r = this.hexToDec(hex.substring(0, 2));
			g = this.hexToDec(hex.substring(2, 4));
			b = this.hexToDec(hex.substring(4, 6));
			return r + ',' + g + ',' + b;
		}
		else {
			return false;
		}
	},
	rgbToHex:function(rgb) {
		var value_array = rgb.split(",");
		hexcode = "#";

		if (value_array[0] < 16) hexcode = hexcode + "0";
		hexcode = hexcode + (value_array[0]-0).toString(16);
		if ( value_array[1] < 16) hexcode = hexcode + "0";            
		hexcode = hexcode + (value_array[1]-0).toString(16);
		if (value_array[2] < 16) hexcode = hexcode + "0";            
		hexcode = hexcode + (value_array[2]-0).toString(16); 

		return hexcode;
	},
	syncSearchBarColor:function() {
		var thebox = $("SearchBarCurrentColorBox");
		var thebox2 = $("SearchBarCurrentColorBox2");
		thebox.style.backgroundColor=thebox2.style.backgroundColor;
		thebox.style.backgroundImage=thebox2.style.backgroundImage;
		this.initialRGB = $('SearchBarColor').value;
	},
	syncPopupColor:function() {
		var thebox = $("SearchBarCurrentColorBox");
		var thebox2 = $("SearchBarCurrentColorBox2");
		thebox2.style.backgroundColor=thebox.style.backgroundColor;
		thebox2.style.backgroundImage=thebox.style.backgroundImage;
		$('SearchBarColor').value= this.initialRGB;
		if(thebox2.style.backgroundColor!="") {
			$("ColorSelectorHex").value=this.rgbToHex(this.initialRGB);
		} else {
			$("ColorSelectorHex").value="";
		}
	}
};

