/*
    Army Jobs Homepage Scripts
	:: Uses jQuery v1.3.2

    Page container object
	:: All functions should sit inside this object
*/
var oAJHome = {
	carouselM1: null,
	carouselM2: null,
	carouselM3: null,
	carousel3Timer: null,
	carousel3Paused: false,
	carousel3Interval: 4000,
	isIE6: false,
	isIE7: false,
	isLteIE7: false,
	armyLearningSiteName: "army-learning",
	// for things that need to happen as soon as possible
	preLoadInit: function() {
		Cufon.now();
		this.isIE6 = ($.browser.msie && parseInt($.browser.version) <= '6');
		this.isIE7 = ($.browser.msie && parseInt($.browser.version) == '7');
		this.isLteIE7 = ($.browser.msie && parseInt($.browser.version) <= '7');
		this.setCufon();
		this.enableStylishSelects();
		this.fixJSOnlyElements();
		if (!this.isLteIE7) $('.jNice').jNice();
		if (this.isIE7) {
		    this.resetIE7LinkWidth();
			this.fixIE7LinkWidth();
		}
	},
	// for things that can happen on DOM load
	postLoadInit: function() {
	    // add mouse over/out events for middle row
		$('#ajMidRow .columnOne').bind('mouseover',function(event) {
			$('#ajMidRow .columnOne .ajHoverText').css({'visibility':'visible'});
		});
		$('#ajMidRow .columnOne').bind('mouseout',function(event) {
			$('#ajMidRow .columnOne .ajHoverText').css({'visibility':'hidden'});
		});
		$('#ajMidRow .columnTwo').bind('mouseover',function(event) {
			$('#ajMidRow .columnTwo .ajHoverText').css({'visibility':'visible'});
		});
		$('#ajMidRow .columnTwo').bind('mouseout',function(event) {
			$('#ajMidRow .columnTwo .ajHoverText').css({'visibility':'hidden'});
		});
		$('#ajMidRow .columnThree').bind('mouseover',function(event) {
			oAJHome.carousel3Paused = true;
		});
		$('#ajMidRow .columnThree').bind('mouseout',function(event) {
			oAJHome.carousel3Paused = false;
			clearInterval(oAJHome.carousel3Timer);
			oAJHome.carousel3Timer = setInterval ( "oAJHome.rotateJob()", oAJHome.carousel3Interval );
		});
		// Add form events
		$('#idJobSearch').bind('submit',function(event) {
			if (!oAJHome.submitJobSearch()) event.preventDefault();
		});
		$('#idRegionSearch').bind('submit',function(event) {
			if (!oAJHome.submitRegionSearch()) event.preventDefault();
		});
		$("#idPostcode").bind("focus", function() {
			if ($("#idPostcode").val() == "Enter postcode") $("#idPostcode").val("");
		});
		$("#idPostcode").bind("blur", function() {
			if ($("#idPostcode").val() == "") $("#idPostcode").val("Enter postcode");
		});
		// load carousels after main page loads - effectively in the background
	    $(window).load(function() {
            oAJHome.initCarousels();
            // adjust for bottom align of carousel 3 details
            $('#ajMidRow .carouselJobs').css({'bottom':'0'});
            // start timer for carousel 3 rotation
            oAJHome.carousel3Timer = setInterval ( "oAJHome.rotateJob()", oAJHome.carousel3Interval );
        });
	},
	setCufon: function(sSelector, bHover) {
		if (this.isIE6) return;
		Cufon.set('fontFamily', 'Univers Condensed Bold');
		// replace all cufon fonts
		if (sSelector == undefined) {
		    Cufon.replace('div#ajHome div#ajBotRow h3')
		    ('div#ajHome .ajNavHover .inside')
		    ('#ajMidRow .carouselContent a.ajMidLink', {
    			hover: true
		    })('#ajMidRow .carouselJobs a.ajMidLink', {
    			hover: true
		    })('#ajTopRow a.ajTopLink', {
    			hover: true
		    });
		// replace specific selector
		} else {
		    Cufon.replace(sSelector, { hover: bHover });
		}
	},
	fixJSOnlyElements: function() {
		$('#ajHome .jsOnlyButton').attr('src','/_layouts/ArmyJobs/HomePage/images/1x1trans.gif');
		$('#ajHome .jsHidden').css({'visibility':'hidden'});
		if ($.browser.msie && parseInt($.browser.version) == '7') {
			$('#ajMidRow .resizeLink .inside').css({'display':'inline'});
		}
	},
	enableStylishSelects: function() {
		$('#idSelQual').sSelect();
		$('#idSelTime').sSelect();
		$('#idSelDist').sSelect();
	},
	initCarousels: function() {
	    // init top 'carousel' items
	    for (i = 0; i < ajArrM0.length; i++) {
			$('#idM0Nav' + i).bind('mouseover', {'i':i,'title':$('#idM0Nav' + i).attr('title')}, function(event) {
				oAJHome.showHoverText('0', event.data.i, event.data.title);
			});
			$('#idM0Nav' + i).attr({'title':''})
			$('#idM0Nav' + i).bind('mouseout', function(event) {
				event.stopPropagation();
				oAJHome.hideHoverText('0');
			});
		}
		this.addCarouselItems('0');
	
	    // init middle row carousel 1
		$('#idCarouselM1').jcarousel({
			initCallback: oAJHome.setCarouselM1,
			start: ajM1Start,
			wrap: 'circular',
			scroll: 1
		});
		$('#idNavM1Next').click(function(event) {
			event.preventDefault();
			oAJHome.carouselNext('1');
		});
		$('#idNavM1Prev').click(function(event) {
			event.preventDefault();
			oAJHome.carouselPrev('1');
		});
		this.addCarouselItems('1');
		
		// init middle row carousel 2
		$('#idCarouselM2').jcarousel({
			initCallback: oAJHome.setCarouselM2,
			start: ajM2Start,
			scroll: 1
		});
		$('#idNavM2Next').click(function(event) {
			event.preventDefault();
			oAJHome.carouselNext('2');
		});
		$('#idNavM2Prev').click(function(event) {
			event.preventDefault();
			oAJHome.carouselPrev('2');
		});
		this.addCarouselItems('2');
		
		// initialise nav icons for carousel 1 & 2
		for (c = 1; c <= 2; c++) {
			for (i = 0; i < oAJHome.getCarouselLength(c); i++) {
				$('#idM' + c + 'Nav' + i).bind('mouseover', {'carouselNum':c,'i':i,'title':$('#idM' + c + 'Nav' + i).attr('title')}, function(event) {
					oAJHome.showHoverText(event.data.carouselNum, event.data.i, event.data.title);
				});
				$('#idM' + c + 'Nav' + i).attr({'title':''})
				$('#idM' + c + 'Nav' + i).bind('mouseout', {'carouselNum':c},function(event) {
					event.stopPropagation();
					oAJHome.hideHoverText(event.data.carouselNum);
				});
			}
		}
		
		// init middle row carousel 3
		$('#idCarouselM3').jcarousel({
			initCallback: oAJHome.setCarouselM3,
			start: ajM3Start,
			scroll: 1
		});
		$('#idNavM3Next').click(function(event) {
			event.preventDefault();
			oAJHome.carouselNext('3');
		});
		$('#idNavM3Prev').click(function(event) {
			event.preventDefault();
			oAJHome.carouselPrev('3');
		});
		this.addCarouselItems('3');
		
		// Initialise nav icons for carousel 3
		for (i = 0; i < oAJHome.getCarouselLength(3); i++) {
			$('#idM3Nav' + i).bind('mouseover', {'carouselNum':'3','i':i,'type':$('#idM3Nav' + i).attr('type')}, function(event) {
				oAJHome.showHoverText(event.data.carouselNum, event.data.i, event.data.type, event.target);
			});
			$('#idM3Nav' + i).bind('mouseout', {'carouselNum':'3'},function(event) {
				event.stopPropagation();
				oAJHome.hideHoverText(event.data.carouselNum, event.target);
			});
			if (!this.isIE6) $('#idM3Nav' + i).attr({'title':''})
		}
	},
	setCarouselM1: function(carousel, state) {
		oAJHome.carouselM1 = carousel;
	},
	setCarouselM2: function(carousel, state) {
		oAJHome.carouselM2 = carousel;
	},
	setCarouselM3: function(carousel, state) {
		oAJHome.carouselM3 = carousel;
	},
	carouselNext: function(carouselNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		if (carousel.first < carousel.options.size) {
		    carousel.next();
		} else {
		    carousel.scroll(1);
		}
		this.setCarouselDetails(carouselNum, carousel.first - 1);
	},
	carouselPrev: function(carouselNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		if (carousel.first > 1) {
		    carousel.prev();
		} else {
		    carousel.scroll(carousel.options.size);
		}
		this.setCarouselDetails(carouselNum, carousel.first - 1);
	},
	carouselSet: function(carouselNum, itemNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		if (carouselNum > 0) {
		    carousel.scroll(itemNum + 1);
		    this.setCarouselDetails(carouselNum, itemNum);
		}
	},
	addCarouselItems: function(carouselNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		eval("var arr = ajArrM" + carouselNum + ";");
		var sHTML;
		if (carouselNum > 0) {
		    if (arr.length > 0) {
    			for (i = 0; i < arr.length; i++) {
				    sHTML = "<img src='" + arr[i].img + "' alt='" + arr[i].alt + "' />";
				    /* add() starts at 1 in Safari/Chrome and 0 in FF/IE */
				    if ($.browser.safari) {
    					carousel.add(i + 1, sHTML);
				    } else {
    					carousel.add(i, sHTML);
				    }
				    $('#idM' + carouselNum + 'Nav' + i).bind('click', {'carouselNum':carouselNum,'i':i}, function(event) {
    					event.preventDefault();
					    oAJHome.carouselSet(event.data.carouselNum, event.data.i)
				    });
			    }
			    carousel.size(i);
		    }
		    // this seems to be required by chrome/safari
		    eval("var startPos = ajM" + carouselNum + "Start;");
		    carousel.scroll(1 ,0);
		    carousel.scroll(startPos ,0);
		} else {
		    if (arr.length > 0) {
			    for (i = 0; i < arr.length; i++) {
				    sHTML = "<img src='" + arr[i].img + "' alt='" + arr[i].alt + "' />";
				    $('#idM0Nav' + i).bind('click', {'i':i}, function(event) {
				    	event.preventDefault();
			    		oAJHome.setCarouselDetails('0', event.data.i);
		    		});
	    		}
    		}
		}
	},
	getCarouselLength: function(carouselNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		return carousel.size();
	},
	getCarouselCurrent: function(carouselNum) {
		eval("var carousel = oAJHome.carouselM" + carouselNum + ";");
		return carousel.first();
	},
	setCarouselDetails: function(carouselNum, itemNum) {
		eval("var arr = ajArrM" + carouselNum + ";");
		if (carouselNum == '0') {
		    // top row - not really a carousel
		    this.resetNavs(carouselNum, ajArrM0.length, itemNum);
		    for (i = 0; i < ajArrM0.length; i++) {
				$('#idTopBG' + i).removeClass('topBackgroundHidden');
				$('#idTopBG' + i).removeClass('topBackgroundCurrent');
				if (i == itemNum) {
					$('#idTopBG' + i).addClass('topBackgroundCurrent');
				} else {
					$('#idTopBG' + i).addClass('topBackgroundHidden');
				}
			}

			var panelContainer = $('#ajHome .topLinkOuter')
			if (ajArrM0[itemNum].url1.indexOf(this.armyLearningSiteName) != -1) {
			    panelContainer.addClass("armyLearningVerticalOffset");
			}
			else {
			    panelContainer.removeClass("armyLearningVerticalOffset");
			}
			
			// set link
			if (ajArrM0[itemNum].buttonStyle == 'Banner1') {
			    var sHTML = '<div class="top-left"></div><div class="top-right"></div><div class="inside" id="idTopLink">';
			    sHTML += '<a href="' + ajArrM0[itemNum].url1 + '" target="'+ajArrM0[itemNum].url1Target+'" class="ajTopLink" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/Carousel/' + ajArrM0[itemNum].link1.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + ajArrM0[itemNum].link1 + ' >></a>';
				sHTML += '</div><div class="bottom-left"></div><div class="bottom-right"></div>';
			    $('#ajHome .topLinkOuter').html(sHTML);
			    // reapply Cufon then fix width for ie7
			    if (this.isIE7) this.resetIE7LinkWidth('#ajHome .topLinkOuter');
			    this.setCufon('#idTopLink', true);
			    if (this.isIE7) this.fixIE7LinkWidth('#ajHome .topLinkOuter');
			} else {
			    var sHTML = '<div class="topCTA">';
			    sHTML += '<a href="' + ajArrM0[itemNum].url1 + '" target="'+ajArrM0[itemNum].url1Target+'" class="ajTopLink" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/Carousel/' + ajArrM0[itemNum].link1.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + ajArrM0[itemNum].link1 + '</a>';
				sHTML += '</div>';
				$('#ajHome .topLinkOuter').html(sHTML);
				this.setCufon('.topCTA', true);
			}
		} else if (carouselNum == '1' || carouselNum == '2') {
			// first 2 carousels on middle row
			this.resetNavs(carouselNum, oAJHome.getCarouselLength(carouselNum), itemNum);

			// set text
			$('#idM' + carouselNum + 'Text').html(arr[itemNum].text);
			// set link
			if (this.isIE7) this.resetIE7LinkWidth('#ajHome .linkM' + carouselNum);
			$('#idM' + carouselNum + 'Link').html('<a href="' + arr[itemNum].url1 + '" id="idM1Link" target="'+arr[itemNum].url1Target+'" class="ajMidLink" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/POD' + carouselNum + '/' + arr[itemNum].link1.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + arr[itemNum].link1 + ' >></a>');
			// reapply Cufon then fix width for ie7
			this.setCufon('#idM' + carouselNum + 'Link', true);
			if (this.isIE7) this.fixIE7LinkWidth('#ajHome .linkM' + carouselNum);
		} else if (carouselNum == '3') {
			// jobs carousel
			// reset navs
			for (i = 0; i < oAJHome.getCarouselLength(carouselNum); i++) {
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndCurrentJob');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndCombat');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndEngineering');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndLogistics');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndIntelligence');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndHR');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndMedical');
				$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndMusic');
				if (i == itemNum) {
					$('#idM' + carouselNum + 'Nav' + i).addClass('navIndCurrentJob');
				} else {
					$('#idM' + carouselNum + 'Nav' + i).addClass('navInd' + arr[i].type);
				}
			}
			// set title & text
			$('#idJobDesc').html(arr[itemNum].text);
			$('#idJobTitle').html('<a href="' + arr[itemNum].url1 + '" target="'+arr[itemNum].url1Target+'" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/POD3/' + arr[itemNum].title.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + arr[itemNum].title + '</a>');
			$('#idJobInterested').html('<a href="' + arr[itemNum].url1 + '" target="'+arr[itemNum].url1Target+'" class="ajMidLink" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/POD3/' + arr[itemNum].link1.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + arr[itemNum].link1 + ' >></a>');
			$('#idJobMore').html('<a href="' + arr[itemNum].url2 + '" class="ajMidLink" onclick="javascript:secondTracker._trackPageview(\'/Homepage/Pages/POD3/' + arr[itemNum].link2.replace(/\ /g, "_").replace(/\'/g, "").replace(/"/g,"").toLowerCase() + '.link\');">' + arr[itemNum].link2 + ' >></a>');
			// reapply Cufon
			this.setCufon('#idJobInterested', true);
			this.setCufon('#idJobMore', true);
		}
	},
	resetNavs: function(carouselNum, carouselLength, itemNum) {
	    for (i = 0; i < carouselLength; i++) {
			$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndCurrent');
			$('#idM' + carouselNum + 'Nav' + i).removeClass('navIndOther');
			if (i == itemNum) {
				$('#idM' + carouselNum + 'Nav' + i).addClass('navIndCurrent');
			} else {
				$('#idM' + carouselNum + 'Nav' + i).addClass('navIndOther');
			}
		}
	},
	resetIE7LinkWidth: function(sSelector) {
	    if (sSelector == undefined) {
	        // reset all - used on page load
		    var links = $('#ajHome .resizeLink');
		} else {
		    // reset specific selector
            var links = $(sSelector);
        }
	    $.each(links, function(link, obj) {
   			$(obj).width('auto');
		    if ($(obj).hasClass('ajNavHover')) $(obj).css({'position':'relative'});
		    $.each(links, function(link, obj) {
   				$(obj).find('.inside').css({'display':'inline'});
		    });
	    });
	},
	fixIE7LinkWidth: function(sSelector) {
        if (sSelector == undefined) {
            // resize all - used on page load
            var links = $('#ajHome .resizeLink');
        } else {
            // reset specific selector
            var links = $(sSelector);
        }
	    $.each(links, function(link, obj) {
   			var width = $(obj).find('.inside').width();
		    $(obj).width(width + (parseInt($(obj).find('.inside').css('padding-left')) * 2));
		    if ($(obj).hasClass('ajNavHover')) $(obj).css({'position':'absolute'});
		    $(obj).find('.inside').css({'display':'inline-block'});
		    $(obj).find('.inside').width(width);
	    });
	},
	showHoverText: function(carouselNum, item, title, obj) {
		if (carouselNum < 3) {
			if (this.isIE7) this.resetIE7LinkWidth('#idNavHover' + carouselNum);
			eval("var arr = ajArrM" + carouselNum + ";");
			$('#idNavHover' + carouselNum + ' .inside').html(arr[item].hover);
			$('#idNavHover' + carouselNum).css({'visibility':'visible'});
			// reapply Cufon then fix width for IE7
			this.setCufon('#idNavHover' + carouselNum + ' .inside', false);
			if (this.isIE7) this.fixIE7LinkWidth('#idNavHover' + carouselNum);
		} else {
			$(obj).find('div').css({'display':'inline-block'});
		}
	},
	hideHoverText: function(carouselNum, obj) {
	    if (carouselNum < 3) {
		    $('#idNavHover' + carouselNum).css({'visibility':'hidden'});
		} else {
		    $(obj).find('div').css({'display':'none'});
		}
	},
	rotateJob: function() {
	    if (!oAJHome.carousel3Paused) {
	        $('#idNavM3Next').click();
	    }
	},
	submitJobSearch: function() {
	    var isError = false;
	    if ($('#idSelQual').attr('selectedIndex') == 0) {
	        $('#ajHome .jobError').html('*Please select<br />&nbsp;qualification');
	        return false;
	    } else if (!$('#idMale').attr('checked') && !$('#idFemale').attr('checked')) {
	        $('#ajHome .jobError').html('*Please select<br />&nbsp;gender');
	        return false;
	    }
	    $('#ajHome .jobError').html('');
	    secondTracker._trackPageview('/Homepage/Pages/Job_search/Find_me_a_job.link');
	    return true;
	},
	submitRegionSearch: function() {
	    var isError = false;
	    if ($('#idPostcode').val() == '' || $('#idPostcode').val() == 'Enter postcode') {
	        $('#ajHome .regionError').html('*Please enter postcode');
	        return false;
	    }
	    $('#ajHome .regionError').html('');
	    secondTracker._trackPageview('/Homepage/Pages/Meet_us/Search.link');
	    return true;
	}
}

/*
    General onload function
*/
$(document).ready(function() {
	oAJHome.postLoadInit();
});

/*
 * jNice
 * version: 1.0 (11.26.08)
 * by Sean Mooney (sean@whitespace-creative.com) 
 * Examples at: http://www.whitespace-creative.com/jquery/jnice/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * To Use: place in the head 
 *  <link href="inc/style/jNice.css" rel="stylesheet" type="text/css" />
 *  <script type="text/javascript" src="inc/js/jquery.jNice.js"></script>
 *
 * And apply the jNice class to the form you want to style
 *
 * To Do: Add textareas, Add File upload
 *
 ******************************************** */
(function($){
	$.fn.jNice = function(options){
		var self = this;
		return this.each(function(){
			$('input:radio', this).each(RadioAdd);
			$('.jNiceHidden').css({opacity:0});
		});		
	};/* End the Plugin */

	var RadioAdd = function(){
		var $input = $(this).addClass('jNiceHidden').wrap('<span class="jRadioWrapper jNiceWrapper"></span>');
		var $wrapper = $input.parent();
		var $a = $('<span class="jNiceRadio"></span>');
		$wrapper.prepend($a);
		/* Click Handler */
		$a.click(function(){
				var $input = $(this).addClass('jNiceChecked').siblings('input').attr('checked',true);
				/* uncheck all others of same name */
				$('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
					$(this).attr('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
				});
				return false;
		});
		$input.click(function(){
			if(this.checked){
				var $input = $(this).siblings('.jNiceRadio').addClass('jNiceChecked').end();
				/* uncheck all others of same name */
				$('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
					$(this).attr('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
				});
			}
		}).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });

		/* set the default state */
		if (this.checked){ $a.addClass('jNiceChecked'); }
	};
})(jQuery);