/**
 * Functions.js v1.0: General javascript functions used throughout Wolfram's websites
 *
 * This file requires flashobject.js in order to be of any use. 
 */
var iedom=document.all||document.getElementById;
var hightraffic=0;
var pluginfound = false;
var test = "";

/**
demonstration player resize code
start
*/

function GetObject(theID)
{
   var obj = document.embeds[theID];
   if (!obj)
       obj = document.getElementById(theID);
   return obj;
}

function cleanup()
{
   var obj = GetObject("currentdemo");
   if (obj.removeEventListener)
       obj.removeEventListener('RecommendedSizeChanged', oursizechanged, false, false);
   else
       obj.detachEvent('RecommendedSizeChanged', oursizechanged);
}

function doneloading()
{
   var obj = GetObject("currentdemo");
   if (obj.addEventListener)
       obj.addEventListener('RecommendedSizeChanged', oursizechanged, false, false);
   else
       obj.attachEvent('RecommendedSizeChanged', oursizechanged);
}

function oursizechanged()
{
   var obj = GetObject("currentdemo");
   obj.width = obj.RecommendedWidth;
   obj.height = obj.RecommendedHeight;
   changedemoflashwidth();
} 

function changedemoflashwidth(){
	if($(".demoflash").css("width") != "auto"){
		$(".demoflash").css("width","auto");
	}

}


/**
demonstration player resize code
end
*/

function writit(text,id)
{
	if (document.getElementById)
	{
		if (!document.all) {
			//NS6 code - works with Firefox
			dynamiccontentNS6(id,text);
		} else {
			x = document.getElementById(id);
			x.innerHTML = '';
			x.innerHTML = text;
		}
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<P CLASS="body">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}

function dynamiccontentNS6(elementid,content){
	if (document.getElementById && !document.all){
		var rng = document.createRange();
		var el = document.getElementById(elementid);
		rng.setStartBefore(el);
		var htmlFrag = rng.createContextualFragment(content);
		while (el.hasChildNodes())
			el.removeChild(el.lastChild);
		el.appendChild(htmlFrag);
	}
}

// the code below adds a Flash script into a DIV, replacing the DIV's content
function loadDivWithFlash(divId, flashPath, flashName, flashWidth, flashHeigth, flashVersionRequired, flashBgColor, flashQuality, flashTransparency) {

   var fo = new FlashObject(flashPath, flashName, flashWidth, flashHeigth, flashVersionRequired, flashBgColor);

   if (flashQuality) {fo.addParam("quality", flashQuality);}
   if (flashTransparency) {fo.addParam("wmode","transparent");}

   //added by jeremyd
   fo.addParam("allowScriptAccess","sameDomain");
   fo.addParam("loop","false");
   fo.addParam("menu","false");
   fo.addParam("scale","noscale");
   fo.addParam("salign","lt");
   //end added code
  
   writit(fo.getFlashHTML(), divId);
}


function loadFlash(flashwidth,flashheight,nbname) {
	var platform= $.client.os;
	var getcookie= 0;
	if(readCookie('gotmathematica') != null){
		getcookie= 1;
	}
	var url=window.location.href;
	var urlarray= url.split("#");
	var thePath= urlarray[0];
	//find root web directory of html page (remove any trailing filenames that contail .html)
	str = thePath;
	re = /\/[^$\/]*\.html$/i;
	found =str.match(re);
	theurl=str; if (found != null) {theurl=(str.split(found))[0]+"/"};

	//hack for preview.html (adjust url to true location of page)
	if (str.match("/preview\.html/") != null) {theurl="/data/"+(str.split("/preview\.html/"))[1]+"/";}
	else if (str.match("/preview\.html\?") != null) {theurl="/data/"+(str.split("/preview\.html\?"))[1]+"/";}
	thePath=theurl;
	
	var playerwidth=(flashwidth+10)+"";
	var playerheight=(flashheight+34)+"";
	if(platform=="Linux"){
		var flashpath="/includes/playback.swf?src="+thePath+"flash.swf&srcwidth="+flashwidth+"&srcheight="+flashheight+"&preimage="+thePath+"preloadGraphic.jpg&playerurl=/download-cdf-player.html&notebookurl="+nbname+".cdf&hightraffic="+hightraffic+"&platform=linux&cookie="+getcookie;
	}else{
		var flashpath="/includes/playback.swf?src="+thePath+"flash.swf&srcwidth="+flashwidth+"&srcheight="+flashheight+"&preimage="+thePath+"preloadGraphic.jpg&notebookurl=/download-cdf-player.html&hightraffic="+hightraffic;
	}
	if (flashinstalled > 0 && flashversion >= 7 ) {
	loadDivWithFlash("mainFlash",flashpath, "mainFlash", playerwidth, playerheight, "7", "#ffffff","high","transparent");} else {
	writit("<a href='/download-cdf-player.html' target='_blank'><img src='"+thePath+"preloadGraphic.jpg' style='margin:14px 0px 14px 5px;' border=0><br><a href='http://adobe.com/go/getflash/ ' target=new><img src='/images/flashrequired.gif' style='margin:0px 0px 24px 7px;' border=0></a>", "mainFlash");}
	
}

// this code if for wolfram demonstrations only
function loadPlugin(flashheight,flashwidth,nbname,signature) {
// Create hidden value to store flashheight,flashwidth,nbname,signature
	var flashvalues = document.createElement("input");
	var tmpvalue = flashheight + "_" + flashwidth + "_" + nbname + "_" + encodeURIComponent(signature) + "_" + $(".demoflash .header h1").html();
	flashvalues.setAttribute("type","text");
	flashvalues.setAttribute("value",tmpvalue);
	flashvalues.setAttribute("id","flashvars");
	flashvalues.setAttribute("style","display:none");
	$("#grayOverlay").append(flashvalues);

	var thePath=window.location.href;

	imagelink=document.createElement("A");
	imagelink.setAttribute("href","");
	imagelink.setAttribute("id","detectplayerplugin");
	myImg=document.createElement("IMG");
	var url = thePath + "preloadGraphic.jpg";
	myImg.setAttribute("src","preloadGraphic.jpg");
	myImg.setAttribute("id","preloadgraphic");
	
	imagelink.appendChild(myImg);	

	var platform=  $.client.os;

// This is the code to hack when testing linux OS, need to be removed after the test.
//	var url = window.location.toString();
//	var currentOS = url.split("#");
//	
//	if(currentOS[1] == "linux"){
//		platform = "Linux";
//	}
//	if(currentOS[1] == "other"){
//		platform = "other";
//	}
	if($("#mathematica7only").length >0){
		platform = "v7";
	}

	if(platform == 'Windows' || platform =='Mac')
	{
	
		// windows and mac platform
		
		if(!$.browser.mathematica)
		{
			if($.browser.flash){
				loadFlash(flashwidth,flashheight,nbname)
			}else{
				
				$("#mainFlash").append("<div class='downloadplayerfordemonstrationn' style='z-index:5001;margin-top:80px;position:absolute; background:none;'><li style='list-style-type: none;'><a href='/download-cdf-player.html' id='getmathematicaplayer' target='_blank'></a></li></div>");
				myImg.setAttribute("class","overlay");
				document.getElementById("mainFlash").appendChild(myImg);
			
				if((flashwidth) > 294){
					var paddingNeeded = (flashwidth- 294)/2;
					$(".downloadplayerfordemonstrationn").css("margin-left",paddingNeeded );
				}
			}
			
		}
		else
		{	
						
			loadplayerfordemonstration(flashwidth+5,flashheight+5	,nbname,signature);
			doneloading();
		}

				
	}

	else

	{
		if(platform == 'Linux')
		{	
			
			//linux platform

			//if(!$.browser.mathematica){

				if($.browser.flash){
					//initNonSupportedPluginMouseover();
					loadFlash(flashwidth,flashheight,nbname)

					}else{										
						$("#mainFlash").append("<div id='detectplayerplugin'><div id='innerWrap' width='"+flashwidth+"'><img src='preloadGraphic.jpg' id='preloadgraphic'/></div></div>");					
						shownonsupportedplatformpopupondemothumbnail(flashwidth, flashheight);				
				     	}
				//}
				

		
	
		}else{

			if(platform=="v7"){

				if($.browser.flash){
					//initNonSupportedPluginMouseover();
					//loadFlash(flashwidth,flashheight,nbname)

					}


			}


			// all other platform

					//$("#mainFlash").append("<div id='detectplayerplugin'><div id='innerWrap' width='"+flashwidth+"'><img src='preloadGraphic.jpg' id='preloadgraphic'/></div></div>");
					//showcdfnonsupportedplatformpopupondemothumbnail(flashwidth, flashheight);	


	}
	}
	
}

function showcdfnonsupportedplatformpopupondemothumbnail(flashwidth, flashheight)
{
	
	$("#mainflash").mouseenter(function (e){ 

		if(!($("#unsupportedplatform").length>0)){
			e.preventDefault();
			var content = '<div id="unsupportedplatform" class="pluginunsupported"><img src="/images/playernonsupported.gif"></div>';
			$(content).prependTo("#mainflash");
			if((flashwidth) > 350){
				var leftPaddingNeeded = (flashwidth- 380)/2;
				$("#unsupportedplatform").css("margin-left",leftPaddingNeeded);
			}
			if((flashheight) > 90){
				var topPaddingNeeded = (flashheight- 85)/3;
				$("#unsupportedplatform").css("margin-top",topPaddingNeeded );
			}
		}

	}).mouseleave(function(e){
		$("#unsupportedplatform").remove();		
  });	

}

function shownonsupportedplatformpopupondemothumbnail(flashwidth, flashheight)
{
	$(".downloadplayerfordemonstrationn").css("display","none");
	
	$("#innerWrap").mouseenter(function (e){ 
		if(!($("#unsupportedplatform").length>0)){
			var content = '<div id="unsupportedplatform" class="pluginunsupported"></div>';

			$(content).insertBefore("#preloadgraphic");
			e.preventDefault();
			$("#unsupportedplatform").load("/includes/getmathematicaplayer.jsp #getmathematicaplayerfordemosunsupportedplatform", function() {			
				initializeunsupportedplatformpopuptext();
				var currentwindowurl = window.location.pathname; 
				var currentwindowurlarray = currentwindowurl.split("/");
				var demonstrationname = currentwindowurlarray[1];
				$("#downloadlivenotebook").click(function(e){e.preventDefault();hidedownloadplayerpopup();downloadNotebook(demonstrationname+".nbp");});
				$("#downloadmathematicaplayerlinux").click(function(e){e.preventDefault();loadplayerform();});
			});
			if((flashwidth) > 350){
				var leftPaddingNeeded = (flashwidth- 380)/2;
				$("#unsupportedplatform").css("margin-left",leftPaddingNeeded);
			}
			if((flashheight) > 90){
				var topPaddingNeeded = (flashheight- 85)/3;
				$("#unsupportedplatform").css("margin-top",topPaddingNeeded );
			}
		}

	}).mouseleave(function(e){
		$("#unsupportedplatform").remove();
		
  });	

}

function getmathematicaplayerfordemonstrations(){
	
//	$("#getmathematicaplayer").click(function(e) {
//		e.preventDefault();
//		loadplayerform();

//	});
}

function loadplayerfordemonstration(flashwidth,flashheight,nbname,signature)
{
	createEmbedObject(flashwidth,flashheight,nbname,signature);	
}

function createEmbedObject(flashwidth,flashheight,nbname,signature)
{
	if(signature=='AAAAAAAAAAAAAAAA') {
		var sig = '';
		var param = ''; 
	} else {
		var sig = 'signature="'+signature+'" ';
	    var param = '<PARAM name="signature" value="'+signature+'">';
	}
	
	var strHref = window.location.href;
	if(strHref.indexOf("/preview.html?") > -1 || strHref.indexOf("/preview.html/") > -1){
		nbname = "data/" + strHref.substr(strHref.indexOf("/preview.html")+14);   
	} 
			
	if($.client.browser != 'Explorer'){
		$("#mainFlash").append('<embed type="application/vnd.wolfram.mathematica" autoresize="true" style="z-index:100;display: block;" name="currentdemo" id="currentdemo" src="/' + nbname + '/flash-embed.cdf" '+sig+'height="'+flashheight+'" width="'+flashwidth+'" pluginspage="http://www.wolfram.com/products/player/download.cgi"/>');
		doneloading();
	}else{
		$("#mainFlash").append('<OBJECT classid="clsid:612AB921-E294-41AA-8E98-87E7E057EF33" id="currentdemo" height="'+flashheight+'" width="'+flashwidth+'"><PARAM name="autoresize" value="true">'+param+'<PARAM name="src" value="flash-embed.cdf"><embed type="application/vnd.wolfram.mathematica" autoresize="true" name="currentdemo" style="z-index:100;display: block;" id="currentdemo" src="flash-embed.cdf" '+sig+'height="'+flashheight+'" width="'+flashwidth+'" pluginspage="http://www.wolfram.com/products/player/download.cgi"/></OBJECT>');
		doneloading();
	}
}





function newpop(url,theWidth,theHeight) {
  var strHref = window.location.href;
  var newUrl = url;
  if(strHref.indexOf("/preview.html?") > -1 || strHref.indexOf("/preview.html/") > -1){
    newUrl = "/data/" + strHref.substr(strHref.indexOf("/preview.html")+14) + "/" + url;   
  } 
  win=window.open(newUrl,'Screenshot','width='+theWidth+',height='+theHeight+',resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,titlebar=no,statusbar=no');
  if (win.focus) { win.focus(); }
}

function addThumbnail() {
  var strHref = window.location.href;
  if(strHref.indexOf("/preview.html?") > -1 || strHref.indexOf("/preview.html/") > -1){
    var titleid = strHref.substr(strHref.indexOf("/preview.html")+26);   
  } else {
    var titleidarr = strHref.split('/');
	var titleid = titleidarr[titleidarr.length - 2];	
  }
	title = document.title;
  window.open('/ext/addthumbnail.jsp?title=' + title + '&titleid=' + titleid, 'Thumbnail', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=640,height=600');
}

function openInAdmin(id) {
  var idVals = id.split('/');
  if(idVals[0].match(/\d+/)) {
    window.location="/admin/view.jsp?id=" + idVals[0];
  }
}

function openDetails(id) {
  window.location="/int/details.jsp?id=" + id + "&limit=10";
}

function checkForDefaultInput(fieldId, defaultInput) {
    var fieldContent;
	var w3 = document.getElementById ? 1 : 0;
	var ie = document.all ? 1 : 0;
    if (w3) {
        fieldContent = document.getElementById(fieldId).value;
    } else if (ie) {
        fieldContent = eval("document.all." + fieldId + ".value");
    } else {
        fieldContent = eval("document.layers." + fieldId + ".value");
    }
    return fieldContent == defaultInput;
}

function initTextInput(element, action, text, cssname, checkForDefault) {
    var txt = text;
    if (text == null || text == "") {
        txt = "SEARCH";
    }
    if (element != null) {
        switch (action) {
          case "clear":
            cl = cssname;
            if (cssname == null) {
                cl = "searchinput-on";
            }
            if (element.value == txt) {
                element.value = "";
                element.className = cl;
            }
            break;
          case "setDefault":
            cl = cssname;
            if (cssname == null) {
                cl = "searchinput";
            }
            if (element.value == "") {
                element.value = txt;
                element.className = cl;
            } else if(element.value != txt) {
		 element.className = "searchinput-on";
	    }
            break;
          default:
            break;
        }
    }
}


// Scrolling for thumbnail

function scrollright(){

var length = $("ul.thumbnaillist li").length;
   $("ul.thumbnaillist li").each(function(i){
        if( $(this).hasClass('active'))
	  {
		$(this).removeClass('active').hide("slide", { direction: "down" }, 1000);
		$(this).css("display", "none");

		$(this).next(".inactive").addClass('active');
		$(this).next(".inactive").css("display", "block");

		
		if(i==(length -1))
		{
			$("ul.thumbnaillist li:first").addClass("active").css("display", "block");
		}
		return false;
	}
	
    });
}
function scrollleft(){
   $("ul.thumbnaillist li").each(function(i){
        if( $(this).hasClass('active'))
	  {
		$(this).removeClass('active');
		$(this).css("display", "none");

		$(this).prev(".inactive").addClass('active');
		$(this).prev(".inactive").css("display", "block");
		
		if(i==(0))
		{
			$("ul.thumbnaillist li:last").addClass("active").css("display", "block");
		}
		return false;
	}
	
    });
}

function initializedemodesctext()
{
	$(".Caption").removeClass("expandable");
	$(".CaptionSectionGroup").addClass("expandable");
	if($(".Caption").length > 0){
		var firstdivlength = $(".Caption").html().length + 27;
		$('div.expandable').expander({
			slicePoint:       firstdivlength,
			expandText:         '[more]',
			userCollapseText: '[less]' ,
			expandSpeed:0
		});
	}
}

function initializeunsupportedplatformpopuptext()
{
	$("#showwhyy").click(function(e) {
		e.preventDefault();
		var details = $(this).attr("href");
		$(details).css("display","block");
	});

}


function getimagearray(){
	var imageArray=new Array();
	$("#mycarousel2 > li > img").each(function(index){
		
	var src = $(this).attr("src");
	var temp=new Array();
	temp.push(src);
	temp.push("");
	temp.push("");
	temp.push("");
	imageArray.push(temp);

	});
	return imageArray;
}


function getPopupDimensionArray(id){
var imageDimensionArray=new Array();	
if($.browser.msie){

	var width = $("#mycarousel2 > li > img").css("width");
	if(width != undefined){
		var w = width.replace("px","");
	}
	var height = $("#mycarousel2 > li > img").css("height");
	if(height != undefined){
		var h = height.replace("px","");
	}
}
else{
	var w = $("#mycarousel2 > li > img").attr("width");
	var h = $("#mycarousel2 > li > img").attr("height");
}	
	imageDimensionArray.push(w);
	imageDimensionArray.push(h);
	return imageDimensionArray;
}



function getwebpreview(platform){
	var showwebpreview  = false;
	if(platform == "other" || platform == "v7"){
		showwebpreview = true;
	}
	else{
		if(!$.browser.mathematica){
			if($.browser.flash){
				showwebpreview = false;
			}else{
				showwebpreview = true;
			}
		}else{
			showwebpreview = false;

			}
	}
	return showwebpreview  ;

}

function initNonSupportedPlayerMouseover(){

	$("#mainFlash").mouseenter(function (e){ 
	
		if(!($("#playerunsupported").length>0)){
			e.preventDefault();
			var content = '<div id="playerunsupported" style="z-index:5002;position:absolute;" class="pluginunsupported"><img src="/images/playernonsupported.png"></div>';
			$(content).prependTo("#mainFlash");


			var dimenstionArray = getPopupDimensionArray();
			flashwidth  = dimenstionArray [0];
			flashheight = dimenstionArray [1];

			if((flashwidth) > 350){
				var leftPaddingNeeded = (flashwidth- 325)/2;
				$("#playerunsupported").css("margin-left",leftPaddingNeeded);
			}
			if((flashheight) > 90){
				var topPaddingNeeded = (flashheight- 100)/4;
				$("#playerunsupported").css("margin-top",topPaddingNeeded );
			}
		}

	}).mouseleave(function(e){
		$("#playerunsupported").remove();		
  });	

}

function initCdfNonCompatibleMouseover(){

	$("#mainFlash").mouseenter(function (e){ 
	
		if(!($("#playerunsupported").length>0)){
			e.preventDefault();
			var content = '<div id="playerunsupported" style="z-index:5002;position:absolute;" class="pluginunsupported"><img src="/images/notCDFcompatible.png"></div>';
			$(content).prependTo("#mainFlash");


			var dimenstionArray = getPopupDimensionArray();
			flashwidth  = dimenstionArray [0];
			flashheight = dimenstionArray [1];

			if((flashwidth) > 350){
				var leftPaddingNeeded = (flashwidth- 325)/2;
				$("#playerunsupported").css("margin-left",leftPaddingNeeded);
			}
			if((flashheight) > 90){
				var topPaddingNeeded = (flashheight- 100)/4;
				$("#playerunsupported").css("margin-top",topPaddingNeeded );
			}
		}

	}).mouseleave(function(e){
		$("#playerunsupported").remove();		
  });	


}

function initNonSupportedPluginMouseover(){

	$("#mainFlash").mouseenter(function (e){ 
		var demonstrationname = getdemonstrationname();
		if(!($("#unsupportedplatformWrapper").length>0)){
				var content = '<div id="unsupportedplatformWrapper" class="pluginunsupported"></div>';
				$(content).prependTo("#mainFlash");
			
			$("#unsupportedplatformWrapper").load("/includes/getmathematicaplayer.jsp #unsupportedplatformmain", function() {


			var dimenstionArray = getPopupDimensionArray();
			flashwidth  = dimenstionArray [0];
			flashheight = dimenstionArray [1];
			if((flashwidth) > 350){
				var leftPaddingNeeded = (flashwidth- 294)/2;
				$("#unsupportedplatformmain").css("margin-left",""+leftPaddingNeeded+"px");
			}
			if((flashheight) > 90){
				var topPaddingNeeded = (flashheight- 75)/6;
				$("#unsupportedplatformmain").css("margin-top",""+topPaddingNeeded +"px");
			}

				$("#pluginunsupportedbottom").hide();
				$("#downloadlivecdfnotebookunsupportedtop").click(function(e){
					e.preventDefault();
						if(readCookie('gotmathematica') != null){			
							
							window.location.href=demonstrationname+".cdf";
							$("#unsupportedplatformWrapper").remove();

						}else{
							
							$("#downloadlivecdfnotebookunsupportedtop").hide();
							$("#pluginunsupportedbottom").show();
							downloadCDFPlayer();
							$("#downloadlivecdfnotebookmain").click(function(e){
								e.preventDefault();
			
								var date = new Date();createCookie('gotmathematica',date.getTime(),365);
								window.location.href=demonstrationname+".cdf";

			
							});

							$("#closedialogmain").click(function(e){
								e.preventDefault();
								$("#downloadlivecdfnotebookunsupportedtop").show();
								$("#pluginunsupportedbottom").hide();

							});
						

						}

				});			

			});

		}

	}).mouseleave(function(e){
	 	$("#unsupportedplatformWrapper").remove();
		
  });	
	

}

function displaywebpreview(platform){


				var webpreviewgallery = null;
				var preview = "<div id='webprevieww'></div>";
				$("#preloadgraphic").remove();
				//var t= '<table  width="100%" id="topPlayWrapper" style="visibility:hidden;"><tr  width="100%"><td align="right" width="100%"><img style="padding-right: 5px;vertical-align:bottom;" src="/images/replay-sm.png"><a style="padding-bottom: 5px;font-weight:bold;" id="topPlay" href="">Replay &raquo;</a></td></tr></table>';
				var t= '<table cellspacing="10" cellpadding="0" width="100%" id="topPlayWrapper" style="visibility: hidden;"><tbody><tr width="100%"><td align="right" width="100%"><a href="" id="topPlay" style="font-weight: bold;font-size:12px;"><img src="/images/replay-sm.png" style="padding-right: 5px; vertical-align: bottom;">Replay »</a></td></tr></tbody></table>';
				$("#mainFlash").prev(".SectionSeparator").append(t);
				//$(t).insertBefore("#mainFlash");


				$("#mainFlash").append("<div id='previewwrapper'><div id='webprevieww'></div></div>");

				//$(preview).insertAfter("#mainFlash");
				

				var imageArray =  getimagearray(); 
				
				
				var popupDimensionArray = getPopupDimensionArray();	
				var numberofimages = $("#mycarousel2 > li").size(); 				
				
					webpreviewgallery =new simpleGallery({
						webpreview: true,						
 						wrapperid: "webprevieww", //ID of main gallery container,
						dimensions: popupDimensionArray , //width/height of gallery in pixels. Should reflect dimensions of the images exactly
 						imagearray: imageArray ,
 						autoplay: [true, 3000, 4], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
						persist: false,
 						fadeduration: 500, //transition duration (milliseconds)
 						oninit:function(){ 

 						},
 						onslide:function(curslide, i){ 
						
						if((i+1) == numberofimages ){
							
							//webpreviewgallery.navigate("stop");
							//$("#mycarousel").find("a#>img").removeAttr("style");
							//$("#webprevieww").remove();
							//$("#preloadgraphic").show();							

						}

 						}
					})

			if(platform == "Linux"){			
				initNonSupportedPluginMouseover();		
			}else{
				if(platform == "v7"){
					initCdfNonCompatibleMouseover();
				}else{
					if(platform != "Windows" && platform != "Mac")	{
						initNonSupportedPlayerMouseover();
					}
				}
			}		
}

function initThumbnailCarousel(){

				var numberofthumbnails = $("#mycarousel li").size();
				$("#mycarousel > li > a > img").css('border','1px solid white');
				$("#mycarousel > li > a > img").mouseenter(function (e){ 
					$("#mycarousel > li > a > img").css('border','1px solid white');
					$(this).css("border","1px solid #ff6600");

				}).mouseleave(function(e){
					e.preventDefault();
					$(this).css('border','1px solid white');
 				 });	

				if(numberofthumbnails > 3)
				{
					$('#mycarousel').jcarousel({visible:3,scroll:1});
					
				}
				else
				{
					$('#mycarousel').find('li').css("display","inline");
					$('#mycarousel').parent().removeAttr("align");

				}



}

function closeSlideShow(mygallery){

	$("#closeSlideshow").click(function(e){	
		e.preventDefault();	
			$(".SnapshotsCarousel").css("position","relative");					
		$(".SnapshotsCarousel").slideUp("slow",function(){
			
			mygallery.navigate("stop");
			$("#mycarousel").find("a#>img").css("border","1px solid white");	
			$("#simplegallery1").empty();
			$(this).remove();						
		});
	});

	
}

function initPopupThumbnailGallery(){
	var slidedown = false;
	var mygallery = null;
	$("a.group").click(function(e){
		e.preventDefault();
		if(  mygallery  != null){
				
			mygallery.navigate("stop");	

			if(!($(".SnapshotsCarousel").length > 0)){

				var preview = '<div class="SnapshotsCarousel"  style="position:relative;"><table width="100%"><tbody><tr><td align="right"><a class="slideshow" id="closeSlideshow" href=""></a></td></tr><tr><td align="center"><div id="simplegallery1" ></div></td></tr></tbody></table></div>';
				
				$(preview).insertAfter(".SnapshotsSectionGroup");
				
				slidedown  = true;
			var popupDimensionArray = getPopupDimensionArray($(this).attr("id")  );
			if(popupDimensionArray.length >= 0){
				mygallery= 	creategalleryobj( $(this).attr("id"));
				$(".SnapshotsCarousel").hide();							
				slideornot(slidedown );
									
			}

			}else{
				
			$("#simplegallery1").empty();
			$("#mycarousel").find("a#>img").css("border","1px solid white");
			slidedown  = false;	
			var popupDimensionArray = getPopupDimensionArray($(this).attr("id")  );
			if(popupDimensionArray.length >= 0){
				mygallery= 	creategalleryobj( $(this).attr("id")  );						
				slideornot(slidedown );
									
			}
			}	
		}else{

				var preview = '<div class="SnapshotsCarousel"  style="position:relative;"><table width="100%"><tbody><tr><td align="right"><a class="slideshow" id="closeSlideshow" href=""></a></td></tr><tr><td align="center"><div id="simplegallery1" ></div></td></tr></tbody></table></div>';
				
				$(preview).insertAfter(".SnapshotsSectionGroup");
				
				slidedown  = true;
				var popupDimensionArray = getPopupDimensionArray($(this).attr("id")  );
				if(popupDimensionArray.length >= 0){
					mygallery= 	creategalleryobj( $(this).attr("id") );	
					$(".SnapshotsCarousel").hide();					
					slideornot(slidedown );											
				}

			}

		return false;
		});




}

function slideornot(slidedown){

	if(slidedown)
	{
													
	$(".SnapshotsCarousel").slideDown("slow", function(){
	$(this).css("position","");
	});
	}else{
								
	$(".SnapshotsCarousel").show();
	}


	}

function creategalleryobj(id){

	var imageArray =  getimagearray(); 
	var popupDimensionArray = getPopupDimensionArray(id);
	mygallery=new simpleGallery({webpreview: false,curimage:id-1,	wrapperid: "simplegallery1",dimensions: popupDimensionArray ,imagearray: imageArray ,autoplay: [false, 2000, 4],persist: false,fadeduration: 1})
	closeSlideShow(mygallery);
	return mygallery;

}

$(document).ready(function(){
	var tmpurl = window.location.toString();
	if(tmpurl.indexOf("embed.jsp") > -1){
		return;
	}

	if($('#previewsidebar')) {
                prevhtml = $('#previewsidebar').clone(true);
                $('#previewsidebar').remove();
		prevhtml.remove('script');
                $('.sidebarContentColumn').append(prevhtml.contents());
        }

	changeUrl();
	$(".demobody").parent().attr("valign","top");
	var platform=  $.client.os;

//	var url = window.location.toString();
//	var currentOS = url.split("#");
	
//	if(currentOS[1] == "linux"){
//		platform = "Linux";
//	}
//	if(currentOS[1] == "other"){
//		platform = "other";
//	}
	if($("#mathematica7only").length >0){
		platform = "v7";
	}


	var showwebpreview = getwebpreview(platform);

	if(showwebpreview){
			displaywebpreview(platform);
	}
	
	if(!($.browser.mathematica) || platform == "v7"){
		if($("#ThingsToTry").length>0){
			$("#ThingsToTry").remove();
		}

	}else{

		if($("#ThingsToTry").length>0){
		 initTryThings();
		}
	}
	
	
	/* 
		If the demonstration desc is more than 200 characters, create more hide button 
	*/
	initializedemodesctext();

	/* 
		If the number of thumbnails are mroe than 3, then create a carousel
	*/
	initThumbnailCarousel();

	/* 
		On click of any thumbnail inside carousel, show popup images with carousel
	*/
	initPopupThumbnailGallery();
						

});

function initTryThings(){

	if($("#gamepadcontrols").length > 0){
		if(!( ($("#rotateandzoomin3d").length>0) ||
		     ($("#draglocators").length>0) || 
		     ($("#createanddeleteloactors").length>0)||
		     ($("#sliderzoom").length>0) ||
		     ($("#automaticanimation").length>0) || 
		     ($("#bookmarkanimation").length>0)))
		{
		      $("#ThingsToTry").remove();
		}else{

			$("#gamepadcontrols").parent().remove();
		}
	}

		if($("#rotateandzoomin3d").length>0){
		var rotateandzoomin3dcontent='<div id="rotateandzoomin3dcontent" class="thingstotrytooltip">Draw a 3D graphic to rotate it. Starting the drag near the center tumbles the graphic; starting near a corner turns it parallel to the plane of the screen. Hold down <span>Ctrl</span> or (<span>Cmd</span> on Mac) and drag up and down to zoom. </div>';
		$(rotateandzoomin3dcontent).insertAfter("#ThingsToTry").hide();
		$('#rotateandzoomin3d').bt({trigger: ['mouseover', 'mouseleave'], positions: 'top',contentSelector: "$('#rotateandzoomin3dcontent')", centerPointX: 0.6,centerPointY: 0.3,width: 320,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}
		if($("#draglocators").length>0){
		var draglocatorscontent='<div id="draglocatorscontent" class="thingstotrytooltip">Drag any locators (<img style="vertical-align:bottom;" src="/images/thingstotryimage2.gif">, etc.) to move it around.</div>';
		$(draglocatorscontent).insertAfter("#draglocators").hide();
		$('#draglocators').bt({trigger: ['mouseover', 'mouseleave'],positions: 'top',contentSelector: "$('#draglocatorscontent')", centerPointX: 0.6,centerPointY: 0.3,width: 240,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}
		if($("#createanddeleteloactors").length>0){
		var createanddeleteloactorscontent='<div id="createanddeleteloactorscontent"  class="thingstotrytooltip">Insert a new locator in the graphic by holding down the <span>Alt</span> key and clicking where you want it to be. Delete a locator by clicking it while holding down the <span>Alt</span> key. </div>';
		$(createanddeleteloactorscontent).insertAfter("#ThingsToTry").hide();
        	$('#createanddeleteloactors').bt({trigger: ['mouseover', 'mouseleave'],positions: 'top',contentSelector: "$('#createanddeleteloactorscontent')", centerPointX: 0.6,centerPointY: 0.3,width: 320,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}
		if($("#sliderzoom").length>0){
		var sliderzoomcontent='<div id="sliderzoomcontent" class="thingstotrytooltip">Hold down the <span>Alt</span> key while moving a slider to make fine adjustments in the slider value. Hold <span>Ctrl</span> and/or <span>Shift</span> at the same time as <span>Alt</span> to make ever fine adjustments. </div>';
		$(sliderzoomcontent).insertAfter("#ThingsToTry").hide();
		$('#sliderzoom').bt({trigger: ['mouseover', 'mouseleave'],positions: 'top',contentSelector: "$('#sliderzoomcontent')",	centerPointX: 0.6,centerPointY: 0.3,width: 300,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}
		if($("#automaticanimation").length>0){
		var automaticanimationcontent= '<div id="automaticanimationcontent" class="thingstotrytooltip">Animate a slider in this Demonstration by clicking the <img style="vertical-align:bottom;" src="/images/thingstotryimage1.gif"> button next to the slider, and then clicking the play button that appears. Animate all controls by selecting <b>AutoRun</b> from the <img style="vertical-align:middle;" src="/images/thingstotryimage3.gif"/>menu.</div>';
		$(automaticanimationcontent).insertAfter("#ThingsToTry").hide();
	       $('#automaticanimation').bt({trigger: ['mouseover', 'mouseleave'],positions: 'top',contentSelector: "$('#automaticanimationcontent')",centerPointX: 0.6,centerPointY: 0.3,width: 320,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}
		if($("#bookmarkanimation").length>0){
		var bookmarkanimationcontent= '<div id="bookmarkanimationcontent" class="thingstotrytooltip">See a prepared animation of this Demonstration by selecting <b>Animated Bookmarks</b> from the <img style="vertical-align:bottom;" src="/images/thingstotryimage1.gif"> menu.</div>';
		$(bookmarkanimationcontent).insertAfter("#ThingsToTry").hide();
		$('#bookmarkanimation').bt({trigger: ['mouseover', 'mouseleave'],positions: 'top',contentSelector: "$('#bookmarkanimationcontent')",centerPointX: 0.55,centerPointY: 0.3,width: 320,hackshift: 15,spikeLength: 24,spikeGirth: 27,padding: 0,fill: '#FFF',strokeStyle: '#AFAFAF',strokeWidth: 3,shadow: true,shadowOffsetX: 3,shadowOffsetY: 3,	shadowBlur: 8,shadowColor: '#CCCCCC',shadowOverlap: false});
		}

		if($(".things").length > 0){$(".things").css("display","inline");}


}


function trackflash(clickcount) {
   var url = document.location.toString().replace(/[^:]\/{2,}/, '/');
   var re = /^(http(s)?:\/\/)?[^\/]+\/([^\/]+)\//g;
   var m = re.exec(url);
   var demo = m[3];
   if(demo == 'preview.html') {
      return;
   }
   var first = false;
   if(clickcount == "first") {
      first = true;
   }
   $.get('/includes/swf.html', {demoid: demo, first: first}, function() { });
}  

function changeUrl()
{
	if($(".relatedLink").length > 0){
		$(".relatedLink").each(function(){
			var authorname = encodeURIComponent($(this).html());
			var index = $(this).attr("href").indexOf("author.html?author=");
			if(index > -1 && $(this).html()){
				var newurl = $(this).attr("href").substring(0,index) + "author.html?author=" + authorname;
				var url = Utf8.encode(newurl);
				$(this).attr("href", url);
			}
			var index1 = $(this).attr("href").indexOf("search.html?query=");
			if(index1 > -1 && $(this).html()){
				var newurl = $(this).attr("href").substring(0,index1) + "search.html?query=" + authorname;
				var url = Utf8.encode(newurl);
				$(this).attr("href", url);
			}
		});
	}
}



// this code if for demonstrations embedding
function loadEmbedPlugin(flashheight,flashwidth,nbname,signature) {
	signature = decodeURIComponent(signature);
	flashheight = parseInt(flashheight);
	flashwidth= parseInt(flashwidth);

	var thePath = getBaseURL() + nbname + "/";
	var src = thePath + "preloadGraphic.jpg";

	imagelink=document.createElement("A");
	imagelink.setAttribute("href","");
	imagelink.setAttribute("id","detectplayerplugin");
	myImg=document.createElement("IMG");
	var url = thePath + "preloadGraphic.jpg";
	myImg.setAttribute("src",src);
	myImg.setAttribute("id","preloadgraphic");
	
	imagelink.appendChild(myImg);	
	var platform=  $.client.os;

// This is the code to hack when testing linux OS, need to be removed after the test.
//	var url = window.location.toString();
//	var currentOS = url.split("#");
//	
//	if(currentOS[1] == "linux"){
//		platform = "Linux";
//	}
//	if(currentOS[1] == "other"){
//		platform = "other";
//	}
	if($("#mathematica7only").length >0){
		platform = "v7";
	}

	if(platform == 'Windows' || platform =='Mac')
	{
		// windows and mac platform
		if(!$.browser.mathematica)
		{
			//if($.browser.flash){
				//loadEmbedFlash(flashwidth,flashheight,nbname)
			//}else{
				$("#mainFlash").append("<div class='downloadplayerfordemonstrationn' style='z-index:5001;margin-top:80px;position:absolute; background:none;'><li style='list-style-type: none;'><a href='/download-cdf-player.html' id='getmathematicaplayer' target='_blank'></a></li></div>");
				myImg.setAttribute("class","overlay");
				document.getElementById("mainFlash").appendChild(myImg);
			
				if((flashwidth) > 294){
					var paddingNeeded = (flashwidth- 294)/2;
					$(".downloadplayerfordemonstrationn").css("margin-left",paddingNeeded );
				}
			//}
		}
		else
		{					
			loadplayerfordemonstration(flashwidth+5,flashheight+5,nbname,signature);
			doneloading();
		}	
	}
	else
	{
		if(platform == 'Linux')
		{	
			//linux platform
			//if($.browser.flash){
				//initNonSupportedPluginMouseover();
				//loadEmbedFlash(flashwidth,flashheight,nbname)
			//}else{									
				$("#mainFlash").append("<div id='detectplayerplugin'><div id='innerWrap' width='"+flashwidth+"'><img src='"+thePath+"preloadGraphic.jpg' id='preloadgraphic'/></div></div>");					
				//shownonsupportedplatformpopupondemothumbnail(flashwidth, flashheight);				
			//}
		}else{
			if(platform=="v7"){
				if($.browser.flash){
					//initNonSupportedPluginMouseover();
					//loadEmbedFlash(flashwidth,flashheight,nbname)
				}
			}
			// all other platform
			//$("#mainFlash").append("<div id='detectplayerplugin'><div id='innerWrap' width='"+flashwidth+"'><img src='preloadGraphic.jpg' id='preloadgraphic'/></div></div>");
			//showcdfnonsupportedplatformpopupondemothumbnail(flashwidth, flashheight);	
		}
	}
}

function loadEmbedFlash(flashwidth,flashheight,nbname) {
	var platform= $.client.os;
	var getcookie= 1;
/*
	if(readCookie('gotmathematica') != null){
		getcookie= 1;
	}
*/
	
	var playerwidth=(flashwidth+10)+"";
	var playerheight=(flashheight+34)+"";

	var thePath = getBaseURL() + nbname + "/";
	
	if(platform=="Linux"){
		var flashpath="/includes/playback.swf?src="+thePath+"flash.swf&srcwidth="+flashwidth+"&srcheight="+flashheight+"&preimage="+thePath+"preloadGraphic.jpg&playerurl=/download-cdf-player.html&notebookurl=/"+nbname+"/"+nbname+".cdf&hightraffic="+hightraffic+"&platform=linux&cookie="+getcookie;
	}else{
		var flashpath="/includes/playback.swf?src="+thePath+"flash.swf&srcwidth="+flashwidth+"&srcheight="+flashheight+"&preimage="+thePath+"preloadGraphic.jpg&notebookurl=/download-cdf-player.html&hightraffic="+hightraffic;
	}
	if (flashinstalled > 0 && flashversion >= 7 ) {
	loadDivWithFlash("mainFlash",flashpath, "mainFlash", playerwidth, playerheight, "7", "#ffffff","high","transparent");} else {
	writit("<a href='/download-cdf-player.html' target='_blank'><img src='"+thePath+"preloadGraphic.jpg' style='margin:14px 0px 14px 5px;' border=0><br><a href='http://adobe.com/go/getflash/ ' target=new><img src='/images/flashrequired.gif' style='margin:0px 0px 24px 7px;' border=0></a>", "mainFlash");}	
}

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }
}

