function initSearchBox( elem ) {
   
/* search box handling */
	defaultValue = "Search";
	$('.header-top input#text', elem ).focus( function() {
			if ( $(this).val() == defaultValue ) {
				$(this).val("");
			}
		}
	);
	$('.header input#text', elem ).blur( function() {
			if ( $(this).val() == '' ) {
				$(this).val(defaultValue);
			}
		}
	);
}

function parseQueryString( str )
{
    if( typeof str === "undefined" || !str )
        return null;

    if( str.indexOf( '?' ) == 0 )
        str = str.substr( 1 );

    var info = {};

    var pairs = str.split( '&' );
    for( var idx = 0; idx < pairs.length; idx++ ) {
        var keyValue = pairs[idx].split( '=' );
        
        info[keyValue[0]] = keyValue[1];
    }

    return info;
}

function setLoginState( loginInfo )
{
    var customerName = '';
    var hideState    = '.nj-logged-in';
    var showState    = '.nj-logged-out';

    if( loginInfo ) 
    {
        customerName = loginInfo.LabelName;
        hideState    = '.nj-logged-out';
        showState    = '.nj-logged-in';
    }

    // Set customer name
    $( '.nj-cname' ).text( customerName );
    
    // Hide html
    $( hideState ).addClass( 'ui-helper-hidden' );
    
    // Show html
    $( showState ).removeClass( 'ui-helper-hidden' );
    
    // Mark first nav item appropriately
    $( '.navbar .first' ).removeClass( 'first' );
    $( '.navbar li:not(.ui-helper-hidden):eq(0)' ).addClass( 'first' );

    return;
} // setLoginState

function checkLoginStatus()
{
    // Check cookie for login status
    var loginInfoStr = $.cookie( 'NJSBACUSTOMERINFO' );
    var loginInfo = parseQueryString( loginInfoStr ) || {};
    
    // If user is logged in
    if( typeof loginInfo.MasterCustomerId !== 'undefined'
        && loginInfo.MasterCustomerId  )
    {
        setLoginState( loginInfo );
    }

    return;
} // checkLoginStatus


jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
	random: function(a, i, m, r){
		if(i==0){
			jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
		};
		return i == jQuery.jQueryRandom;
	}
});
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function quoteRandomizer(){
	var length = $('.blockquote').length;
	var rand = (Math.random() * length);
	rand -= rand % 1; 
	$($(".blockquote")[rand]).show();
}

/*automatically assign a class:"pdf_link" to all anchors with an href to a pdf*/
function pdfLinkInit(){
	if($('.issues_list_body').length > 0){return;}
	$('a:regex(href,.*\.pdf)').each(function(index, element){
		
		$(element).addClass("pdf_link");
		$(element).append(' (PDF)');
	});
}

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 externalLinkInit(){
	//console.log(location.protocol+"//"+location.host);
	//$('a:regex(href, (?<!'+location.host+').* )').each(function(index, element){
	$('a:not(.target-blank)').each(function(index, element){
		var temp_str = $(element).attr('href');
		if(temp_str == undefined){return;}
		if((temp_str.charAt(0)!= "#" && !temp_str.match(location.host) && temp_str.charAt(0)!="/" && !temp_str.match("tcms.njsba.com") && !temp_str.match("community.njsba.com") && !temp_str.match("mailto:")) || temp_str.match(".pdf")){
			//$(element).css("target-name", "new"); //not support as of yet
			//$(element).css("target-new", "tab"); //not supported as of yet 
			$(element).click(function(){window.open(this.href); return false;});
		}
	});

}

    function initPhotoSlideshow()
    {
        $( '.gallery  a' ).colorbox({
            //loop: false,
            rel: 'group1',
            transition: 'elastic',
            onLoad: function () {
                //positionColorbox();
            },
            onComplete: function () {
                //$(window).unbind('resize.cbox');
                //positionColorbox();
            }/*,
            onOpen: function () {
                $( '#cboxDownload' ).remove();
                var downloadHTML = '<div id="cboxDownload">DOWNLOAD</a>';
                $( '#cboxContent' ).append( downloadHTML );
                $( '#cboxDownload' ).click( function () {
                    var item = $.colorbox.element();
                    var originalImage = item.find( '.original-image' );
                    var originalImageURL = originalImage.text();

                    window.open( originalImageURL );
                    return false;
                } );

            }*/
            
        });

    } // initPhotoSlideshow
 

$(document).ready(function() {

        checkLoginStatus();
	initSearchBox( this );
	if($(".quote_list").length>0){
		quoteRandomizer();
	}
	pdfLinkInit();
    initPopupWindows();
	externalLinkInit();
    initPhotoSlideshow();

        /* Forms - Add required asterisk via JS, because CSS :after no good */
        $( '.form .rtg-widget.required .rtg-input input, '
           + '.form .rtg-widget.required .rtg-input textarea, ' 
           + '.form .rtg-widget.required .rtg-input select', 
           this ).after( '<span class="required-field">*</span>' );

	$(".slideshow-lightbox").colorbox({ width:"574px", height:"690px", iframe:true});

    $( '.comments-label' ).click( function () {
        $( '.comments-content' ).slideToggle();
        return false;
    } );

    $( '.comments' ).frontendForm();
});	

