/// <reference path="jquery-1.3-vsdoc.js/> 

// JavaScript Document
var scripts_isIE = jQuery.browser.msie;
var scripts_isIE6 = (scripts_isIE && jQuery.browser.version.substr(0,1)=="6");
var highlightSpeed = 2500;


function getDrinkReceipeRatings(elem) {
    var data = new Object();
    data.name = $("#" + elem).val();
    
    ajax.makeCall({url:'GetRecipePicks', data: data, func: updateDrinkReceipes });
}

function updateDrinkReceipes(data) {
    data = eval(data.d);
    var $drinkItemsList = $('.drinkItemsList').eq(0)
    
    $drinkItemsList
        .next('.lbLink').toggle('blind').end()
        .toggle('blind', function(){
            $(this)
                .html("")
                .setTemplate($("#TemplateRecipeTable").html())
                .processTemplate(data)
                .toggle('blind', function(){ $(this).next('.lbLink').toggle('blind') })
        });
}
    
/* ************************************ */


jQuery.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

String.prototype.leftTrim = function() {
    return this.replace(/^\s+/,'');
};
String.prototype.rightTrim = function() {
    return this.replace(/\s+$/,'');
};
String.prototype.trim = function() {
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
};
String.prototype.isEmail = function() {
    if (this.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
    else return false;
};


function RolloverImage(offImage, onImage)
{
	this.offImage = offImage;
	this.onImage = onImage;
}

var leftPlusMinusImg = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/icons/plus.gif","http://static.thebar.com/v2/CSS-JS-IMAGES/icons/minus.gif");

var mainNavImages = new Array();
mainNavImages["mainNav0"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_type.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_type_over.png");
mainNavImages["mainNav1"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_occasion.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_occasion_over.png");
mainNavImages["mainNav2"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_brand.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_drinks_brand_over.png");
mainNavImages["mainNav3"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_quick_drinks.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_quick_drinks_over.png");
mainNavImages["mainNav4"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_wine.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_wine_over.png");
mainNavImages["mainNav5"] = new RolloverImage("http://static.thebar.com/v2/CSS-JS-IMAGES/nav_articles_videos.png","http://static.thebar.com/v2/CSS-JS-IMAGES/nav_articles_videos_over.png");

addWindowEvent("load", function() {
	for (var i in mainNavImages){
		$.preloadImages(mainNavImages[i].onImage);
	}
});


/*
if (scripts_isIE6) {
	window.attachEvent("onload", function() {
		if (document.all&&document.getElementById) {
			navRoot = document.getElementById("ulMainNav");
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
						this.className+=" over";
					}
					node.onmouseout=function() {
						this.className=this.className.replace(" over", "");
					}
				}
			}
		}
	});*/
	
	/*window.attachEvent("onload", function() { 
		for(var i=0; i<document.images.length; i++) {
			var img = document.images[i];
			if (ie6CorrectPng(img)) {
				i = i-1;
			}
		}
   	});
}
*/

/*jQuery.preloadImages = function() {
	jQuery.each (arguments,function (e) {
		jQuery ('<img src="' + this + '" />');
	});
}*/
/*
function ie6CorrectPng(img) {
	var imgName = img.src.toUpperCase();
	//if (img.className.indexOf("ie6PngNoFix") == -1 && imgName.substring(imgName.length-3, imgName.length) == "PNG") {
	if (img.className.indexOf("ie6PngFix") > -1 && imgName.substring(imgName.length-3, imgName.length) == "PNG") {
		var imgID = (img.id) ? "id='" + img.id + "' " : "";
		var imgClass = (img.className) ? "class='" + img.className + "' " : "";
		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
		var imgStyle = "display:inline-block;" + img.style.cssText;
		if (img.align == "left") imgStyle = "float:left;" + imgStyle;
		if (img.align == "right") imgStyle = "float:right;" + imgStyle;
		if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;		
		var strNewHTML = "<span " + imgID + imgClass + imgTitle
		+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
		+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		+ "(src=\'" + img.src + "\');\"></span>";
		img.outerHTML = strNewHTML;
		return true;
	}
	return false;
}*/

function ie6HideSearchDropDown() {    
	if (scripts_isIE6) {
		$('#ctl00_search_searchDDList').hide();
		// Added the below line as the control id for the Search dropdown is different than that generated on the homepage
		$('#ctl00_ctl00_search_searchDDList').hide();
	}	
}
function ie6ShowSearchDropDown() {
    if (scripts_isIE6 && !scripts_menuShowing) {	
	    $('#ctl00_search_searchDDList').show();
	    // Added the below line as the control id for the Search dropdown is different than that generated on the homepage
	    $('#ctl00_ctl00_search_searchDDList').show();
	}
}

function showSearchInput() {
	document.getElementById("divSearchText").style.display = "none";
	document.getElementById("divSearchUserText").style.display = "none";
	document.getElementById("divSearchInput").style.display = "inline";
	//document.getElementById("divSearchInput").childNodes[0].focus();
	document.getElementById("divSearchInput").getElementsByTagName("input")[0].focus();
	
}
function hideSearchInput() {
	var text = document.getElementById("divSearchText");
	var userText = document.getElementById("divSearchUserText");
	var inputDiv = document.getElementById("divSearchInput");
	//var input = inputDiv.childNodes[0];
	var input = inputDiv.getElementsByTagName("input")[0];
	if (input.value.trim() != "") {
		userText.innerHTML = input.value;
		userText.style.display = "inline";
	} else { 
		text.style.display = "inline";
	}
	inputDiv.style.display = "none";
}

function showMyBarNotifications(callback) {
	$('#ctl00_search_searchDDList').blur(); //remove focus from search select field
	// Added the below line as the control id for the Search dropdown is different than that generated on the homepage
	$('#ctl00_ctl00_search_searchDDList').blur();
	ie6HideSearchDropDown();
	if (scripts_isIE6) $('#divMyBarNotify').bgiframe();
	$("#divMyBarNotify").slideDown("normal", callback);
}

function hideMyBarNotifications() {
	$("#divMyBarNotify").slideUp("normal", ie6ShowSearchDropDown);
    $('span[id$=addednewingredients]').text('').hide('slow');	
}

var scripts_myBarTimeout = null;

function showMyBar() {
    if (scripts_myBarTimeout != null)
	    window.clearTimeout(scripts_myBarTimeout);
	
	showMyBarNotifications(null);
}
function hideMyBar() {
	scripts_myBarTimeout = window.setTimeout(hideMyBarNotifications, 200);
}
function saveToMyBar() {
	showHideMyBar();
}

function showHideMyBar() {
	showMyBarNotifications(function() {
		window.setTimeout(hideMyBarNotifications, 5000);
	});
}

// This funtion updates the count of recipes or articles and videos or shopping list 
// and total items counts when the corresponding items is saved to my bar
//Param1 - artifactSaved - acceptable values 'Recipes', 'Articles' and 'ShoppingLists'
function updateTopNavMyBarDetails(artifactSaved, countToIncrement)
{   
    var currentCount;
    var addedString = '';
    var splitArray;
    var $link;

    switch(artifactSaved) {
        case 'Recipes':         addedString = '(numberofrecipes)';      $link = $("a[id$=numberofrecipes]"); break;
        case 'ArticlesVideos':  addedString = '(numberofarticles)';     $link = $("a[id$=numberofarticles]"); break;
        case 'ShoppingLists':   addedString = '(numberofshoppinglists)'; $link = $("a[id$=numberofshoppinglists]"); break;
        case 'Ingredients':     addedString = '(numberofingredients)';   break;
    }

    if ($link) {
        // Update new link count
        currentCount = Math.abs($link.text().match("([0-9]+)")[0]);
	    $link.text($link.text().replace(/[0-9]+/, currentCount + countToIncrement));                
                        
        // Finally update the total items count
        $link = $('span[id$=navSignedinmessage]');
        currentCount = Math.abs($link.text().match("([0-9]+)")[0]);
        $link.text($link.text().replace(/[0-9]+/, currentCount + countToIncrement));

        if (artifactSaved == 'ShoppingLists' && countToIncrement < 0) {
            UpdateMyProfileLeftNavCounts()
        }
 	}
    
    // Get hidded alert text to display msg to user. 
    splitArray = $("input:hidden[id$=" + artifactSaved + "Text]").val().split("##");
    if(countToIncrement > 0)          
        addedString = splitArray[0].replace(addedString, countToIncrement);
    else 
        addedString = splitArray[1].replace(addedString, countToIncrement * -1);           
 	
    $('[id$=addednewingredients]').text(addedString).show();
                   
	showHideMyBar();
}

function addWindowEvent(eventName, func) {
	if (window.attachEvent) {
		window.attachEvent("on"+eventName, func);
	} else {
		window.addEventListener(eventName, func, false);
	}
}

/*var scripts_currentLeftNavItem = null;
var scripts_currentLeftNavOptions = null;
var scripts_currentLeftNavCount = null;*/
function showLeftNavOptions(index) {
        //var scripts_currentLeftNavItem = "navItem"+index;
        var scripts_currentLeftNavOptions = "navOptions"+index;
	    var scripts_currentLeftNavDisp = document.getElementById(scripts_currentLeftNavOptions).style.display;

	    if (scripts_currentLeftNavDisp!="block") {
		    //document.getElementById("navItem"+index).style.listStyleImage = "url(http://static.thebar.com/v2/CSS-JS-IMAGES/icons/minus.gif)";
		    $("#plusMinus"+index).attr("src", leftPlusMinusImg.onImage);		    
		    //document.getElementById("navOptions"+index).style.display = "block";
		    document.getElementById(scripts_currentLeftNavOptions).style.display = "block";
	    } else {
		    //document.getElementById(scripts_currentLeftNavItem).style.listStyleImage = "url(http://static.thebar.com/v2/CSS-JS-IMAGES/icons/plus.gif)";
		    $("#plusMinus"+index).attr("src", leftPlusMinusImg.offImage);		    
		    document.getElementById(scripts_currentLeftNavOptions).style.display = "none";
	    }
	
        /*
        if (scripts_currentLeftNavItem != null) {
		document.getElementById(scripts_currentLeftNavItem).style.listStyleImage = "url(http://static.thebar.com/v2/CSS-JS-IMAGES/icons/plus.gif)";
        }
        if (scripts_currentLeftNavOptions != null) {
            document.getElementById(scripts_currentLeftNavOptions).style.display = "none";
        }
	document.getElementById("navItem"+index).style.listStyleImage = "url(http://static.thebar.com/v2/CSS-JS-IMAGES/icons/minus.gif)";
	document.getElementById("navOptions"+index).style.display = "block";
	scripts_currentLeftNavItem = "navItem"+index;
	scripts_currentLeftNavOptions = "navOptions"+index;
        */
        
        /*if(scripts_isIE) {
        if (scripts_currentLeftNavCount != null) {
        document.getElementById(scripts_currentLeftNavCount).style.top = "-2em";
        }
        document.getElementById("navCount"+index).style.top = "-1.7em";
        scripts_currentLeftNavCount = "navCount"+index;
        }*/

}

function setRating(ratingDivID, rating) {    
	document.getElementById(ratingDivID).value = rating;	
}
function highlightRating(ratingDivID, rating) {
	document.getElementById(ratingDivID).className = "rating"+rating;
}
function resetRating(ratingDivID, ratingHidInputID) {
	var lastRating = parseInt(document.getElementById(ratingHidInputID).value);
	document.getElementById(ratingDivID).className = "rating"+lastRating;
}

var scripts_lastShown = null;
var scripts_fadeTimeout = Array();
var scripts_menuShowing = false;    
function showMainSub(index, navID, hideSearchSelect) {
	$("#"+navID).attr("src", mainNavImages["mainNav"+index].onImage);
		
	if (scripts_isIE6) $('#subMenu'+index).bgiframe();	
		
	$('#ctl00_search_searchDDList').blur(); //remove focus from search select field
	// Added the below line as the control id for the Search dropdown is different than that generated on the homepage
    $('#ctl00_ctl00_search_searchDDList').blur();
    
    if (index == 5) //articles & videos tab
		hideMyBarNotifications();
	if (scripts_lastShown != null && scripts_lastShown != index)
		doFadeOut(scripts_lastShown);
	if (scripts_fadeTimeout[index])
		window.clearTimeout(scripts_fadeTimeout[index]);
	if (hideSearchSelect) 
		ie6HideSearchDropDown()
	$("#subMenu"+index).fadeIn("fast", function() {
		if (hideSearchSelect)
			ie6HideSearchDropDown();
		scripts_menuShowing = true;
	});
	scripts_lastShown = index;
}
function hideMainSub(index, navID, showSearchSelect) {
	scripts_fadeTimeout[index] = window.setTimeout("doFadeOut("+index+",'"+navID+"',"+showSearchSelect+")", 100);
}
function doFadeOut(index, navID, showSearchSelect) {
	$("#"+navID).attr("src", mainNavImages["mainNav"+index].offImage); 
	$("#subMenu"+index).fadeOut("fast", function() {
                  scripts_menuShowing = false;		
                  if (showSearchSelect)
			ie6ShowSearchDropDown();
		
	});
}

function toggleBtn(objImg, btnPath) {
    toggleImg(objImg, btnPath);
}
function toggleImg(objImg, imagePath) {
    objImg.src = imagePath;
}

// MAKE THESE VARS GLOBAL FOR CLICKDIV() FUNCTION
var leftVal;
var topVal;
var clickDivID = 'divMain'; //set some default;
var clickDivPageX=300;
var clickDivPageY=300;
$(function(){
    $(document).click(function(e){
	//alert("you clicked!");
	clickDivPageX = e.pageX;
	clickDivPageY = e.pageY;
    });
}); 

function clickDiv(){

    //getting height and width of the message box
     var height = $('#'+clickDivID).height();
     var width = $('#'+clickDivID).width();
    //calculating offset for displaying popup message
     //leftVal=e.pageX-(width/2)+"px";
     leftVal=clickDivPageX-Math.round(width/1.2)+"px";
     topVal=clickDivPageY-Math.round(height/3)+"px";
}

/*
function showNutrPopupDiv(divID) 
{
    clickDivID = divID;
    clickDiv();

    //show the layer

    leftVal = Math.round(parseInt(leftVal)-650) + "px";
    topVal = Math.round(parseInt(topVal)-650) + "px";
    
    if (scripts_isIE6) $('#'+divID).bgiframe();

     $('#'+divID).css({left:leftVal,top:topVal}).show();

    document.getElementById(divID).style.visibility = "visible";
}
*/

function showNutrPopupDiv(divID) 
{
    if (scripts_isIE6) $('#'+divID).bgiframe();
    $('#'+divID).css({left:-200,top:0}).show();

    document.getElementById(divID).style.visibility = "visible";
}

function showPopupDiv(divID) 
{
	
    clickDivID = divID;
    clickDiv();
    //show the layer
    if (scripts_isIE6) $('#'+divID).bgiframe();
    
     $('#'+divID).css({left:leftVal,top:topVal}).show();
    document.getElementById(divID).style.visibility = "visible";
}

function showPopupDivCenter(divID) 
{
    if (scripts_isIE6) $('#'+divID).bgiframe();

    centerLyr(divID);
    rePositionLyr(true,divID);
    document.getElementById(divID).style.visibility = "visible";
}

function centerLyr(divID)
{
 $('#'+divID).css("position","absolute");
 $('#'+divID).css("top", ( $(window).height() - $('#'+divID).height() ) / 2+$(window).scrollTop() + "px");
 $('#'+divID).css("left", ( $(window).width() - $('#'+divID).width() ) / 2+$(window).scrollLeft() + "px");
}

function rePositionLyr(status,divID) {
	switch(status) {
		case true:
			$(window).bind('resize', function() {
				centerLyr(divID);
			});
			$(window).bind('scroll', function() {
				centerLyr(divID);
			});
		break;
		case false:
			$(window).unbind('resize');
			$(window).unbind('scroll');
		break;
	}
}

function hidePopupDiv(divID) {
    //changed to hidden instead of display: none, because IE6 doesn't render the PNG fix for those images that are display: none
    document.getElementById(divID).style.visibility = "hidden";
}

var scripts_selectedPrintSizeImg = null;
var printSize = null;
function selectPrintSize(imgID, size) {
    var img = document.getElementById(imgID);
    if (scripts_selectedPrintSizeImg != null) {
        scripts_selectedPrintSizeImg.className = scripts_selectedPrintSizeImg.className.replace(/Sel$/, "");
    }
    printSize = size;
    img.className += "Sel";
    scripts_selectedPrintSizeImg = img;
    
}
function openPrintWindow(url) {
    window.open(url + printSize);
}

function openShoppingListPrintWindow(url) {
    window.open(url);
}
function openArticlePrintWindow(url) {
    window.open(url);
}
function printpage() {
    window.print();
}

function openVideoPlayer(divID, flashDivID, flvUrl) {

   showPopupDivCenter(divID);
    callTrack();
     //alert(flvUrl);
     var so = new SWFObject("~/_layouts/TheBar/swf/the_bar_video_player_no_bkgd.swf", "the_bar_video_player", "480", "303", "9", "#ffffff"); 
     so.addParam("scale", "showall");
     so.addParam("allowFullScreen", "true");
     so.addParam("salign", "ct");
     so.addParam("wmode", "transparent");
     so.addVariable("debugger", "false");
     so.addVariable("flv_path", "http://cp18256.edgefcs.net/ondemand/18256/v2/"+flvUrl); 
     so.write(flashDivID);
}

function closeVideoPlayer(divID, flashDivID) {

    rePositionLyr(false,divID);
    hidePopupDiv(divID);
    if(!document.getElementById('nonflashcontent'))
       document.getElementById(flashDivID).innerHTML = '';

}

function swapNavClass(obj,cls)
{
    obj.className=cls;
}

function restoreNavClass(obj,cls)
{
    obj.className=cls;

}

function go(u)
{
    window.location = u;
}

/** dev specific **/

function closeVideoPlayerFromFlash() 
{
	closeVideoPlayer('flash-lyr', 'flashcontent');
}

var geocoder;
function initialize() {
        if (GBrowserIsCompatible()){
        geocoder = new GClientGeocoder();
   }
}

function showLatLong(response) {
        if (!response || response.Status.code != 200) {

          alert("Sorry, we were unable to geocode that address");

        } else {
          place = response.Placemark[0];
          point = new GLatLng(place.Point.coordinates[1],
                     place.Point.coordinates[0]);
          lat = point.lat();
          lng = point.lng();
          alert(lat);
          alert(lng);
         // document.getElementById("my_lat").value = lat;
         // document.getElementById("my_lng").value = lng;
         // postSubmitHiddenForm(lat,lng);
        }
}
// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
   function showLocation() {
     var address = document.forms[0].q.value;
     geocoder.getLocations(address,showLatLong);    
    }
 

// findLocation() is used to enter the sample addresses into the form.

    function findLocation(address) {

      document.forms[0].q.value = address;

      showLocation();

    }  
    
    
    

// postSubmitHiddenForm() is used to send the hidden form containing Latitude and Longitude via a POST request.

function postSubmitHiddenForm(Lat,Lng) {

  document.myHiddenForm.LAT.value=Lat;

  document.myHiddenForm.LNG.value=Lng;

  document.myHiddenForm.submit();

}
   
   
function validateZIP(field) {
var valid = "0123456789-";
var hyphencount = 0;

if (field.length!=5 && field.length!=10) {
alert("Please enter your 5 digit or 5 digit+4 zip code.");
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (temp == "-") hyphencount++;
if (valid.indexOf(temp) == "-1") {
alert("Invalid characters in your zip code.  Please try again.");
return false;
}
if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
return false;
   }
}
return true;
}

function CheckCount(text,length) 

  

{

  

      var maxlength = new Number(length); // Change number to your max length.

  

if(text.value.length > maxlength){

  

                text.value = text.value.substring(0,maxlength);

  

                alert(" Only " + maxlength + " characters allowed");

            } 

}

function changeDivDisplay(divID, btnID) {
    
    if(document.getElementById(divID).style.display == "block")
    {
        document.getElementById(divID).style.display = "none";
    }
    else
    {
        document.getElementById(divID).style.display = "block";
    }
    var k = 0;
    for (j=0;j<=10;j++)
    {
        var x = document.getElementsByName("ctl00$ctl00$PlaceHolderMain$col2$chkWhatUDrink" + j);
        for(l=0; l<x.length; l++)
        {
            
            if(document.getElementById(x[l].id).checked)
            {
                k++;
            }
        }
    }
    
    if(k < 1)
    {
        
        document.getElementById("divError").style.display = "block";
        document.getElementById(btnID).disabled=true
        document.getElementById("topText").style.display = "none";
    }
    else
    {
    
        document.getElementById("divError").style.display = "none";
        document.getElementById(btnID).disabled=false
	    document.getElementById("topText").style.display = "block";
       
    }
}
function addValueToHiddenFld(hndID, ddID)
{
    document.getElementById(hndID).value = document.getElementById(ddID).text;
    alert("done");
}
function changeMyBarFooter()
{
    document.getElementById("divFooter").className = "myBarFooter";
}
function hideDivByClass(clname)
{ 
    $('.' + clname).hide();
}

function setRating(ratingDivID, rating, recipeID) 
{  
    //CallServer(rating, " ");    	
    CallServerForSmallRating(rating, " ");    	
    document.getElementById(ratingDivID).value = rating;
    // This is done to set the rating value to the hidden field so that it can be used to get it on the server side.
    document.getElementById("ctl00_ctl00_PlaceHolderMain_MainCol_mainContent2_hdnRatingValue").value = rating;
}

function highlightRating(ratingDivID, rating) 
{	
    document.getElementById(ratingDivID).className = "rating"+rating;
}

function resetRating(ratingDivID, ratingHidInputID) 
{	
    var lastRating = parseInt(document.getElementById(ratingHidInputID).value);	
    document.getElementById(ratingDivID).className = "rating"+lastRating;
}

function setRatingLrg(ratingDivID, rating, recipeID) 
{	
    //cbkLrgRating.callback(rating);	    
    //CallServer(rating, " ");	    
    CallServerForLargeRating(rating, " ");	    
    document.getElementById(ratingDivID).value = rating;	
}

function highlightRatingLrg(ratingDivID, rating) 
{	
    document.getElementById(ratingDivID).className = "lrgRating"+rating;
}

function resetRatingLrg(ratingDivID, ratingHidInputID) 
{    	
    var lastRating = document.getElementById(ratingHidInputID).value;	
    document.getElementById(ratingDivID).className = "lrgRating"+lastRating;
}

function ReceiveServerData(arg, context)
{
    // If arg contains ##, it means that the call is from the Rating Large user control
    if(arg.indexOf("##") != -1)
    {
        // arg argument has the image path as well as the new text for lblAvgRating   
        var splitArray = arg.split("##")
        document.getElementById("pnlLrgRatingControl").style.display = "none";    
        //document.getElementById("imgRating").src = arg;
        document.getElementById("imgRating").src = splitArray[0];        
        document.getElementById("imgRating").title = splitArray[2];        
        document.getElementById("pnlLrgRatingImg").style.display = "block";
        // Set the lblAvgRating innet html
        document.getElementById("ctl00_ctl00_PlaceHolderMain_RightCol_rightContent1_ratingControl1_lblAvgRating").innerHTML = splitArray[1];    
    }
    else
    {
        
    }
}

function addListener(element, type, expression, bubbling)
{  
    bubbling = bubbling || false;  
    if(window.addEventListener)	{ // Standard    
        element.addEventListener(type, expression, bubbling);    
        return true;  
    } 
    else if(window.attachEvent) { // IE    
        element.attachEvent('on' + type, expression);    
        return true;  
    } 
    else 
        return false;
}

var ImageLoader = function(url)
{  
    this.url = url;  
    this.image = null;  
    this.loadEvent = null;
};

ImageLoader.prototype = {  load:function()
    {    
        this.image = document.createElement('img');    
        var url = this.url;    
        var image = this.image;    
        var loadEvent = this.loadEvent;    
        addListener(this.image, 'load', function(e){      
                if(loadEvent != null)
                {        
                    loadEvent(url, image);      
                }    
            }, false);    
            this.image.src = this.url;  
        },  getImage:function()
        {    
            return this.image;  
        }
    };
    
function UpdateMyProfileLeftNavCounts()
{
    var openBracketIndex;    
    var currentCount;
          
    openBracketIndex = document.getElementById("ctl00_ctl00_topNav_numberofrecipes").innerHTML.indexOf("(");
    currentCount = document.getElementById("ctl00_ctl00_topNav_numberofrecipes").innerHTML.slice((openBracketIndex*1) + 1, -1);    
    document.getElementById("ctl00_ctl00_PlaceHolderMain_lblRecipesCount").innerHTML = "(" + currentCount + ")";

    openBracketIndex = document.getElementById("ctl00_ctl00_topNav_numberofarticles").innerHTML.indexOf("(");
    currentCount = document.getElementById("ctl00_ctl00_topNav_numberofarticles").innerHTML.slice((openBracketIndex*1) + 1, -1);    
    document.getElementById("ctl00_ctl00_PlaceHolderMain_lblArticlesVideosCount").innerHTML = "(" + currentCount + ")";

    openBracketIndex = document.getElementById("ctl00_ctl00_topNav_numberofshoppinglists").innerHTML.indexOf("(");
    currentCount = document.getElementById("ctl00_ctl00_topNav_numberofshoppinglists").innerHTML.slice((openBracketIndex*1) + 1, -1);
    document.getElementById("ctl00_ctl00_PlaceHolderMain_lblShoppingListsCount").innerHTML = "(" + currentCount + ")";    
}

function UpdateLargeRating(avgRatingString, avgRatingWithHalfString)
{   
    document.getElementById("divRating2").className = "lrgRating" + avgRatingWithHalfString;
    document.getElementById("hidRating2").value = "lrgRating" + avgRatingWithHalfString;
    document.getElementById("ctl00_ctl00_PlaceHolderMain_RightCol_rightContent1_ratingControl1_lblAvgRating").innerHTML = avgRatingString;
}

/*
function SubtractTopNavMyBarValues()
{
    var openBracketIndex;    
    var currentCount;
          
    openBracketIndex = document.getElementById("ctl00_ctl00_topNav_numberofrecipes").innerHTML.indexOf("(");
    currentCount = document.getElementById("ctl00_ctl00_topNav_numberofrecipes").innerHTML.slice((openBracketIndex*1) + 1, -1);
    currentCount = currentCount * 1;
    currentCount = currentCount / 10;
    currentCount = Math.round(currentCount);
    document.getElementById("ctl00_ctl00_PlaceHolderMain_col2_rptMyRecipes_ctl11_lblTotalPages").innerHTML = currentCount;    
}
*/

function mbsb_Toggle(elid,imgPath,DivID){
   var sArr = elid.split('_');
   var sVal = sArr.pop(); //get last element in array.
   var pnlID = DivID;
   var sSrc = $('#shoppingListToggleIcon_'+sVal).children("img").attr("src");
   if(sSrc.indexOf("plus")!=-1) {

	//already open
	$('#shoppingListToggleIcon_'+sVal).children("img").attr("src",imgPath+"minus.gif");
	$('#shoppingListToggleIcon_'+sVal).children("img").attr("alt","Hide This Shopping List");
	$('[id$=ViewShoppingList' + sVal + ']').text("Hide This Shopping List");
	$('#shoppingTDRow_'+sVal).css("background-color","#dfdee0");
	$('#dateTD_'+sVal).css("background-color","#dfdee0");
	$('#printTD_'+sVal).css("background-color","#dfdee0");
	$('#deleteTD_'+sVal).css("background-color","#dfdee0");
	
	$('#'+pnlID).show();

   } else {

	//is closed
	$('#shoppingListToggleIcon_'+sVal).children("img").attr("src",imgPath+"plus.gif");
	$('#shoppingListToggleIcon_'+sVal).children("img").attr("alt","View This Shopping List");
	$('[id$=ViewShoppingList' + sVal + ']').text("View This Shopping List");
	$('#shoppingTDRow_'+sVal).css("background-color","#ffffff");
	$('#dateTD_'+sVal).css("background-color","#f0f0f0");
	$('#printTD_'+sVal).css("background-color","#ffffff");
	$('#deleteTD_'+sVal).css("background-color","#f0f0f0");
	
	$('#'+pnlID).hide();
   }
}

// Quantity Adjuster for Drink Recipe. New Feature in 2.0
function AdjustDrinkRecipeQuantity(qaListId, selectList) {
    var iCount = selectList.value;
    
    $('#' + qaListId + ' li').each(
        function(intIndex) {
            var dDefault = $(this).find('var').attr('defVal');
            dDefault = dDefault == "" ? 1 : dDefault;
            
            if (!isNaN(iCount) && !isNaN(dDefault)) {
                var result = roundNumber(iCount * dDefault, 1);
                $(this).find('var').text(result);
            }
        }
    );
    var PrintRecipeBtn =  $('a[id$=lnkBtnPrint]');
    PrintRecipeBtn.attr('href', PrintRecipeBtn.attr('href').replace(/&servings=\d+/, '&servings=' + iCount))
}

/* Use this function for only Recipe Details page */
function AdjDrinkRecipeQty(qaListId, selectList) {
    var iCount = selectList.value;
    
    $('#' + qaListId + ' li').each(
        function(intIndex) {
            var dDefault = $(this).find('var').attr('defVal');
            dDefault = dDefault == "" ? 1 : dDefault;         
            
            if (!isNaN(iCount) && !isNaN(dDefault)) {
                var result = roundNumber(iCount * dDefault, 1);
                if($(this).find('var').attr('defVal') == "" && result == 1) {
                    result = "";      /* if default is "" then disply "" instead of 1 */
                }
                $(this).find('var').text(result);
            }
        }
    );
    var PrintRecipeBtn =  $('a[id$=lnkBtnPrint]');
    PrintRecipeBtn.attr('href', PrintRecipeBtn.attr('href').replace(/&servings=\d+/, '&servings=' + iCount))
}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

/* ******************************
 ShoppingList Section
****************************** */
function AdjustShoppingListQty(DropDown) {
    $DropDown = $(DropDown)
    var recipeid = $DropDown.closest(".MyBarRecipes_Container").find("input[id$='hdnRecipeid']").val();
    var $DropDown_Container = $DropDown.closest(".divShoppingHide");
    var ParentContainer = $DropDown_Container.find("ul");
    var SpiritItems;
    var IngredientItems;
    
	// Loop thru Your Spirits/Brands
    SpiritItems = ParentContainer.eq(0).find("li[recipeid*='" + recipeid + "']");
    if (SpiritItems.length > 0) {
        SpiritItems.each(
            function(intIndex) {
                var elem = $(this);
			    var result = 0;
                var arrRecipeID = elem.attr('recipeid').split('|');
			    var arrNumOfOz = elem.attr('defVal').split('|');
			    var arrBrandvolume = elem.attr('brandvolume').split('|');
    			          
			    arrRecipeID.pop(); // Remove blank dimension from the array
    			            
                // loop thru array of RecipeIds
                $.map(arrRecipeID, function(recipeID, recipeIndex) {    			
                    if (arrNumOfOz[recipeIndex] != '' && arrBrandvolume[recipeIndex] != '') {
                        var numOfServings = $DropDown_Container.find("select[recipeid$='" + recipeID + "']").val(); 
                        result += numOfServings * (arrNumOfOz[recipeIndex] / arrBrandvolume[recipeIndex])                    
                    }
                })
                if (!isNaN(result)) {
			        elem.find("span").text(Math.ceil(result))
			    }
			    elem.effect("highlight", {}, highlightSpeed)			    
		    }
        );
    }
    
	// Loop thru Your Ingredients
    IngredientItems = ParentContainer.eq(1).find("li[recipeid*='" + recipeid + "']");
    if (IngredientItems.length > 0) {    
        IngredientItems.each(
            function(intIndex) {
                var elem = $(this);
			    var result = 0;
                var arrRecipeID = elem.attr('recipeid').split('|');
			    var arrNumOfOz = elem.attr('defVal').split('|');
			    var arrBrandvolume = elem.attr('brandvolume').split('|');
    			            
			    arrRecipeID.pop(); // Remove blank dimension from the array
    			            
                // loop thru array of RecipeIds
                $.map(arrRecipeID, function(recipeID, recipeIndex) {    			
                    arrNumOfOz[recipeIndex] = /[1-9]/.test(arrNumOfOz[recipeIndex]) ? arrNumOfOz[recipeIndex] : 1;
                    if (arrNumOfOz[recipeIndex] != '') {
                        var numOfServings = $DropDown_Container.find("select[recipeid$='" + recipeID + "']").val();                    
                        
                        var Stirrings = arrBrandvolume[recipeIndex]
                        if (Stirrings == 0){
                            result += numOfServings * arrNumOfOz[recipeIndex]   
                        } else {
                            result += numOfServings * (arrNumOfOz[recipeIndex] / arrBrandvolume[recipeIndex])
                        }                 
                    }
                })
			    elem.find("span").text(Math.ceil(result))
			    elem.effect("highlight", {}, highlightSpeed)			    
		    }
        );
    }
}

function deleteShoppingList(elem) {
    if (!confirm("Are you sure you want to delete this Shopping List?"))
        return;

    var $elParentDiv = $(elem).closest(".ShoppingListContainer")
    var shoppingListID = $elParentDiv.find("input[id$='hdnShoppingID']").val();
    var data = new Object();
    data.shoppinglistid = shoppingListID;
    
    // Make Ajax call
    ajax.makeCall({url:'DeleteShoppingList', data: data, 
        func: function(){
            // Delete Elem from page
            $elParentDiv
                .effect('highlight', {}, highlightSpeed, function(){
                    $(this).toggle('blind', function(){
                       $(this).remove()
						
						var ShoppingListOnPageCount = $('.ShoppingListContainer').length;	    
                        if (ShoppingListOnPageCount == 0) {	
                            updateTopNavMyBarDetails('ShoppingLists', -1)
                            
                            if ($("a[id$=numberofshoppinglists]").text() != '(0)') {	
                                eval($("a[id$='lnkbPrevious']").attr('href'))	
                            }						    
                        } 
                        else {						    
					        var ShoppingList_Left = $("span[id$='lblShoppingListsCount']");
					        var ShoppingList_TopNav = $("a[id$='numberofshoppinglists']");
    					    
					        var ShoppingListsCount = Math.ceil(ShoppingList_Left.text().match("([0-9]+)")[0] - 1);
					        
				            $("span[id$='lblTotalPages']").text(Math.ceil(ShoppingListsCount / 10));				    
				            ShoppingList_Left.text(ShoppingList_Left.text().replace(/[0-9]+/, ShoppingListsCount));
					        
					        if (ShoppingListOnPageCount == 9 && ShoppingListsCount >= 10) {
					            var btnShoppingList_UpdatePanel = $("[id$='RunHidden']").attr('id');
					            __doPostBack(btnShoppingList_UpdatePanel,'');
					        }

                            // Alert user of results
                            updateTopNavMyBarDetails('ShoppingLists', -1)
                                
						}                      
                    });  
                })               
        } 
    });
}

function deleteShoppingList_Recipe(elem) {
    if (!confirm("Are you sure you want to delete this Recipe?"))
        return;
    
    var $el = $(elem)
    var shoppingListID = $el.closest(".ShoppingListContainer").find("input[id$='hdnShoppingID']").val();
    
    var $Parent_MyBarRecipes_Div = $el.closest(".MyBarRecipes_Container")
    var recipeid = $Parent_MyBarRecipes_Div.find("input[id$='hdnRecipeid']").val();
    var $ddl = $Parent_MyBarRecipes_Div.find("select");                    
    
    var $ShoppingList_Items = $el.closest(".divShoppingHide").find("li[recipeid*='" + recipeid + "']")
        
    var data = new Object();
    data.recipeid = recipeid;
    data.shoppinglistid = shoppingListID;
    
    // Make Ajax call
    ajax.makeCall({  url:'DeleteRecipefromShoppingList', 
                    data: data, 
                    func: deleteShoppingList_Recipe_OnComplete($ShoppingList_Items, recipeid, $ddl, $Parent_MyBarRecipes_Div)
                });
}

function deleteShoppingList_Recipe_OnComplete($ShoppingList_Items, recipeid, $ddl, $Parent_MyBarRecipes_Div) {    
	var iCount = 1;
    $ddl.val('1');                                      // Reset ddl
    AdjustShoppingListQty($ddl[0])                      // Re-calculate Recipes Items
    var $ShoppingListWrapper;
    var closeRecipeDetailsArea = false;
	
	// Remove Your Spirits/Brand items
	$ShoppingList_Items
	    .each(function(){
	        var $ListItem = $(this);
	        var txt = $ListItem.attr('recipeid').replace(recipeid + '|','')
	        $ListItem.attr('recipeid', txt)

		    if ($ListItem.attr('recipeid') == '') {
			    $ListItem.toggle('blind', function(){
				    if ($ListItem.siblings().length == 0){
				        $ListItem.parent().prev('h3').remove();
				        $ListItem.parent().remove();
				    } else {
				        $ListItem.remove(); // Remove Your Spirits/Brand
				    }
			    })
			}
    				
		    // Alert user of results and re-calculate display
		    if ($ShoppingList_Items.length == iCount) {
                $ShoppingListWrapper = $Parent_MyBarRecipes_Div.closest(".ShoppingListContainer")
                closeRecipeDetailsArea = $ShoppingListWrapper.find('.MyBarRecipes_Container').length == 1
				$Parent_MyBarRecipes_Div.toggle('blind').remove();  // Remove Recipe
			    updateTopNavMyBarDetails('Ingredients', -iCount)         // Update Top & Left Nav bar
			    //updateTopNavMyBarDetails('Ingredients', -1)         // Update Top & Left Nav bar
			    
		    }
		    iCount++
		});
		
        if (closeRecipeDetailsArea) {	
            eval($ShoppingListWrapper.find('a[id^=ViewShoppingList]').attr('href'));
            $ShoppingListWrapper.find('.divShoppingHide').empty()							    
        } 			    
		
}

function AlertUser(Header, Msg) {
	$(notice.replace('[Header]', Header).replace('[Msg]', Msg)).purr({ usingTransparentPNG: true, removeTimer: 2000 });            
}


function AddServingCountToPrintQueryString(elem)
{
    var $el = $(elem)
    var href = '&servings=';
    var $wrapper = $el.closest(".ShoppingListContainer");
    
    $wrapper
        .find("select option:selected")
        .each(function(){href += $(this).text() + "-"})
    
    // populate global variables with li items
    g_SpiritsListItems = $wrapper.find("ul").eq(0).find('li').clone();
    g_IngredientsListItems = $wrapper.find("ul").eq(1).find('li').clone();
    
    href = $el.attr('href') + href
    href = href.substring(0,href.length-1)
    //href = href.replace(/-$/,"");
    
    // Open Popup window
    openShoppingListPrintWindow(href)
}

// Alert User of successful Ajax operation
var notice = '<div class="notice">'
		  + '<div class="notice-body">' 
			  //+ '<img src="/_layouts/TheBar/CSS-JS-IMAGES/purrInfo.png" alt="" />'
			  + '<img src="http://static.thebar.com/v2/CSS-JS-IMAGES/purrInfo.png" alt="" />'
			  + '<h3>[Header]</h3>'
			  + '<p>[Msg]</p>'
		  + '</div>'
		  + '<div class="notice-bottom">'
		  + '</div>'
	  + '</div>';
	  
/* ************************************
 * Get Selected Brands
 * *********************************** */
function GetBrands(ddl)
{
    var data = new Object();
    data.brandid = $(ddl).val();
    data.localeid = $("input[id$='hdnLocaleId']").val();;
        
    // Make Ajax call
    ajax.makeCall({url:'GetBrands', data: data, 
        func: function(result){
            var $ddlflavour = $("select[id$='ddlflavour']")
            $ddlflavour.empty();
            
            $.each(result, function(i, b) {
                $("<option/>").attr("value", b.BrandId).text(b.BrandName).appendTo($ddlflavour)
            })
            
            if (result.length > 1)
                $(".brandFlavour").show('slow');
            else
                $(".brandFlavour").hide('slow');
            
        } 
    });
}


/* ************************************
 * Ajax Section
 * *********************************** */
var ajax = function() {};
ajax.onPageError = function(error) {	
    alert("An error occurred:\r\n\r\n" + error.Message);
}

ajax.makeCall = function(options) {
    var theBarWebSvcURL = "_layouts/TheBar/Webservices/theBarSvc.asmx/"
    var error = ajax.onPageError;
    options.data = JSON2.stringify(options.data)
    
    $.ajax({
        type:       "POST",
        url:        theBarWebSvcURL + options.url,
        data:       options.data,
        contentType:"application/json; charset=utf-8",
        dataType:   "json",
        success:    options.func,
        error: function(xhr) {
                if (!error) return;
                var res = xhr.responseText;
                if (res && res.charAt(0) == '{')
                    var err = JSON2.parse(res);
                if (err)
                    error(err);
                else
                    if (xhr.status != 200)
                    error({ Message: "Http Error: " + xhr.statusText });
                else
                    error({ Message: "Unknown Error Response" });
                return;
            }
    });
};

// PERT Tags functions
function openSurveyPopup(){
    maskSiteForSurvey("divSurveyPopup");
}

function closeSurveyPopup(){
    surveyClose();
}

function closeSurveyPopupDelay(){
    setTimeout(surveyClose, 1500);
}

function surveyClose(){
    unmaskSiteForSurvey();
    $("#divSurveyPopup").hide();
}

function ShowPERTSurvey(userFrequency){
    var num = 1;
    
    if(num == rand(userFrequency))
    {
        // Show Survey
        openSurveyPopup();
    }
};

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

function maskSiteForSurvey(divID)
{
    toShow="";

    var newHeight=$(document).height();

   // Build the background overlay div
   toShow += "<div class='pert_overlay'></div>";

   $('body').append(toShow);

    $('div.pert_overlay').css('opacity',0).fadeTo('slow',0.65, function(){
	showPopupDivCenter(divID);
	$('div.pert_overlay').css("z-index","2000");
	$('div.pert_overlay').height(newHeight);
	$('#'+divID).css("z-index","3000");
	$('div.pert_overlay').show();
   });
}


function unmaskSiteForSurvey()
{
   $('div.pert_overlay').remove();   
}
