var arrIngredients = new Array();
var arrIngredientsNames = new Array();

function showShadowBox(strTitle, strContent) {
	objAddJoke = document.getElementById('add_joke');
	objShadowBox = document.getElementById('shadow_box');
	objShadowBoxTitle = document.getElementById('shadow_box_top');

	objShadowBoxContent = document.getElementById('shadow_box_content');
	document.getElementById('shadow_box').style.display = 'block';
	document.getElementById('shadow_box').style.top = getScrollTop()+ (objShadowBox.clientHeight / 2) + 'px';//getAbsoluteTop(objAddJoke)+ 'px';
	document.getElementById('shadow_box').style.left = (getWindowWidth() / 2) - (objShadowBox.clientWidth / 2) + 'px';

	objShadowBoxTitle.innerHTML = strTitle;
	objShadowBoxContent.innerHTML = '<br />'+strContent;

	darkenBackground();
}

function hideShadowBox() {
	objShadowBox = document.getElementById('shadow_box');
	document.getElementById('shadow_box').style.display = 'none';

	normalBackground()
}


function getScrollTop() {
	var intScrollTop = null;
	if(window.innerHeight) {
		intScrollTop = window.pageYOffset;
	} else if(document.documentElement.clientHeight) {
		intScrollTop = document.documentElement.scrollTop;
	} else {
		intScrollTop = document.body.scrollTop;
	}
	return intScrollTop;
}

function getScrollLeft() {
	var intScrollLeft = null;
	if(window.innerWidth) {
		intXOffset = window.pageXOffset;
	} else if(document.documentElement.clientWidth) {
		intXOffset = document.documentElement.scrollLeft;
	} else {
		intXOffset = document.body.scrollLeft;
	}
	return intScrollLeft;
}

function getWindowHeight() {
	var intHeight = null;
	if(window.innerHeight) {
		intHeight = window.innerHeight;
	} else if(document.documentElement.clientHeight) {
		intHeight = document.documentElement.clientHeight;
	} else {
		intHeight = document.body.clientHeight;
	}
	return intHeight;
}

function getWindowWidth() {
	var intWidth = null;
	if(window.innerWidth) {
		intWidth = window.innerWidth - 17;
	} else if(document.documentElement.clientWidth) {
		intWidth = document.documentElement.clientWidth;
	} else {
		intWidth = document.body.clientWidth;
	}
	return intWidth;
}

/*
*   Return: The page 'left' position of the element
*/
function getAbsoluteLeft(objElement) {
    var intXPos = objElement.offsetLeft;
    var objTemp = objElement.offsetParent;
    while (objTemp != null) {
        intXPos += objTemp.offsetLeft;
        objTemp = objTemp.offsetParent;
    }
    return intXPos;
}

/*
*   Return: The page 'left' position of the element
*/
function getAbsoluteTop(objElement) {
    var intYPos = objElement.offsetTop;
    var objTemp = objElement.offsetParent;
    while (objTemp != null) {
        intYPos += objTemp.offsetTop;
        objTemp = objTemp.offsetParent;
    }
    return intYPos;
}

function darkenBackground() {
    objDarkBG = document.getElementById('winDarkBackground');

	objDarkBG.style.top = '0px';
	objDarkBG.style.display = 'block';
}
function normalBackground() {
    objDarkBG = document.getElementById('winDarkBackground');

	objDarkBG.style.display = 'none';
}


/*********************Generic Useful Functions *****************************************/
//function gets url parameters for js
//Example on url http://www.volge.com/example.php?strArtistName=BenGibbard&flag=true
//eg getURLParamValue( 'strArtistName', true ) will return BenGibbard
//eg getURLParamValue( 'strArtistName', false ) will return strArtistName=BenGibbard
function getURLParamValue( strParamName, blnValueOnly ) {
	if(blnValueOnly)
    	intReturnType = 1; //setting this to 1 returns only the value of the param
	else
		intReturnType = 0; //setting this to 0 returns the param and value

	var strRegex = "[\\?&]"+strParamName+"=([^&#]*)";
	var objRegex = new RegExp( strRegex );
	var results = objRegex.exec( location.href );
	if( results == null )
		return '';
	else
	    return results[intReturnType];
}

//will take a url and replace the current value of a param, or it will just add the param if new
function replaceURLParamValue(strURL, strParamName, strParamValue) {
	strURLParam = getURLParamValue(strParamName, false);
	strSeperator = '';

	if(strURLParam == '') {
		if(strURL.indexOf('&') < 0)
			strSeperator = '?';
		else
			strSeperator = '&';

		strNewURL = strURL + strSeperator + strParamName + '=' + strParamValue;
		
	}
	else {
		if(strURLParam.charAt(0)=='?') {
			strSeperator = '?';
		}
		strURLParam = strURLParam.replace('&', '');
		strNewURL = strURL.replace(strURLParam, strSeperator+strParamName + '=' + strParamValue)
	}
	return strNewURL;
}



function bookmarkUs() {
	if (window.sidebar) { // Firefox
		window.sidebar.addPanel('Joking Jokes - Be Funny.', 'http://www.jokingjokes.com', "");
	} else if(window.opera && window.print) { // Opera
		var strAnchor = document.createElement('a');
		strAnchor.setAttribute('href','http://www.jokingjokes.com');
		strAnchor.setAttribute('title','Joking Jokes - Be Funny.');
		strAnchor.setAttribute('rel','sidebar');
		strAnchor.click();
	} else if(document.all) { // IE
		window.external.AddFavorite('http://www.jokingjokes.com}', 'Joking Jokes - Be Funny.');
	}
}


/*
*   Desc: Function fills all the specified selection fields with specified values on the page
*   Return: none
*/
function fillSelections( strForm, objSelects ) {
    var objForm = document.getElementById( strForm );
	
    for (var i in objSelects) {
		if(objSelects[i] != '') { //&& parseInt(objSelects[i], 10) != 0
			objForm.elements[i].value = objSelects[i];
		}
    }
}

function loadPage( intPage, strPageURL , strParams, blnAjax, strInto ) {
	var strURL = '';
 	if(strPageURL.indexOf('http://localhost')==-1) {
		//strURL = 'http://localhost';
	}

	strPageURL = strPageURL.slice(1);

	if( getURLParamValue('intPage') == '' ) {
		if(strParams!='') strParams = strParams+'&';
		strURL += strSiteURL+strPageURL + '?' + strParams + 'intPage=' + intPage;
	}
	else {
		strURL += strSiteURL+strPageURL + '?' + strParams.replace(getURLParamValue('intPage').replace('?', ''), '&intPage=' + intPage);
	}

	//if( strURL != strVisitedURL ){
		if( blnAjax )
			//alert(strURL);
			AjaxRequest( strURL, strInto, default_handle );
		else
			location.href = strURL;
	//}

	strVisitedURL = strURL;
}

function notLoggedIn() {
	strTitle='You Must Login.';
	strContent='You must Login to perform that action.'; //PENDING, add a login here...

	showShadowBox(strTitle, strContent);
}

function IsNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}


function formatItem(row) {
	arrInfo = new Array();
	arrInfo = row[1].split('_'); //arrInfo[0] - strDrinkURL ... arrInfo[1] - strCategory
	strReturn = '';

	strReturn += '<b>' + row[0] + '</b><br />';

	strReturn += '<div class="fs0">Drink contains keyword <b>'+objTextSearch.value+'</b></div>';

	strReturn += '<hr />';

	return strReturn;
}

function formatItemIngredient(row) {
	arrInfo = new Array();
	//arrInfo = row[1].split('_'); //arrInfo[0] - strDrinkURL ... arrInfo[1] - strCategory
	strReturn = '';

	strReturn += '<b>' + row[0] + '</b><br />';

	strReturn += '<hr />';


	return strReturn;
}

function findValue(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

	alert("The value you selected was: " + sValue);
}

function selectItem(li) {
	arrInfo = li.extra[0].split('_'); //arrInfo[0] - strDrinkURL ... arrInfo[1] - strCategory

	window.location.href = strSiteURL+arrInfo[1]+'/' + arrInfo[0];
}

function selectItemIngredient(li) {
	//arrInfo = li.extra[0].split('_');
	//alert('Picked!');
	//window.location.href = strSiteURL+arrInfo[1]+'/' + arrInfo[0];
	
	addIngredientWithResults((li.selectValue).stripslashes(), li.extra[0]);
}


function lookupAjax(){
	var oSuggest = $("#txtJokeSearch")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

function lookupLocal(){
	var oSuggest = $("#CityLocal")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

function showMoreCategory() {
	document.getElementById('hiddenMore').style.display = 'block';
}
function hideMoreCategory() {
	document.getElementById('hiddenMore').style.display = 'none';
}
function selectSearchTextBox(objThis) {
	if(objThis.value == 'Enter drink here...')
		objThis.value=''
}
function outSearchTextBox(objThis) {
	if(objThis.value == '')
		objThis.value='Enter drink here...'
}

function selectIngredientTextBox(objThis) {
	if(objThis.value == 'Search Ingredients...')
		objThis.value=''
}
function outIngredientTextBox(objThis) {
	if(objThis.value == '')
		objThis.value='Search Ingredients...'
}

function searchDrink() {
	if( objTextSearch.value == 'Enter drink here...' )
		objTextSearch.focus();
	else
		window.location.href=strSiteURL+"search.php?strDrinkName="+objTextSearch.value;
}

function addIngredient(strIngredientName, intIngredientId) {
	if(!arrIngredients.in_array(intIngredientId)) {
		objSelectedIngredients = document.getElementById('selectedIngredients');
		objResultsDrinks = document.getElementById('resultsDrinks');
		objStrSearchIngredient = document.getElementById('strSearchIngredient');
	
		var objNewIngredient = document.createElement('div');
		objNewIngredient.setAttribute('id', 'ingredient_'+intIngredientId);
		strIngredient = ' &#8250; '+strIngredientName + ' <div class="nCr fs0">(<a href="javascript: removeIngredient(\''+strIngredientName.stripslashes()+'\', '+intIngredientId+');">Remove</a>)</div> <br />';
		objNewIngredient.innerHTML = strIngredient;
	
		objResultsDrinks.innerHTML = '<img src="'+strSiteURL+'images/indicator.gif" alt="Loading..."/>';
		if(objSelectedIngredients.innerHTML == 'No Ingredients Selected.') {
			objSelectedIngredients.innerHTML = '';
		}
		objSelectedIngredients.appendChild(objNewIngredient);
		
		objStrSearchIngredient.value = 'Search Ingredients...';
	
		arrIngredients.push(intIngredientId);//add ingredient id to js array
		arrIngredientsNames.push(strIngredientName);
	}

}

function addIngredientWithResults(strIngredientName, intIngredientId) {
	addIngredient(strIngredientName, intIngredientId);
	getResults();
}

function getResults() {
	strIngredients=arrIngredients.join(','); // move array to string
	strIngredientsNames=arrIngredientsNames.join(',');
	AjaxRequest(strSiteURL+'ajaxUpdateIngredientsResults.php?strIngredients='+strIngredients+'&strIngredientsNames='+strIngredientsNames, 'resultsDrinks', default_handle);
}


function removeIngredient(strIngredientName, intIngredientId) {
  	var d = document.getElementById('selectedIngredients');
  	var olddiv = document.getElementById('ingredient_'+intIngredientId);
  	objResultsDrinks = document.getElementById('resultsDrinks');
  	d.removeChild(olddiv);
  	removeItems(arrIngredients, intIngredientId);
	removeItems(arrIngredientsNames, strIngredientName);
	strIngredients=arrIngredients.join(','); // move array to string
	strIngredientsNames = arrIngredientsNames.join(',');
	objResultsDrinks.innerHTML = '<img src="'+strSiteURL+'images/indicator.gif" alt="Loading..."/>';
	AjaxRequest(strSiteURL+'ajaxUpdateIngredientsResults.php?strIngredients='+strIngredients+'&strIngredientsNames='+strIngredientsNames, 'resultsDrinks', default_handle);
}

function selectedIngredientCategory() {
	objStrSelectIngredientCategory = document.getElementById('strSelectIngredientCategory');
	objSelectIngredientsResults = document.getElementById('selectIngredientsResults');

	strCategory = objStrSelectIngredientCategory.value;
	objSelectIngredientsResults.innerHTML = '<img src="'+strSiteURL+'images/indicator.gif" alt="Loading..."/>';
	AjaxRequest(strSiteURL+'ajaxSearchIngredientCategory.php?strCategory='+strCategory, 'selectIngredientsResults', default_handle);
}

function selectOrderBy() {
	strURL = window.location.href;

	strParamValue = document.getElementById('strOrderBy').value;

	strNewURL = replaceURLParamValue(strURL, 'strOrderBy', strParamValue);
	strNewURL = strNewURL.replace(/&/g, '...');
	window.location.href =strSiteURL+ 'process_drink.php?strProcessType=8&strOrderBy='+strParamValue+'&strURL='+strNewURL;
}

function removeItems(array, item) {
	var i = 0;
	while (i < array.length) {
		if (array[i] == item) {
			array.splice(i, 1);
		} else {
			i++;
		}
	}
	return array;
}

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

String.prototype.stripslashes = function () {
	str=this.replace("'", "");
	str=str.replace('"', '');
	
	return str;
}

function getElementPosition( objThis ) {
	var intPosLeft = intPosTop = 0;
	if(objThis) {
		if(objThis.offsetParent) {
			do {
				intPosLeft += objThis.offsetLeft;
				intPosTop += objThis.offsetTop;
				//alert(objThis.id +'|'+objThis.name+'|'+objThis.className + '|' + intPosTop);
			} while (objThis = objThis.offsetParent);
		}

		//browser hacks.. this basically gets the positions on the same level for each browser.
		if( BrowserDetect.browser==SA ){
			intPosTop += 4;
		} else if(BrowserDetect.browser==IE && BrowserDetect.version == 6) {
			//intPosTop -= 22;
		}

		return [intPosLeft, intPosTop];
	}
	return false;
}

function showToolTip( objThis, strCaption, blnFlipped ) {
	blnAnimation = false;
	if(blnAnimation == false) {
		arrPosition = getElementPosition( objThis );
		//alert(arrPosition[0] + '|' + arrPosition[1]);
		intPosLeft = arrPosition[0]-2;
		intPosTop = arrPosition[1] - 26;
		//alert(intPosLeft + ' | ' + intPosTop);

		intCaptionLength = strCaption.length;

		objToolTip 					= document.getElementById('tooltip');
		objToolTipInfo 				= document.getElementById('tooltip_info');
		objToolTipArrow 			= document.getElementById('tooltip_arrow');
		objToolTip.className 		= 'vYes';
		objToolTipArrow.className 	= 'tooltip';
		objToolTip.style.left 		= intPosLeft+ 'px';
		objToolTip.style.top 		= intPosTop+ 'px';

		objToolTip.className = '';
		objToolTipInfo.innerHTML = strCaption;

		if( blnFlipped ){
			objToolTip.style.width = (intCaptionLength * 7) + 'px';
			objToolTipArrow.style.width = objToolTip.style.width; //(intCaptionLength * 7) + 'px';
			intFlippedPosition = ( intPosLeft - objToolTip.offsetWidth + objThis.offsetWidth ) + 'px';
			objToolTip.style.left = intFlippedPosition;
			objToolTipArrow.style.backgroundPosition = 'top right'; // Doesn't work using CSS class
		} else {
			objToolTipArrow.style.backgroundPosition = 'top left'; // Things get weird if this isn't explicitly set
		}
	}
}
function showDrinkToolHelp(objThis) {
	strCaption = '<b>Find drinks based on your Ingredients:</b> <br />';
	strCaption += '<b>Step 1:</b> <br />';
	strCaption += 'Add what ingredients you have by searching through categories or entered the ingredient name.<br />';	
	strCaption += '<b>Step 2:</b> <br />';
	strCaption += 'View/Edit the ingredients you have added.<br />';
	strCaption += '<b>Step 3:</b> <br />';
	strCaption += 'See the possible drinks you can make with your ingredients and view the recipes.<br />';
	showToolTip( objThis, strCaption, false )
}

function showDrinkSearchHelp(objThis) {
	strCaption = 'Start typing in the name of your favourite drink and a list of suggested drinks will appear.';
	showToolTip( objThis, strCaption, false )
}

function hideToolTip( ) {
	objToolTip = document.getElementById('tooltip');
	objToolTip.className = 'vNo';
}
