$(function(){
    rotateTopBanner();
	careerSelector();
	map();
	contentScroll();
	gridList();
	//pf();
	pageCurl();
	showPopup();
	featuredEmployerScroll();
	
	setTimeout(function(){
        if( $('.scrollable').size() )
            $('.scrollable').jScrollPane();
    }, 300);

});

function showPopup(){
    if(!$('#popup-content').size())
        return;
    
    var 
        box = $('#container .content'),
        offset = box.offset(),
        top = offset.top + 10,
        left = offset.left + 10,
        height = parseInt(box.height()),
        width = parseInt(box.width());
        
    $.openDOMWindow({
        'windowSourceID': '#popup-content',
        'width': (width - 40),
        'height': (height - 40),
        'overlayOpacity': 50,
        'borderSize': 0,
        'positionType': 'fixed',
        'positionTop': top,
        'positionLeft': left
    });
    
    $('#popup-content-wrapper').jScrollPane();
}

function careerSelector(){
	var slideWidth = 42,
	    slides = $('#selector ul li'),
	    numberOfSlides = slides.size(),
	    Width = (Math.round(numberOfSlides*slideWidth)),
	    currentPosition = 0;
	    
	// Wrap all slides with #slideInner div
	$('#selector ul').wrapAll('<div id="slideOuter"><div id="slideInner"></div></div>');
	$('#selector').append('<dfn></dfn>');
	$('#slideInner ul').css('width', Width);
	// Remove scrollbar in JS
	$('#slideInner').css('overflow', 'hidden');
	// Insert left and right arrow controls in the DOM
	$('#selector').prepend('<span class="control" id="leftControl"></span>').append('<span class="control" id="rightControl"></span>');
	// Hide left arrow control on first load
	manageControls(currentPosition);
	setText();
	
	// Create event listeners for .controls clicks
	$('.control').bind('click', function(){
		// Determine new position
		currentPosition = ($(this).attr('id')=='rightControl')
		? currentPosition+1 : currentPosition-1;
		// Hide / show controls
		manageControls(currentPosition);
		
		// Move slideInner using margin-left
		$('#slideInner ul').animate({
			'marginLeft' : slideWidth*(-currentPosition)
		},500);
		setText();
	});
	
	function setText(){
		$('#selector dfn').text($('#slideInner ul li:eq('+currentPosition+') a').attr('title'));
	}
	
	// manageControls: Hides and shows controls depending on currentPosition
	function manageControls(position){
		// Hide left arrow if position is first slide
		position == 0 
		    ? $('#leftControl').hide() 
		    : $('#leftControl').show();
		    
		// Hide right arrow if position is last slide
		position == (numberOfSlides-1) 
		    ? $('#rightControl').hide() 
		    : $('#rightControl').show();
	}	

}

// map hover 

function map() {
	$('#Map area').each(function(i){
		$(this).addClass("item" + (i+1));
		$('.item'+(i+1)).mouseenter(function() 
		{
			$('#mapBkg').css('background-position',-(141*(i+1)) + 'px')
			$('#title').css('background-image','text'+(i+1))
		});
		$('.item'+(i+1)).mouseleave(function() 
		{
			$('#mapBkg').css('background-position','0px')
			$('#title').css('background-image','none')
		});
	});
}

//content scroller
function contentScroll(){
	var slideHeight = 110;
	var cSlides = $('#grid li');
	var cNumberOfSlides = cSlides.length;
	var cHeight = cNumberOfSlides*slideHeight;
	var cCurrentPosition = 0;

	// Wrap all slides with #slideInner div
	$('#grid').wrapAll('<div id="heightWrap"></div>');
	$('#grid').css('height', cHeight);
	// Remove scrollbar in JS
	$('#heightWrap').css('overflow', 'hidden');
	$('#heightWrap').css('height', 330);
	// Insert left and right arrow controls in the DOM
	$('#twoColDir2').prepend('<span class="control" id="topControl"></span>').append('<span class="control" id="bottomControl"></span>');
	// Hide left arrow control on first load
	cManageControls(cCurrentPosition);
	
	// Create event listeners for .controls clicks
	$('.control').bind('click', function(){
		// Determine new position
		cCurrentPosition = ($(this).attr('id')=='bottomControl')
		? cCurrentPosition+1 : cCurrentPosition-1;
		// Hide / show controls
		cManageControls(cCurrentPosition);
		
		// Move slideInner using margin-left
		$('#grid').animate({
			'marginTop' : slideHeight*(-cCurrentPosition)
		},500);
	});
	// manageControls: Hides and shows controls depending on currentPosition
	function cManageControls(position){
		// Hide left arrow if position is first slide
		if(position==0){ 
			$('#topControl').hide() }
		else{ $('#topControl').show() }
		//alert(numberOfSlides);
		// Hide right arrow if position is last slide
		if(position==(cNumberOfSlides/3)-3){ 
			$('#bottomControl').hide() }
		else{ $('#bottomControl').show() }
	}	

}

// allows list to degrade to be viewable with javascript disabled
function gridList(){
	$('.hide').css('display','none');
	$('#grid li').css( {'float':'left','width': 110+'px','height': 110+'px'} );
	$('#grid li a').css('position','absolute');
}

// prettyPhoto setup
function pf() {
	$("a[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		opacity: 0.80, /* Value between 0 and 1 */
		showTitle: true, /* true/false */
		theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
		wmode: 'opaque', /* Set the flash wmode attribute */
		hideflash: true /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
	});
}

function featuredEmployerScroll() {
    if( !$('#employersDirectory').size() )
        return;
        
    var container = $('#employersDirectory #fe-list'),
        items = $('li', container),
        total = items.size(),
        current = -1;
    
    function next(){
        current += 1;
        if( current == total )
            current = 0;
        $('li:visible', container).fadeOut('slow');
        $('li:eq('+current+')', container).fadeIn('slow');
    }
    
    next();
    setInterval(next, 5000);
    
}

function pageCurl() {
    $('#page-corner a').append('<img src="/images/bkg/page-curl.png" class="curl" />');
    
    
    $("#page-corner a").hover(function() {
    
        //Animate and expand the image
        $("#page-corner a, #page-corner a img.curl")
            .stop()
            .animate({ 
                width: '150px',
                height: '150px'
            }, 500);
        } , function() {

        //On hover out, go back to original size
        $("#page-corner a img.curl")
            .stop() 
            .animate({
                width: '75px',
                height: '75px'
            }, 150);
            
        $("#page-corner a")
            .stop() 
            .animate({
                width: '75px',
                height: '75px'
            }, 150);        

    });
    
}


function validate_signup(frm) 
{
    var emailAddress = frm.Email.value, 
        errorString = '',
        els = frm.getElementsByTagName('input');

    if (emailAddress == '' || emailAddress.indexOf('@') == -1)
        errorString = 'Please enter your email address';

    for (var i = 0; i < els.length; i++)
    {

        if( els[i].className == 'text' || 
            els[i].className == 'date' || 
            els[i].className == 'number' )
        {

            if (els[i].value == '')
                errorString = 'Please complete all required fields.';

        }
        else if (els[i].className == 'radio')
        {

            var toCheck = document.getElementsByName(els[i].name),
                radioChecked = false;

            for (var j = 0; j < toCheck.length; j++)
            {

                if (toCheck[j].name == els[i].name && toCheck[j].checked)
                    radioChecked = true;

            }

            if (!radioChecked)
                errorString = 'Please complete all required fields.';

        }
    }

    var isError = false;

        if (errorString.length > 0)
            isError = true;

    if (isError)
        alert(errorString);

    return !isError;
}

function rotateTopBanner()
{
    
    var timeout = 15, //seconds
        current = 0,
        bannerTimeout = null,
        container = jQuery('#header #advert'),
        items = jQuery('a', container),
        count = jQuery('a', container).size();        
        
    function doRotate() {
        if( current == count )
            current = 0;
            
        items.hide(0);
        jQuery('a:eq('+current+')', container).show(0);
        
        current += 1;
        
        clearTimeout(bannerTimeout);
        bannerTimeout = setTimeout(doRotate, timeout * 1000);
    }

    if( count > 1 )
        doRotate();
}
