/**
* ieVersion is set to the return result 
* of and annonymous function that detects
* if browser ie and which version.
* Thus, to detect IE:
*  if (ieVersion) {}
* And to detect the version:
* ieVersion === 6 // IE6
* ieVersion > 7 // IE8, IE9 ...
* ieVersion < 9 // Anything less than IE9
*/
var ieVersion = (function(){
		var undef,
				v = 3,
				div = document.createElement('div'),
				all = div.getElementsByTagName('i');
		while (
			div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
			all[0]
		);

		return v > 4 ? v : undef;
	}());

/**
* Fixes the IE cropping issue when you set a fixed 
* width on select boxes.
*/
function ieSelectWidth(elem){
	if(ieVersion < 9){ //applies this only to IE6,7 and 8
		$(elem).each(function(){
		    /* Use mousedown rather than focus because the focus event gets 
		     * interrupted and the dropdown does not appear 
		     */
		    var width = $(this).width();
		    $(this).data("origWidth", $(this).css("width"))
		    
		    $(this).mousedown(function(){
		        if($(this).css("width") != "auto") {
		            $(this).css({"width": "auto"})
		            $(this).next('input').hide();
		            /* if the width is now less than before then undo */
		            if($(this).width() < width) {
		                $(this).css("width", $(this).data("origWidth"));
		                
		            }
		        }
		    })
		    
		    /* Handle blur if the user does not change the value */
		    $(this).blur(function(){
		        $(this).css("width", $(this).data("origWidth"));
		        $(this).next('input').show();
		
		    })
		    /* Handle change of the user does change the value */
		    $(this).change(function(){
		        $(this).css("width", $(this).data("origWidth"));
				$(this).next('input').show();
		    });
		});
	}
}


jQuery(document).ready(function($) {



	// These are all only for the home page.
	if($("body").hasClass("ap-home")) {

				// Move this line outside if the header is used on pages other than the homepage
				/*
				
				ieSelectWidth("#practice_id");
				ieSelectWidth("#office_id");
                */
				
				// This is simply pasted in verbatim (minus the doc-ready bit, which I've already called) from AP's original site.
				// I've retained the ID attribute "search_last_name," so the task now is to hook it up to AP's backend.
			
					// setup the autocomplete drop-down
					/*
					$("#search_last_name").autocomplete("http://www.arnoldporter.com/extensions/ajax_actions/do_att_search.cfm", 
													  { minChars:2,
														matchSubset:1,
														matchContains:1,
														cacheLength:10,
														onItemSelect:selectItem,
														formatItem:formatItem,
														selectOnly:true,
														selectFirst:false });
					*/
					// now make sure that return will fire the search form
					// $("#search_last_name").bind("keypress",function(e) {
					// 	var code=e.charCode || e.keyCode;
					//	if(code==13) {
					//		$("#att_search_form").submit();
					//	}
					//}
					//);

				
				
				


				// Let's roll up our sleeves...
				$("body").addClass("hasJs");




				// Open certain links in external window
				if($('body a[rel="external"]').length != 0) {
			    	$('a[rel="external"]').click( function() {
			        	window.open( $(this).attr('href') );
			        	return false;
			    	});
				}




				// "Advisories" rotator
				// 1. Give it a preceding card
				if($(".advisories li").length != 0) {
					$(".advisories li:last").prependTo(".advisories ul");
				}
				// 2. Make it do stuff
				$(".advisories span").click(function(){
					if(!$(".advisories").hasClass("locked")) {
						if($(this).hasClass("prev")) {
							$(".advisories ul").clearQueue().addClass("locked").animate({
								left: '+=572'
							}, 500, function() {
								$(".advisories ul").css("left","-572px");
								$(".advisories ul li:last").prependTo(".advisories ul");
								$(".advisories ul").removeClass("locked");
								// Animation complete.
							});
						} else {
							$(".advisories ul").clearQueue().addClass("locked").animate({
								left: '-=572'
							}, 500, function() {
								$(".advisories ul").css("left","-572px");
								$(".advisories ul li:first").appendTo(".advisories ul");
								$(".advisories ul").removeClass("locked");
								// Animation complete.
							});
						}		
					} // end "locked?" check
				});
				
				


				
				// Clearfix the image-laden "Timelies"
				if($(".timely img").length != 0) {
					$(".timely:has(img)").each(function(){
						$(this).addClass("c");
					});
				}


				
				// "Languages" dropdown.
				if($(".languages li li").length != 0) {
					$(".languagesOptions").mouseover(function(){
						$(".languages > ul").addClass("expanded");
					}).mouseout(function(){
						$(".languages > ul").removeClass("expanded");
					});
				}
				



				// Clear text inputs on focus.
				// THIS BIT: Credit: http://threespot.com
			    $("input[type='text']").each(function(){
			        this.orig_value = $(this).val();
			        $(this).focus(function(){ 
			            if ( $(this).val() == this.orig_value) 
			                $(this).val(''); 
			        }).blur(function(){
			            if ( ($(this).val() == this.orig_value) || (!$(this).val().length)) 
			                $(this).val(this.orig_value);
			        });
			    });

			
				// Auto-flip the SUBMIT source image.
				// THIS BIT: Credit: http://threespot.com (...specifically DZ)
				jQuery.fn.rolloverSubmit = function(options){		
				    settings = jQuery.extend( {
				        postfix: "_hover"
				    }, options);
				    $filename = new RegExp("^(.*?)\.(gif|jpg|png)", "i");
				    $filename_hover = new RegExp("^(.*?)" + settings['postfix'] + "\.(gif|jpg|png)", "i");
					return this.each(function() {	
				        jQuery(this).hover(function(){
				            $m = $filename.exec(jQuery(this).attr('src'));
				            jQuery(this).attr('src', $m[1] + settings['postfix'] + "." + $m[2]);
				        }, function(){
				            $m = $filename_hover.exec(jQuery(this).attr('src'));
				            jQuery(this).attr('src', $m[1] + "." + $m[2]);        
				        }); 
					});
				};
				// Single-line instantiation of above:
				$("input[type='image']").rolloverSubmit();
				


				// Global Nav.
				if($(".globalNav").length != 0) {
					$(".globalNav li:has(ul)").each(function(){
						$(this).mouseover(function(){
							$(this).addClass("lit");
							$(this).find("ul").show();
						}).mouseout(function(){
							$(this).removeClass("lit");
							$(this).find("ul").hide();
						});
					});
				}
				
				
				// THIS BIT: Credit: http://threespot.com (...specifically DZ)
				$(".globalNav .about ul,.globalNav .offices ul").each(function(){
			        $lis = $(this).find("li");
			        $inc = parseInt(($lis.length/2) + ($lis.length % 2 > 0 )); //Where N = 4
			        $.map([$inc, $inc*2], function(value) { //Where [$inc*1, $inc*2,...$inc*N]
			            $lis.slice(value-$inc, value).wrapAll("<div class='wrap'></div>");
			        });
			    });
			    $('.globalNav .about ul div.wrap:last-child').addClass('wrap_last');
			    $('.globalNav .offices ul div.wrap:last-child').addClass('wrap_last');





				// Minor ephemeral stylistic tweaking
				if($(".findAttorney .advSearch").length != 0) {
					$(".findAttorney .advSearch a").append("&nbsp;&raquo;");
				}
				if($(".recognition .awards img").length != 0) {
					$(".recognition .awards img:last").addClass("last");
				}
				if($(".header .jumps ul").length != 0) {
					$(".header .jumps ul li:first").addClass("first");
				}
				if($(".articleStubs h3 a").length != 0) {
					$(".articleStubs h3 a").each(function(){
						$(this).append(" &raquo;");
					});
				}
				if($(".globalNav ul li").length != 0) {
					$(".globalNav ul li a").append("&nbsp;&raquo;");
					$(".globalNav ul,.globalNav .wrap").each(function(){
						$(this).find("li:last").addClass("last");
					});
				}
				if($(".billboard .learnMore").length != 0) {
					$(".billboard .learnMore a").each(function(){
						$(this).append("&nbsp;&raquo;");
					});
				}
				if($(".findAttorney .byLetter").length != 0) {
					$(".byLetter li.findAttorneyHACK").each(function(){
						$(this).wrapInner("<span />");
						$(this).mouseover(function(){
							$(this).addClass("lit");
						}).mouseout(function(){
							$(this).removeClass("lit");
						});
					});
					$(".byLetter li.noLink").each(function(){
						$(this).wrapInner("<span style=\"cursor: default;\" />");
					});
				}
				if($(".findAttorney .toggler").length != 0) {
					$(".findAttorney .toggler").click(function(){
						$(".findAttorney").toggleClass("findAttorney-activated");
					});
				}

				



				// Find an Attorney
				if($(".findAttorney").length != 0) {

					// By Letter
					/*$(".findAttorney .byLetter span").each(function(){
						$(this).click(function(){
							var myLetter = $(this).html();
							var rootPath = "http://www.arnoldporter.com/professionals.cfm?action=search&search_letter=";
							window.location.href = rootPath + myLetter;
							$(".byLetter li").removeClass("lit");
						});
					});*/

					// Simple flyout
					// attempt at Hover
					/*$(".findAttorney").mouseover(function(){
						$(".navigator").show();	
						$(".findAttorney").addClass("findAttorney-activated");	
					}).mouseout(function() {
						$(".navigator").hide();	
						$(".findAttorney").removeClass("findAttorney-activated");	
					});*/
					
					// Simple flyout
					$(".findAttorney h2").click(function(){
						if($(".navigator").is(":visible")) {
							$(".navigator").slideUp("fast");
						} else {
							$(".navigator").slideDown("fast");	
						}
					});
					
					
					
					/*
					$(".navigator").mouseover(function(){
							$(".navigator").addClass("findAttorney-activated");	
					});
					
					$(".navigator").mouseout(function(){
							$(".navigator").slideUp("fast");
					});
					*/
					
					/* Link to advanced search page on click */
					/*$(".findAttorney h2").click(function(){
							var advancedPath = "professionals.cfm";
							window.location.href = advancedPath;
   					});*/

				}






				// Billboard!
				if($(".billboard .panelsViewport").length != 0) {
			
					// Define each panel's visual class (based on its contents).
					$(".panelsViewport .panel").each(function(){

						if (($(this).find("img").size() > 0) && ($(this).find(".flag").size() > 0)) {
							$(this).addClass("panelStyle-d");
						}
						if (($(this).find("img").size() == 0) && ($(this).find(".flag").size() > 0)) {
							$(this).addClass("panelStyle-c");
						}
						if (($(this).find("img").size() > 0) && ($(this).find(".flag").size() == 0)) {
							$(this).addClass("panelStyle-b");
						}
						if (($(this).find("img").size() == 0) && ($(this).find(".flag").size() == 0)) {
							$(this).addClass("panelStyle-a");
						}

					});
					
				}
				
				
				// Billboard cycling
				$('.panelsViewport').cycle({ 
				    fx:     'fade', 
				    speed:  750, 
				    timeout: 5000, 
				    pager:  '.panelsPager' 
				});
				$('.panelsPager a').click(function(){
					$('.panelsViewport').cycle('pause');
				});
				

				






	} // end "Home" check

});
