// site-wide generic js scripts

var $j = jQuery.noConflict();

  $j(document).ready(function() {

	$j(function() { 
		$j('.rollover').hover(function() { 
			var currentImg = $j(this).attr('src'); 
			$j(this).attr('src', $(this).attr('hover')); 
			$j(this).attr('hover', currentImg); 
		}, function() { 
			var currentImg = $j(this).attr('src'); 
			$j(this).attr('src', $(this).attr('hover')); 
			$j(this).attr('hover', currentImg); 
		}
	);

	//Top Login Clicks
	$j('.login-top-btn').click(function() {
		var sv = $j('#email-address').val();
		if(sv != '' &&  sv != 'Email') {
			$j('#login-form').submit();
		}
	});
	
	//Top Search Button Clicks
	$j('.search-box-top-btn').click(function() {
		var sv = $j('#search-query').val();
		if(sv != '' &&  sv != 'Search') {
			$j('#search-form').submit();
		}
	});

	//Sidebar Search Button Clicks
/*	$j('.search-btn-bulletin').click(function() {
		var sv = $j('.sidebar-search-bulletin').find('#search-query').val();
		if(sv != '' &&  sv != 'Search') {
			$j('#sidebar-search-bulletin').submit();
		}
	});*/

	$j('.lawcate-sidebar-search-button').click(function() {
		$j("input:checkbox").each( function() {
			$j("#fake"+this.id).hasClass('fakechecked') ? $j(this).attr("checked", "checked") : $j(this).removeAttr("checked");
		});											
		$j('#lawcate-sidebar-search').submit();
	});

	//Common Tag Link Clicks
	$j('a.common-tag-link').click(function() {
		// prevalence bump ajax
		var term = $j(this).text()
		$j.post('/cbdr/common-ajax.php?process_name=bump_tag_prevalence', { 
			   'term' : term
			   }, 
			   function(data) {}
		);
		// remove click
		$j(this).unbind('click');
		// navigation
		switch(true) {
			case $j(this).attr('name') == 'article-tag':
				document.location = '/bulletin/search.php?tag='+Base64.encode(term)+'';
				break;
			case $j(this).attr('name') == 'lawcate-tag':
				document.location = '/lawcate/search.php?tag='+Base64.encode(term)+'';
				break;
			default:
				document.location = '/search.php?tag='+Base64.encode(term)+'';
		}
	});

	//Slide Search Panel for LawCATE quick search
	$j('#toggle').toggle(function() {
		var currentToogleImg=$j(this).attr('src');
		$j(this).attr('src',($j(this).attr('src').replace(/\./,"_on.")));
	}, function() {
		$j(this).attr('src',($j(this).attr('src').replace(/_on\./,".")));
	});
	$j('.lawcate-advanced-options-slider').hide();
	$j('.lawcate-advanced-options-slider-btn').click(function() {
		$j('.lawcate-advanced-options-slider').animate(
			{ height: 'toggle' },
			1000,
			function() {}
		);
	});

	//Fake Checkboxes for LawCATE quick search
	// check for what is/isn't already checked and match it on the fake ones
	$j("input:checkbox").each( function() {
		(this.checked) ? $j("#fake"+this.id).addClass('fakechecked') : $j("#fake"+this.id).removeClass('fakechecked');
	});
	// function to 'check' the fake ones and their matching checkboxes
	$j(".fakecheck").click(function(){
		($j(this).hasClass('fakechecked')) ? $j(this).removeClass('fakechecked') : $j(this).addClass('fakechecked');
		$j(this.hash).trigger("click");
		return false;
	});

	// Carousel	
	$j('ul.carousel').innerfade({
			speed: 3000,
			timeout: 10000,
			type: 'sequence',
			containerheight: '230px'
		}
	);

	});

	// Section Fader
	$j("div.section-block").fadeTo("slow", 0.3); // This sets the opacity of the thumbs to fade down to 30% when the page loads
		$j("div.section-block").hover(function(){
			$j(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
		},
		function(){
			$j(this).fadeTo("slow", 0.3); // This should set the opacity back to 30% on mouseout
		}
	);
		
	//Gallery clickers
	$j(".gallery-3column-images #pop-gallery").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + '</span>';
		}
	});
	//Event image clickers
	$j(".event-gallery-wrapper #pop-gallery").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'none',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
			return '';//'<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + '</span>';
		}
	});
	
	//Event scroll / anchor clicks
	$j(".event-scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();
		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;
		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];
		//get the top offset of the target anchor
		var target_offset = $j("#"+trgt).offset();
		var target_top = target_offset.top;
		//goto that anchor by setting the body scroll top to anchor top
		$j('html, body').animate({scrollTop:target_top}, 500);
	});
						   
	//Hover Menu - Needs Hover Intent Plugin
	function megaHoverOver() {
		$j(this).click(function () {
  	 });
	$j(this).find(".sub").parent().children('a').addClass("top-nav-hover");
    $j(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
	
    (function($j) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $j(this).find("ul").each(function() { //for each ul...
                rowWidth += $j(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $j(this).find(".row").length > 0 ) { //If row exists...
		var biggestRow = 0;	

        $j(this).find(".row").each(function() {	//for each row...
            $j(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $j(this).find(".sub").css({'width' :biggestRow}); //Set width
        $j(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $j(this).calcSubWidth();  //Call function to calculate width of all ul's
        $j(this).find(".sub").css({'width' : rowWidth}); //Set Width

    }
}
	
//On Hover Out
function megaHoverOut(){
  $j(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $j(this).parent().find('a').removeClass('top-nav-hover');
	  $j(this).hide();  //after fading, hide it
	 
  });
}

//LawCATE search clicks/focus
$j('#lc-query-input').focus(function(){
	$j('.lawcate-filter-search-input').addClass('lawcate-filter-search-input-focus');
	//var class = $(this).parent().attr("class");
});

//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};

$j("ul.top-nav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
$j("ul.top-nav li").hoverIntent(config); //Trigger Hover intent with custom configurations

});

function ClickFLBSearch() {
	var sv = $j('.sidebar-search-bulletin').find('#search-query').val();
	if(sv != '' &&  sv != 'Search') {
		$j('#sidebar-search-bulletin').submit();
	}
}

//Article / Search Sort Change
function listSortChange(suffix) {
	if($j('#pagination-sort').val()) {
		var ampos = document.location.href.lastIndexOf('&');
		if(ampos != -1) { // sort var is always last
			hr = document.location.href.substr(0, ampos);
			var s = "&";
		} else {
			if(document.location.href.lastIndexOf('?') != -1) {
				var s = "&";
			} else {
				var s = "?";
			}
			hr = document.location.href;
		}
		document.location = hr + s + "sort=" + $j('#pagination-sort').val() + suffix;
	}
}

//Clear LawCATE quick search options
function clearLawCATESearchOptions() {
  $j("input:checkbox").each( function() {
	  $j("#fake"+this.id).removeClass('fakechecked');
	  $j(this).removeAttr("checked")
  })
};
function leadingZeros(num, totalChars, padWith) {
	num = num + "";
	padWith = (padWith) ? padWith : "0";
	if(num.length < totalChars) {
		while (num.length < totalChars) {
		num = padWith + num;
		}
	} else {
		if(num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
			num = num.substring((num.length - totalChars), totalChars);
		}
	}
	return num;
}
function trimString(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}
//PEPS Rollovers
$j(document).ready( function()
{
   PEPS.rollover.init();
});

PEPS = {};

PEPS.rollover =
{
   init: function()
   {
      this.preload();
     
      $j(".ro").hover(
         function () { $j(this).attr( 'src', PEPS.rollover.newimage($j(this).attr('src')) ); },
         function () { $j(this).attr( 'src', PEPS.rollover.oldimage($j(this).attr('src')) ); }
      );
   },

   preload: function()
   {
      $j(window).bind('load', function() {
         $j('.ro').each( function( key, elm ) { $j('<img>').attr( 'src', PEPS.rollover.newimage( $j(this).attr('src') ) ); });
      });
   },
   
   newimage: function( src )
   {
      return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_o' + src.match(/(\.[a-z]+)$/)[0];
   },

   oldimage: function( src )
   {
      return src.replace(/_o\./, '.');
   }
};
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
};
var ArrayFnc = {
	Find : function(arr, value) {
		rtn = false;
		for(var i=0; i<arr.length; i++) {
			if(arr[i] == value) {
				rtn = true;	
			}
		}
		return rtn;
	},
	FindArray : function(arr, ray) {
		rtn = false;
		for(var i=0; i<arr.length; i++) {
			if(arr[i].compare(ray)) {
				rtn = true;	
			}
		}
		return rtn;	
	},
	IndexOf : function(arr, value) {
		rtn = -1;
		for(var i=0; i<arr.length; i++) {
			if(arr[i] == value) {
				rtn = i;	
			}
		}
		return rtn;
	},
	IndexOfArray : function(arr, ray) {
		rtn = -1;
		for(var i=0; i<arr.length; i++) {
			if(arr[i].compare(ray)) {
				rtn = i;	
			}
		}
		return rtn;
	},
	Join : function(arr, char) {
		var rtn = "";
		for(var i=0; i<arr.length; i++) {
			if((arr[i] == '' || arr[i] == null) || arr[i] == "undefined") {
			} else {
				if(i == 0) {
					rtn += arr[i];
				} else {
					rtn += (char + arr[i]);
				}
			}
		}
		return rtn;
	},
	DeleteIndex : function(arr, index) {
		var rtn = new Array();
		for(var i=0; i<arr.length; i++) {
			if(i != index) {
				rtn[rtn.length] = arr[i];
			}
		}
		return rtn;
	},
	Delete : function(arr, value) {
		var rtn = new Array();
		for(var i=0; i<arr.length; i++) {
			if(arr[i] != value) {
				rtn[rtn.length] = arr[i];
			}
		}
		return rtn;
	},
	/* 
	gets the value at the index of array 2 that the value is at in array 1
	arr1 = ['dog','cat','mouse','gerbil']
	arr2 = ['loyal','devious','cute','wierd']
	arrayAssociatedValueAt(arr1, arr2, 'mouse') returns 'cute'
	*/
	AssociatedValueAt : function(arr1, arr2, valu) {
		rtn = false;
		for(var i=0; i<arr1.length; i++) {
			if(arr1[i] == valu) {
				rtn = arr2[i];	
			}
		}
		return rtn;
	}
}