window.addEvent('domready', function() {
	$$('#content input.search').each(function(searchbtn){
		searchbtn.addEvent('click',function(event){
			var re1 = /\d+/;
			var re2 = /mystyle/;
			var searchIdx = searchbtn.name.match(re1);
			if(searchIdx && !re2.test(searchbtn.name)){
				submitMyStyleForm(this);
				event.preventDefault();
			}
			else if(searchIdx && re2.test(searchbtn.name)){
				openPopLayer(this,'popsearch-'+searchIdx,event,null);
			}
		});
	});	
	$(document.body).addEvent('click',function(event){
		resetPopups(event); 
	});
});

submitMyStyleForm = function(submitBtn){
	var idx = submitBtn.name.substring(submitBtn.name.indexOf('-')+1,submitBtn.name.length);
	var fields = $$('input[name$=-' + idx + ']');
	fields.combine($$('select[name$=-' + idx + ']'));
	var formActionStr = document.forms['searchform'].action;
	var queryStr = "?";
	$('noAdults-'+idx).value = getPaxCount("Adult",idx);
	$('noChildren-'+idx).value = getPaxCount("Child",idx);
	$('noInfants-'+idx).value = getPaxCount("Infant",idx);
	fields.each(function(field){
		queryStr += field.name.substring(0,field.name.indexOf('-')) + "=" + field.value + "&";
	});
	window.location = formActionStr + queryStr;
};

getPaxCount = function(type,idx){
	//type = Adult/Child/Infant
	var paxNo=0;
	var selector = 'select[name^=room'+type+']';
	var rooms = $$(selector);
	rooms.each(function(room){
		if(room.name.indexOf('-'+idx)!=-1){
			paxNo += parseInt(room.value);
		}
	});
	return paxNo;
};

//IE6 compatible
openPopLayer = function(ele,layerID,event,mm1){
	//Reset all popups to hidden except the current popup
	["popsearch-1","popsearch-2","popsearch-3","popsearch-4","popsearch-5","popsearch-6","popsearch-7"].each(function(popup, index){
		if( $(popup) && (popup != layerID) && $(popup).style.visibility=="visible" ){
			$(popup).fade('out');
		}else if( $(popup) && (popup == layerID) && $(popup).style.visibility=="hidden" ){
			$(popup).fade('in');
		}
	});
	var layerObj = $(layerID);  
	var popup = {x:-40, y:-300};
	layerObj.setPosition(popup);
	event.stop();
};
//IE6 compatible
resetPopups = function(evt){
	var ele = evt.target;
	var con = getContainerEle(ele);
	["popsearch-1","popsearch-2","popsearch-3","popsearch-4","popsearch-5","popsearch-6","popsearch-7"].each(function(popupId){
		if(popupId != con.getAttribute("id") && $(popupId)){			
			if($(popupId).style.visibility!="hidden"){
				$(popupId).fade('out');
			}
		}
	});
};
//IE6 compatible
getContainerEle = function(ele){
	var temp = ele;	
	var index = 12;
	while(temp.parentNode!=null && temp.parentNode.nodeType!=9 && index>0){
		if((temp.getAttribute("id") && temp.getAttribute("id").indexOf('popsearch')==-1) || (!temp.getAttribute("id")) ){
			temp = temp.parentNode;
		}
		index--;
	}
	return temp;
};
