jQuery(document).ready(function () {
    if (document.getElementById('primaryNav')) { navHover(); }
    //    if (document.getElementById('bgStage')) { setBgSlider(); }
    if (document.getElementById('window')) { setWindowPromotionBoxClick(); }
    if (document.getElementById('flyoutWrap')) { setFlyout(); }
    if (document.getElementById('newsSignup')) { newsLetterFlyout(); }
    if (document.getElementById('tabNav')) { tabNav(); }
    if (document.getElementById('homeSlider')) { homeSlider(); }
    if (document.getElementById('tipTripWindow')) { tripTipSlider(); }
    if (document.getElementById('embedOverlay')) { setEmbedClick(); }

    if (jQuery('a.embedOverlay')[0]) { setEmbedClick(); videoSlideShow(); }

    if (jQuery('div.actionShots')[0]) { actionSlideShow(); }
    if (jQuery('a.popup')[0]) { setProdPopups(); }
    if (jQuery('div.colorOptions')[0]) { colorOpt(); }
    if (jQuery('.clearOnFocus')[0]) { jQuery('.clearOnFocus').clearOnFocus(); }
    if (jQuery('.familyBox')[0]) { setDivClicks(); }

    if (jQuery('.pageNav')[0]) { setLiHovers(); }

    jQuery('.search input').clearOnFocus();
    jQuery('.search input').enterKey('.search a');
    if (document.getElementById('locator')) {
        createLocator();
    }
    if (document.getElementById('servicelocator')) {
        createServiceLocator();
    }

    if (document.getElementById('newsSignup')) {
        jQuery(window).resize(function () {
            var flyoutHeight = jQuery('#newsFlyoutWrap').height();
            var linkPos = jQuery('#newsSignup').offset();

            jQuery('#newsFlyoutWrap').css({
                'left': linkPos.left,
                'top': (linkPos.top - flyoutHeight)
            });
        });
    }

    if (document.getElementById('mapWrap')) {
        jQuery(window).load(function () {
            setTimeout(function () {
                jQuery('#mapBgImage').animate({ 'opacity': 1 }, function () {
                    jQuery('#mapWrap ul').animate({ 'opacity': 1 },
					function () {
					    setMapHovers();
					});
                });
            }, 1000);
        });
    }

});

function setLiHovers() {
    var li = jQuery('div.pageNav ul > li');

    li.hover(
    function(){
        jQuery(this).addClass('hovered');
    },
    function(){
        jQuery(this).removeClass('hovered');
    });
}

function setWindowPromotionBoxClick() {
    $('#homeSlider .popup').live("click", function () {
        var destination = $(this).find('a.readMore').attr('href');
        if (destination) {
            document.location.href = destination;
        }
    });
}

function Search() {
    jQuery("#inputSearchActive").val('yes');
    window.location = "/search.aspx?s=" + escape(jQuery("#inputMasterSearchSite").val());
}

function setMapHovers() {
    var li = jQuery('li.hotSpot'),
		mapOverlay = jQuery('#mapOverlay'),
		mapBgImg = jQuery('#mapBgImage'),
		extLinks = jQuery('ul.ext a'),
		numClicked, numHovered;

    setHover();

    function setHover() {
    	li.bind({
    		mouseenter: function () {
    			numHovered = jQuery.inArray(this, li);
    			mapOverlay.addClass('numHovered_' + numHovered);
    			li.addClass('notHovered');
    			jQuery(this).removeClass('notHovered');

    		},
    		mouseleave: function () {
    			mapOverlay.removeClass('numHovered_' + numHovered);
    			li.removeClass('notHovered');
    			jQuery('#staticWrap').toggleClass('change');
    		}
    	});
    }

    li.click(function () {

    	li.unbind('mouseenter');
    	li.unbind('mouseleave');

    	mapBgImg.css('opacity', .25);

    	li.addClass('notActive');
    	jQuery(this).removeClass('notActive');

    	li.removeClass('notHovered');
    	li.removeClass('active');
    	jQuery(this).addClass('active');

    	mapOverlay[0].className = '';

    	numClicked = jQuery.inArray(this, li);

    	mapOverlay.addClass('numClicked_' + numClicked);

    });

    jQuery(document).click(function (e) {
    	var id = e.target.id;
    	var cl = e.target.className;
    	if (id == 'mapOverlay' || id == 'staticWrap' || cl == 'wrap') {
    		mapOverlay[0].className = '';
    		li.removeClass('active');
    		li.removeClass('notActive');
    		li.removeClass('notHovered');
    		mapBgImg.css('opacity', '1');
    		setHover();
    	}
    });

    extLinks.click(function (e) {
    	e.preventDefault();

    	li.unbind();
    	extLinks.unbind();

    	var self = this;
    	jQuery(this).animate({ 'opacity': 1 }, function () {

    		jQuery('.notActive').animate({ 'opacity': 0 });

    		mapBgImg.animate({ 'opacity': 0 }, function () {

    			var checkbox = document.getElementById('remember');
    			var id = self.href.substring(self.href.lastIndexOf('=') + 1, self.href.length);
    			if (checkbox != null & checkbox.checked) {
    				Set_Cookie('NeckyLanguage', id, 500, '/', null, null);
    			} else {
    				Set_Cookie('NeckyLanguage', id, null, '/', null, null);
    			}

    			jQuery(self).stop();
    			jQuery('.notActive').stop();
    			jQuery(this).stop();

    			var referrer = jQuery('#ReferrerField').val();
    			if (referrer != null & referrer != '') {
    				window.location = referrer;
    			} else {
    				window.location = self.href;
    			}
    		});

    	});
    });

}

function NewCaptchaCode() {
    jQuery.ajax({
        async: true,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservice.asmx/NewCaptchaCode",
        data: "{}",
        dataType: "json",
        success: function (result, textStatus) {
            jQuery('#imgCaptcha').attr("src", "/Captcha.aspx?" + result.d);
        },
        error: function (request, status, err) {
            alert('failure - ' + status + ' ' + err);
        },
        complete: function (XMLHttpRequest, textStatus) {
            return false;
        }
    });
}

function getQuery(param) {
    var p = escape(unescape(param));
    var regex = new RegExp("[?&]" + p + "(?:=([^&]*))?", "i");
    var match = regex.exec(window.location.search);
    var value = null;
    if (match != null) {
        value = match[1];
    }
    return value;
}

jQuery(window).load(function () {
    if (document.getElementById('bgStage')) { setBgSlider(); }
});

var jsNeckyDealerId;

function createLocator() {
    Map = new DealerMap();
    Map.brand = jsNeckyDealerId;
    Map.initialLocation = 'Oklahoma';
    Map.loadMap();
    
}
function createServiceLocator() {
    Map = new DealerMap();
    Map.brand = jsNeckyDealerId;
    Map.initialLocation = 'Oklahoma';
    Map.featureFilter = [3];
    Map.loadMap();
}

function submitAddress() {
    if (document.getElementById('locator')) {
        createLocator();
    }
    if (document.getElementById('servicelocator')) {
        createServiceLocator();
    }
    Map.showAddress(jQuery('#g_address').val(), jQuery('#g_distance').val());
}


function setDivClicks() {
    jQuery('.familyBox').click(function () {
        window.location = jQuery(this).find('.boxImage a')[0].href;
    });
}

function setEmbedClick() {
    var a = $('a.embedOverlay');
    a.click(function (e) {
        e.preventDefault();
        renderFlash(this.href);
     //   this.style.display = 'none';
    });
}

function onYouTubePlayerReady() {
    if (document.getElementById('theVideo') && document.getElementById('embedOverlay')) {
        document.getElementById('theVideo').playVideo();
    }
}


function renderFlash(url) {
    $('div#embedCode').css('display', 'block');
    $('a.embedOverlay').css('display', 'none');
    var params = { allowScriptAccess: "always", wmode: "transparent" };
    var atts = { id: "theVideo" };

    if (url.indexOf('?') > 0) {
        url = url + '&';
    }
    else {
        url = url + '?';
    }

    swfobject.embedSWF(
		url + 'enablejsapi=1&playerapiid=ytVideo',
		'ytVideo',
		'365',
		'204',
		'8',
		null, null,
		params,
		atts
	);
    
}

function uploadValidation() {
    var inputs = jQuery('.uploadLeft input[type=text]:not(".disabledForm input[type=text]")'),
        inputs = inputs.add('#requiredPhoto'),
		email = jQuery('.uploadLeft .email'),
		submit = jQuery('.accept .bigOrangeButton'),
		agree = jQuery('#agree'),
		capCode = jQuery('#capCode').html(),
		capContain = jQuery('.captcha'),
		capInput = jQuery('#captchaInput'),
		errorCnt = 0, errors = [], terms = '',
		emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/ig;

    submit.unbind();

    submit.click(function (e) {
        jQuery('.uploadLeft .errors').remove();
        jQuery('.uploadRight .errors').remove();
        errors = [];
        errorCnt = 0;
        terms = '';
        inputs.each(function () {
            if (this.className.match('email')) {
                if (this.value == this.defaultValue) {
                    errorCnt++;
                    if(this.className.match('submitter')){
                        errors.push(' Submitter\'s email');
                    }
                    if(this.className.match('photographer')){
                        errors.push(' Photographer\'s email');
                    }
                }
                else if (!this.value.match(emailRegex)) {
                    errorCnt++;
                    if(this.className.match('submitter')){
                        errors.push(' Valid submitter\'s email');
                    }
                    if(this.className.match('photographer')){
                        errors.push(' Valid photographer\'s email');
                    }
                }
            }
            else if (this.value == this.defaultValue || this.id == 'requiredPhoto') {
                if (this.id == 'requiredPhoto') {
                    if (this.value == '') {
                        errorCnt++;
                        errors.push(' A required photo');
                    }
                }
                else {
                    if (this.className.match('submitter')) {
                        errorCnt++;
                        errors.push(' Submitter\'s ' + this.value);
                    }
                    if (this.className.match('photographer')) {
                        errorCnt++;
                        errors.push(' Photographer\'s ' + this.value);
                    }
                    if (this.className.match('generic')) {
                        errorCnt++;
                        errors.push(' ' + this.value);
                    }
                }
            }
        });

        if (!agree[0].checked) {
            if (errors.length == 0) {
                errors.push(' Please agree to our terms');
            }
            else {
                errors.push(' Please agree to our terms');
            }
            errorCnt++;
        }

        if (capInput[0].value == '' || capInput[0].value != capCode) {
            errorCnt++;
            capContain.append('<div class="errors">Please enter the correct security code.</div>');
        }

        if (errorCnt > 0) {
            e.preventDefault();
            if (errors.length > 0) {
                jQuery('.uploadLeft').append('<div class="errors"><strong>* The following fields are required:</strong>' + errors + terms + '</div');
            }
        }
        /*else {
        e.preventDefault();
        alert('valid');
        }*/
    });
}

function tripTipSlider() {
    var slider = $('#tipTripWindow>ul'),
		slides = slider.find('>li'),
		fiv = 0,
		starting = slider.find('>li.selected'),
		imgAchr = slides.find('a.swap'),
	//	leftAll = $('#leftAll'),
	//	rightAll = $('#rightAll'),
		next = $('#next'),
		prev = $('#prev'),
		imgContain = $('#fullImage'),
		contentContain = $('#contentHolder'),
		curPos = 0, newPos, moving = false,
		viewWidth = 143 * 6,
		slideLen = slides.length,
		slidesWidth = slideLen * 143,
		maxLength = slidesWidth - viewWidth,
		wantedImg, wantedContent, numInFront, posOfFiv;

    setup();

    function setup() {
        wantedImg = starting.find('.swap').html();
        wantedContent = starting.find('.hiddenDetails').html();

        slider.css('width', slidesWidth);
        fiv = $.inArray(starting[0], slides);

        if (slideLen > 6 && (slideLen - fiv) < 6) {

            var numShowing = slideLen - fiv;

            fiv = fiv - (6 - numShowing);
            curPos = -(fiv * 143);
            slider.css('left', curPos);

            imgContain.html(wantedImg);
            contentContain.html(wantedContent);

            slides.eq(fiv)[0].id = 'firstInView';
        }

        else {

            if (slideLen > 6) {

                curPos = -(fiv * 143);
                slider.css('left', curPos);

                imgContain.html(wantedImg);
                contentContain.html(wantedContent);

                slides.eq(fiv)[0].id = 'firstInView';

            }

            else {

                next.css('visibility', 'hidden');
                prev.css('visibility', 'hidden');

                curPos = 0;
                slider.css('left', curPos);

                imgContain.html(wantedImg);
                contentContain.html(wantedContent);

                slides.eq(fiv)[0].id = 'firstInView';

            }

        }

        if ($('.tripPhoto')[0]) {
            setSwapForThumbs();
        }
    }

    //dynimically generate <div class="title">	
    slides.each(function () {
        var thisA = $(this).find('.swap');
        var title = thisA[0].title;
        thisA.after('<div class="title">' + title + '</div>');
    });

    imgAchr.hover(
		function () {
		    $(this).next('.title').css('display', 'block');
		},
		function () {
		    $(this).next('.title').css('display', 'none');
		}
	);

    imgAchr.click(function (e) {
        e.preventDefault();

        slides.removeClass('selected');
        $(this).parent('li').addClass('selected');

        wantedImg = $(this).html();
        wantedContent = $(this).parent().find('.hiddenDetails').html();

        imgContain.html(wantedImg);
        contentContain.html(wantedContent);

        if ($('.tripPhoto')[0]) {
            setSwapForThumbs();
        }
    });

    function setSwapForThumbs() {
        var thumbA = $('.photoThumbs a');

        thumbA.eq(0).addClass('selected');
        thumbA.click(function (e) {
            e.preventDefault();
            thumbA.removeClass('selected');
            $(this).addClass('selected');
            imgContain.html($(this).html());
        });
    }

    //	rightAll.click(function(e){
    next.click(function (e) {
        e.preventDefault();
        if (!moving && curPos >= -maxLength) {

            moving = true;
            posOfFiv = $.inArray($('#firstInView')[0], slides);
            numInFront = slideLen - (posOfFiv + 1);
            //	console.log('right clicked: numInFront=' + numInFront);
            if (curPos == -maxLength) {
                newPos = 0;
                curPos = newPos;
                slider.animate({ left: newPos }, function () {
                    slides.attr('id', '');
                    fiv = 0;
                    slides.eq(fiv)[0].id = 'firstInView';
                    moving = false;
                });
            }
            else {
                if (numInFront <= 11 && numInFront > 5) {
                    newPos = curPos - ((numInFront - 5) * 143);
                    curPos = newPos;
                    slider.animate({ left: newPos }, function () {
                        slides.attr('id', '');
                        fiv = slideLen - 6;
                        slides.eq(fiv)[0].id = 'firstInView';
                        moving = false;
                    });
                }
                else {
                    newPos = curPos - viewWidth;
                    curPos = newPos;
                    slider.animate({ left: newPos }, function () {
                        slides.attr('id', '');
                        fiv += 6;
                        slides.eq(fiv)[0].id = 'firstInView';
                        moving = false;
                    });
                }
            }
        }
    });

    //	leftAll.click(function(e){
    prev.click(function (e) {
        e.preventDefault();
        if (!moving) {
            moving = true;
            posOfFiv = $.inArray($('#firstInView')[0], slides);
            numBehind = posOfFiv;
            if (curPos === 0) {
                newPos = -maxLength;
                curPos = newPos;
                slider.animate({ left: newPos }, function () {
                    slides.attr('id', '');
                    fiv = slideLen - 6;
                    slides.eq(fiv)[0].id = 'firstInView';
                    moving = false;
                });
            }
            else {
                if (numBehind >= 6) {
                    newPos = curPos + viewWidth;
                    curPos = newPos;
                    slider.animate({ left: newPos }, function () {
                        slides.attr('id', '');
                        fiv = numBehind - 6;
                        slides.eq(fiv)[0].id = 'firstInView';
                        moving = false;
                    });
                }
                else {
                    newPos = 0;
                    curPos = newPos;
                    slider.animate({ left: newPos }, function () {
                        slides.attr('id', '');
                        fiv = 0;
                        slides.eq(fiv)[0].id = 'firstInView';
                        moving = false;
                    });
                }
            }
        }
    });
    /*
    next.click(function(e){
    e.preventDefault();
    if(!moving && curPos > -maxLength){
    moving = true;
    newPos = curPos - 143;
    curPos = newPos;
    slider.animate({left: newPos}, function(){
    fiv++;
    slides.attr('id', '');
    slides.eq(fiv)[0].id = 'firstInView';
    moving = false;
    });
    }
    });
    prev.click(function(e){
    e.preventDefault();
    if(!moving && curPos != 0){
    moving = true;
    newPos = curPos + 143;
    curPos = newPos;
    slider.animate({left: newPos}, function(){
    fiv--;
    slides.attr('id', '');
    slides.eq(fiv)[0].id = 'firstInView';
    moving = false;
    });
    }
    });
    */
}

function homeSlider() {
    var wrap = jQuery('#homeSliderWrap'),
		homeSlider = jQuery('#homeSlider'),
		next = jQuery('#nextSlide'),
		prev = jQuery('#prevSlide'),
		slider = jQuery('#window>ul'),
		slides = slider.find('>li'), goToNext = false,
		popups = wrap.find('.popup'), popupHovered = false, moving = false;

    var curPos = -17, firstInView = 0;
    var maxLength = ((slides.length - 3) * 317) + 17;

    setViews();
    setHovers();

    next.click(function (e) {
        e.preventDefault();
        if (!moving /* && !checkPopStates()*/) {
            moving = true;
            if (curPos === -maxLength) {
                newPos = -17;
                curPos = newPos;
                firstInView = 0;
            }
            else {
                firstInView++;
                newPos = curPos - 317;
                curPos = newPos;
            }
            slider.animate({ 'left': newPos },
				function () {
				    setViews();
				    setHovers();
				    moving = false;
				}
			);
        }
    });

    prev.click(function (e) {
        e.preventDefault();
        if (!moving /* && !checkPopStates()*/) {
            moving = true;
            if (curPos === -17) {
                newPos = -maxLength;
                curPos = newPos;
                firstInView = slides.length - 3;
            }
            else {
                firstInView--;
                newPos = curPos + 317;
                curPos = newPos;
            }
            slider.animate({ 'left': newPos },
				function () {
				    setViews();
				    setHovers();
				    moving = false;
				}
			);
        }
    });

    function checkPopStates() {
        var pu = jQuery('.popup'), open;
        pu.each(function () {
            if (jQuery(this).css('display') == 'block') {
                open = true;
            }
            else {
                open = false;
            }
        });
        return open;
    }

    var popMotion = false, goToNext = false, nextUp, inViews, wait, waitAgain, oneMovingNow;

    homeSlider.mouseleave(function () {
        popupHovered = false;
        clearTimeout(wait);
        clearTimeout(waitAagin);
        nextUp = null,
		goToNext = false;
    });

    popups.mouseleave(function () {
        clearTimeout(waitAgain);
        clearTimeout(wait);
		$(this).stop().animate({top: 0}, 150,
			function(){
				homeSlider[0].className = '';
				$(this).css('display','none');
				inViews.eq(oneMovingNow).find('.popupContent').css('visibility','visible');
			}
		);
	});

    jQuery('#bgStage').mouseover(function () { closeOpenPopup(); });
    next.mouseover(function () { closeOpenPopup(); });
    prev.mouseover(function () { closeOpenPopup(); });
    jQuery(document).mouseleave(function () { closeOpenPopup(); });

    function closeOpenPopup() {
        clearTimeout(waitAgain);
        clearTimeout(wait);
        popups.eq(oneMovingNow).stop().animate({ top: 0 }, 150,
		    function () {
		        homeSlider[0].className = '';
		        jQuery(this).css('display', 'none');
		        inViews.eq(oneMovingNow).find('.popupContent').css('visibility', 'visible');
		    }
        );
    }

    function setHovers() {
        var wanted;
        inViews = slider.find('.inView');

        popups.eq(0).html(inViews.eq(0).html());
        popups.eq(1).html(inViews.eq(1).html());
        popups.eq(2).html(inViews.eq(2).html());

        // remove the hovered events previous attached
        inViews.unbind();

        inViews.mouseenter(
			function () {
			    if (!moving) {
			        if (popupHovered) {
			            clearTimeout(wait);
			            popupHovered = false;
			            goToNext = true;
			            nextUp = jQuery.inArray(this, inViews);
			        }
			        if (!popupHovered/* && !popMotion*/) {
			            clearTimeout(wait);
			            clearTimeout(waitAgain);
			            goToNext = false;
                        popupHovered = true;
			            wanted = jQuery.inArray(this, inViews);
			            wait = setTimeout(function () {
			                popItOut(wanted);
			            }, 400);
			        }
			    }
			}
		);
    }

    function popItOut(needed) {

        oneMovingNow = needed;    

        inViews.eq(needed).find('.popupContent').css('visibility', 'hidden');

        popMotion = true;
        homeSlider[0].className = 'hover' + (needed + 1);

        popups.eq(needed).css('display', 'block').stop().animate({ top: -104 }, 150,
		  function () {
		      popups.eq(needed).unbind();
		      popups.eq(needed).mouseleave(function () {
		          popups.eq(needed).stop().animate({ top: 0 }, 150,
						function () {
						    homeSlider[0].className = '';
						    popupHovered = false;
						    inViews.eq(needed).find('.popupContent').css('visibility', 'visible');
						    popups.eq(needed).css('display', 'none');
						    popMotion = false;
						    if (goToNext) {
						        clearTimeout(waitAgain);
						        clearTimeout(wait);
						        popupHovered = true;
						        waitAgain = setTimeout(function () {
						            popItOut(nextUp);
						        }, 400);
						        goToNext = false;
						    }
						}
					);
		      });
		  }
		);
    }

    function setViews() {
        slides.removeClass('inView');
        for (var i = 0; i < 3; i++) {
            slides.eq(firstInView + i).addClass('inView');
        }
    }
}

function videoSlideShow() {
    var a = $('.videoShotControls a').not('#prevVid, #nextVid'),
		next = $('#nextVid'), prev = $('#prevVid'),
		img = $('.videoShots a.embedOverlay'),
		sel = 0, fading = false;

    if (a.length > 1) {

        img.eq(sel).css('z-index', '2');

        a.click(function (e) {
            e.preventDefault();
            if (!fading && sel != $.inArray(this, a)) {
                sel = $.inArray(this, a);
                changeImg();
            }
        });

        next.click(function (e) {
            e.preventDefault();
            if (!fading) {
                if (sel == a.length - 1) { sel = 0; }
                else { sel++; }
                changeImg();
            }
        });

        prev.click(function (e) {
            e.preventDefault();
            if (!fading) {
                if (sel == 0) { sel = a.length - 1; }
                else { sel--; }
                changeImg();
            }
        });

        function changeImg() {
            fading = true;
            $('#embedCode').html('');
            $('#embedCode').html('<div id="ytVideo"></div>');
            img.css('display', 'block');
            a.removeClass('selected');
            a.eq(sel).addClass('selected');
            img.eq(sel).css({
                'opacity': 0,
                'z-index': 3
            }).animate({ 'opacity': 1 }, function () {
                img.not(img.eq(sel)).css('z-index', '1');
                img.eq(sel).css('z-index', '2');
                fading = false;
            });
        }
    }
    else { $('.videoShotControls').css('display', 'none'); }
}

function actionSlideShow() {
    var a = jQuery('.actionShotControls a').not('#prev, #next'),
		next = jQuery('#next'), prev = jQuery('#prev'),
		img = jQuery('.actionShots img'),
		sel = 0, fading = false;

    if (a.length > 1) {

        img.eq(sel).css('z-index', '2');

        a.click(function (e) {
            e.preventDefault();
            if (!fading && sel != jQuery.inArray(this, a)) {
                sel = jQuery.inArray(this, a);
                changeImg();
            }
        });

        next.click(function (e) {
            e.preventDefault();
            if (!fading) {
                if (sel == a.length - 1) { sel = 0; }
                else { sel++; }
                changeImg();
            }
        });

        prev.click(function (e) {
            e.preventDefault();
            if (!fading) {
                if (sel == 0) { sel = a.length - 1; }
                else { sel--; }
                changeImg();
            }
        });

        function changeImg() {
            fading = true;
            a.removeClass('selected');
            a.eq(sel).addClass('selected');
            img.eq(sel).css({
                'opacity': 0,
                'z-index': 3
            }).animate({ 'opacity': 1 }, function () {
                img.not(img.eq(sel)).css('z-index', '1');
                img.eq(sel).css('z-index', '2');
                fading = false;
            });
        }
    }
    else { jQuery('.actionShotControls').css('display', 'none'); }
}

function tabNav() {
    var a = $('#tabNav a'), selected,
		content = $('.tabBox .tabContent'),
		video;

    a.click(function (e) {
        e.preventDefault();
        selected = $.inArray(this, a);
        a.parent().removeClass('selected');
        a.eq(selected).parent().addClass('selected');
        content.css('z-index', '1');
        content.eq(selected).css('z-index', '10');

        if (document.getElementById('theVideo')) {
            video = document.getElementById('theVideo');
        }
        if (!this.className.match('hasVideo')) {
            if (document.getElementById('theVideo')) {
                video.pauseVideo();
            }
        }
    });
}

function colorOpt() {
    var a = jQuery('.colorOptions a:not(".disableZoom")');
    a.click(function () {
        a.removeClass('selected');
        this.className = 'selected';
    });
    jQuery('.colorOptions a.disableZoom').click(function (e) {
        return false;
    });
}

function newsLetterFlyout() {
    var newsFlyout = jQuery('#newsFlyoutWrap'),
		close = jQuery('#newsFlyoutWrap .closeFlyout'),
		newsAnchor = jQuery('#newsSignup'),
		linkPos, flyoutHeight;

    newsAnchor.click(function (e) {
        e.preventDefault();

        newsFlyout.css('display', 'block');

        flyoutHeight = newsFlyout.height();
        linkPos = jQuery(this).offset();

        newsFlyout.css({
            'left': linkPos.left,
            'top': (linkPos.top - flyoutHeight)
        });

    });

    close.click(function (e) {
        e.preventDefault();
        newsFlyout.css('display', 'none');
    });
}

function setFlyout() {
    var flyout = jQuery('#flyoutWrap'),
		contentArea = flyout.find('.flyoutContent'),
		modal = jQuery('#modal'),
		openLink = jQuery('.detailFlyout'),
		overlay = jQuery('#overlay'),
        flyoutCont = jQuery('#flyout'),

		closeLink = jQuery('.closeFlyout, #modal .submit .bigOrangeButton');


    if (document.getElementById('newsFlyout')) {
        var requiredFields = jQuery('#newsFlyout input.required'),
            newsFlyout = jQuery('#newsFlyoutWrap');
        
        requiredFields.blur(function () {
            var linkPos, flyoutHeight;

            flyoutHeight = newsFlyout.height();
            linkPos = jQuery('#newsSignup').offset();

            newsFlyout.css({
                'left': linkPos.left,
                'top': (linkPos.top - flyoutHeight)
            });
        });
    }

    openLink.click(function (e) {
        e.preventDefault();

        var con = jQuery(this).parent().find('.detailContent').html();
        contentArea.html(con);

        flyoutCont.css('display', 'block');

        flyoutHeight = flyout.height(),
		linkPos = jQuery(this).offset();
      
        flyout.css({
            'left': linkPos.left,
            'top': (linkPos.top - flyoutHeight),
            'display': 'block'
        });
        jQuery('.flyoutContent input[type=text]').clearOnFocus();
    });

    closeLink.click(function (e) {
        e.preventDefault();
        flyout.css('display', 'none');
        flyoutCont.css('display', 'none');
        if (overlay) {
            overlay.css('display', 'none');
        }
        if (modal) {
            modal.css('display', 'none');
        }
    })
}

function setBgSlider() {
    var stage = jQuery('#bgStage'),
		imgs = stage.find('img'),
		titles = stage.find('.title'),
		controls = jQuery('#controls a').not('#prev').not('#next'),
		prev = stage.find('#prev'),
		next = stage.find('#next'),
		current = 0, curImg, curTitle, timer;

    timer = setInterval(
		function () {

		    imgs.eq(current).css('z-index', 5);
		    titles.eq(current).css('z-index', 6);

		    current++;
		    if (current == controls.length) { current = 0; }

		    change();
		}, 5000
	);

    controls.click(function (e) {
        e.preventDefault();
        clearInterval(timer);
        imgs.eq(current).css('z-index', 5);
        titles.eq(current).css('z-index', 6);

        current = jQuery.inArray(this, controls);
        change();
    });

    // Fix z-indexing...
    function change() {
        controls.removeClass('selected');
        controls.eq(current).addClass('selected');

        curImg = imgs.eq(current);
        curTitle = titles.eq(current);

        curTitle.css('z-index', 15);
        curImg.css('z-index', 10);

        curTitle.animate({ 'left': 490 });
        curImg.animate({ 'left': 0 },
		function () {
		    jQuery(titles).not(curTitle).css({
		        'left': 1900,
		        'z-index': 1
		    });
		    jQuery(imgs).not(curImg).css({
		        'left': -1900,
		        'z-index': 1
		    });
		    curTitle.css('z-index', 16);
		    curImg.css('z-index', 11);
		});
    }

    next.click(function (e) {
        e.preventDefault();
        clearInterval(timer);
        imgs.eq(current).css('z-index', 5);
        titles.eq(current).css('z-index', 6);

        current++;
        if (current == controls.length) { current = 0; }
        change();
    });

    prev.click(function (e) {
        e.preventDefault();
        clearInterval(timer);
        imgs.eq(current).css('z-index', 5);
        titles.eq(current).css('z-index', 6);

        current--;
        if (current == -1) { current = (controls.length - 1); }
        change();
    });

}

function navHover() {
    var li = jQuery('#primaryNav>div>ul>li');
    li.hover(
		function () { jQuery(this).addClass('hover'); },
		function () { jQuery(this).removeClass('hover'); }
	);
}

function setProdPopups() {
    var a = jQuery('a.popup');

    a.click(function (e) {
        e.preventDefault();
        // openWindow(this.href, this.title, { height: '400', width: '900' });
        var win = window.open(this.href, 'title', 'height = 400, width = 900', status = 1, scrollbars = 1);
        win.focus();
    });
}

function openWindow(url, name, specs, replace) {
    var _url = "";
    var _name = "_blank";
    var _replace = false;
    // assign site defaults in _specs, remove fields you don't need
    var _specs = {
        height: 500,
        width: 900,
        location: 'yes',
        menubar: 'no',
        resizable: 'yes',
        scrollbars: 'yes',
        status: 'yes',
        titlebar: 'yes',
        toolbar: 'no'
    };
    if (url) { _url = url; }
    // cleans up name so it doesn't cause ie6 errors
    if (name) { _name = name.replace(/[\s-]*/g, ""); }
    if (replace) { _replace = replace; }
    jQuery.extend(_specs, specs);
    specs = "";
    for (var key in _specs) {
        if (specs.length !== 0) { specs += ","; }
        specs += key + '=' + _specs[key];
    }
    var win = window.open(_url, _name, specs, _replace);
    win.focus();
    return false;
}

// jquery plug in to clear input/textareas on focus
// just add class="clearOnFocus" and call $('.clearOnFocus').clearOnFocus(); when DOM ready
(function (jQuery) {
    jQuery.fn.extend({
        clearOnFocus: function () {
            return this.each(function () {
                var obj = jQuery(this);
                if (obj.attr('type') == 'text') {
                    obj.focusin(
						function () {
						    if (this.value == this.defaultValue) {
						        this.value = '';
						    }
						}
					);
                    obj.focusout(function () {
                        if (this.value == '' || jQuery.trim(this.value) == '') {
                            this.value = this.defaultValue;
                        }
                    }
					);
                }
                if (obj[0].tagName == 'TEXTAREA') {
                    var tempVal = obj.val();
                    obj.focusin(
						function () {
						    if (obj.val() == tempVal) {
						        obj.val('');
						    }
						}
					);
                    obj.focusout(
						function () {
						    if (obj.val() == '' || jQuery.trim(obj.val()) == '') {
						        obj.val(tempVal);
						    }
						}
					);
                }
            });
        }
    });
})(jQuery);

(function(jQuery) {

jQuery.fn.enterKey = function(selector) {
	return this.each(function() {
		jQuery(this).keypress(function(e) {
			if(e.which == 13) {
				jQuery(selector).each(function() {
					if(this.tagName == 'A') {
						var href = this.href.replace(window.location,"");
						if(href.indexOf('javascript') >= 0) {
							eval(unescape(this.href.replace(/^javascript:/i,"")));
						}
						else {
							this.onclick();
						}
						e.preventDefault();
					}
					else if(this.tagName == 'INPUT' || this.tagName == 'BUTTON') {
						this.click();
						e.preventDefault();
					}
					else if(this.tagName == 'FORM') {
						this.submit();
					}
				});
			}
		});
	});
};

})(jQuery);

function enterKey(e,selector) {
 if(!e) e = window.event;
 var key = e.which;
 if(!key) key = e.keyCode;
 if (key && key == 13) {
  jQuery(selector).each(function() {
   if(this.tagName == 'A') {
    var href = this.href.replace(window.location,"");
    if(href.indexOf('javascript') >= 0) {
     eval(unescape(this.href.replace(/^javascript:/i,"")));
    }
    else {
     this.onclick();
    }
   }
   else if(this.tagName == 'INPUT' || this.tagName == 'BUTTON') {
    this.click();
   }
   else if(this.tagName == 'FORM') {
    this.submit();
   }
  });
  return false;
 }
 return true;
}

function Set_Cookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for (i = 0; i < a_all_cookies.length; i++) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1) {
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return null;
	}
}

function Delete_Cookie(name, path, domain) {
	if (Get_Cookie(name)) document.cookie = name + "=" +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function ResetLanguage() {
	Delete_Cookie('NeckyLanguage', '/', null);
	//window.location = '/language.aspx';
}



