var noFX = true;

function toggleItemDetails(itemID, detailType, darkRow)
{	
	var visible = $(detailType+'Details_'+itemID).visible();
	if (noFX==true) {
		$(detailType+'Details_'+itemID).toggle();		
	} else {
		Effect.toggle(detailType+'Details_'+itemID, 'blind', { duration: 0.3 });
	}
	if (darkRow==true)
		var arrCol = '_dr';
	else
		var arrCol = '_lr';
		
	if (visible==true)
	{	
		//we've just closed the details
		//$('recipeDetails_Arrow_'+itemID).style.backgroundImage = 'url(imgs/itemList/recipearrow_right'+arrCol+'.gif)';	
		$('recipeDetails_Arrow_'+itemID).src = 'imgs/itemList/recipearrow_right'+arrCol+'_off.gif';	
	} else {
		//we've just opened the details
		$('recipeDetails_Arrow_'+itemID).src = 'imgs/itemList/recipearrow_down'+arrCol+'_off.gif';
		//$('recipeDetails_Arrow_'+itemID).style.backgroundImage = 'url(imgs/itemList/recipearrow_down'+arrCol+'.gif)';			
	}
}


/*-----------------------------------------*/
/* Search Bar Functions                    */
/*                                         */
/* All the functions used by the different */
/* search panels                           */
/*-----------------------------------------*/

//list of all the open panels
var openPanelsArray = new Array();

//open all the panels listed above (well, actually toggle them, so assumes they start closed)
function openPanels()
{
	if ($F('openPanels') != '')
	{
		panelArr = $F('openPanels').split(',');
		panelArr.uniq();
		
		//open each panel 
		panelArr.each(function (s)	{	togglePanel(s);		});	
	}	
}
// open or close the navigation panel with the specified ID
function togglePanel(panelID)
{
	var panel = $('SB_Contents_'+panelID);
	var visible = panel.visible();
	if (visible==true)
	{	
		//close a panel
		openPanelsArray = openPanelsArray.without(panelID);
		if (noFX==true) {
			panel.hide();
		} else {
			new Effect.BlindUp(panel, { duration:0.5 });
		}		
		
		$('SB_Header_Arrow_'+panelID).style.backgroundImage = 'url(imgs/searchpanel/SBarrow_left.gif)';
	} else {
		//open a panel
		openPanelsArray.push(panelID);
		$('SB_Header_Arrow_'+panelID).style.backgroundImage = 'url(imgs/searchpanel/SBarrow_down.gif)';
		
		if (noFX==true) {
			panel.show();
		} else {
			new Effect.BlindDown(panel, { duration:0.5 });
		}
		
		//track every time a panel is opened
		urchinTracker('/panels/opened_'+panelID);					
	}
	/*new Effect.toggle(panel, 'blind',{ duration: 0.5 });*/

	$('openPanels').value = openPanelsArray;
}


var defaultSerializedStr = 'itemSearch=1&q_name=&q_minLvl%5Bmin%5D=&q_minLvl%5Bmax%5D=&q_itemLvl%5Bmin%5D=&q_itemLvl%5Bmax%5D=&q_quality%5Bmin%5D=0&q_quality%5Bmax%5D=6&q_crafted=&q_bindType=&searchButton=Search&q_selectedTypes=&selectedTypes_select=&q_raids=&raids_select=&q_instances=&instances_select=&q_heroicInstances=&heroicInstances_select=&q_bosses=&bosses_select=&q_otherSources=&otherSources_select=&q_selectedStats1=&selectedStats1_select=&q_selectedStats2=&selectedStats2_select=&q_selectedStats3=&selectedStats3_select=&q_selectedStats4=&selectedStats4_select=&q_reqFactions=&reqFactions_select=&q_tradeSkills=&tradeSkills_select=&q_socketColors=&socketColors_select=&q_reqCharClass=&reqCharClass_select=&q_tiers=&tiers_select=';


function checkChange(form)
{
	newStr = form.serialize()
	newStr = newStr.gsub(/openPanels(.*?)&/, '');

	if (newStr!=defaultSerializedStr)
	{
		$('resetButton').src = "imgs/searchpanel/reset_button.gif";
		$('resetButton').setStyle({ cursor: 'pointer' });
	} else {
		$('resetButton').src = "imgs/searchpanel/reset_button_disabled.gif";
		$('resetButton').setStyle({ cursor: '' });
	}
}

// reset all the seach bar fields
function resetSearch()
{
	//track every time the search bar is reset
	urchinTracker('/search_criteria/reset');

	openPanels();
	
	//unset values for all the fields
	$('q_name').value = '';
	$('q_minLvl[min]').value = '';
	$('q_minLvl[max]').value = '';
	$('q_itemLvl[min]').value = '';
	$('q_itemLvl[max]').value = '';
	
	$('q_quality[min]').value = 0;
	$('q_quality[max]').value = 6;
	
	$('q_crafted').value = '';
	$('q_bindType').value = '';
	
	
	//empty all the lists
	for (listID in selectedLists)
	{
		if(typeof(selectedLists[listID]) != "function")
		{ 				
			listArr = selectedLists[listID];
			var len = listArr.length;
			for (var i=0; i<len; i++)
			{
				removeFromList(listID, listArr[i].replace('*',''));
			}
		
		}
	}
	
	//deselect all checkboxes
	checkboxes = $('searchForm').getInputs('checkbox');
	for (var i=0; i<checkboxes.length; i++)
		checkboxes[i].checked=false;

	checkChange($('searchForm'));
	
	
	$('q_name').focus()
		
}

function dropdownPushUp(pusher, pushee)
{
	if (pusher.value > pushee.value)
		pushee.value = pusher.value;
}
function dropdownPushDown(pusher, pushee)
{
	if (pusher.value < pushee.value)
		pushee.value = pusher.value;
}
/*--------------------------*/
/* Search list functions    */
/*--------------------------*/
//array that we add the IDs of the lists that we are going to be searching 
var selectedLists = new Array();

//adds elementID to the specified list, inserting row HTML grabbed from AJAX
function addToList(listID, selectedIndex, destListID, openPanel, initial)
{
	if (listID!='' && selectedIndex!='')
	{
		var value = $(listID+'_select').options[selectedIndex].value
		var title = $(listID+'_select').options[selectedIndex].text
		var key = selectedIndex+":"+value;		

		//reset dropdown
		$(listID+'_select').value = '';
		
		//add the list to the array of lists
		if (typeof(selectedLists[listID]) == 'undefined')
		{
			selectedLists[listID] = new Array();
		}	

		//check if the element is already in that list
		if (selectedLists[listID].indexOf(key) == -1 && selectedLists[listID].indexOf(key+'*') == -1)	
		{				
			//add the element
			selectedLists[listID].push(key);

			$('q_'+listID).value = selectedLists[listID];
									
			new Ajax.Updater(destListID, 'ajaxRequests.php?'+decodeURI(window.location.search.substring(1)), {
							method: 'post',
							parameters: { reqType: 'searchListRow', value: value, title: title, 
											selectedIndex: selectedIndex, listID: listID },
							onComplete: function(transport){
								//dont do animation at the beginning - it is annoying
								
								if (initial==true || noFX==true)
								{																
									$(listID+"_Row:"+key).show();
									
									if (openPanel==true)
										toggleDetails(listID, key, true);																										
								} else	{
									new Effect.BlindDown(listID+"_Row:"+key, {
															duration:0.3,
															afterFinish: function (obj) 
																		{
																		if (openPanel==true)
																			toggleDetails(listID, key);	
																		}																	
															});
															
								}																
								//$(destListID).getElementsByClassName('small_text_box').first().focus();
							},
							insertion: Insertion.Top
			});
			
			//track every time a search criteria is added to the list
			urchinTracker('/search_criteria/added_'+title);

			checkChange($('searchForm'));						

		} else {
			/*new Effect.Pulsate(listID+"_Row:"+key, {
							pulses: 2,
							duration:0.7
							});*/
		}
	}	
}

//remove from selectedLists array and from HTML list
//key never contains '*'
function removeFromList(listID, key)
{
	//remove from list if it's open or not
	if (selectedLists[listID].indexOf(key+'*')!=-1)
		selectedLists[listID] = selectedLists[listID].without(key+'*');
	else
		selectedLists[listID] = selectedLists[listID].without(key);			

	$('q_'+listID).value = selectedLists[listID];

	if (noFX == true)
	{
		$(listID+"_Row:"+key).remove();
	} else {
		new Effect.BlindUp(listID+"_Row:"+key, {
												duration:0.3,
												afterFinish: function (obj) {
																	obj.element.remove();	
																}
												});
	}	
	
	checkChange($('searchForm'));
}

function generateList(listID, destListID)
{	
	var listArr = $F("q_"+listID).split(',');
	listArr.uniq();
	//add each element 
	listArr.each(function (s)	{
								if (s!='')
								{
									tmpVal = s.split(':');										
									addToList(listID, tmpVal[0], destListID, (s.indexOf('*') != -1), true); 
								}
								});	
}

//open or close the details area of item types panel
function toggleDetails(listID, key, noFX_in)
{
	//use global noFX
	if (noFX==true) noFX_in = true;
	
	details = $(listID+'_Details:'+key);
	//noFX = true;
	if (details.visible()==true)
	{
		$(listID+'_MinMaxArrow:'+key).src = 'imgs/searchpanel/details_minArrow.gif';
		if (noFX_in==true)
		{
			details.hide();
		} else {
			new Effect.BlindUp(details, { duration:0.3 });
		}
		selectedLists[listID][selectedLists[listID].indexOf(key+'*')] = key;			
	
	} else {		
		$(listID+'_MinMaxArrow:'+key).src = 'imgs/searchpanel/details_maxArrow.gif';	
		if (noFX_in==true)
		{
			details.show();
		} else {
			new Effect.BlindDown(details, { duration:0.3 });
		}		
		selectedLists[listID][selectedLists[listID].indexOf(key)] = key+'*';		
	}	
	$('q_'+listID).value = selectedLists[listID];
}
/*-------------------------------------------*/
/* END Search List Functions			     */
/*-------------------------------------------*/

/*-------------------------------------------------------------------------------------------------------*/
/* END Search Bar Functions                    															 */
/*-------------------------------------------------------------------------------------------------------*/



/*------------------------------------------*/
/* Comparator Functions                     */
/*                                          */
/* All the functions used by the comparator */
/*------------------------------------------*/

//take an itemID, and store this itemID in the PHP session variables1
//then fill the comparator div with the HTML for that items tooltip box
function addToComparator(itemID, compBox)
{
	if (parseInt(compBox)!='NaN')
	{
		//deselect the currently selected box
		if (comparatorContents[compBox] != '' && comparatorContents[compBox] != itemID && $("itemrow_comparatorControl_"+comparatorContents[compBox]+"_"+compBox)) 
		{
			$("itemrow_comparatorControl_"+comparatorContents[compBox]+"_"+compBox).setStyle({  backgroundColor: comparatorColors[compBox]	});	
		}
		comparatorContents[compBox] = itemID;
		
														
		new Effect.Fade('comparatorBox_'+compBox, { 	duration:0.5, 
														to: 0.01,
														afterFinish: function(obj) { 
																obj.element.update(tooltipHTML[itemID]);																			$('comparatorCloser_'+compBox).show();
																
																new Effect.Appear('comparatorBox_'+compBox, { 	duration:0.5,
																				  					from: 0.01
																								});														
																}
													});
		
		new Ajax.Request('ajaxRequests.php', {
				method: 'post',
				parameters: { reqType: 'comparatorSession', itemID: itemID, compBox: compBox }
				});
		//track every time the comparator is used
		urchinTracker('/comparator/compBox_'+compBox);
	}
	
}		

//revert the contents of the specified comparator box, and nullify the session variable
function removeFromComparator(compBox)
{
	if (parseInt(compBox)!='NaN')
	{
		if ($("itemrow_comparatorControl_"+comparatorContents[compBox]+"_"+compBox)) 
		{
			$("itemrow_comparatorControl_"+comparatorContents[compBox]+"_"+compBox).setStyle({  backgroundColor: comparatorColors[compBox]	});	
		}
		comparatorContents[compBox] = '';
		
		$('comparatorCloser_'+compBox).hide();
				
		$('comparatorBox_'+compBox).innerHTML = "<div class='itembox'>To view an item here, click its <span style='color:"+comparatorColors_on[compBox]+";'>"+comparatorColorNames[compBox]+"</span> bar</div>";
		
		new Ajax.Request('ajaxRequests.php', {
				method: 'post',
				parameters: { reqType: 'comparatorSession_remove', compBox: compBox }
				});
	}
}


//changes the style of a comparator box when MOUSEOVER-ing
function highlightComparator(itemID, compBox)
{	
	$("itemrow_comparatorControl_"+itemID+"_"+compBox).setStyle({ backgroundColor: comparatorColors_on[compBox]	});
	$('comparatorWrapper_'+compBox).setStyle({ backgroundColor: comparatorColors_on[compBox]	});
}

//changes the style of a comparator box when the MOUSEOUT-ing
function deselectComparator(itemID, compBox)
{	
	//only deselect if not a selected comparator
	if (itemID != comparatorContents[compBox]) 
	{
		$("itemrow_comparatorControl_"+itemID+"_"+compBox).setStyle({  backgroundColor: comparatorColors[compBox]	});	
	}
	$('comparatorWrapper_'+compBox).setStyle({  backgroundColor: comparatorColors[compBox]	});
}

/*------------------------------------------------------------------*/
/* END Comparator Functions                 						*/
/*------------------------------------------------------------------*/


//Replicates the _GET() php function, getting the value of a variable
// passed into the address (returns defaultVal if token doesnt exist)
function _GET(token, defaultVal) {
	var query = decodeURI(window.location.search.substring(1));
	//look for our token
	start = query.indexOf(token);
	if(start >-1) {//if we find it
		start += token.length+1; //location of value start 
		end = query.indexOf('&', start);
		if (end == -1)
			end = query.length;
			
		return query.substr(start, (end-start) ); //run a substring based on location of the value
		
		//return Ya[1]; //ignore the first value, output the second in the array    	
	} else { //or
		if (defaultVal==null)
			defaultVal ='';
			
		return defaultVal;
	}
}


function changeBackgroundPosition(element,pos_x, pos_y)
{
	document.getElementById(element).style.backgroundPosition= pos_x + "px " + pos_y + "px";
}

// fill the dest with the image (if it isnt there already). If it is then toggle the dest 
function toggleMap(dest, imgName)
{
	if (dest.name==imgName) {		
		//if (dest.visible() != true)
			//dest.scrollTo();
		new Effect.toggle(dest, 'appear', {duration:0.5});			
	} else {
		dest.name=imgName;
		dest.src = 'imgs/guide/maps/'+imgName+'.jpg';
		//dest.scrollTo();
		if (dest.visible() != true)
			new Effect.Appear(dest, {duration:0.5});
	}
}

function selectMobDetails(mobName)
{
		$(currentMob+'_link').removeClassName('mob_entry_selected');
		$(currentMob+'_info').hide();
		
		currentMob = mobName;		
		$(currentMob+'_link').addClassName('mob_entry_selected');
		$(currentMob+'_info').show();
		
		$('mob_image').src = 'imgs/guide/instances/'+instanceName+'/'+mobName+'.jpg';
		
		
}

/*
function toggle(elementID, displayStyle) 
{
	var el = document.getElementById(elementID);
	
	if (el.style.display != 'none')		
	{
		el.style.display = 'none';
		return 'off';
	}
	else
	{	
		if (displayStyle==null) displayStyle='block';		
		el.style.display = displayStyle;
		
		return 'on';
	}
}
*/

/* return array with x/y coords of cursor event*/
function findCoords(e) {
   var posX = 0, posY = 0;
   if( !e ) { e = window.event; } if( !e ) { return [ 0, 0 ]; }
   if( typeof( e.pageX ) == 'number' ) {
      posX = e.pageX; posY = e.pageY;
   } else {
      if( typeof( e.clientX ) == 'number' ) {
         posX = e.clientX; posY = e.clientY;
         if( document.body && ( document.body.scrollTop || document.body.scrollLeft ) && !( window.opera || window.debug || navigator.vendor == 'KDE' ) ) {
               posX += document.body.scrollLeft; posY += document.body.scrollTop;
         }  else {
            if( document.documentElement && ( document.documentElement.scrollTop || document.documentElement.scrollLeft ) && !( window.opera || window.debug || navigator.vendor == 'KDE' ) ) {
               posX += document.documentElement.scrollLeft; posY += document.documentElement.scrollTop;
            }
         }
      }
   }
   return [ posX, posY ];
}

function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

function redirector(dest)
{
	window.location = dest;
}

function checkAllBoxes_matchSource(sourceID, groupName, scope)
{
	checked = $(sourceID).checked;
	$(scope).getElementsBySelector('[group="'+groupName+'"]').each(	function(s) { 
																		$(s).checked = checked;
																				} 
																	);
}


//go through all the checkboxes with nameprefix from 0 to boxCnt 
function toggleAllBoxes(namePrefix, boxCnt)
{
	for(i=0; i<boxCnt; i++)
	{
		box = document.getElementById(namePrefix+i);
			
		if (box.checked==true)
			box.checked = false;
		else
			box.checked = true;
	}	
}



function populateSelect(selectSourceID, selectDestID, dataArray, selectedIndex)
{
	var source = document.getElementById(selectSourceID);
	var number = source.options[source.selectedIndex].value;
	if (!number) return;
	
	var list = dataArray[number];
	var dest = document.getElementById(selectDestID);
	dest.options.length = 0;
	for(i=0;i<list.length;i+=2)
	{
		dest.options[i/2] = new Option(list[i],list[i+1]);
		if (dest.options[i/2].value == selectedIndex) 
			dest.options[i/2].selected = true;
	}
}

function alertChange(element, initVal)
{	
	if (!element.selectedIndex)
	{
		value = element.value;
	} else {
		value = element.options[element.selectedIndex].value;
	}
	
	if (value != initVal)
	{
		element.style.backgroundColor = "#FFcc66";
	} else {
		element.style.backgroundColor = "";
	}
}

function convertBitMask(bitMask, addedBits)
{

	if (addedBits!="" && bitMask >= addedBits)
		bitMask = bitMask - addedBits;
		
	settings = new Array();
	settingsCnt = 0;
	maxPwr = 14; <!-- 0->14 -->	
	for (pwr=maxPwr; pwr>=0; pwr--)
	{
		binval=1;
		for (i=0; i<pwr; i++)
			binval = binval * 2;
	
		if (bitMask-binval >= 0)
		{
			<!-- bitMask exists -->
			bitMask = bitMask - binval;
			settings[settingsCnt] = pwr+1;
			settingsCnt++;
		}
	}
	return settings;
}

function calcBitMask(sourceIDname, sourceCnt, destID)
{
	total = 0;
	for(i=0;i<sourceCnt;i++)
	{
		source = document.getElementById(sourceIDname+"_"+i);
		if (!source.selectedIndex) {
			value = source.value;
		} else {
			value = source.options[source.selectedIndex].value;
		}
		
		if (value != -1 && value != "")
		{
			total += parseInt(value);
		}
	}
	
	document.getElementById(destID).value = total;
}
