var console_debug = false;
//if((location.host).match(/\.howard/i) && typeof window.loadFirebugConsole != 'undefined' ){
if(typeof window.loadFirebugConsole != 'undefined' ){
    console_debug = true;
}
if (console_debug && !$.browser.msie) {
    if($.browser.mozilla){
        window.loadFirebugConsole();
    }
} else if($.browser.msie) {
    window.console = {};
    window.console.info =
    window.console.log =
    window.console.warn =
    window.console.error = function(){}
} else {
    window.console = {};
    window.console.info =
    window.console.log =
    window.console.warn =
    window.console.error = function(){}
}
// Remove noscript.css immediately
$("link[rel='stylesheet']").each(function(i,e){
    if($(e).attr("href").match(/noscript\.css/)){
        $(e).remove();
    }
});

jQuery.fn.getPath = function () {
    // console.log(this);
    if (this.length != 1) throw 'Requires one element.';

    var path, node = this;
    while (node.length) {
        var realNode = node[0], name = realNode.localName;
        if (!name) break;
        name = name.toLowerCase();

        var parent = node.parent();

        var siblings = parent.children(name);
        if (siblings.length > 1) { 
            name += ':eq(' + siblings.index(realNode) + ')';
        }

        path = name + (path ? '>' + path : '');
        node = parent;
    }

    return path;
};


function isIphone(){
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||
        (navigator.userAgent.match(/iPad/i)) ) {
        return true;
    }
}

function isDroid(){
    if( navigator.userAgent.match(/Android/i)   ) {
        return true;
    }
}
function isBlackberry(){
    if( navigator.userAgent.match(/BlackBerry/i)   ) {
        return true;
    }
}


// init custom select
function initCustomSelect(){
	jQuery('select').selectmenu();
}

// init gallery
function initGallery(){
	var activeClass = 'active';
	var links = jQuery('.switcher li, .number-area a');

    function mycarousel_initCallback(carousel){
        var dashboard = carousel.container.closest(".dashboard");
        var homedash = $(".box",carousel.container);
        homedash.mouseover(function() {
            carousel.stopAuto();
        });
        homedash.mouseleave(function() {
            carousel.startAuto();
        });
        dashboard.mouseover(function() {
            carousel.stopAuto();
        });
        dashboard.mouseleave(function() {
            carousel.startAuto();
        });
        // Disable autoscrolling if the user clicks the prev or next button.
        carousel.buttonNext.bind('click', function() {
                carousel.startAuto(0);
        });

        carousel.buttonPrev.bind('click', function() {
                carousel.startAuto(0);
        });
        mycarousel_initCarouselNav(carousel);
        //console.log(carousel);
        var tabanimator = $(".tab-animator",dashboard);
        if(tabanimator.length > 0){ 
            tabanimator.data("carousel_prev_idx", 1);
            tabanimator.data("carousel_prev_first", 1);

        }
        if(carousel.container.closest(".dashboard").length > 0){
            //* setup tab clicks
            var dashboard = carousel.container.closest(".dashboard");
            var tabanimator = $(".tab-animator",dashboard);
            $(".tabset a", dashboard).each(function(i,e){
                $(e).click(function(){
                    tabanimator.data("carousel_prev_first", i);
                    tabanimator.data("carousel_prev_idx", i);
                       carousel.scroll( i+1);  
                    return false;
                });
            });
        }
    }
    function mycarousel_initCarouselNav(carousel) {
        $(".switcher li").each(function(i,e){
		    $(e).click(function(){
				// alert('clicked ' + i);
                carousel.scroll(i+1);
                return false;
            });
        });
        $(".number-area:not(.number-hover) a:not(.number-text-hover)").each(function(i,e){
            if(!(isIphone() || isDroid())){
	            $(e).mouseover(function(){
	                //console.log("mouse over", e);
	                //* fade in hover
	                //$(e).next(".number-text-hover").stop().css("opacity","1");
	                $(".number-area:not(.number-hover) a.number-text-hover").fadeOut();
	                $(e).next(".number-text-hover").addClass("active").fadeIn(function(){

	                    //$(e).css("visibility","hidden");

	                });
	            });
            }
		    $(e).click(function(){
				// alert('e click i is ' + i);
                carousel.scroll(i+2);
                return false;
            });
        });
        $(".number-area a.number-text-hover").each(function(i,e){
            
            $(e).mouseleave(function(){
				// alert('mouseout.');
                //console.log("mouse out", e);
                //* fade out hover
                    $(".number-area a:not(.number-text-hover)").css("visibility","visible");
                    //$(e).prev(".number-text").css("visibility","visible");
                //$(e).stop().css("opacity","1");
                $(e).fadeOut(function(){
                    $(e).removeClass("active");
                });
            });
		    $(e).click(function(){
				// alert('mmkay ' + i);
                carousel.scroll(i+2);
                return false;
            });
        });
        $(".number-area:not(.number-hover), .banner-btn").click(function(){
			// alert('scroll 1');
            carousel.scroll(1);
            return false;
        });
        /*
        if($(".number-area").length > 0){
            $(".wrapper-holder").click(function(event){
                
                if($(event.currentTarget).hasClass("wrapper-holder") && event.pageY >= 150 && event.pageY <= 450){
                carousel.scroll(1);
                }
            });
        }
        */
    };
    function mycarousel_itemLoadCallback(carousel) {
	    var switchers = jQuery('.switcher li');
	    var numbers = jQuery('.number-area a');
			var ind = carousel.last-1;
            ind %= carousel.container.data("data_length"); 
        if(switchers.length > 0){
            //console.log(info, info.first, ind); 
		    switchers.removeClass(activeClass).eq(ind).addClass(activeClass);
        }
        /*
        else if(numbers.length > 0){
            if(ind == 0) {
                $(".number-area").addClass( "all-active" );
            }
            else{
		        numbers.removeClass(activeClass).eq(ind-1).addClass(activeClass);
                $(".number-area").removeClass( "all-active" );
            }
        }
        */
    }
    function mycarousel_visibleOutBefore(carousel, item, idx, state){
        idx = carousel.first;
        if(idx < 0){
            idx %= carousel.container.data("data_length"); 
            idx = carousel.container.data("data_length")+idx;
        }
        idx %= carousel.container.data("data_length"); 
        if(idx == 0){idx = carousel.container.data("data_length");}
        //* switching highlight state of careers slideshow faster
	    var numbers = jQuery('.number-area a:not(.number-text-hover)');
	    var numbers_hover = jQuery('.number-area a.number-text-hover');
        //console.log(numbers, numbers_hover);
    
        if(numbers.length > 0){
            if(idx == 1) {
                //* we fade all the images that are black to white
                $(".number-area").addClass( "all-active" );
                var other_numbers = numbers_hover.not(".active");
                //console.log("all 7 days", other_numbers);
                other_numbers.show();
                    numbers.removeClass(activeClass);
                other_numbers.addClass(activeClass).fadeOut(function(){
                    other_numbers.removeClass(activeClass);
                    numbers_hover.removeClass(activeClass);
                    numbers_hover.hide();
                });

            }
            else if( $(".number-area").hasClass("all-active")){
                //* we need to fade in hover and fade out the rest;
                $(".number-area").removeClass( "all-active" );
                var current_active = numbers_hover.eq(idx-2);
                var no_animate = false;
                if(!current_active.hasClass("active")){no_animate = true;}
                numbers_hover.eq(idx-2).addClass(activeClass);
                numbers.eq(idx-2).addClass(activeClass);
                var other_numbers = numbers_hover.not(".active");
                //numbers_hover.eq(idx-2).removeClass(activeClass);
                
                if(!no_animate){
                    current_active.hide().fadeIn(function(){
                        current_active.prev(".number-text").addClass("active");
                    });
                }
                other_numbers.addClass(activeClass).show().fadeOut(function(){
                    other_numbers.removeClass(activeClass);
                });
            }
            else{
                $(".number-area").removeClass( "all-active" );
                //* fade target number in
		        //numbers.removeClass(activeClass).eq(idx-2).addClass(activeClass);
                //numbers_hover.is(":visible")
                    numbers.removeClass(activeClass);
                if(numbers_hover.eq(idx-2).hasClass(activeClass)){
                    numbers.eq(idx-2).addClass(activeClass);
                }
                else{
                numbers_hover.removeClass(activeClass);
                numbers_hover.fadeOut();
                numbers_hover.eq(idx-2).addClass(activeClass).fadeIn(function(){
                    numbers.eq(idx-2).addClass(activeClass);
                    numbers_hover.eq(idx-2).addClass(activeClass).hide();
                    
                });
                }
            }
        }
        //alert("before animation");
        //if(idx == 1 && $('#tab1', carousel.container).hasClass("active")){return;}
        if(carousel.container.closest(".dashboard").length == 0){return;}
        var dashboard = carousel.container.closest(".dashboard");
        //console.log("before animation", idx, carousel.first);
            //* animate .tab-animator
        var tabanimator = $(".tab-animator",dashboard);
        var tabanimator_x = $(".tabset-animator-x",dashboard);
        var tabanimator_neg_handler = $(".tabset-animator-x ul",dashboard);
        tabanimator.css("visibility","hidden");
            //* if prev < idx, then we animate right
        var prev_idx = tabanimator.data("carousel_prev_idx");
        var prev_first = tabanimator.data("carousel_prev_first");
        var new_loc = tabanimator.addClass("tabpos"+idx).position().left;
            //*remove classes after finding new location
        tabanimator.removeClass("tabpos1");
        tabanimator.removeClass("tabpos2");
        tabanimator.removeClass("tabpos3");
        tabanimator.removeClass("tabpos4");
        //var cur_loc = tabanimator.position().left;
        var cur_loc = parseInt(tabanimator_x.css("margin-left"));
        //console.log(tabanimator, new_loc, prev_idx, prev_first);
            //* we we're at the last position, and we need to animate cyclically
	    	$(".tabset li a",dashboard).removeClass(activeClass);
            //if(prev_idx == 4 && prev_first < carousel.first){
                //console.log(prev_first, carousel.first, prev_idx);
            if(prev_first < carousel.first && prev_idx == 4 || new_loc <  cur_loc||
                prev_first > carousel.first && prev_idx ==1
            ){
                //* note: the prev_idx == 1 bit is ONLY for making the tab go right all the time
                /*
                tabanimator.animate({
                    left: "720px"
                }, 200 ,function(){
                    tabanimator.css({left: "-90px"});
                    tabanimator.animate({
                        left: new_loc+"px"
                    }, 200 ,function(){
	    	            $(".tabset li a",dashboard).eq(idx-1).addClass(activeClass);
                    });
                });
                */

                //* synchronized animation
                tabanimator_x.animate({
                    "margin-left": "720px"
                }, {
                    duration: 200,
                    //queue:false,
                    step: function(now, fx) {
                        /*
                        if (fx.prop == "left") {
                               positioner.css("left", ""+ (-1 *now) + "px");
                        //console.log(-1 * now);
                        }
                        else if (fx.prop == "top") {
                               positioner.css("top", ""+ (-1* now) + "px");
                        }*/
                        tabanimator_neg_handler.css("margin-left", ""+(-1 * now)+"px");
                    },
                    complete: function(){
                        tabanimator_x.css("margin-left","-90px");
                        tabanimator_neg_handler.css("margin-left", "90px");
                       
                        //* animate to first location
                tabanimator_x.animate({
                    "margin-left": new_loc+"px"
                }, {
                    duration: 200,
                    //queue:false,
                    step: function(now, fx) {
                        /*
                        if (fx.prop == "left") {
                               positioner.css("left", ""+ (-1 *now) + "px");
                        //console.log(-1 * now);
                        }
                        else if (fx.prop == "top") {
                               positioner.css("top", ""+ (-1* now) + "px");
                        }*/
                        tabanimator_neg_handler.css("margin-left", ""+(-1 * now)+"px");
                    },
                    complete: function(){
                        tabanimator.css("left",new_loc+"px");
	    	            $(".tabset li a",dashboard).eq(idx-1).addClass(activeClass);
                    }
                });




 
                    }
                });

            }
            /*
            else if(prev_idx == 1 && prev_first > carousel.first){
                //* we animate the other way around
                tabanimator.animate({
                    left: "-90px"
                }, 200, function(){
                    tabanimator.css({left: "720px"});
                    tabanimator.animate({
                        left: new_loc+"px"
                    }, 200, function(){
	    	            $(".tabset li a",dashboard).eq(idx-1).addClass(activeClass);
                    });
                });
            }
            */
            else{
                //normally animate
                /*
                tabanimator.animate({
                    left: new_loc+"px"
                }, function(){
	    	        $(".tabset li a",dashboard).eq(idx-1).addClass(activeClass);
                });
                */

                //* synchronized animation
                tabanimator_x.animate({
                    "margin-left": new_loc+"px"
                }, {
                    //duration: 1000,
                    //queue:false,
                    step: function(now, fx) {
                        /*
                        if (fx.prop == "left") {
                               positioner.css("left", ""+ (-1 *now) + "px");
                        //console.log(-1 * now);
                        }
                        else if (fx.prop == "top") {
                               positioner.css("top", ""+ (-1* now) + "px");
                        }*/
                        tabanimator_neg_handler.css("margin-left", ""+(-1 * now)+"px");
                    },
                    complete: function(){
                        tabanimator.css("left",new_loc+"px");
	    	            $(".tabset li a",dashboard).eq(idx-1).addClass(activeClass);
                    }
                });





            }
        //* tabanimator.css("visibility","visible"); //* NOTE: remove this to show simple tabbing
        tabanimator.data("carousel_prev_first", carousel.first);
        tabanimator.data("carousel_prev_idx", idx);

        
    }

	jQuery('div.gallery-text').each(function(i,e){
        var dashboard = $(e).closest(".dashboard");
        var auto_sec = 0;
        if(dashboard.length > 0 || $("body").hasClass("homepage")){auto_sec = 3;} 
        var data_length = $(".box li", e).length;
        $(e).data("data_length", data_length);
        //console.log("datalength:", data_length);
        //console.log($("li",e));
      if($(".box li", e).length > 1){
        $(e).addClass("js-init");
        $(".switcher",e).show();
		jQuery(this).jcarousel({
			wrap: 'circular',
            auto: auto_sec,
			scroll: 1,
			buttonNextHTML: '<span class="btn-next"></span>',
			buttonPrevHTML: '<span class="btn-prev"></span>',
			itemLoadCallback: mycarousel_itemLoadCallback,
            initCallback: mycarousel_initCallback,
            itemVisibleOutCallback: {
                onBeforeAnimation:mycarousel_visibleOutBefore 
            } 
		});
      }
	});
}


// init tabs
function initTabs() {
	$('ul.tabset').each(function(){
		var _list = $(this);
		var _links = _list.find('a.tab');
		_links.each(function() {
			var _link = $(this);
			var _href = _link.attr('href');
			var _tab = $(_href);
			if(_link.hasClass('active')) _tab.show();
			else _tab.hide();
			_link.click(function(){
				_links.filter('.active').each(function(){
					$($(this).removeClass('active').attr('href')).hide();
				});
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
	});
}

// clear inputs
function clearInputs(){
	clearFormFields({
		clearInputs: false,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if( !$(inputs[i]).data("clear_initd") && (inputs[i].type == "text" || inputs[i].type == "password" || inputs[i].type == "email") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
                $(inputs[i]).data("clear_initd", true); //** CUSTOM
				inputs[i].onfocus = function ()	{
                    this.valueHtml = $(this).attr("title");
                    console.log(this.valueHtml, this.value);
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

// init custom forms
var _selectHeight = 23;
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var radios = new Array();
var radioLabels = new Array();
var checkboxes = new Array();
var checkboxLabels = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var selectText = "please select";

function is_mac() {
	if (navigator.appVersion.indexOf("Safari") != -1)
	{
		if(!window.getComputedStyle)
		{
			return true;
		}
	}
	
	return false;
}

function initCustomForms() {
	if(!document.getElementById) {return false;}
	getElements();
	separateElements();
	replaceRadios();
	//replaceCheckboxes();
	//replaceSelects();

	var _selects = document.getElementsByTagName('select');
	var _SelctClassName = [];
	if (_selects) {
		for (var i = 0; i < _selects.length; i++) {
			if (_selects[i].className != '' && _selects[i].className != 'outtaHere')
				_SelctClassName[i] = ' drop-'+_selects[i].className;
		}
		for (var i = 0; i < _SelctClassName.length; i++) {
			var _selectDrop = document.getElementById('optionsDiv'+i);
			if (_selectDrop) {
				if (_SelctClassName[i]) 
					_selectDrop.className += _SelctClassName[i];
			}
		}
	}
}


// getting all the required elements
function getElements() {
	var _frms = document.getElementsByTagName("form");
	for (var nf = 0; nf < _frms.length; nf++) {
		if(_frms[nf].className.indexOf("default") == -1) {
			var a = document.forms[nf].getElementsByTagName("input");
			for(var nfi = 0; nfi < a.length; nfi++) {
				inputs.push(a[nfi]);
			}
			var b = document.forms[nf].getElementsByTagName("label");
			for(var nfl = 0; nfl < b.length; nfl++) {
				labels.push(b[nfl]);
			}
			var c = document.forms[nf].getElementsByTagName("select");
			for(var nfs = 0; nfs < c.length; nfs++) {
				selects.push(c[nfs]);
			}
		}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
				}
			}
			++rl;
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
				}
			}
			++cl;
		}
		if((inputs[q].type == "submit") || (inputs[q].type == "button")) {
			buttons[b] = inputs[q]; ++b;
		}
	}
}

//replacing radio buttons
function replaceRadios() {
	for (var q = 0; q < radios.length; q++) {
		radios[q].className += " outtaHere";
		var radioArea = document.createElement("div");
		if(radios[q].checked) {
			radioArea.className = "radioAreaChecked";
			if (radioLabels[q])
			{
				radioLabels[q].className += "radioAreaCheckedLabel"
			}
			
		}
		else
		{
			radioArea.className = "radioArea";
		}
		radioArea.id = "myRadio" + q;
		radios[q].parentNode.insertBefore(radioArea, radios[q]);
		radios[q]._ra = radioArea;

		radioArea.onclick = new Function('rechangeRadios('+q+')');
		if (radioLabels[q])
		{
			radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
		}
	}
	return true;
}

//checking radios
function checkRadios(who) {
	var what = radios[who]._ra;
	for(var q = 0; q < radios.length; q++) {
		if((radios[q]._ra.className == "radioAreaChecked")&&(radios[q]._ra.nextSibling.name == radios[who].name))
		{
			radios[q]._ra.className = "radioArea";
			if (radioLabels[q])
			{
				radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel", "");
			}
		}
	}
	what.className = "radioAreaChecked";
	if(radioLabels[who])
		radioLabels[who].className += " radioAreaCheckedLabel";
}

//changing radios
function changeRadios(who) {
	if(radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false;
			} 
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//rechanging radios
function rechangeRadios(who) {
	if(!radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name)	{
				radios[q].checked = false; 
			}
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//replacing checkboxes
function replaceCheckboxes() {
	for (var q = 0; q < checkboxes.length; q++) {
		checkboxes[q].className += " outtaHere";
		var checkboxArea = document.createElement("div");
		if(checkboxes[q].checked) {
			checkboxArea.className = "checkboxAreaChecked";
			if(checkboxLabels[q])
				checkboxLabels[q].className += "checkboxAreaCheckedLabel"
		}
		else {
			checkboxArea.className = "checkboxArea";
		}
		checkboxArea.id = "myCheckbox" + q;
		checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
		checkboxes[q]._ca = checkboxArea;
		checkboxArea.onclick = checkboxArea.onclick2 = new Function('rechangeCheckboxes('+q+')');
		if (checkboxLabels[q])
		{
			checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
		}
		
		checkboxes[q].onkeydown = checkEvent;
	}
	return true;
}

//checking checkboxes
function checkCheckboxes(who, action) {
	var what = checkboxes[who]._ca;
	if(action == true) {
		what.className = "checkboxAreaChecked";
		what.checked = true;
		if(checkboxLabels[who])
			checkboxLabels[who].className += " checkboxAreaCheckedLabel";
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
		if(checkboxLabels[who])
			checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
	}
}

//changing checkboxes
function changeCheckboxes(who) {
	if(checkboxes[who].checked) {
		checkCheckboxes(who, false);
	}
	else {
		checkCheckboxes(who, true);
	} 
}

//rechanging checkboxes
function rechangeCheckboxes(who) {
	var tester = false;
	if(checkboxes[who].checked == true) {
		tester = false;
	}
	else {
		tester = true;
	}
	checkboxes[who].checked = tester;
	checkCheckboxes(who, tester);
}

//check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}


function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {
	if (!selects[q].replaced && selects[q].offsetWidth && selects[q].className.indexOf("default") == -1)
	{
		selects[q]._number = q;
		//create and build div structure
		var selectArea = document.createElement("div");
		var left = document.createElement("span");
		left.className = "left";
		selectArea.appendChild(left);
		
		var disabled = document.createElement("span");
		disabled.className = "disabled";
		selectArea.appendChild(disabled);
		
		selects[q]._disabled = disabled;
		var center = document.createElement("span");
		var button = document.createElement("a");
		var text = document.createTextNode(selectText);
		center.id = "mySelectText"+q;
		
		var stWidth = selects[q].offsetWidth;
		selectArea.style.width = stWidth + "px";
		if (selects[q].parentNode.className.indexOf("type2") != -1){
			button.href = "javascript:showOptions("+q+",true)";
		} else {
			button.href = "javascript:showOptions("+q+",false)";
		}
		button.className = "selectButton";
		selectArea.className = "selectArea";

		selectArea.className += " " + selects[q].className;
		selectArea.id = "sarea"+q;
		center.className = "center";
		center.appendChild(text);
		selectArea.appendChild(center);
		selectArea.appendChild(button);
		
		//hide the select field
		selects[q].className += " outtaHere";
		//insert select div
		selects[q].parentNode.insertBefore(selectArea, selects[q]);
		//build & place options div

		var optionsDiv = document.createElement("div");
		var optionsListParent = document.createElement("div");
		optionsListParent.className = "select-center";
		var optionsListParent2 = document.createElement("div");
		optionsListParent2.className = "select-center-right";
		var optionsList = document.createElement("ul");
		optionsDiv.innerHTML += "<div class='select-top'><div class='select-top-left'></div><div class='select-top-right'></div></div>";
		optionsListParent.appendChild(optionsListParent2);
		optionsListParent.appendChild(optionsList);
		optionsDiv.appendChild(optionsListParent);
		
		selects[q]._options = optionsList;
		
		optionsDiv.style.width = stWidth + "px";
		optionsDiv._parent = selectArea;
		
		optionsDiv.className = "optionsDivInvisible";
		optionsDiv.id = "optionsDiv"+q;
		
	
		populateSelectOptions(selects[q]);
		optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
		document.getElementsByTagName("body")[0].appendChild(optionsDiv);
		selects[q].replaced = true;
		}
	all_selects = true;
	}
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";
	
	for(var w = 0; w < me.options.length; w++) {
		if(me.options[w].title.indexOf("title") == -1) {
			var optionHolder = document.createElement('li');
			var optionLink = document.createElement('a');
			var optionTxt;
			if (me.options[w].title.indexOf('image') != -1) {
				optionTxt = document.createElement('img');
				optionSpan = document.createElement('span');
				optionTxt.src = me.options[w].title;
				optionSpan = document.createTextNode(me.options[w].text);
			} else {
				optionTxt = document.createTextNode(me.options[w].text);
			}
			
			optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
			if (me.options[w].title.indexOf('image') != -1) {
				optionLink.appendChild(optionTxt);
				optionLink.appendChild(optionSpan);
			} else {
				optionLink.appendChild(optionTxt);
			}
			optionHolder.appendChild(optionLink);
			me._options.appendChild(optionHolder);
			//check for pre-selected items
			if(me.options[w].selected) {
				selectMe(me.id,w,me._number);
			}
		}
		else if(me.options[w].selected)
			selectMe(me.id,w,me._number);
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
		textVar.appendChild(optionSpan);	
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
	}
	if (selectField.onchange && all_selects)
		{
			eval(selectField.onchange());
		}
}
//showing options
function showOptions(g) {
		_elem = document.getElementById("optionsDiv"+g);
		var divArea = document.getElementById("sarea"+g);
		if (active_select && active_select != _elem) {
			active_select.className = active_select.className.replace('optionsDivVisible','optionsDivInvisible');
			active_select.style.height = "auto";
			_active.className = _active.className.replace('selectAreaActive','');
		}
		if(_elem.className.indexOf("optionsDivInvisible") != -1) {
			_elem.style.left = "-9999px";
			_elem.style.top = findPosY(divArea) + _selectHeight + 'px';
			_elem.className = _elem.className.replace('optionsDivInvisible','');
			_elem.className += " optionsDivVisible";
			/*if (_elem.offsetHeight > 200)
			{
				_elem.style.height = "200px";
			}*/
			_elem.style.left = findPosX(divArea) + 'px';
			divArea.className += ' selectAreaActive';
			_active = divArea;
			
			active_select = _elem;
			if(document.documentElement)
			{
				document.documentElement.onclick = hideSelectOptions;
			}
			else
			{
				window.onclick = hideSelectOptions;
			}
		}
		else if(_elem.className.indexOf("optionsDivVisible") != -1) {
			_elem.style.height = "auto";
			_elem.className = _elem.className.replace('optionsDivVisible','');
			_elem.className += " optionsDivInvisible";
			divArea.className = divArea.className.replace('selectAreaActive','');
		}
		
		// for mouseout
		/*_elem.timer = false;
		_elem.onmouseover = function() {
			if (this.timer) clearTimeout(this.timer);
		}
		_elem.onmouseout = function() {
			var _this = this;
			this.timer = setTimeout(function(){
				_this.style.height = "auto";
				_this.className = _this.className.replace('optionsDivVisible','');
				if (_elem.className.indexOf('optionsDivInvisible') == -1)
					_this.className += " optionsDivInvisible";
			},200);
		}*/
}
_active = false;
function hideSelectOptions(e)
{
	if(active_select)
	{
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(isElementBefore(_target,'selectArea') == 0 && isElementBefore(_target,'optionsDiv') == 0)
		{
			active_select.className = active_select.className.replace('optionsDivVisible', '');
			active_select.className = active_select.className.replace('optionsDivInvisible', '');
			active_select.className += " optionsDivInvisible";
			_active.className = _active.className.replace('selectAreaActive','');
			active_select = false;

			if(document.documentElement)
			{
				document.documentElement.onclick = function(){};
			}
			else
			{
				window.onclick = null;
			}
		}
	}
}

function isElementBefore(_el,_class)
{
	var _parent = _el;	
	do
	{
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	
	if(_parent.className && _parent.className.indexOf(_class) != -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

function initAccordion(){
    if($(".accordion .opener").length == 0){return;}
    if($(".accordion").closest("#sidebar").length > 0){return;}

    $(".accordion li").each(function(i,e){
        e = $(e);
        if(e.find(".slide") == 0){return;}

        var temp_opener = $(".opener", e);
        temp_opener.click(function(){
            if(temp_opener.hasClass("open")){
                temp_opener.removeClass("open");
                temp_opener.text("Show All");
                $(".slide",e).slideUp();
            }
            else{
                temp_opener.addClass("open");
                temp_opener.text("Hide All");
                $(".slide",e).slideDown();
            }
            return false;
        });
    });
}

function initAccordionDroid(){
    if($(".accordion .opener").length == 0){return;}
    if($(".accordion").closest("#sidebar").length > 0){return;}

    $(".accordion li").each(function(i,e){
        e = $(e);
        if(e.find(".slide") == 0){return;}

        var temp_opener = $(".opener", e);
        temp_opener.click(function(){
            if(temp_opener.hasClass("open")){
                temp_opener.removeClass("open");
                temp_opener.text("Show All");
                $(".slide",e).hide();
            }
            else{
                temp_opener.addClass("open");
                temp_opener.text("Hide All");
                $(".slide",e).show();
            }
            return false;
        });
    });
}

var jwplayer_skin = '/images/flash/modieus/modieus.xml';
if(window.location.pathname == "/careers/summer-and-seven-at-milbank.html"){
    var jwplayer_skin = '/images/flash/modieus2/modieus.xml';
}

function initAudio(){
    if($(".fe-audio").length == 0){return;}
        var  temp_video = $( '.fe-audio' ).frontendVideo({
            jwplayer_params:{
                flashplayer: '/javascript/jwplayer/player.swf',
                "controlbar.position": "bottom",
                "icons": false,
                skin: jwplayer_skin
            }
        });
}
function initIEVideo(){
    if($(".fe-video").length == 0){return;}

        console.log( $( '.ie-nyro-video .fe-video, careers-inside .fe-video' ));
        //* remove ID for all videos in nyro-video
        $(".nyro-video .fe-video").attr("id","");

        $(window).load(function(){
            var  temp_video = $( '.ie-nyro-video .fe-video, .careers-inside .fe-video' ).frontendVideo({
                jwplayer_params:{
                    flashplayer: '/javascript/jwplayer/player.swf',
                    skin: jwplayer_skin
                }
            });
        });
        //console.log(temp_video);
    function ie_video_reposition(nyro_handler){
        //alert("ie reposition");
        console.log(nyro_handler);
        var temp = $(".nyroModalDom").offset();
        //alert("top:"+temp.top+ " left:"+temp.left);
        var temp_position = {
            top: parseInt($(".nyroModalCont").css("top")),
            left: parseInt($(".nyroModalCont").css("left"))
        }
        if(($.browser.msie && $.browser.version == "6.0")){ //weird problem with ie6 since it uses position absolute for the lightbox;
            var id_wrapper_left = $("#wrapper").offset().left; 
            $(".nyro-video-wrapper").css("left","-"+id_wrapper_left); //we need to git nyro-video-wrapper a negative left position
        }
        var dom_padding = 10; 
        var border_width = 4;
        var cont_margin = 25;
    
        nyro_handler.css({
            top: (temp_position.top+cont_margin+dom_padding+border_width)+"px",
            left: (temp_position.left+cont_margin+dom_padding+border_width)+"px"
        });
        
    }
    if($('.nyro-video').length > 0){
        $(".btn-play").each(function(i,e){
            var self =$(e);
                console.log(e);
            var nyro_id = $(e).attr("href");
          $(self).nyroModal({
            callbacks: {
                beforeShowCont: function(){
                    //console.log($(".nyroModalDom"));
                },
                beforeHideCont: function(){
                    var nyro_handler = $(nyro_id+"-handler");
                    jwplayer($("object", nyro_handler).attr("id")).pause();
                    //nyro_handler.hide();
                    //nyro_handler.css("visibility","hidden");
                    nyro_handler.css("top", "-9999px");
                },
                afterHideCont: function(){
                },
                afterClose: function(){
                },
                afterShowCont: function(){
                    //$('.nyro-video').prevAll(".btn-play").nyroModal({
                    //console.log($(".nyroModalDom object").attr("id"));
                    //* show the hidden video, reposition it
                    var nyro_handler = $(nyro_id+"-handler");
                    ie_video_reposition(nyro_handler);
                    //nyro_handler.show();
                    nyro_handler.css("visibility","visible");
                        setTimeout(function(){
                            console.log( $("object", nyro_handler).attr("id"));
                            jwplayer($("object", nyro_handler).attr("id")).play(); 
                        },1200);
                },//afterShowCont
                reposition:function(){
                    alert("reposition");
                },
                afterReposition: function(){
                    var nyro_handler = $(nyro_id+"-handler");
                    ie_video_reposition(nyro_handler);
                }
            },
            showCloseButton: true,  // Indicates if the closeButonn should be added^M
            closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton" title="close">Close</a>'    // Close button HTML^M

      });
    });
        //* rewriting bg fade animation 
        $.nmAnims({
            fade: {
                showBg: function(nm, clb) {
                    nm.elts.bg.fadeTo(250, 0.5, clb); //* second arg is opacity
                }
            }
        });
    }

}


function initVideo(){
    if(swfobject.hasFlashPlayerVersion("1")){
        console.log("has flash");
    }
    else{
        console.log("no flash");
    }
    if( (!swfobject.hasFlashPlayerVersion("1")&& !isIphone()) ||($.browser.msie ) ){
        initIEVideo(); //we're using this method for every non-mobile browser because 
        return;
    }
    $( '.ie-nyro-video .fe-video' ).remove();
    if($(".fe-video").length == 0){return;}
        //* initialize video

    if(!(isIphone() && $(".nyro-video").length > 0)){
        $(window).load(function(){
            var  temp_video = $( '.fe-video' ).frontendVideo({
                jwplayer_params:{
                    flashplayer: '/javascript/jwplayer/player.swf',
                    skin: jwplayer_skin
                }
            });
        });
    }
    else if ($(".nyro-video").length > 0){
        //initialize scrolling
            var myScroll;
            $(window).resize(function(){
                $(".careers-page").css({
                    height :  $(window).height()+40+"px",
                    "background-image": "none"
                });
                if(typeof myScroll != "undefined"){
                    myScroll.destroy();
                }
                myScroll = new iScroll("iscrollWrapper", {zoom: true});
            }).trigger("resize");
    }
    if($('.nyro-video').length > 0){
        
        //$('.nyro-video').prevAll(".btn-play").nyroModal({
        $(".btn-play").each(function(i,e){
            var self =$(e);
          $(self).nyroModal({
            callbacks: {
                beforeShowCont: function(){
                    //console.log($(".nyroModalDom"));
                },
                beforeHideCont: function(){
                    $("video").hide();
                },
                afterHideCont: function(){
                    if(isIphone()){
                        $("#"+$(self).data("video_id")).remove();
                        $(".page-wrapper").animate({"opacity": "1"});
                    }
                },
                afterClose: function(){
                        $(self.attr("href")).html($(self).data("original_video"));
                },
                afterShowCont: function(){
                    //$('.nyro-video').prevAll(".btn-play").nyroModal({
                    //console.log($(".nyroModalDom object").attr("id"));
                    if(!isIphone()){
                        setTimeout(function(){
                        jwplayer($(".nyroModalDom object").attr("id")).play();
                        },1200);
                    }
                    else{
                        //* testing iscroll
                        $(".page-wrapper").css("opacity", ".2");
                        $(".nyroModalBg").hide();
                        //alert($("#iscrollWrapper").html().substr(0, 100));
                        //* resize background to height of page
                        var body = document.body, html = document.documentElement;


                        $(".nyroModalBg").css({height: Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight )+"px"});
                        var new_id_flag= false;
                        if(typeof $(self).data("original_video") != "undefined"){
                               new_id_flag = true;
                        }
                        else{
                            $(self).data("original_video", $(".nyroModalDom").html());
                            //* grab initial lightbox size
                            //$(self).data("original_height", $(".nyroModalDom").outerHeight(true));
                            $(self).data("original_height", $(".nyroModalDom video").outerHeight(true)+20);
                            $(self).data("original_width", $(".nyroModalDom video").outerWidth(true)+20);
                        }
                        $(".nyroModalDom video").show();
                        $(".nyroModalDom video").css("visiblity","visible");
                        var vid_id = $(".nyroModalDom .fe-video").attr("id"); 
                        if(new_id_flag){
                            vid_id = "video_"+new Date().getTime(); 
                            $(".nyroModalDom .fe-video").attr("id", vid_id ); 
                            //console.log($(".nyroModalDom .fe-video").height());
                            //console.log($(".nyroModalDom .fe-video").width());
                        }
                        $(self).data("video_id", vid_id);
                        
                        
        var  temp_video = $( '.nyroModalDom .fe-video' ).frontendVideo({
            jwplayer_params:{
                flashplayer: '/javascript/jwplayer/player.swf',
                //autostart: true,
                skin: jwplayer_skin
            }
        });

                    }
                },//afterShowCont
                afterReposition: function(){
                    if(isIphone()){
                        $(".nyroModalCont").css({
                            height: $(self).data("original_height")+"px",
                            width: $(self).data("original_width")+"px"
                        });
                        var lightbox_height = $(".nyroModalCont").outerHeight(true);
                        var lightbox_width = $(".nyroModalCont").outerWidth(true);
                        $(".nyroModalCont").css({
                            top: ($(window).height() - lightbox_height)/2 + "px",
                            left: ($(window).width() - lightbox_width)/2 + "px"
                        });
                    }
                }
            },
            showCloseButton: true,  // Indicates if the closeButonn should be added^M
            closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton" title="close">Close</a>'    // Close button HTML^M

      });
    });
        //* rewriting bg fade animation 
        $.nmAnims({
            fade: {
                showBg: function(nm, clb) {
                    nm.elts.bg.fadeTo(250, 0.5, clb); //* second arg is opacity
                }
            }
        });
    }
    
    //initModalTouch();
}

function initModalTouch(){
    
    if(isIphone()){
        var start_loc = {
            x:0,
            y:0
        }
        var offset_y = 0;
        var mouse_move  = false;
        document.addEventListener('touchstart', function(event) {
            
            var touch = event.touches[0];
            start_loc = {
                x : touch.pageX,
                y : touch.pageY
            };
            //alert(start_loc.y);
            mouse_move = true;
        }, false);
        document.addEventListener('touchend', function(event) {
            mouse_move = false;
        }, false);
        document.addEventListener('touchmove', function(event) {
            var touch = event.touches[0];
            //alert($(touch.target).closest(".nyroModalBg").attr("class"));
                //console.log(touch.clientY+ "....."+ touch.pageY+"....."+touch.screenY);
            if($(touch.target).closest(".nyroModalBg").length > 0){
                //console.log("touch pageX:" +touch.pageX);
                //console.log("touch pageY:" +touch.pageY);
                //console.log("offset y:" + (start_loc.y - touch.pageY));
                
                offset_y = (start_loc.y - touch.pageY);
                console.log(offset_y);
                //offset_y = touch.pageY;
                //* reposition lightbox;
                var current_top = parseInt($(".nyroModalCont").css("top"));
                //console.log("current_top:"+current_top + " new top:"+ current_top + offset_y);
                //$(".nyroModalCont").css("top", current_top+offset_y+"px");
                $(".nyroModalCont").css("top", offset_y+"px");
                //event.preventDefault();

                //$(".nyroModalCont").style.webkitTransform = 'translate(' + 0 + 'px, ' + offset_y + 'px)';


            }
            return;
        }, false);
    }

}


function initMap(){
    if($("#map_canvas").length == 0){return;}
/*
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
  zoom: 8,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
*/
    var geo_callback = function(arr, result, status){
        console.log(arr, result, status);

        var myOptions = {
          zoom: 15,
          center: arr[0].geometry.location,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };


        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        var marker = new google.maps.Marker({
                position: myOptions.center,
                map: map
        });

    };


    var geocoder =  new google.maps.Geocoder();
    var latitude;
    var longitude;
    if($("address.address-proper .lat").length > 0 && $("address.address-proper .long").length > 0 ){
        var latlng_obj = new google.maps.LatLng(parseFloat($("address.address-proper .lat").text()) , parseFloat($("address.address-proper .long").text()), true);
        geocoder.geocode({
            location: latlng_obj
        }, geo_callback);
    }
    else{
        geocoder.geocode({
            address: $("address").text()
        }, geo_callback);
    }


        //var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function attorney_autocomplete_source_fn(request, response){
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
    response( $.grep( attorney_data , function( value ) {
        return matcher.test( value ) || matcher.test(  attorney_data_alt[value] );
    }) ); 
}

function initInputs(){
    if($("input[type=text]").length ==0 ){return;}
    //$("input[type=text]:not(.header-search), input[type=email] ").each(function(i,e){
    $("input[type=text], input[type=email], .form textarea ").each(function(i,e){
        //** create helpertext/ reposition label as helper text;
        //$(e).after($("<span class='helper-input'>"+$(e).attr("title")+"</span>"));
        //console.log(e);
        $(e).addClass("js-init");
        $(e).data("input_default", $(e).attr("title"));

            var custom_label = $(e).siblings(".custom-label");
            if(custom_label.length == 0){
                
                custom_label = $(e).closest(".rtg-input").siblings(".rtg-label");
            }

            custom_label.click(function(){
                $(e).trigger("focus");
            });
        $(e).focus(function(){
            custom_label.hide();
        });
        $(e).blur(function(){
            console.log("intial val", $(e).val());
            if($(e).val().length == 0){
                custom_label.show();
            }
        }).trigger("focus").trigger("blur");
    });
    //$("#myRadio0, #myRadio1").each(function(i,e){
        //$(e).click(function(){
        $("#myRadio0, #myRadio1, #myRadio0 ~ label, #myRadio1 ~ label").click(function(){
                var e = $("input.header-search");
                var custom_label = $(e).siblings(".custom-label");
                if(custom_label.length == 0){
                
                    custom_label = $(e).closest(".rtg-input").siblings(".rtg-label");
                }
                custom_label = $("label",custom_label);

            var radio_title = $(".radioAreaChecked").next("input").attr("title");
         
                $("input.header-search").removeClass("active");
                //$(e).val($(e).attr("title"));
                //$("input.header-search").val(radio_title);
                custom_label.html(radio_title);
                $("input.header-search").attr("title",radio_title);

                
                if( $("input[type=text].header-search").attr("title") == "Attorney Name"){
                    $("input[type=text].header-search").autocomplete( "option", "disabled", false );
                    //* hide site search
                    $(".header-site-search-wrapper").hide();
                    $(".header-att-search-wrapper").show()
                }
                else{
                    $("input[type=text].header-search").autocomplete( "option", "disabled", true );
                    //* hide attorney search
                    $(".header-att-search-wrapper").hide();
                    $(".header-site-search-wrapper").show();
                }

        });
    //});
    //** INITing header input area
            $(".radioAreaChecked").trigger("click");

    var source_function = function(){
        console.log("source test");
    }
    $("input[type=text].header-search").each(function(i,e){
        //** initializing header autocomplete
        var disabled_flag = false;
        if($(e).attr("title") != "Attorney Name"){
            disabled_flag = true;
        }
            $(e).autocomplete({
                disabled: disabled_flag,
                source: attorney_autocomplete_source_fn,
                //source: source_function,
                appendTo: ".nav-search .search .header-search-wrapper"
            });
            /*
            setTimeout(function(){
                $(e).autocomplete("search","t");
            }, 3000);
            */
            if(($.browser.msie && $.browser.version == "6.0")){
                $(e).bind("autocompleteopen",function(event,ui){
                    console.log(event,ui);
                    var auto_block = $(e).siblings(".ui-autocomplete");
                    var auto_height = auto_block.height();
                    console.log(auto_height);
                    if(auto_height > 300){
                        auto_block.css("height",300+"px");
                    }
                });
                $(e).bind("autocompletefocus",function(event,ui){
                    $('.ui-parent-active-menuitem').removeClass("ui-parent-active-menuitem");
                    $("#ui-active-menuitem").parent().addClass("ui-parent-active-menuitem");
        
                });
                $(e).siblings(".ui-autocomplete").mouseleave(function(){
                    $('.ui-parent-active-menuitem').removeClass("ui-parent-active-menuitem");
                });
                
            }
                $(e).bind("autocompleteselect",function(event,ui){ //auto redirect to an attorney if we selected him from the autocomplete dropdown
                    window.location = attorney_data_link[ui.item.value];
                });
            
    });

    //** initialize header form submission
    //*** we don't need this anymore, we're handling it on the backend via a redirect
    //*** the action is handled by selecting the radio
    //arg_str ?action=attorneys&rule001_field=name&rule001_value=test
    /* 
    $(".nav-search form").submit(function(){
    });
    $(".nav-search form input[type='submit']").click(function(){
        //** check if title == Attorney Name or Search Term,
        var header_input = $("input[type=text].header-search");
        var arg_str;
        //alert(header_input.val().length);
        if(header_input.val().length == 0){return false;}
        if( header_input.attr("title") == "Attorney Name"){
            arg_str = "/attorneys/index.html";
            arg_str +="?action=attorneys&rule001_field=name&rule001_value="+header_input.val();
        }
        else{
            //** GOOGLE CSE
            arg_str = "/search-results.html";
            //arg_str +="?action=gcse&rule001_field="+header_input.val();
            return true; 
        }
        
        window.location = arg_str;
        return false;
    });
    */
}

function initNewsSearch(){
    var total_checked = $(".news-check-holder input[type=checkbox]:not(.checkbox-all)").length;
    $(".news-check-holder input[type=checkbox].checkbox-all").change(function(event){
        //console.log("change", event);
        if($(this).is(":checked")){
            $(".news-check-holder input[type=checkbox]").attr("checked","checked");
        }
        else{
            $(".news-check-holder input[type=checkbox]").removeAttr("checked");
        }
    });
    $(".news-check-holder input[type=checkbox]:not(.checkbox-all)").each(function(i,e){

        $(e).change(function(event){
            if(!$(this).is(":checked")){
                $(".news-check-holder input[type=checkbox].checkbox-all").removeAttr("checked");
            }
            else{ 
                if($(".news-check-holder input[type=checkbox]:not(.checkbox-all):checked").length == total_checked){
                    $(".news-check-holder input[type=checkbox].checkbox-all").attr("checked","checked");

                }
            }
        });

    });
    
}

function initHeaderNav(){
    if( ($.browser.msie && $.browser.version == "6.0")){
        $("#nav li a").mouseover(function(){
            $(this).addClass("active");
        });
        $("#nav li a").mouseleave(function(){
            $(this).removeClass("active");
        });
        return;
    }
    if($("#nav-fade").length ==0){return;}
    $("#nav-fade li a").mouseover(function(){
            $(this).animate({"opacity":"1"});
        //$(this).fadeIn();
    });
    $("#nav-fade li a").mouseleave(function(){
            $(this).animate({"opacity":"0"});
        //$(this).fadeOut();
    });
}

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

function initAttorneySearch(){
    if($(".dynamic-rows").length == 0){  return;}
    $(".dynamic-rows.reference").show();
    $(".dynaimic-row-js-remove").show();
    //$("option").removeAttr("selected");
    console.log($("option:selected"));
    //$("option[value='.practice-area-input']").attr("selected","selected");

    //** save first three rows for reset
    //var original_rows = $(".dynamic-rows").clone();
    var original_rows = $(".dynamic-rows.reference").detach();
    console.log("original rows" , original_rows);
    //* we force refresh the dropdown to it's default selected state
    $("option[selected='selected']").each(function(i,e){
        $(e).removeAttr("selected");
        $(e).attr("selected","selected");
    });

    //** if .dynamic-rows.row-no-args, we only want the first two rows
    $(".dynamic-row-js-remove").remove();
    
    var initInput_refresh = function(target_inputs){

        $(target_inputs).each(function(i,e){
            //console.log(e);
            $(e).data("input_default", $(e).attr("title"));
            var custom_label = $(e).siblings(".custom-label");
            if(custom_label.length == 0){
                
                custom_label = $(e).closest(".rtg-input").siblings(".rtg-label");
            }

            custom_label.click(function(){
                $(e).trigger("focus");
            })
            $(e).focus(function(){
                custom_label.hide();
            });
            $(e).blur(function(){
                console.log("intial val", $(e).val());
                if($(e).val().length == 0){
                    custom_label.show();
                }
            }).trigger("focus").trigger("blur");
        });
    }

    //* reinitializing row 
    var row_select_fn = function(event){
        console.log(this, event);
        var self = $(this);
        var target = $("option:selected", self);
        var target_class = ".attorney-search-input."+$("option:selected", self).val();
        console.log(target_class, target, target.hasClass("attorney-search-and"));
        //* disable all inputs, enable one specified by target_class
        if(!target.hasClass("attorney-search-and") ){

            console.log("input block", input_block);
            //** remove and option
            var row = self.closest(".row");
            //** insert close after the last row
            if( $("option.attorney-search-and",self).length > 0){ //** IF we're inserting a new row
                var clone = self.closest(".row").clone();
                row.after(clone);
                $($("select", clone)[0]).change(row_select_fn); //** have to add the function to the cloned item
                $(".remove-block a", clone).click(row_remove_fn); 
                $("input[type='text']", clone).focus(autosuggest_fn);
                
                initInput_refresh($("input[type='text']", clone));
            }

            var input_block = $(self).next(".input-block").addClass("active");
            self.removeClass("attorney-search-and");
            
            if( ($.browser.msie && $.browser.version == "6.0" )){
                $("option.attorney-search-and", self).hide();
            }
            else{
                $("option.attorney-search-and", self).remove();
            }
            //** make target_class active
            $(".attorney-search-input", input_block).removeClass("active");
            console.log(target_class, $(target_class, input_block));
            $(target_class, input_block).addClass("active");
        }
    }
    $(".row select.search-field").change(row_select_fn);

    //** initializing autosuggest

    var autosuggest_fn = function(event){
        var self = $(this);
        var wrapper = self.closest(".attorney-search-input");
        //console.log("getpath", $(wrapper).getPath(), $(wrapper.getPath()));
        if(!self.data("autocomplete_init")){
            console.log(self.data("autocomplete_init"));
            self.data("autocomplete_init",true);
            wrapper.attr("id","search_wrapper_"+new Date().getTime());
            console.log(wrapper, wrapper.attr("id"), $("#"+wrapper.attr("id")));
            self.autocomplete({
                //disabled: disabled_flag,
                source: attorney_autocomplete_source_fn,
                appendTo: "#"+wrapper.attr("id")+" .autocomplete-wrapper"
            });
         
            /* 
            setTimeout(function(){
                $(self).autocomplete("search","t");
            }, 3000);
            */
            if($.browser.msie){

                $(self).bind("autocompleteopen",function(event,ui){
                        var auto_block = $(self).siblings(".autocomplete-wrapper").find(".ui-autocomplete");
                        var auto_height = auto_block.height();
                        var row = $(self).closest(".row");
                        console.log(row);
                    if( $.browser.version == "6.0"){
                        console.log(event,ui);
                        //var auto_block = $(self).siblings(".ui-autocomplete");
                        console.log(auto_height);
                        if(auto_height > 160){
                            auto_block.css("height",160+"px");
                        }
                        //* insert iframe shim if not avail
                        var iframe_shim = $(self).siblings(".autocomplete-wrapper").find("iframe");
                        if($(self).siblings(".autocomplete-wrapper").find("iframe").length == 0){
                            $(self).siblings(".autocomplete-wrapper").append($("<iframe src='/images/transparent.gif'></iframe>"));
                        }
                        else{
                            iframe_shim.show();
                        }
                    }
                    if($.browser.version == "7.0" || $.browser.version == "6.0"){
                        var row_offset = row.offset();
                        var row_height = row.height();
                        $(".row").each(function(i,e){
                            console.log(i, e);
                            var row_offset2 = $(e).offset();
                            console.log(i, e, row_offset, row_offset2,row_height);
                            
                            if(row_offset.top+auto_height+row_height > row_offset2.top && row_offset2.top > row_offset.top){
                                //$(".attorney-search-input.active", e).hide();
                                $(".input-block",e).addClass("active-hide");
                            }
                        });
                    }
                });
                $(self).bind("autocompleteclose",function(event,ui){
                    if( $.browser.version == "6.0"){
                        var iframe_shim = $(self).siblings(".autocomplete-wrapper").find("iframe");
                        if($(self).siblings(".autocomplete-wrapper").find("iframe").length != 0){
                            iframe_shim.hide();
                        }
                    }
                    if( $.browser.version == "7.0" ||  $.browser.version == "6.0"){
                                $(".input-block").removeClass("active-hide");
                    }
                });
            }

                $(self).bind("autocompleteselect",function(event,ui){ //auto redirect to an attorney if we selected him from the autocomplete dropdown
                    window.location = attorney_data_link[ui.item.value];
                });
        }
    }

    $(".row input[type='text']").focus(autosuggest_fn);
    


    //** initializing remove click
    var row_remove_fn = function(event){
        //** this is on remove-block a click;
        var self = $(this);
        var row = self.closest(".row");
        console.log("row", row);
        row.remove();
        return false;
    }
    $(".row .remove-block a").click(row_remove_fn);

    //** initializing reset_all click
    $(".reset-block a").click(function(){
        $(".dynamic-rows .row").remove();
        $(".dynamic-rows").replaceWith(original_rows.clone());
        $(".row select.search-field").change(row_select_fn);
        $(".row .remove-block a").click(row_remove_fn);
        $(".row input[type='text']").focus(autosuggest_fn);
                
        initInput_refresh($(".row input[type='text']"));
        
        return false;
    });
    //** form notes:
    //** ?rule001_field=name&rule001_value=a*&action=attorneys
    //** override submit click
    $("form.search-form").submit(function(){
    });
    $(".submit-row input[type='submit']").click(function(){
        var form_action = $("form.search-form").attr("action");
        
        console.log("submit click", form_action);
        var arg_str ="?action=attorneys";
        var j = 0;
        console.log($(".search-field option:selected:not('.attorney-search-and')") );
        $(".search-field option:selected:not('.attorney-search-and')").each(function(i,e){
            var temp_val;
            var temp_field = $(e).val();
            var row = $(e).closest(".row");
            var target_class = ".attorney-search-input."+$(e).val();
            var value_field = $(target_class, row).children("input,select")[0];
            
            if(value_field.tagName == "INPUT" && $(value_field).attr("type") == "text" && $(value_field).val().length > 0){
                //** it's a text input field, we save the value
                temp_val = $(value_field).val();
                console.log("tempval", temp_val);
            }
            else if(value_field.tagName == "SELECT"){
                temp_val = $("option:selected", value_field).val();
                if(temp_val == ""){return;}
                
            }
            else{
                //** we should not get here, but if we do, then the selected dropdowns matches no field input criteria and we must skip it
                return;
            }
            j++;
            //** continue to add more field's if there are
            var padded_num = pad(j, 3);
            arg_str += "&rule" + padded_num + "_field=" + temp_field + "&rule" + padded_num + "_value=" + temp_val;
        });
        console.log("arg_str",arg_str);
        //** iterate through inputs and compile the inputs
        
        window.location = arg_str;
        return false;
    });

    $(document).scrollTop(0); //* need to force scrollTop on the attorney's page because when the js removed some fields, it changes the document height and the scroll height is not at 0
}

function initFEgallery(){
    if($(".gal-holder").length == 0){return;}
    //** make the height of the li's the height of the tallest one
    var max_height = 0;
    $(".frontend-slideshow .slide li").each(function(i,e){
        if($(e).height() > max_height){max_height = $(e).height()};
    });
    $(".frontend-slideshow .slide li").css("height", max_height+"px");

    //** we may adjust the width of the images here
    max_height = 0;
    $(".gal-full-wrapper, .gallery-full").show();
    $(".gallery-holder-full .slide li").each(function(i,e){
        $(e).css("height", "auto!important");
        if($(e).height() > max_height){max_height = $(e).height()};
        // console.log($(e).height());
    });
    $(".gal-full-wrapper").hide();
    $(".gallery-holder-full .slide li").css("height", max_height+"px");


    $('.frontend-slideshow').frontendSlideshow();
    return;

            if($('.gal-holder').length > 0){

                var loaded_count = 0;
                var timeout_id=0;
                var img_ref_count = $('.frontend-slideshow img').length;
                    //* we have to wait until the images load before we create the slideshow
                $('.frontend-slideshow img').load(function(){
                    loaded_count++;
                    if(loaded_count == img_ref_count){
                        //console.log("image loaded",timeout_id);
                        if(!timeout_id){
                            clearTimeout(timeout_id);
                            $('.frontend-slideshow').frontendSlideshow();
                        }
                    }
                });
                //* if img load doesn't get called in 8 seconds, we process the slideshow anyways
                timeout_id = setTimeout(function(){
                        //console.log("timeout", timeout_id);
                        timeout_id = 0;
                        $('.frontend-slideshow').frontendSlideshow();
                }, 8000);
            }

}
function initAjaxForm(){
    if($('.signup-box').length == 0){return;}
    $('.signup-box').bind("rubySuccess", function(){
        // console.log("signupbox submit click");
        $(".signup-box input[type='text']").each(function(i,e){
            if($(e).val().length == 0){
                $(e).trigger("blur");
            }
        });
    });
    $( '.signup-box' ).frontendForm({ clear_form_on_success: true}); //enable right column ajax form submission for newsletter
    //** handle submit for subscribe form
    
    $("form.search-form").submit(function(){
    });
    //$(".signup-box button.ruby-button-save").click(function(){
    
}

function externalLinkInit(){
    //console.log(location.protocol+"//"+location.host);
    //$('a:regex(href, (?<!'+location.host+').* )').each(function(index, element){
    $('a:not(.target-blank)').each(function(index, element){
        //console.log($(element));
        var temp_str = $(element).attr('href');
        if(temp_str == undefined){return;}
        temp_str = temp_str.toLowerCase();

        //** check if link is pdf
        if( temp_str.match(".pdf")) {
            //$(element).after("<span class='icon-pdf'/>");//perl is handling this now
            $(element).click(function(){window.open(this.href); return false;});
        }
        else if(    temp_str.charAt(0)!= "?" && 
                temp_str.charAt(0)!= "#" && 
                !temp_str.match(location.host) && 
                temp_str.charAt(0)!="/" && 
                !temp_str.match("mailto:") && 
                !temp_str.match("javascript:")  ){
            //$(element).css("target-name", "new"); //not support as of yet
            //$(element).css("target-new", "tab"); //not supported as of yet 
            //$(element).after("<span class='icon-ext'/>"); //perl is handling this now
            $(element).click(function(){window.open(this.href); return false;});
        }



    });
    
}
function popWindow(element){
	$(element).click(function(){
		window.open(this.href);
		return false;
	});
}
function initPopupWindows(){
    $('a.popup, a.target-blank').each(function(index, element){popWindow(element);});
}

function dotify(el, num_lines){
    if(el.length == 0){return;}
    var temp_obj = $(el); //this is the obj we're truncating
    //var more_string = "&#8230; &nbsp;&nbsp;&nbsp;&nbsp;"; 
    var more_string = "&#8230; "; 
    var line_height = parseInt(el.css("line-height"));
    var target_height = num_lines * line_height;
    if(target_height >= $(el).height()){return;}
    $(el).css("height", num_lines*line_height+"px");
    $(el).addClass("dotified");
    //* insert span with ellipsis and a right padding of 5px+18px in the text until we find the last line
    var temp_html = temp_obj.html();
    var done = false;
    var temp_html_1 = '';
    var temp_html_2 = temp_html;
    var temp_index;
    var temp_index2;
			temp_obj.html(temp_html_1+"<span class='locator'>"+more_string+"</span>"+temp_html_2);
    /*
    var letter_count = 10; //NOTE: we need the span class to be inserted inside the P tag
				//letter_count is a var holding a simple heuristic that allows the algorithm to jump by many characters instead of one by one, decreasing calculation time
			//var letter_count = temp_obj.width()/(parseInt(temp_obj.find("p").css("font-size"))/2)*(Math.ceil(img_height/line_height) - 1);
			temp_html_1 += temp_html_2.substring(0, letter_count+1);
			temp_html_2 = temp_html_2.substring(letter_count+1);
    */
				/*--- finding next available word to insert span tag ---*/
                // console.log(temp_obj);
				temp_index = temp_html_2.indexOf(' ');
				temp_html_1 += temp_html_2.substring(0, temp_index+1);
				temp_html_2 = temp_html_2.substring(temp_index+1);
                // console.log(temp_index, temp_html_1, temp_html_2, temp_html_2.length);
			/*
			split the html text in tween, the 
			the way it works is that some text will be transferred from the right element to the left element;
			The span tag/more button is inserted between the two strings and the html element is rebuilt.
			The location of the button is grabbed and checked for whether it has surpassed the target truncated height
			*/
			
                
		
			//letter_count = letter_count/28;
			//leitter_count = (letter_count/(temp_obj.width()/(parseInt(temp_obj.find("p").css("font-size"))/2)))/5;
			var previous_top_position = $( "span.locator", temp_obj ).offset().top;
            var previous_html_1 = '';
            var previous_html_2 = '';
			var temp_position;
            var line_count = 0;
		    
            var count = 0;	
			while( temp_html_2.length > 10 && count < 100){ //while its not done, keep on moving text from the right to the left
					//temp_html_1 += temp_html_2.substring(0, letter_count+1);
					//temp_html_2 = temp_html_2.substring(letter_count+1);

					temp_index = temp_html_2.indexOf(' ');
					temp_index2 = temp_html_1.lastIndexOf('</'); //we need to check for this because it might look like this: 'some text.</p>', we need to inject the locator right before the closing tag
				    if(temp_index2 > temp_index){
						temp_index = temp_index2;
					}
					temp_html_1 += temp_html_2.substring(0, temp_index+1);
					temp_html_2 = temp_html_2.substring(temp_index+1);
                    if(temp_index == -1){done = true; break;}//* we've reached the end and it's a single line
                //console.log(temp_index, temp_html_1,"!!", temp_html_2, temp_html_2.length, line_count);

				temp_obj.html(temp_html_1+"<span class='locator'>"+more_string+"</span>"+temp_html_2);
				temp_position = $("span.locator", temp_obj).offset();
					//reinsert the span tag and grab at its location
				//console.log(temp_position);
				
				//console_text +="<br/> LOCATOR left: "+ temp_position.left;
				if(temp_position == null){
                    //** this is odd but IE doesn't like handling span tags in wrong places like <a <span/> > so we check for null
                }
				else if(previous_top_position == temp_position.top){
					//if the previous location is the same as the current location
					//it is on the same line
					//letter_count+= temp_index;
                    //* continue
				}
				else{
					//the tag just encountered a new line, reduce the amount of characters
					//to skip cause we might be going to fast
					//letter_count-= temp_index;

                    line_count ++;
					previous_top_position = temp_position.top; //next line
                    // console.log(line_count, previous_top_position, line_count);
					if(line_count == num_lines){
						//we must backtrack
						done = true;
						break;
					}
				}
                    count++;
                    previous_html_1 = temp_html_1;
                    previous_html_2 = temp_html_2;
			}
			//backtrack;
			
			done = false;
            // console.log(temp_html_1, previous_html_1);
			temp_obj.html(previous_html_1+"<span class='ellipsor'>"+more_string+"</span>"+previous_html_2);
                

            var ellipsor = $(".ellipsor", el);
            if($(".icon-ext, .icon-pdf", el).length > 0){
                $(".icon-ext, .icon-pdf", el).insertAfter($(".ellipsor", el));
                var icon = $(".icon-ext, .icon-pdf", el);
                //* find location of  ellipsor 
                var temp_position = ellipsor.position();
                // console.log(temp_position);
                icon.css({
                    "top": temp_position.top+"px",
                    "left": temp_position.left+ ellipsor.width() +"px"
                });
            }
                ellipsor.html(ellipsor.html()+"<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                
}

function initDotify(){
    $("#dashboard .text-box.text-box-no-more").each(function(i,e){
        //* this should be the 'featured' tab
        dotify($("strong.title", $(e)), 4);
        dotify($("p", $(e)), 3);
    });
    $("#dashboard .text-box.text-box-has-more .box-area").each(function(i,e){
        // console.log("HAS MORE", e, i);
        //* this should be the 'featured' tab
        var temp_el = $("strong.link", $(e));
        var temp_line_height = parseInt(temp_el.css("line-height"));
        if($("strong.link", $(e)).height() >= temp_line_height * 2 ){
            //* if strong.link is == 2 lines, then the first dotify call is ignored,
            //* and the second one is correctly truncated to 1 line
            
            dotify($("strong.link", $(e)), 2);
            dotify($("p", $(e)), 1);
        }
        else{
            //* else we assump strong.link is only 1 line, so we need to truncate the second line
            //* to two
            //dotify($("strong.link", $(e)), 1);
            dotify($("p", $(e)), 2);
        }
    });
    $(".search-page .results-block li div").each(function(i,e){
        //* truncating google cse results
        dotify($("h5", $(e)), 1);
        dotify($("p", $(e)), 2);
    });

    

            //** readjusting vertical height for ie7-6
            if( ($.browser.msie && $.browser.version == "6.0" || $.browser.version == "7.0")){
                $("#dashboard .text-box.text-box-no-more,  #dashboard .text-box.text-box-has-more .vertical-positioner").each(function(i,e){
                    var vertical_offset = e.parentNode.offsetHeight > e.offsetHeight ? ((e.parentNode.offsetHeight-e.offsetHeight)/2 + "px") : "0";
                    $(e).css("margin-top", vertical_offset);
                    //alert($(e).css("margin-top"));
                });
            }
}

function initFormAfter(){
    // Add the 'required' asterisk for required fields in IE 6/7
    if( ($.browser.msie && ($.browser.version == "6.0" || $.browser.version == "7.0")) ){
        $(".rtg-widget.required label").each(function(i,e){
            $(e).html($(e).html()+"*");
        });
    }
}

function initGoogleSearch(){
    
  google.load('search', '1', {language : 'en'});
  google.setOnLoadCallback(function() {
    //var customSearchControl = new google.search.CustomSearchControl('004983444642968987554:eomqqci2nvu');
    var customSearchControl = new google.search.CustomSearchControl(google_cx);
    //var customSearchControl = new google.search.CustomSearchControl('');
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    var options = new google.search.DrawOptions();
    options.setAutoComplete(true);
    customSearchControl.draw('cse', options);
    // console.log(customSearchControl);



    $("#cse input.gsc-search-button").click(function(){
        window.location = "/search-results.html?action=gcse&start=0&num=10&q="+encodeURIComponent($("#cse input.gsc-input").val());
    });
    //* set up google search results page
    $("#cse-search-box").hide(); //* hide the static version of the form
    customSearchControl.draw('cse-body', options);
    $(".gsc-wrapper").remove();




    //replacing cse label
    $("input.gsc-input").click(function(){
        var self=this;
        $(self).removeClass("custom-gsc-label");
    }).blur(function(){
        var self=this;
        if($(self).val().length ==  0){
            $(self).addClass("custom-gsc-label");
        }
    }).addClass("custom-gsc-label");


    if( $("#cse-search-box input.text").val() && $("#cse-search-box input.text").val().length != 0 ){
        // console.log($("#cse-search-box input.text").val());
        $("#cse-body input.gsc-input").val( $("#cse-search-box input.text").val());
        $("#cse-body input.gsc-input").removeClass("custom-gsc-label");
        $("#cse-body input.gsc-input").css("background","none");
    }
    $("#cse-body input.gsc-search-button").click(function(){
//        console.log(encodeURIComponent($("#cse-body input.gsc-input").val()));
        window.location = "/search-results.html?action=gcse&start=0&num=10&q="+encodeURIComponent($("#cse-body input.gsc-input").val());
    });


  }, true);
}

var hash_interval_id;
var last_hash = "";
var hash_flag = true;
function hashCheck(){
        var temp_hash = window.location.hash;
        
        if ( temp_hash == last_hash ) {
            return;
        }
        hashCheckFn();
}
function initHashControl(){

    // Poll, setting timeout_id so the polling loop can be canceled.
    hashCheckFn(1);
    hash_interval_id = setInterval( hashCheck, 100 );
}

function hashCheckFn(init){
    //* check if window.location has a hash, if so swap out alt bio
    var hash_str = window.location.hash.substr(1);
    if(hash_str.length > 0){
        //* swap at bio
        var alt_main = $(".origin-"+hash_str);
        if(alt_main.length > 0){
            $(".origin-body.origin-0 .wysiwyg-content").remove();
            $(".origin-body.origin-0 .info-box").remove();
            $(".origin-body.origin-0 h1").remove();
            $(alt_main[0]).show();
                //* if there's a dashboard, move it
                $($(".wysiwyg-content", $(alt_main[0]))[0]).after($(".dashboard"));
        }
    }
}

function checkBioOrigins(){
    //* only check it if the page is an attorney page
    if($(".attorney-page").length == 0){return;}

    var ck = $.cookie('origin');
    //console.log(document.referrer);
    //alert(window.location.protocol+"//"+window.location.hostname);
    //console.log("CK",ck, typeof ck);
    if(  ck != null ){
        var type, id, url;
        var split_arr = ck.split(",");
        type = split_arr[0];
        id = split_arr[1];
        url = window.location.protocol + "//" + window.location.hostname + split_arr[2];
        //console.log(type, id, url);
        var referrer = document.referrer;
        if(referrer == url){
            //* we can show alt bio if there is one
            var alt_main = $(".origin-"+id);
            if(alt_main.length > 0){
                $(".origin-body.origin-0 .wysiwyg-content").remove();
                $(".origin-body.origin-0 .info-box").remove();
                $(".origin-body.origin-0 h1").remove();
                $(alt_main[0]).show();
                //* if there's a dashboard, move it
                $($(".wysiwyg-content", $(alt_main[0]))[0]).after($(".dashboard"));
                //* update hash
                window.location.hash = id;
            }
        }
    }

    initHashControl(); //* we want to check if window.location.hash is specified  
}

function hideShowSearchForm(){
        //something else//
        if( $(".modify-search-btn").length > 0){
              /*code block*/
            $(".modify-search-btn").click(function(){
                    if( $( "form.search-form").is(":visible")){
                        $(".modify-search-btn").text("MODIFY SEARCH");
                    $("form.search-form").slideToggle(function(){});
                        $(".results-block.summary").removeClass("add-background");
                    }else{
                        $(".modify-search-btn").text("HIDE SEARCH");
                    $("form.search-form").slideToggle(function(){});
                        $(".results-block.summary").addClass("add-background");
                    }
                return false;
            }).trigger("click");
        }
    } 
//* hiding rows before init
$(".dynamic-rows.reference").hide();
$(".dynaimic-row-js-remove").hide();
//jQuery(function(){

$(document).ready(function(){
    checkBioOrigins(); //we want to do this immediately
    //blackberryTests();
    /*
    if($.browser.msie && $.browser.version == '6.0'){
        //alert("in browser check ");
        $(".simulator-table table tr th:first-child, .simulator-table table tr td:first-child").addClass("firstChild");
    }
    */
    //alert("after browser check");

    externalLinkInit();
    //alert("after external Link");

    //additional inputInitialization to instantiate the default value of the inputs
    //clearInputs();

    initCustomForms();
    //alert("after custom forms");
    //initCustomSelect();
    initInputs();
    //alert("after inputs");
    initNewsSearch();
    //alert("after news search");
    initGallery();
    //alert("after gallery");
    //initTabs();
    if ( isDroid() ) {
        initAccordionDroid();
    }
    else {
        initAccordion();
    }
    //alert("after Accordion");
    initVideo();
    initAudio();
    initMap();
    initHeaderNav();
    initAttorneySearch();
    initFEgallery();
    initAjaxForm();
    initDotify();

    initFormAfter();
    initPopupWindows();
    hideShowSearchForm();
});

initGoogleSearch();


/*
if(isBlackberry()){
    $(window).load(function(){ //for blackberry
		initBlackberry();
	});
}
*/

