
if ($.browser.version)
{
	if ($.browser.msie)
	{
		$.browser.msie7 = ($.browser.version.indexOf("7") == 0);
		$.browser.msie6 = ($.browser.version.indexOf("6") == 0);
	}
	else if ($.browser.safari)
	{
		// Safari 3 uses webkit version 522+
		$.browser.safari3 = ($.browser.version.indexOf("5") == 0);
		$.browser.safari2 = ($.browser.version.indexOf("4") == 0);
		$.browser.safari1 = ($.browser.version.indexOf("3") == 0);
	}
}

$(document).ready(onDOMLoaded);

function onDOMLoaded()
{
	if (window.dhtmlHistory)
		dhtmlHistory.initialize();
	
	var url = document.baseURI || document.URL;
    if (url.toLowerCase().indexOf("/docs/60/") < 0)
    {
		if (document.body.innerHTML.indexOf("/docs/60/") != -1)
		{
			$("a[href*='/docs/60/']")
				.click( function( event ) { popHelpWin(event, this); } ).end()
				.attr("target", "_blank");
		}
    }
}

// slideshow
//
// Create a slideshow out of a single <img> tag
// and an array of image src strings.
//
function slideshow(idImg, rgSrc, /* optional */ rgThickboxSrc)
{
	var el = $("#" + idImg);	
	if (!el.length) return;
	if (!rgSrc.length) return;
	
	var elThickbox = null;
	if (rgThickboxSrc)
	{
	    var elParents = el.parents("a");   
        if (elParents.length > 0)
            elThickbox = $(elParents[0]);        
	}

	smartPreload(rgSrc, 0);
	if (elThickbox) setTimeout(function(){smartPreload(rgThickboxSrc, 0); });
	preloadImgs(["/images/slideshow/lefthover.png", "/images/slideshow/righthover.png"]);
	
	var ix = 0;

	function go(e, fxnIx)
	{
		var btnCode = getButtonCode(e);
		if (btnCode == MOUSE_BUTTON_LEFT || btnCode == undefined)
		{
			fxnIx();
			el[0].src = rgSrc[ix];			
			setTimeout(function(){smartPreload(rgSrc, ix)},1);
			
			if (elThickbox)
			{
			    elThickbox[0].href = rgThickboxSrc[ix];
			    setTimeout(function(){smartPreload(rgThickboxSrc, ix)},1);
			}
		}
		e.stopPropagation();
		return false;
	}

	function next(e)
	{
		return go(e, function(){
			ix++;
			if (ix >= rgSrc.length) ix = 0;
		});
	}

	function prev(e)
	{
		return go(e, function(){
			ix--;
			if (ix < 0) ix = rgSrc.length - 1;
		});
	}

	function attachGoBehavior(el, fxn)
	{
		el.click(fxn);
		if ($.browser.msie || $.browser.opera)
			el.dblclick(fxn);

		disableSelection(el);
	}

	function attachArrowImg(el, fLeft)
	{
		var sDir = fLeft ? "left" : "right";
		var sUrl = "/images/slideshow/" + sDir + ".png";
		var sUrlHover = "/images/slideshow/" + sDir + "hover.png";

		var sCssKey = $.browser.msie6 ? "filter" : "background";
		var sCssVal = $.browser.msie6 ? "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='%1', sizingMethod='scale');" : "url('%1') no-repeat top left";

		el.css(sCssKey, swap1(sCssVal, sUrl));

		el.mouseover(function(){el.css(sCssKey, swap1(sCssVal, sUrlHover));});
		el.mouseout(function(){el.css(sCssKey, swap1(sCssVal, sUrl));});
	}
	
	var elParent = el.parent();
	if (elParent)
	{
		elParent.mousedown(function(){return false;});
		
		var elImgLeft = $("<div>");
		var elImgRight = $("<div>");
		
		$([elImgLeft[0], elImgRight[0]]).css(
			"position", "relative").css(
			"top", ($.browser.msie ? "-23px" : "-19px")).css(
			"float", "right").css(
			"width", "15px").css(
			"height", "18px");
			
		if (rgSrc.length > 1)
		{
		    attachArrowImg(elImgLeft, true);
		    attachArrowImg(elImgRight, false);

		    attachGoBehavior(elImgLeft, prev);
		    attachGoBehavior(elImgRight, next);
		
		    elParent.append(elImgRight).append(elImgLeft);
		}
	}
	
	if (!elThickbox && !rgSrc.length <= 1)
	    attachGoBehavior(el, next);
}

function SectionedPage(idDiv, hashS, hashTitle, rgS)
{
	this.el = $("#" + idDiv);
	this.elTitle = $("#idSectionTitle");
	this.hashS = hashS;
	this.hashTitle = hashTitle;
	this.fxnOnSwitch = null;
	this.rgS = rgS;
	
	var cSwaps = 0;
	var oSelf = this;
	var sIDInit = null;
	
	this.init = function()
	{
		if (null != sIDInit) return;
		
		oSelf.rgA = $("a.sectionlink");
		
		oSelf.rgA.click(function(e){
			oSelf.switchSection(e, this);
		});
		
		var elPrev = $("#idSectionPrev");
		var elNext = $("#idSectionNext");
		
		if (elPrev)
			elPrev.click(oSelf.prev);
		if (elNext)
			elNext.click(oSelf.next);
		
		var ixCurrent = oSelf.getCurrentIx();
		if (ixCurrent > -1)
		{
			var elACurrent = oSelf.getCurrentElA();
			sIDInit = elACurrent.attr("id");
			
			// get the section from the hash ("#") portion of the location
			var sHashSection = "";
			if(window.location && window.location.hash && window.location.hash.indexOf("_") >= 0)
			    sHashSection = "idSection_" + window.location.hash.split("_")[1];
			
			// if the hash portion doesn't match the current, switch sections
			if (sIDInit != sHashSection && $("#" + sHashSection).length)
			{
			    oSelf.switchSection(null, $("#" + sHashSection)[0]);
			}
			else if (dhtmlHistory.isFirstLoad() || $.browser.safari2 || $.browser.safari1) 
			{
				selectSection(ixCurrent);
			}
			
			// unhide the page and title if we have a hash
			if(window.location.hash)
			{
			    $("#idSectionedPage").css("visibility", "");
		        $("#idSectionTitle").css("visibility", "");	
		    }
			
			$(window).load(function(){oSelf.preload(ixCurrent);});
		}
		
		//if (!$.browser.safari2 && !$.browser.safari1)
		//	dhtmlHistory.addListener(oSelf.onBrowserHistory);
	}
	
	this.preload = function( ix )
	{
		if (!window.sThumbPath) return;
		
		var rgSrc = $(rgS).map(function(ix, _){return sThumbPath + "/" + _ + "_small.png";});
		
		smartPreload(rgSrc, ix, Math.ceil(rgSrc.length / 2));
	}
	
	this.prev = function( e )
	{
		try {this.blur();} catch(e){};
		oSelf.go(-1);
		return cancel(e);
	}
	
	this.next = function( e )
	{
		try {this.blur();} catch(e){};
		oSelf.go(1);
		return cancel(e);
	}
	
	this.go = function( dx )
	{
		var s = oSelf.getCurrent();
		var ixC = 0;
		for (var ix = 0; ix < oSelf.rgS.length; ix++)
		{
			if (oSelf.rgS[ix] == s)
			{
				ixC = ix;
				break;
			}
		}
		
		ixC += dx;
		if (ixC < 0)
			ixC = oSelf.rgS.length + ixC;
		if (ixC >= oSelf.rgS.length)
			ixC = ixC - oSelf.rgS.length;
		
		this.switchSection(null, $("#idSection_" + oSelf.rgS[ixC])[0]);
	}
	
	this.getCurrent = function()
	{
	    var elA = this.getCurrentElA();
	    return (elA.length ? elA.attr("id").substring("idSection_".length) : "");
	}
	
	this.getCurrentElA = function()
	{
		return $(".current a.sectionlink");
	}
	
	this.getCurrentIx = function()
	{
		var elA = this.getCurrentElA();
		return (elA.length ? elA.attr("sectioni") || 0 : -1);
	}
	
	this.switchSection = function( e, elA, fFromHistory )
	{
		if (!elA || !elA.id || (elA.id.indexOf("idSection_") != 0)) return;		
		
		$("#lang-redirect").attr("value", "/" + sCurrentProduct + "/learnmore.html?section=" + elA.id.substring("idSection_".length));
		
		this.swapHTML(this.hashS[elA.id]);
		
		var s = document.title;
		document.title = s.substring(0, s.lastIndexOf(" - ")).replace(/^\s+|\s+$/g, '') + " - " + this.hashTitle[elA.id];
		
		if (this.elTitle)
			this.elTitle.html(this.hashTitle[elA.id]);
		
		if (!$.browser.safari2 && !$.browser.safari1)
		{
			if (!fFromHistory)
				dhtmlHistory.add("hist_" + elA.id.substring("idSection_".length), {sID: elA.id});
		}
		
		// Update Accordion UI
		selectSection($(elA).attr("sectioni"));
		
		if (e) cancel(e);
		return false;
	}
	
	this.swapHTML = function( sHTML )
	{
		if (!sHTML) sHTML = "";

		this.el.html(sHTML);
		
		if (window.tb_init)
			tb_init("a.thickbox");

		if (this.fxnOnSwitch)
			this.fxnOnSwitch();
	}
	
	this.onBrowserHistory = function( sLoc, stateHistory )
	{
		if (null == sIDInit) oSelf.init();
		
		var sID = sIDInit;
		if (stateHistory)
			sID = stateHistory.sID;
		
		oSelf.switchSection(null, $("#" + sID)[0], true);
	}
	
	$(document).ready(this.init);
}

// disableSelection
//
// Attempt to disable selection for an element
// modified from http://ajaxcookbook.org/disable-text-selection/
//
function disableSelection(el)
{
	if (!el || !el.length) return;
	el.bind("selectstart", function(){return false;});
	el.attr(
		"unselectable", "on").css(
		"MozUserSelect", "none").css(
		"cursor", "default");
}

// applyDropShadow
//
// Apply a simple drop shadow via CSS styled wrapper <div>s
// to an element, el, and give the outermost <div> wrapper
// an id of sIdWrap
//
function applyDropShadow(el, sIdWrap)
{
	if (!el || !el.length) return;
	el.wrap("<div id='" + sIdWrap + "' class='wrap1'><div class='wrap2'><div class='wrap3'></div></div></div>");
}

// smartPreload
//
// Preload the cRadius image srcs directly
// before/after ix in rgSrc
//
function smartPreload(rgSrc, ix, cRadius)
{
	if (null == cRadius) cRadius = 2;

	var rgSlice = [];
	var c;

	var ixH = ix;
	for (c = 0; c < cRadius; c++)
	{
		ixH++;
		if (ixH >= rgSrc.length) ixH = 0;
		rgSlice.push(rgSrc[ixH]);
	}

	var ixL = ix;
	for (c = 0; c < cRadius; c++)
	{
		ixL--;
		if (ixL < 0) ixL = rgSrc.length - 1;
		rgSlice.push(rgSrc[ixL]);
	}

	preloadImgs(rgSlice);
}

// preloadImgs
//
// Preload/cache all image src strings supplied in rgSrc array
//
function preloadImgs(rgSrc)
{
	if (!preloadImgs.hash) preloadImgs.hash = {};

	var ix = 0;
	$("<img>").bind("load", function(){

		while (ix < rgSrc.length && preloadImgs.hash[rgSrc[ix]])
		{
			// Already preloaded this img
			ix++;
		}

		if (ix < rgSrc.length)
		{
			preloadImgs.hash[rgSrc[ix]] = true;
			this.src = rgSrc[ix];
			ix++;
		}

	}).trigger("load");
}

// clearOnFocus
//
// Fill a textbox with an initial grayed-out value, sInit,
// and clear the textbox's gray contents on focus.  Used for
// textbox hints like "Search" that disappear on click.
//
function clearOnFocus( el, sInit )
{
	if (!el) return;

	function clear()
	{
		if (el[0].fReset)
		{
			el.attr("class", "filled");
			el.val("");
			el[0].fReset = false;
		}
	}

	function reset()
	{
		if (!el.val().length || el.val() == sInit)
		{
			el.attr("class", "empty");
			el.val(sInit);
			el[0].fReset = true;
		}
	}

	el.focus(clear);
	el.blur(reset);
    
    el[0].fReset = false;
	reset();
};

var rgMouseButtonMap = [];
var MOUSE_BUTTON_LEFT = 0;
var MOUSE_BUTTON_RIGHT = 1;
var MOUSE_BUTTON_MIDDLE = 2;

if ($.browser.msie || $.browser.safari)
{
	rgMouseButtonMap[1] = MOUSE_BUTTON_LEFT;
	rgMouseButtonMap[2] = MOUSE_BUTTON_RIGHT;
	rgMouseButtonMap[4] = MOUSE_BUTTON_MIDDLE;
}
else
{
	rgMouseButtonMap[0] = MOUSE_BUTTON_LEFT;
	rgMouseButtonMap[1] = MOUSE_BUTTON_RIGHT;
	rgMouseButtonMap[2] = MOUSE_BUTTON_MIDDLE;
}

function getButtonCode(e)
{
	if (e.button == null) return null;
	return rgMouseButtonMap[e.button];
}

// Return sOrig w/ %1 occurrences replaced by sInsert
function swap1(sOrig, sInsert)
{
	if (!sOrig || !sInsert) return "";
	return sOrig.replace(/%1/g, sInsert);
}

function cancel(e)
{
	if (document.all && event) 
		event.returnValue = false;
	else if (e)
		e.preventDefault();
   	return false;
}

// Pop the help window, or bring it to the front if it already exists
function popHelpWin(e, elA)
{
	if (!elA || !elA.href) return;
	var helpWin = window.open(elA.href, 'fbHelp', 'width=800, height=600, scrollbars=yes, toolbar=yes, location=' + ($.browser.msie ? 'yes' : 'no') + ', status=yes, menubar=yes, copyhistory=no, resizable=yes'); 
	safeFocus(helpWin); 
	return cancel(e);
}

function safeFocus( el )
{
	try { el.focus(); } catch(e) {};
}

function SiteNameTest( sLang, sResponseId, sInputId )
{
    var timeoutId = null;

    this.valid = false;    

    this.test = function( e, sSiteName ) {
        if (   13 == e.keyCode // RETURN
		    ||  9 == e.keyCode // TAB
		    || 16 == e.keyCode // SHIFT
		) return;
		
		this.valid = true; 
		
		// Unschedule the previous call
		if (null != timeoutId) clearTimeout(timeoutId);
		
		var o = this;		
		// Create the functions that we'll use
		function _callback( xmlResponse ) {
		    o.valid = $("fAvailable", xmlResponse).text() == "true";
		    var sResponse = $("s", xmlResponse).text();
		    $("#"+sResponseId).html(sResponse)
		                      .css("color", o.valid ? "#338833" : "#CC3333")
		                      .css("visibility", sSiteName == "" ? "hidden" : "visible");
            if(o.valid) $("#"+sInputId).attr("class", "");
	    }
	    
	    function _error( ) {
	        o.valid = true;
	        $("#"+sResponseId).css("visibility", "hidden");
	        $("#"+sInputId).attr("class", "");
	    }
	    
	    function _run() { jQuery.ajax({ type: "GET", 
                      url:"/" + sCurrentProduct + "/CheckSiteName.html", 
                      data: { sLang: sLang, s: sSiteName }, 
                      success: _callback,
                      error: _error,
                      timeout: 5000
                     }); }

    	// Schedule the next call
        timeoutId = setTimeout(function() { _run(); }, 300);
    }
}

function checkBuySubmit( oForm, fValidSiteName )
{
    var selected = $("*[name=sCategory]:checked", oForm)[0];
    
    var fValid = false;
    if(selected && selected.value)
        fValid = (selected.value == "FOGBUGZ" || (selected.value == "HOSTEDFB" && fValidSiteName));
    
    if(!fValid) $("#hostedSiteNameError").css("visibility", "visible");
    $("#hosted-url").attr("class", fValid ? "" : "error");
    	    
	return fValid;
}

function checkTrySubmit( oForm, fValidSiteName )
{
    var fValid = fValidSiteName;
    
    if(!fValid) $("#trialSiteNameError").css("visibility", "visible");
    $("#trial-url").attr("class", fValid ? "" : "error");
    
    return fValid;
}

function checkWebinarSubmit( oForm )
{    
    var fValid = true;
    
    if ($("#id-name")[0].value == "")
    {
        $("#webinar-nameError").css("display", "");
        fValid = false;
    }
    else
    {
        $("#webinar-nameError").css("display", "none");
    }
    
    if ($("#id-email")[0].value == "")
    {
        $("#webinar-emailError").css("display", "");
        fValid = false;
    }
    else
    {
        $("#webinar-emailError").css("display", "none");
    }
    
    return fValid;
}
