/****************************************************************************************


This software is the confidential and proprietary information of EES. ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with EES.

DOC			Site Scripts
VERSION 	1.0
AUTHOR		Eric Gmutza

DATE       	NAME           	DESCRIPTON
05/28/2010 	Eric Gmutza 	Initial creation.

****************************************************************************************/


/* =EXTEND JQUERY / JQUERY PLUGINS
---------------------------------------------------------------------------------------*/

	
	$.fn.unwrap = function() {
	  this.parent(':not(body)')
	    .each(function(){
	      $(this).replaceWith( this.childNodes );
	    });
	
	  return this;
	};

/*!
// Infinite Scroll jQuery plugin
// copyright Paul Irish, licensed GPL & MIT
// version 1.5.100504

// home and docs: http://www.infinite-scroll.com
*/
 
;(function($){
    
  $.fn.infinitescroll = function(options,callback){
    
    // console log wrapper.
    function debug(){
      if (opts.debug) { window.console && console.log.call(console,arguments)}
    }
    
    // grab each selector option and see if any fail.
    function areSelectorsValid(opts){
      for (var key in opts){
        if (key.indexOf && key.indexOf('Selector') > -1 && $(opts[key]).length === 0){
            debug('Your ' + key + ' found no elements.');    
            return false;
        } 
        return true;
      }
    }


    // find the number to increment in the path.
    function determinePath(path){
      
      path.match(relurl) ? path.match(relurl)[2] : path; 

      // there is a 2 in the url surrounded by slashes, e.g. /page/2/
      if ( path.match(/^(.*?)\b2\b(.*?$)/) ){  
          path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1);
      } else 
        // if there is any 2 in the url at all.
        if (path.match(/^(.*?)2(.*?$)/)){
          
          // page= is used in django:
          //   http://www.infinite-scroll.com/changelog/comment-page-1/#comment-127
          if ( path.match(/^(.*?page=)2(\/.*|$)/) ){
            path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1);
            return path;
          }
          
          debug('Trying backup next selector parse technique. Treacherous waters here, matey.');
          path = path.match(/^(.*?)2(.*?$)/).slice(1);
      } else {
          
        // page= is used in drupal too but second page is page=1 not page=2:
        // thx Jerod Fritz, vladikoff
        if (path.match(/^(.*?page=)1(\/.*|$)/)) {
          path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1);
          return path;
        }  

        debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.');    
        props.isInvalidPage = true;  //prevent it from running on this page.
      }
      
      return path;
    }


    // 'document' means the full document usually, but sometimes the content of the overflow'd div in local mode
    function getDocumentHeight(){
      // weird doubletouch of scrollheight because http://soulpass.com/2006/07/24/ie-and-scrollheight/
      return opts.localMode ? ($(props.container)[0].scrollHeight && $(props.container)[0].scrollHeight) 
                                // needs to be document's height. (not props.container's) html's height is wrong in IE.
                                : $(document).height()
    }
    
    
        
    function isNearBottom(){
      
      // distance remaining in the scroll
      // computed as: document height - distance already scroll - viewport height - buffer
      var pixelsFromWindowBottomToBottom = 0 +
                getDocumentHeight()  - (
                    opts.localMode ? $(props.container).scrollTop() : 
                    // have to do this bs because safari doesnt report a scrollTop on the html element
                    ($(props.container).scrollTop() || $(props.container.ownerDocument.body).scrollTop())
                    ) - $(opts.localMode ? props.container : window).height();
      
      debug('math:',pixelsFromWindowBottomToBottom, props.pixelsFromNavToBottom);
      
      // if distance remaining in the scroll (including buffer) is less than the orignal nav to bottom....
      return (pixelsFromWindowBottomToBottom  - opts.bufferPx < props.pixelsFromNavToBottom);    
    }    
    
    function showDoneMsg(){
      props.loadingMsg
        .find('img').hide()
        .parent()
          .find('div').html(opts.donetext).animate({opacity: 1},2000).fadeOut('normal');
      
      // user provided callback when done    
      opts.errorCallback();
    }
    
    function infscrSetup(){
    
        if (props.isDuringAjax || props.isInvalidPage || props.isDone) return; 
        
        if ( !isNearBottom(opts,props) ) return; 
        
        $(document).trigger('retrieve.infscr');
                
                
    }  // end of infscrSetup()
          
  
      
    function kickOffAjax(){
        
        // we dont want to fire the ajax multiple times
        props.isDuringAjax = true; 
        
        // show the loading message and hide the previous/next links
        props.loadingMsg.appendTo( opts.contentSelector ).show();
        $( opts.navSelector ).hide(); 
        
        // increment the URL bit. e.g. /page/3/
        props.currPage++;
        
        debug('heading into ajax',path);
        
        // if we're dealing with a table we can't use DIVs
        box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>');  
        frag = document.createDocumentFragment();


        box.load( path.join( props.currPage ) + ' ' + opts.itemSelector,null,loadCallback); 
        
    }
    
    function loadCallback(){
        // if we've hit the last page...
        if (props.isDone){ 
            showDoneMsg();
            return false;    
              
        } else {
          
            var children = box.children().get();
            
            // if it didn't return anything
            if (children.length == 0){
              // fake an ajaxError so we can quit.
              return $.event.trigger( "ajaxError", [{status:404}] ); 
            } 
            
            // use a documentFragment because it works when content is going into a table or UL
            while (box[0].firstChild){
              frag.appendChild(  box[0].firstChild );
            }

           	$(opts.contentSelector)[0].appendChild(frag);
            
            // fadeout currently makes the <em>'d text ugly in IE6
            props.loadingMsg.fadeOut('normal' ); 

            // smooth scroll to ease in the new content
            if (opts.animate){ 
                var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px';
                $('html,body').animate({scrollTop: scrollTo}, 800,function(){ props.isDuringAjax = false; }); 
            }
        
            // previously, we would pass in the new DOM element as context for the callback
            // however we're now using a documentfragment, which doesnt havent parents or children,
            // so the context is the contentContainer guy, and we pass in an array
            //   of the elements collected as the first argument.
            callback.call( $(opts.contentSelector)[0], children );
        
            if (!opts.animate) props.isDuringAjax = false; // once the call is done, we can allow it again.
        }
    }
    
      
    // lets get started.
    $.browser.ie6 = $.browser.msie && $.browser.version < 7;
    
    var opts    = $.extend({}, $.infinitescroll.defaults, options),
        props   = $.infinitescroll, // shorthand
        box, frag;
        
    callback    = callback || function(){};
    
    if (!areSelectorsValid(opts)){ return false;  }
    
     // we doing this on an overflow:auto div?
    props.container   =  opts.localMode ? this : document.documentElement;
                          
    // contentSelector we'll use for our .load()
    opts.contentSelector = opts.contentSelector || this; 
    
    
    // get the relative URL - everything past the domain name.
    var relurl        = /(.*?\/\/).*?(\/.*)/,
        path          = $(opts.nextSelector).attr('href');
    
    
    if (!path) { debug('Navigation selector not found'); return; }
    
    // set the path to be a relative URL from root.
    path          = determinePath(path);
    

    // reset scrollTop in case of page refresh:
    if (opts.localMode) $(props.container)[0].scrollTop = 0;

    // distance from nav links to bottom
    // computed as: height of the document + top offset of container - top offset of nav link
    props.pixelsFromNavToBottom =  getDocumentHeight()  +
                                     (props.container == document.documentElement ? 0 : $(props.container).offset().top )- 
                                     $(opts.navSelector).offset().top;
    
    // define loading msg
    props.loadingMsg = $('<div id="infscr-loading" style="text-align: center;"><img alt="Loading..." src="'+
                                  opts.loadingImg+'" /><div>'+opts.loadingText+'</div></div>');    
     // preload the image
    (new Image()).src    = opts.loadingImg;
              

  
    // set up our bindings
    $(document).ajaxError(function(e,xhr,opt){
      debug('Page not found. Self-destructing...');    
      
      // die if we're out of pages.
      if (xhr.status == 404){ 
        showDoneMsg();
        props.isDone = true; 
        $(opts.localMode ? this : window).unbind('scroll.infscr');
      } 
    });
    
    // bind scroll handler to element (if its a local scroll) or window  
    $(opts.localMode ? this : window)
      .bind('scroll.infscr', infscrSetup)
      .trigger('scroll.infscr'); // trigger the event, in case it's a short page
    
    $(document).bind('retrieve.infscr',kickOffAjax);
    
    return this;
  
  }  // end of $.fn.infinitescroll()
  

  
  // options and read-only properties object
  
  $.infinitescroll = {     
        defaults      : {
                          debug           : false,
                          preload         : false,
                          nextSelector    : "div.navigation a:first",
                          loadingImg      : "http://www.infinite-scroll.com/loading.gif",
                          loadingText     : "<em>Loading the next set of posts...</em>",
                          donetext        : "<em>Congratulations, you've reached the end of the internet.</em>",
                          navSelector     : "div.navigation",
                          contentSelector : null,           // not really a selector. :) it's whatever the method was called on..
                          extraScrollPx   : 150,
                          itemSelector    : "div.post",
                          animate         : false,
                          localMode      : false,
                          bufferPx        : 40,
                          errorCallback   : function(){}
                        }, 
        loadingImg    : undefined,
        loadingMsg    : undefined,
        container     : undefined,
        currPage      : 1,
        currDOMChunk  : null,  // defined in setup()'s load()
        isDuringAjax  : false,
        isInvalidPage : false,
        isDone        : false  // for when it goes all the way through the archive.
  };
  


})(jQuery);
	
/*
 *	TypeWatch 2.0 - Original by Denny Ferrassoli / Refactored by Charles Christolini
 *
 *	Examples/Docs: www.dennydotnet.com
 *	
 *  Copyright(c) 2007 Denny Ferrassoli - DennyDotNet.com
 *  Coprright(c) 2008 Charles Christolini - BinaryPie.com
 *  
 *  Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
*/


	$.fn.typeWatch = function(o){
		// Options
		var options = jQuery.extend({
			wait : 350,
			callback : function() { },
			highlight : true,
			captureEnter : true,
			minTextLength : 2
		}, o);
			
		function checkElement(timer, override) {
			var elTxt = jQuery(timer.el).val();
		
			// Fire if text > options.minTextLength AND text != saved txt OR if override AND text > options.minTextLength
			if ((elTxt.length > options.minTextLength && elTxt.toUpperCase() != timer.text) 
			|| (override && elTxt.length > options.minTextLength)) {
				timer.text = elTxt.toUpperCase();
				timer.cb(elTxt);
			}
		};
		
		function watchElement(elem) {			
			// Must be text or textarea
			if (elem.type.toUpperCase() == "TEXT" || elem.nodeName.toUpperCase() == "TEXTAREA") {

				// Allocate timer element
				var timer = {
					timer : null, 
					text : jQuery(elem).val().toUpperCase(),
					cb : options.callback, 
					el : elem, 
					wait : options.wait
				};

				// Set focus action (highlight)
				if (options.highlight) {
					jQuery(elem).focus(
						function() {
							this.select();
						});
				}

				// Key watcher / clear and reset the timer
				var startWatch = function(evt) {
					var timerWait = timer.wait;
					var overrideBool = false;
					
					if (evt.keyCode == 13 && this.type.toUpperCase() == "TEXT") {
						timerWait = 1;
						overrideBool = true;
					}
					
					var timerCallbackFx = function()
					{
						checkElement(timer, overrideBool)
					}
					
					// Clear timer					
					clearTimeout(timer.timer);
					timer.timer = setTimeout(timerCallbackFx, timerWait);				
										
				};
				
				jQuery(elem).keydown(startWatch);
			}
		};
		
		// Watch Each Element
		return this.each(function(index){
			watchElement(this);
		});
		
	};


	

/**/

/* =DOM MANIPULATION
---------------------------------------------------------------------------------------*/

	
	function firstLastListItems(){
		$('ul li:first-child').addClass( 'first_item' );
		$('ul li:last-child').addClass( 'last_item' );
		$('table tbody tr:first-child').addClass( 'first_row' );
		$('table tbody tr:last-child').addClass( 'last_row' );
		$('table tbody tr td:first-child').addClass( 'first_cell' );
		$('table thead tr th:first-child').addClass( 'first_cell' );
		$('table tbody tr td:last-child').addClass( 'last_cell' );
		$('table thead tr th:last-child').addClass( 'last_cell' );
	}
	
	function resizeThumbs(){
		//$(".listingResultsWrap img.prodThmb").scale("stretch"); 
	}

	
	function searchTabs(){
		fieldValue="";
		searchField = $('.mainSearchField');

		$(searchField).focus(function() {
		    if ($('.mainSearchField').val() == "") {
		        if (!$(searchField).hasClass('textEntered')) {
		            $(this).val(fieldValue);
		        }
		    }
		    else {
		        //alert($('.mainSearchField').val());
		        if ($('.mainSearchField').val() == "The most powerful job search on the internet!") {
		            if (!$(searchField).hasClass('textEntered')) {
		                $(this).val(fieldValue);
		            }
		        }
		        else {
		            if ($('.mainSearchField').val() == "Looking for the perfect candidate?") {
		                if (!$(searchField).hasClass('textEntered')) {
		                    $(this).val(fieldValue);
		                }
		            } else {
		                if ($('.mainSearchField').val() == "Your dream home awaits!") {
		                    if (!$(searchField).hasClass('textEntered')) {
		                        $(this).val(fieldValue);
		                    }
		                }
		                else {
		                    if ($('.mainSearchField').val() == "Search for the best car deals on the web!") {
		                        if (!$(searchField).hasClass('textEntered')) {
		                            $(this).val(fieldValue);
		                        }
		                    }
		                    else {
		                        if ($('.mainSearchField').val() == "Perform a general search - works for anything!") {
		                            if (!$(searchField).hasClass('textEntered')) {
		                                $(this).val(fieldValue);
		                            }
		                        }
		                    }
		                }
		            } 
		        } 
		    }


		});
		
		$(searchField).typeWatch( { highlight:true, callback:finished } );

		function finished(txt) {
			$(searchField).addClass("textEntered");
		}
		/*
		if (!$('.homeDescriptor').length){
			$('.searchBanner').attr('id','noDesc');
		}*/
		
		$('.searchTabs ul li.activeTab').removeClass('activeTab');
		$('.searchTabs ul li input:checked').closest('li').addClass('activeTab');
		$('div.searchTabs li').each(function() {
		    $('.fieldBlock').hide();
		    tabIndex = $('.searchTabs ul li.activeTab').index() + 1;
		    $('.set' + tabIndex).fadeIn(300);
		    $(this).bind("mouseover", function() {
		        $(searchField).blur();
		        if ($('.mainSearchField').val() == "") {
		            if (!$('.mainSearchField').hasClass('textEntered')) {
		                $('.mainSearchField').val($(this).find('input').attr('title'));
		            }
		        }
		        else {
		            //alert($('.mainSearchField').val());
		            if ($('.mainSearchField').val() == "The most powerful job search on the internet!") {
		                if (!$('.mainSearchField').hasClass('textEntered')) {
		                    $('.mainSearchField').val($(this).find('input').attr('title'));
		                }
		            }
		            else {
		                if ($('.mainSearchField').val() == "Looking for the perfect candidate?") {
		                    if (!$('.mainSearchField').hasClass('textEntered')) {
		                        $('.mainSearchField').val($(this).find('input').attr('title'));
		                    }
		                } else {
		                    if ($('.mainSearchField').val() == "Your dream home awaits!") {
		                        if (!$('.mainSearchField').hasClass('textEntered')) {
		                            $('.mainSearchField').val($(this).find('input').attr('title'));
		                        }
		                    }
		                    else {
		                        if ($('.mainSearchField').val() == "Search for the best car deals on the web!") {
		                            if (!$('.mainSearchField').hasClass('textEntered')) {
		                                $('.mainSearchField').val($(this).find('input').attr('title'));
		                            }
		                        }
		                        else {
		                            if ($('.mainSearchField').val() == "Perform a general search - works for anything!") {
		                                if (!$('.mainSearchField').hasClass('textEntered')) {
		                                    $('.mainSearchField').val($(this).find('input').attr('title'));
		                                }
		                            }
		                        }
		                    }
		                }

		            }

		        }

		    });
		    $(this).bind("click", function() {
		        tabIndex = $('.searchTabs ul li').index($(this)) + 1;
		        $(this).addClass('activeTab');
		        $(this).find('input').attr('checked', true);
		        if ($('.mainSearchField').val() == "") {
		            if (!$(searchField).hasClass('textEntered')) {
		                $('.mainSearchField').val($(this).find('input').attr('title'));
		            }
		        }
		        else {
		            //alert($('.mainSearchField').val());
		            if ($('.mainSearchField').val() == "The most powerful job search on the internet!") {
		                if (!$(searchField).hasClass('textEntered')) {
		                    $('.mainSearchField').val($(this).find('input').attr('title'));
		                }
		            }
		            else {
		                if ($('.mainSearchField').val() == "Looking for the perfect candidate?") {
		                    if (!$(searchField).hasClass('textEntered')) {
		                        $('.mainSearchField').val($(this).find('input').attr('title'));
		                    }
		                } else {
		                    if ($('.mainSearchField').val() == "Your dream home awaits!") {
		                        if (!$(searchField).hasClass('textEntered')) {
		                            $('.mainSearchField').val($(this).find('input').attr('title'));
		                        }
		                    }
		                    else {
		                        if ($('.mainSearchField').val() == "Search for the best car deals on the web!") {
		                            if (!$(searchField).hasClass('textEntered')) {
		                                $('.mainSearchField').val($(this).find('input').attr('title'));
		                            }
		                        }
		                        else {
		                            if ($('.mainSearchField').val() == "Perform a general search - works for anything!") {
		                                if (!$(searchField).hasClass('textEntered')) {
		                                    $('.mainSearchField').val($(this).find('input').attr('title'));
		                                }
		                            }
		                        }
		                    }
		                }

		            }

		        }
		        $(this).find('input').blur();
		        $(this).siblings().removeClass('activeTab');
		        $('.fieldBlock').not('.set' + tabIndex).hide();
		        $('.set' + tabIndex).fadeIn(300);
		    });
		});
	}
	
	 function tabs(){
	 	$(".tabs").tabs();
	 }

/* =CALL EVENTS
---------------------------------------------------------------------------------------*/
	 $(document).ready(function() {
	     //Functions to Execute

	     //DOM MANIPULATION
	     firstLastListItems();
	     searchTabs();
	     //
	     //

	     $('.listingResultsWrap').infinitescroll({
	         debug: false,
	         nextSelector: "div.pagination:last .nextPage a",
	         loadingImg: "../images/interface/ajax-loader.gif",
	         text: "Loading more results...",
	         donetext: "<em>End of results.</em>",
	         navSelector: "div.pagination:last", debug: true,
	         itemSelector: ".resultItem"
	     });


	 });
