var isCMSPreview; // This var is to swap functionality when page is in CMS Preview

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};		
jquery_inputDefault=function(){this.init=function(){var a=$("input.inputDef");a.each(function(){$(this).attr('value',$(this).attr('default')).addClass('jqueryInputDefault')});a.focus(function(){if($(this).attr('value')==$(this).attr('default')){$(this).attr('value','').removeClass('jqueryInputDefault')}});a.blur(function(){if($(this).attr('value')==''){$(this).attr('value',$(this).attr('default')).addClass('jqueryInputDefault')}})}};$(document).ready(function(){var a=new jquery_inputDefault();a.init()});

;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

//(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);

(function($){$.fn.hashchange=function(fn){$(window).bind("jQuery.hashchange",fn);return this;};$.observeHashChange=function(options){var opts=$.extend({},$.observeHashChange.defaults,options);if(isHashChangeEventSupported()){nativeVersion();}
else{setIntervalVersion(opts);}};var locationHash=null;var functionStore=null;var interval=0;$.observeHashChange.defaults={interval:500};function isHashChangeEventSupported(){return typeof window.onhashchange!=='undefined';}
function nativeVersion(){locationHash=document.location.hash;window.onhashchange=onhashchangeHandler;}
function onhashchangeHandler(e,data){var oldHash=locationHash;locationHash=document.location.hash;$(window).trigger("jQuery.hashchange",{before:oldHash,after:locationHash});}
function setIntervalVersion(opts){if(locationHash==null){locationHash=document.location.hash;}
if(functionStore!=null){clearInterval(functionStore);}
if(interval!=opts.interval){functionStore=setInterval(checkLocationHash,opts.interval);interval=opts.interval;}}
function checkLocationHash(){if(locationHash!=document.location.hash){var oldHash=locationHash;locationHash=document.location.hash;$(window).trigger("jQuery.hashchange",{before:oldHash,after:locationHash});}}
$.observeHashChange();})(jQuery);


$(document).ajaxStart(function () {
$('#ajaxBusy').show();
}).ajaxStop(function (){
$('#ajaxBusy').hide();
});


$(function(){


	$("#accordion").accordion({
			collapsible: true,
			active: false,
				autoHeight:false,
				header: '.expand',
			//	navigation:true,
				change: function(){
					if($(this).children('.ui-accordion-content-active').is(':visible'))
					{
					$('html').scrollTo($(this).children('.ui-accordion-content-active').offset().top - 50);
					}
				}
		});

//$("li.expand a").click(function(event){
//		  window.location.hash=this.hash;
//	 });	
	


 $('#searchbtn').append('<div id="ajaxBusy"><img src="/images/loading2.gif"/></div>');


$('#ajaxBusy').css({
display:"none",
margin:"auto",
paddingLeft:"0px",
paddingRight:"0px",
paddingTop:"0px",
paddingBottom:"0px",
right:"3px",
top:"100px",
width:"50px"
});




 $('head').append('<!--[if IE 6]> <link href="css/iestyle.css" rel="stylesheet" type="text/css"> <![endif]-->  ');

window.scrollTo(0,1);


$('.alphaHeader').next('ul').hide();
$('.alphaHeader').click(function(){
	$(this).next('ul').toggle();
});

	$('.backbutton').click(function(){
		//history.go(-1);
		history.back();

		return false;
	});
 
	$('#infoButton').click(function(){
	if ($("#dropMenu").is(':hidden'))
                $("#dropMenu").show();
             else{
                 $("#dropMenu").hide();
            }
             return false;
	});


 $('#dropMenu,#topicTools').click(function(e) {
            e.stopPropagation();
        });

$(document).click(function() {
             $('#dropMenu,#topicTools').hide();
         });

$('.menu_99732').click(function(){
//alert('s');
$('#ddSearch').toggle();
$('#zoom_query').focus();
});

$('.menu_tools').click(function(){
//alert('s');
$('#topicTools').toggle();
});


	$('#sub').click(function(){
	//alert('s');
	$('#subscribe_form').toggle();
	});

	$('#unsub').click(function(){
	//alert('s');
	$('#unsubscribeForm').toggle();
	});


$("a").filter(function() {
    return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');


	$('a[target="_blank"]').click(function(){
		if((envCode=="sa")?confirm('This link will open using Safari.'):confirm('This link opens in a new window.'))
		{
			return true;
		}
		else
		{
			$(this).removeClass('active');
			return false;
		}
	});

	$('.updBtn_Bar div').hover(function(){
			$(this).addClass('updBtn_Highlight');
		},function(){
			$(this).removeClass('updBtn_Highlight');
	});

	//$('#zoom_query').focus();
	/* Search functions */
	if(window.location.search.indexOf('zoom_query')>0){ //If there is a zoom_query parameter in URL, let's assume we need to perform a search
		$("#searchbtn").insertAfter(".titleBar"); // Move the search box into the search results section
		$("#home").hide(); // Hide regular homepage content
		$("#resultsbox").show(); // Show search results
		$("#zoom_query").val(decodeURIComponent($.getUrlVar('zoom_query').replace(/\+/g," ").replace(/\%2B/g," "))); // Populate search field with search term
		$(".result_title:has(a[href*='pdf'])").addClass('zalgorithm'); // Add class only for algorithms in the search results
		document.title = 'Search Results';
		if(envCode != "prev" && envCode != "sa"){ //Check to see if the page is in preview or stand-alone mode and perform AJAX call to get results for live view
			var url = '/zsearch/php/search.php' + window.location.search;
			$.ajax({
				type: "GET",
				url: url,
				cache: false,
				success: function(html){
					$("#zresults").html(html);
					$(".result_title:has(a[href*='pdf'])").removeClass('result_title').addClass('zalgorithm'); // Add class only for algorithms in the search results
					configPDFs();//setup pdf links to use in page display technique
				},
				error: function(xhr,err){
					alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
					alert("responseText: "+xhr.responseText);
				}
			});
		}
	}
	$('#zsearch').submit(function(e){ // On form submit let's prevent the default and add search params to existing query string
		if(envCode == "prev"){ //Check to see if the page is in preview mode in the CMS
			e.preventDefault();
			var s = window.location.search.split('zoom_query');
			window.location.search = s[0]+"&"+$("#zsearch").serialize();
			return false;
		}
		else if($('#zoom_query').val()=='Search'||$('#zoom_query').val()==''){ //Prevent unintentional searches
			e.preventDefault();
			return false;
		}
		else {
			return true;
		}
	});
	if(window.location.search.indexOf('topvisits')>0){ //If there is a topvisits parameter in URL, let's assume we need to show visits
		$("#resultsbox .toolbar").prependTo("#freqtopics"); // Move toolbar from search div to this div
		$("#home").hide(); // Hide regular homepage content
		$("#freqtopics").show(); // Show search results
		document.title = 'Top Topics';
		var url = '../topicsVisited.plist';
		$.ajax({
			type: "GET",
			url: url,
			dataType: "xml",
			cache: false,
			success: function(xml){
				function visitedTopic (visits,title,url) {
					this.visits = visits;
					this.title = title;
					this.url = url;
				}
				function setVisitedTopic(visits,title,url) {
					visitedTopicsArray[z++] = new visitedTopic(visits,title,url);
				}
				var z = 0;
				var visitedTopicsArray = new Array();
				
				var x=xml.getElementsByTagName("key");
				for (i=0;i<x.length;i++) {
					y=x[i].nextSibling;
					while (y.nodeType!=1) {
					  y=y.nextSibling;
					}
					var topicPathTitle = x[i].childNodes[0].nodeValue.split("|");
					var topicTitle = topicPathTitle[1];
					var topicURL = topicPathTitle[0];
					var topicVisits = y.childNodes[0].nodeValue;
					//alert(topicTitle);
					//topicTitle = topicTitle[0].replace(/([A-Z])/g, " $1");
					setVisitedTopic(topicVisits,topicTitle,topicURL);
				}
				function compareVisits(a,b){
					return b.visits - a.visits;
				}
				visitedTopicsArray = visitedTopicsArray.sort(compareVisits);
				if(visitedTopicsArray.length>0) {
					for (t=0;t<25;t++) { 
						$('<div class="gr_arrow"><span class="linkText"><a href="'+visitedTopicsArray[t].url+'">'+visitedTopicsArray[t].title+'</a></span></div>').appendTo("#freqtopicslist");
					}
				} else {
					$('<p>You have not yet visited any topics. The topics that you visit will be collected here and displayed in order of those most visited.</p>').appendTo("#freqtopicslist");
				}
			},
			error: function(xhr,err){
				alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
				alert("responseText: "+xhr.responseText);
			}
		});
	}
//initMenu();
initTables();
//currFontSize();


var target = $('input[type=text]'), val = target.val();
function monitor()
{
    var current_val = $(this).val();
    if (current_val != val) {
       // console.log('changed from', val, 'to', current_val);
        //val = current_val;
		//$('.searchContainer').css('width','90%');
		$('.resetsearchForm').show();
    }
	else{
		//$('.searchContainer').css('width','80%');
	$('.resetsearchForm').hide();
	
	}

}

target.keypress(monitor);
target.blur(monitor);


$('.resetsearchForm').click(function(){
   $('.searchField').val('');
});

var doReloadOnNavigate = false; //used by expanding items and uniqueTables

$(window).hashchange(function(){
	//alert('s');

	if(doReloadOnNavigate) {
		window.location.reload();//refresh content on page
	}
	 if(location.hash){
		

		var hash =  (location.hash)?location.hash.substring(1):	'';
		var checkElement = $('#'+hash);
		 $('li.active').removeClass('active').addClass('expand');

		if((checkElement.is('#algo,div.topic,div[id*=alpha]')) && (checkElement.is(':visible'))) {
		$(checkElement).hide();
		//$(checkElement).prev().removeClass('active').addClass('expand');
        }
      if((checkElement.is('#algo,div.topic,div[id*=alpha]')) && (checkElement.is(':hidden'))) {
        $('#algo,#accordion div.topic:visible, #accordion div[id*=alpha]').hide();
		checkElement.show();
		$(checkElement).prev().removeClass('expand').addClass('active');		
		// $.scrollTo(checkElement.prev())
        }	

		
	 }
	 else{
	//$('#accordion div.topic').hide();
	 $('li.active').removeClass('active').addClass('expand');
	 }

	
})
//$(window).trigger( 'hashchange' );

//***************************************************************
//* Code for expanding item (in same page) content
//***************************************************************
$xtbl = $('div.expandingItem').children('span').children('a');
$xtbl.parent().next().hide();
$xtbl.click(function(){
	return displayContent($(this).parent().next());
});

function initTables() {
	var $tbl = $('.uniqueTable').not($('.expandingItem>div>table'));
	$tbl.hide();
	$tbl.after('<a class="showTable" href="#"><img border="0" alt="Opens in new Window" title="Opens in new Window" src="images/b_plus.png"/>View Table</a>');
	$(".showTable").click(function() {
		return displayContent($(this).prev());
	});   
}

configPDFs();

//***************************************************************
//* END Code for expanding item (in same page) content
//***************************************************************

var crntFnt = $.cookie('userFontSize');
$('.topic').css('font-size', crntFnt);

});

//end jquery onload stuff
//stuff below does NOT run automatically unless called above
function configPDFs() { //for expanding items in page, and pdfs in page
	$(".algorithm a, .zalgorithm a").click(function(){
		return displayContent("<iframe style='height: 840px; width: 100%;' id='docView' src='" + this.href + "'></iframe>");
	});
}

function displayContent(content){ //for expanding items in page, and pdfs in page
	doReloadOnNavigate = true;//reload page if back button is used, to restore original content
	var header = '<div class="toolbar"><a href="index.html"><img style="border:none" src="images/mobilogo2.png"/></a>';
	header += '<a class="backbutton" href="javascript:window.location.reload();">Back</a></div><div style="height:100%; width: 100%;" id="docContents">';
	var footer = '</div>';
	$('meta[name=viewport]').attr('content','initial-scale = 1.0, user-scalable = yes, minimum-scale = .25, maximum-scale = 4.0, height=840, width=840');
	$('body').html(header + footer);//replace body contents with new stuff
	$('#docContents').append(content);
	$('#docContents').children().show();//ensure child tables are not hidden
	$.scrollTo(0);//scroll to top
	//$('#docView').load(function(){$('#docView').width('auto');});//after PDF document loads, set the width & height, forcing a redraw.
	return false; //prevent link from navigating
}


function selectUpd(obj)
{
	for (var x = 1; x <= 3; x++)
	{
		$("#browseTab"+x).attr('class', 'updBtn');
		$("#updContent"+x).hide();
	}
	//
	$(obj).attr('class','updBtn_Selected');
	var tmp = obj.id;
	var num = tmp.substr(tmp.length-1);
    location.hash = tmp;
	var hash = window.location.hash.substr(1);
	$("#updContent"+num).show();
	var t = $(obj).text();
	$('.titleBar').text(t);
}

function toggle(obj,id,cls)
{
		$('#'+id).toggle( );
		$(obj).toggleClass(cls);
		return false;
}


function initMenu() {
 // $('#accordion div.topic').hide();
 // $('#menu ul:first').show(); 
	$('#accordion li.expand a').click(
		 function() {
			var browserString = navigator.userAgent||navigator.vendor||window.opera;
			  //var checkElement = (/windows ce; (iemobile|ppc)/i.test(browserString))?$(this).next('div'):$(this).parent().next();
			  ua   = navigator.userAgent.toLowerCase();
			  ie  = (ua.indexOf("msie") && document.all && ua.indexOf("netscape") == -1);
			  var checkElement = (ie||/windows ce; (iemobile|ppc)/i.test(browserString))?$(this).next('div'):$(this).parent().next();
			  $('li.active').removeClass('active').addClass('expand');

					   if((checkElement.is('#algo,div.topic,div[id*=alpha]')) && (checkElement.is(':visible'))) {
						$(checkElement).hide();
						
						return false;
						}
						  if((checkElement.is('#algo,div.topic,div[id*=alpha]')) && (!checkElement.is(':visible'))) {
							$('#algo,#accordion div.topic:visible, #accordion div[id*=alpha]').hide();
							checkElement.show();
							var ltr =  (ie||/windows ce; (iemobile|ppc)/i.test(browserString))?$(this).next('div').attr('id'):$(this).parent().next().attr('id');
							//alert(ltr);		
						location.hash = ltr;
						$(this).parent().removeClass('expand').addClass('active');		
						   //var elementClicked = $(this).attr("href");
							//var destination = $(checkElement).offset().top-50;
							//console.log(destination);
							//window.scrollTo(0, destination);
							//$(this).parent().addClass('fixed');
							//$.scrollTo(destination);
							//Gentle_Anchors.Setup('$(checkElement).prev()');
							//console.log (x);
							return false;		
						}	
      }
    );
  }


function changeFontSize(s){
   
   var domain = document.domain;
	var c = $('.topic');

	if(s == 'normal'){
    c.css('font-size','1.0em');
	$.cookie('userFontSize', '1.0em', { expires: 365, path: '/', domain: domain });
	}
		if(s == 'medium'){
    c.css('font-size','1.2em');
	$.cookie('userFontSize', '1.2em', { expires: 365, path: '/', domain: domain });
	}
		if(s == 'large'){
    c.css('font-size','1.4em');
	$.cookie('userFontSize', '1.4em', { expires: 365, path: '/', domain: domain });
	}

}

//***************************************************************
//* Search autocomplete functionality
//***************************************************************
if(ac_source) {
	$(document).ready(function () {
		$(".searchField").autocomplete({
			source: ac_source,
			delay:500,
			minLength:2,
			open:function(){
				$("html").scrollTo($(".searchField").offset().top - $("body").children().first().offset().top);
			},
			select:function(){
				setTimeout(function(){
					$("#zsearch").submit()
				},50);
			}
		});
	});
}
//***************************************************************
//* End search autocomplete functionality
//***************************************************************

function scrollAccordion(e){
//console.log($(e).children('.ui-state-active'));
//console.log($(e).children('.ui-accordion-content-active').offset().top);
	$(window).scrollTo($(e).children('.ui-accordion-content-active').offset().top - 50);
	//console.log($(e).children('.ui-accordion-content-active').offset().top -50);
}
