// begin when document has completed loading
$(document).ready(function(){
        
    // first, fill out forms on page to match their current search
    populateSearchForms();

    // bind onchange event to category drop down
    $("#categoryselect").bind("change", function(){

        

        // fade form2 div to 0 opacity
        $("#form2").animate({opacity: "toggle"},"fast", function(){
            
            // display loading gif
            $("#loading").css("display","block");
            
            // when it's done submit form
            $('#form1').ajaxSubmit(function(data) {
    
                // when it is done, fill div with reponse
                $("#form2").html(data);
                
                // hide loading gif
                $("#loading").css({ display: "none" });
                
                // then fade in to 100% opactity
                $("#form2").animate({opacity: "toggle"}, "fast", function(){
                    if (document.getElementById('pagelength'))
                    {
                        var qplg = getQueryVariable('pagelength');
                        var plg = document.forms.subform.elements['pagelength'];
                        plg.selectedIndex = getOptionIndex(plg,qplg);
                    }

                });
            });
        });      
    });
    
    // bind onchange event to page drop down
    $("#page").bind("change", function(){
            document.forms.pagecount.submit();

    });

    // move record to "notebook" effect 
    $("a.saverecord").bind("click", function(){
        $(this).parent(".resultmenu").parent(".searchresult").TransferTo({to:'notebook',className:'transfer', duration: 600, easing: 'in'});
    });
    
    /*
     * width-dependant layout script
     * http://www.colly.com/?/comments/redesign-notes-1-width-based-layout/
     * Simon Collison / Colly Logic
     */ 
    wraphandler = {
          init: function() {
            if (!document.getElementById) return;
            // set up the appropriate wrapper
            wraphandler.setWrapper();
            // and make sure it gets set up again if you resize the window
            wraphandler.addEvent(window,"resize",wraphandler.setWrapper);
          },
        
          setWrapper: function() {
            // width stuff from ppk's evolt.org/article/document_body_doctype_switching_and_more/17/30655/index.html
            var theWidth = 0;
            if (window.innerWidth) {
        	theWidth = window.innerWidth
            } else if (document.documentElement &&
                        document.documentElement.clientWidth) {
        	theWidth = document.documentElement.clientWidth
            } else if (document.body) {
        	theWidth = document.body.clientWidth
            }
            
            /*
             * This piece changes the layout to fit smaller screens
             * commented out at Matt's request
            
            
            if (theWidth != 0) {
              if (theWidth <= 1000) {
                document.getElementById('leaderboard').className = 'narrowleaderboard';
                document.getElementById('h1').className = 'narrowh1';
              } else {
                document.getElementById('leaderboard').className = 'wideleaderboard';
                document.getElementById('h1').className = 'wideh1';
              }
            }
            */
            
            
            
            // added by Chris Wible to handle resizing of footer elements
            var adheight = $("#placead").css("height");
            var pubheight = $("#publications").css("height");
            if (adheight > pubheight)
            {
                $("#publications").height(adheight);
            }else{
                $("#placead").height(pubheight);
            }
          },
        
        // addEvent stuff from John Resig's ejohn.org/projects/flexible-javascript-events
          addEvent: function( obj, type, fn ) {
            if ( obj.attachEvent ) {
              obj['e'+type+fn] = fn;
              obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
              obj.attachEvent( 'on'+type, obj[type+fn] );
            } else {
              obj.addEventListener( type, fn, false );
            }
          }
        }
        
        wraphandler.addEvent(window,"load",wraphandler.init); // end width-dependant layout script
        
    // be nice to IE (attach class to Jim's dropdown menu on the red bar
    $("#topnav > ul > li, #topnav > ul > li > ul > li").hover(function(){
        $(this).addClass("sfHover");
        },function(){
        $(this).removeClass("sfHover");
    });
    
    // activate slideshow if there are display results
    if (document.getElementById('displayresults'))
    {
        showImage(0); 
    }
    // call print ad rotator as wel no longer search print ads (01.02.2008)
    rotatePrAds();
}); // end on doc load

// begin other functions

    function showImage(show)
    {
        $("#displayresults > a > img").hide();
        curr = parseInt(document.getElementById('currentimage').innerHTML)-1;
        total = $("#displayresults > a > img").length-1;
        if (show == "prev")
        {
            clearTimeout(timer);
            show = curr-1;
        }
        if (show == "next")
        {
            clearTimeout(timer);
            show = curr+1;
        }
        if (show > total) {show = 0}
        if (show < 0){show = total}
        $("#displayresults > a > img").each(function(i){
          if (i == show)
          {
              $(this).show();
              document.getElementById('currentimage').innerHTML = i+1;
          }
        });
        timer = setTimeout("showImage('next')",15000)
    }
function populateSearchForms()
{
/* 
 * Tests for existence of form fields and if form fields exist
 * retrieves values from get parameters and populates form
 */
    if (document.forms.subform.elements['keyword'])
    {
        var qkey = getQueryVariable('keyword');
        var key = document.forms.subform.elements['keyword'];
		  if (!qkey){qkey=''};
        key.value = qkey;
    }
    
    if (document.forms.subform.elements['categories'])
    {
        var qcat = getQueryVariable('categories');
        var cat = document.forms.subform.elements['categories'];
        cat.selectedIndex = getOptionIndex(cat,qcat);
    }

    if (document.forms.subform.elements['locale'])
    {
        var loc = document.forms.subform.elements['locale'];
        var qloc = getQueryVariable('locale');
        loc.selectedIndex = getOptionIndex(loc,qloc);
    }

    if (document.forms.subform.elements['pricerng'])
    {
        var qpri = getQueryVariable('pricerng');
        var pri = document.forms.subform.elements['pricerng'];
        pri.selectedIndex = getOptionIndex(pri,qpri);
    }

    if (document.getElementById('pagelength'))
    {
        var qplg = getQueryVariable('pagelength');
        var plg = document.forms.subform.elements['pagelength'];
        plg.selectedIndex = getOptionIndex(plg,qplg);
    }
    
    if (document.getElementById('page'))
    {
        var qpag = getQueryVariable('page');
        var pag = document.forms.pagecount.elements['page'];
        pag.selectedIndex = getOptionIndex(pag,qpag);
    }
}

function getOptionIndex(obj, optionValue) {
	// by default return the current index
	var returnIndex = obj.selectedIndex;
	for (i = 0; i < obj.options.length; i++) {
		if (obj.options[i].value == optionValue) {
			returnIndex = i;
			i = obj.options.length;
		}
	}
	return returnIndex;
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (unescape(pair[0]) == variable) {
      pair[1] = pair[1].replace(/\+/g,' ');
      return unescape(pair[1]);
    }
  } 
  // alert('Query Variable ' + variable + ' not found');
}



// Global variables for keeping track of rotated ads
// adCount - the number of ads that have been displayed
// adCycles - the number of times the script has cycled through all ads
// adUses - an array containing the number of times each ad was used
// maxMisses - the number of times the script will attempt to try picking a random
//   number that has not been choosen already, when that time is reached it
//   will iterate through all ads and pick one that has not been picked in that cycle.
var adCount = 0;
var adCycles = 0;
var adUses = new Array();
var maxMisses = 100;

function rotatePrAds(action) {
  var validIdx = 0;
  var numMisses = 0;
  while (validIdx <= 0) {

   	// choose a random number based on the number of ads.
 		PrAdIndex = Math.floor(Math.random() * (PrAds.length-1)); 	
  	
  	// check to make sure that the ad has not been used in the current cycle
  	if (typeof(adUses[PrAdIndex]) == "undefined") {
  		adUses[PrAdIndex] = 1;
  		validIdx = 1;
  	} else {
  		if (adUses[PrAdIndex] <= adCycles) {
  			// increment the number of uses for this ad
  			adUses[PrAdIndex] = adUses[PrAdIndex] + 1;
  			validIdx = 1;
  		} else {
  			// we were not able to determine a number randomly, so increment the misses
  			// if we hit maxMisses then iterate through adUses and find the next ad that 
  			// has not been used.
  			numMisses = numMisses + 1;
  			if (numMisses > maxMisses) {
  				for (i = 0; i < PrAds.length; i++) {
  					if (typeof(adUses[i]) == "undefined") {
						adUses[i] = 1;
						PrAdIndex = i;
						validIdx = 1;	
						break;
  					} else {
  						if ( adUses[i] <= adCycles) {
							adUses[i] = adUses[i] + 1;
							PrAdIndex = i;
							validIdx = 1;	
							break;
						}
  					}
  				}
  			}
  		}
  	}
  }
  // Increment the ad counter, so that we know when we ran through the cycle.
  adCount = adCount + 1;
  if ((adCount % PrAds.length) == 0) {
  	// we ran through a cycle so increment adCycles
  	adCycles = adCycles + 1;
  }
  
  // this is old code that remains unchanged
  var imagesource = PrAds[PrAdIndex].getSrc();
  if(document.getElementById("primage")) { // iffed by CW 5/10 - only do if primage exists
  	window.document.getElementById("primage").src = imagesource;
  	window.document.getElementById("primageurl").href=PrAds[PrAdIndex].getUrl();
  	window.document.getElementById("primage").style.display = "inline";
  }
// GMb 04/19/07 Commented this out because we do not want the print ads to rotate any more
//PrTimer = setTimeout("rotatePrAds()", 10000);
}


