//create refernce to $
window.$ = $telerik.$;


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



/*function hoverRollOver() {
	//alert("startHover");
	try
	{
		var currentClass = $(this).attr("class");
		$(this).attr("origClass", currentClass);

		var newClasses = new Array();
		$( currentClass.split(/\s+/) ).each( function(){
			var className = this;
			//alert("classname: " + className);
			newClasses.push(className);
			newClasses.push(className+"Hover");
		});
		newClasses.push("hover");
		$(this).attr("class", newClasses.join(" "));

		//alert($(this).attr("class"));

		// Adjust the body to be high enough to allow the whole dropdown to be visible
		var bodyDiv = $("#middleDiv").get(0);
		var rolloverRequiredHeight = $(this).attr("rolloverHeight");
		var currentBodyHeight = bodyDiv.clientHeight;

		if(rolloverRequiredHeight > currentBodyHeight) {
			$(bodyDiv).height(rolloverRequiredHeight);
		}
	}
	catch (Err)
	{
		//alert(Err);
	}
	//alert("endHover");
}

function hoverRollOff() {
	if ($(this).attr("origClass") != null)
	{
		$(this).attr("class", $(this).attr("origClass"));
		$("#middleDiv").height("auto");
	}
}*/


var productNames = {}; // hash array
var searchPopupdisabled=false;
$(function(){
	$('.productsMenu .internalProductList a').each(function(){
		productNames[$(this).text()] = $(this).attr('href');
	});
	var preload_image = new Image(25,25);
	preload_image.src = '/images/searchPopupBorder.png'; 

});

function escapeTerm(term)
{
	var returnStr = "";
	if (term!=undefined && term.length > 0)
	{
		for(var i=0; i < term.length; i++)
		{
			var char = term.charAt(i);
			// all the regex characters that should be escaped.
			if (char == '+' || char == '.' || char == '[' || char == '\\' || char == '^' || char == '$' || char == '|' || char == '?' || char == '*' || char == '(' || char == ')')
			{
				returnStr += "\\"+char;
			}
			else
			{
				returnStr += char;
			}
		}
	}

	return returnStr;
}

function submitFormOnEnter(field,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if (keycode == 13)
	{
		field.form.submit();
	}
}

function updateSearchQuery(textbox, KEYCODE) {

    //var unescapedTerm = $('#sidebarLeft\\:cms_template_leftsearch\\:search_form\\:searchterm').val();
    var unescapedTerm = textbox.value;
	var term = escapeTerm(unescapedTerm);

	if (searchPopupdisabled) {
		return;
	}

	var htmlReturn = '';
	var i = 0;
	if (productNames != undefined && term.length > 2) {
		var regEx = new RegExp(".*"+term+".*", "gi");

		// find all matching product names
		var allMatched = [];
		var index = new Array();
		var j=0;
		for (var key in productNames) {
			if (key.match(regEx)) {
				allMatched[j] = {'productName' : key, 'href' : productNames[key]};
				index[j] = j;
				j++;
			}
		}

		var regExStartWith = new RegExp("^"+term+".*", "gi");
		// sort the entries by name - if the product name Starts with the search term then order it first
		for (var x = 0; x < allMatched.length; x++) {
			for (var y = 0; y < (allMatched.length-1); y++) {
				if (allMatched[y+1].productName.match(regExStartWith))
				{
					var holder = allMatched[y+1];
					allMatched[y+1] = allMatched[y];
					allMatched[y] = holder;
				}
			}
		}

		for (var k=0; k < allMatched.length; k++) {
			if (k < 10) {
				htmlReturn += '<li><a href="'+ allMatched[k].href +'" onclick="pageTracker._trackPageview(\'/searchSuggestions/product/'+escape( allMatched[k].productName )+'\'); return true;">'+allMatched[k].productName+'</a></li>';
				i++;
			}
		}
	}

	if (KEYCODE == 27 || term.length < 3 || i == 0) {
		hidePopup();
		//$('#searchPopPane').attr('style', 'display:none; z-index: 10; width:313px');
	} else {
		if (htmlReturn.length > 0) {
			resizePopupBorders(i);
			$('#searchPopPane').attr('style', 'z-index: 500; width:313px');
			//$('#searchPopPane').style('display:none; z-index: 10; width:313px'); // this is to hide it
			htmlReturn = '<ul id="searchTermList">' + htmlReturn + '</ul>';
			$('#searchPopBody').empty();
			$('#searchPopBody').append(htmlReturn);
		}
	}
}

function closePopupSearch() {
	searchPopupdisabled = true; // disable it for as long as this JS has scope
	hidePopup();
}

function hidePopup() {
	$('#searchPopPane').attr('style', 'display:none; width:313px');
}

function resizePopupBorders(listCount) {
	if (parseInt(jQuery.browser.version) == 6 && $.browser.msie) {
		// ie 6 only
		var height=40+(10*20); // fixed height because of a sizing issue with the borders at different sizes of the pane (the left/right pop out above/below)
		$('#searchPopPaneBorder1').attr('style', 'background-image: url(/images/topBorder.png); height: 25px; width: 320px; position: absolute; top: 0px; left: 0px;'); // top
		fixIEAlpha(document.getElementById("searchPopPaneBorder1"));
		$('#searchPopPaneBorder2').attr('style', 'background-image: url(/images/rightBorder.png); height: '+height+'px; width: 25px; position: absolute; left: 320px; top: 0px;'); // right side
		fixIEAlpha(document.getElementById("searchPopPaneBorder2"));
		$('#searchPopPaneBorder3').attr('style', 'background-image: url(/images/bottomBorder.png); height: 25px; width: 320px; position: absolute; top: '+(height)+'px; left: 25px;'); // bottom
		fixIEAlpha(document.getElementById("searchPopPaneBorder3"));
		$('#searchPopPaneBorder4').attr('style', 'background-image: url(/images/leftBorder.png); height: '+(height)+'px; width: 25px; position: absolute; top: 25px; left: 0px;'); // left side
		fixIEAlpha(document.getElementById("searchPopPaneBorder4"));
		$('#searchPopPaneBorder5').attr('style', 'background-image: url(/images/borderPointer.png); height: 27px; width: 15px; position: absolute; top: 22px; left: -4px;'); // pointer
		fixIEAlpha(document.getElementById("searchPopPaneBorder5"));

	} else {
		// firefox and ie 7+ & opera etc.
		var height=40+listCount*20;
		$('#searchPopPaneBorder1').attr('style', 'background-image: url(/images/searchPopupBorder.png); background-position: 0px 0px; height: 25px; width: 320px; position: absolute; top: 0px; left: 0px;'); // top
		$('#searchPopPaneBorder2').attr('style', 'background-image: url(/images/searchPopupBorder.png); background-position: -529px 0px; height: '+height+'px; width: 25px; position: absolute; left: 320px; top: 0px;'); // right side
		$('#searchPopPaneBorder3').attr('style', 'background-image: url(/images/searchPopupBorder.png); background-position: -234px -518px; height: 25px; width: 320px; position: absolute; top: '+(height)+'px; left: 25px;'); // bottom
		$('#searchPopPaneBorder4').attr('style', 'background-image: url(/images/searchPopupBorder.png); background-position: 0px -'+(543-height)+'px; height: '+(height)+'px; width: 25px; position: absolute; top: 25px; left: 0px;'); // left side
		$('#searchPopPaneBorder5').attr('style', 'background-image: url(/images/searchPopupBorder.png); background-position: -36px -359px; height: 27px; width: 15px; position: absolute; top: 20px; left: -4px;');
	}
}

function fixIEAlpha (DIV) {
	if (DIV!=null && parseInt(jQuery.browser.version) == 6 && $.browser.msie && DIV.style.filter=="") {
		document.getElementById("searchPopBody").style.height = (10*20);
		var bg	= DIV.currentStyle.backgroundImage;
		var src = bg.substring(5,bg.length-2);
		DIV.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		DIV.style.backgroundImage = '/images/transp.gif)';
	}
}

// this is the config to make the Hover Intent work for the main menu items
function displayMainMenuDropdown()
{
	var currentDropDown = $(this);
	$('.showMainMenu').each(function(){
		$(this).removeClass('showMainMenu');
	});

	var children = currentDropDown.children('.menuDropDown');
	if (children && children.length>0)
	{
		children.each(function(){
			$(this).addClass('showMainMenu');
		});
	}
}

function hideMainMenuDropdown()
{
	$(this).children('.showMainMenu').each(function(){
		$(this).removeClass('showMainMenu');
	});
	$('.lettersGroup .activeHighlight').each(function(){
		$(this).removeClass('activeHighlight');
	});
}

var mainMenuconfig = {
     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
     interval: 80, // number = milliseconds for onMouseOver polling interval
     over: displayMainMenuDropdown, // function = onMouseOver callback (REQUIRED)
     timeout: 350, // number = milliseconds delay before onMouseOut
     out: hideMainMenuDropdown // function = onMouseOut callback (REQUIRED)
};


// this is the config to make the Hover Intent work for the letter items
function displayLettersDropdown()
{
	$('.lettersGroup .activeHighlight').each(function(){
		$(this).removeClass('activeHighlight');
	});
	var currentDropDown = $(this);
	currentDropDown.addClass('activeHighlight');
}

function hideLettersDropdown()
{
	var currentDropDown = $(this);
	currentDropDown.removeClass('activeHighlight');
}

var lettersconfig = {
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
     interval: 60, // number = milliseconds for onMouseOver polling interval
     over: displayLettersDropdown, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: hideLettersDropdown // function = onMouseOut callback (REQUIRED)
};

function displayCategoriesDropdown()
{
	$('.categoriesGroup .activeHighlight').each(function(){
		$(this).removeClass('activeHighlight');
	});
	var currentDropDown = $(this);
	currentDropDown.addClass('activeHighlight');
}

function hideCategoriesDropdown()
{
	var currentDropDown = $(this);
	currentDropDown.removeClass('activeHighlight');
}

var categoriesconfig = {
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
     interval: 60, // number = milliseconds for onMouseOver polling interval
     over: displayCategoriesDropdown, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: hideCategoriesDropdown // function = onMouseOut callback (REQUIRED)
};

var creditCardHelp = {
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
     interval: 60, // number = milliseconds for onMouseOver polling interval
     over: function(){
	     if ($.browser.msie)
	     {
	        $(".maestroSwitchOnly #maestroNeedHelpPopup .helpBody").show();
	     }
	     else
	     {
		    $(".maestroSwitchOnly #maestroNeedHelpPopup .helpBody").fadeIn("normal");
	     }

     }, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: function(){
	     if ($.browser.msie)
	     {
	        $(".maestroSwitchOnly #maestroNeedHelpPopup .helpBody").hide();
	     }
	     else
	     {
		    $(".maestroSwitchOnly #maestroNeedHelpPopup .helpBody").fadeOut("normal");
	     }

     } // function = onMouseOut callback (REQUIRED)
};

var securityCodeHelp = {
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
     interval: 60, // number = milliseconds for onMouseOver polling interval
     over: function(){
	     if ($.browser.msie)
	     {
	        $("#securityCodePopup .helpBody").show();
	     }
	     else
	     {
		    $("#securityCodePopup .helpBody").fadeIn("normal");
	     }

     }, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: function(){
	     if ($.browser.msie)
	     {
	        $("#securityCodePopup .helpBody").hide();
	     }
	     else
	     {
		    $("#securityCodePopup .helpBody").fadeOut("normal");
	     }

     } // function = onMouseOut callback (REQUIRED)
};

$(document).ready(function(){
	$(".menuTop .menuItem").hoverIntent( mainMenuconfig );
	$(".lettersGroup .letterHead").hoverIntent( lettersconfig );
	$(".categoriesGroup .categoriesHead").hoverIntent( categoriesconfig );

	$('.menuBottomItem').hover(function(){
			$(this).addClass('activeHighlight');
		}, function(){
		$(this).removeClass('activeHighlight');
	});

	fixIEAlphaInstances();

	$("#maestroHelp").hoverIntent( creditCardHelp );
	$("#securityCode").hoverIntent( securityCodeHelp );

	if (parseInt(jQuery.browser.version) == 6 && $.browser.msie)
	{
		$(".iebackgroundfix").each(function(){
			if (this!=null && this.style.filter=="") {
				var bg	= this.currentStyle.backgroundImage;
				var src = bg.substring(5,bg.length-2);
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
				this.style.backgroundImage = '/images/transp.gif)';
			}
		});
	}

});

function fixIEAlphaInstances()
{
	if ($.browser.msie && parseInt($.browser.version.substr(0, 1)) < 7) { // ie6 or 5
		$(".transparent").each(function(){
			var bg = $(this).css("backgroundImage");
			var scaleType = 'scale';
			if ($(this).hasClass('paneArrow')) {
				scaleType = 'image';
			}
			bg.match(/^url[("']+(.*\.png)[)"']+$/i);
			bg = RegExp.$1;
			$(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bg + "', sizingMethod='"+scaleType+"')").css("backgroundImage", "none");
		});
	}
}


$(function() {
	try
	{
		var api = $("#overlay").overlay({
			api:true,
			expose: {
				color: '#000000',
				opacity: 0.7,
				closeSpeed: 1200
			},
			finish: {top: 'center'}
		});
		// define function that opens the overlay
		window.openOverlay = function() {
			api.load();
		};
	}
	catch(ERR)
	{
		//alert(ERR);
	}
});






function selectProductTab(tabID, tabPanelID) {

    // hide them all first
    hideProductTabs();

    // remove any 'selected' classes
    removeProductTabStyles()

    // show the selected panel
    document.getElementById(tabPanelID).style.display = 'block';

    // set the class of the selected tab to selected
    document.getElementById(tabID).className = 'selected';
}


function hideProductTabs() {
    document.getElementById('TabPanel_Product').style.display = 'none';
    document.getElementById('TabPanel_MoreInfo').style.display = 'none';
    document.getElementById('TabPanel_Benefits').style.display = 'none';
    document.getElementById('TabPanel_Ingredients').style.display = 'none';
    document.getElementById('TabPanel_Dosage').style.display = 'none';
    document.getElementById('TabPanel_Cautions').style.display = 'none';
    document.getElementById('TabPanel_Reviews').style.display = 'none';
}

function removeProductTabStyles() {
    document.getElementById('Tab_Product').className = '';
    document.getElementById('Tab_MoreInfo').className = '';
    document.getElementById('Tab_Benefits').className = '';
    document.getElementById('Tab_Ingredients').className = '';
    document.getElementById('Tab_Dosage').className = '';
    document.getElementById('Tab_Cautions').className = '';
    document.getElementById('Tab_Reviews').className = '';
}


function CloseActiveToolTip(supplierID) {
    var controller = Telerik.Web.UI.RadToolTipController.getInstance();
    var tooltip = controller.get_activeToolTip();
    if (tooltip) tooltip.hide();
} 
