var fancyboxRedirectUrl = "";

//var curvyCornersVerbose = false;

(function ($) {
    var zIndex = 999;
    $.fn.select = function () {
        return this.each(function () {

            // init
            var $select,
				$select_div,
				$select_ul,
				$select_options,
				select_title;

            $select = $(this);

            var sortable = 0;
            if( $select.attr('id') == "community-sort-by-filter" ){
                sortable = 1;
            }

            $select.css({ display: 'none' });

            $select_div = $select.wrap('<div class="select"></div>').parent().css({ zIndex: --zIndex });
            $select_ul = $select_div.prepend('<div class="ul-holder"></div>').children().eq(0);
            $select_ul = $select_ul.prepend('<ul></ul>').children().eq(0);
            $select_options = $('option', $(this));

            var shift_options = false;
            for (var i = 0; i < $select_options.length; i++) {
                if( $select_options.eq(i).val() == "" && sortable ){
                    shift_options = true;
                } else {
                    $select_ul.append('<li><a href="#">' + $select_options.eq(i).text() + '</a></li>');
                }
            }
            if (shift_options) {
                $select.change(function () {
                    this.selectedIndex++;
                });
            }
            select_title = $select_options.eq($select[0].selectedIndex).text();
            $select_div.prepend('<a href="#" class="btn">' + select_title + '</a>');

            // events
            $select_div.find(".btn").click(function () {
                var ul = $(this).parent().find('.ul-holder');
                var visible = ul.is(':visible');
                $('.select .ul-holder:visible').hide();
                if (visible) ul.show();
                $(this).parent().find('.ul-holder').slideToggle(200);
                return false;
            });
            $select_div.find("li a").click(function () {
                var div = $(this).parents('.select');
                div.find('select')[0].selectedIndex = div.find('li a').index(this);
                div.find('select').change();
                div.find('.btn').text($(this).text());
                div.find('.ul-holder').slideUp();
                return false;
            });
            $(document).click(function (e) {
                if (!$(e.target).parents().hasClass('select')) {
                    $('.select .ul-holder').slideUp();
                }
            });

        });
    };
})(jQuery);

function handlePasswordFields() {
          
    var pField = $('.password-field');
    var pClip = $('.password-clip');

    //show and populate the correct password field when the page loads
    if (pField.val() != '') {
      pField.show();
      pClip.hide();
    } else {
      pField.hide();
      pClip.show();
    }

    //add the password label just in case it doesn't get added becase of browser caching
    pClip.val(pClip.attr("title"));
    
    //clear the password field of the label
    pClip.focus(function () {
        $(this).hide();
        $(this).next().show().focus();
    });
  
    //populate the values after they're edited  
    pField.blur(function () {
        if ($(this).val() == '') {
          pField.hide();
          pClip.show();
        };     
    });

}

function ValidatePhone(phoneVal) {
    var phoneRegExp = /^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}$/;
    var numbers = phoneVal.split("").length;
    if (10 <= numbers && numbers <= 20 && phoneRegExp.test(phoneVal)) {
        return true;
    }
    return false;
}

function SubmitForm(obj) {

    var $form = $(obj);

//    $form.submit(function () {

        var isValid = true;

        $form.find('input[type="text"].required, input[type="password"].required, select.required, textarea.required').each(function () {
            if ($(this).val() == $(this).attr('title') || $(this).val().length == "") {
                if ($(this).attr('class').indexOf('password-clip') == -1) {
                    isValid = false;
                    $(this).val("");
                    $(this).addClass('error');
                    $(this).parents('.row').filter(':first').find('.errorbox-error-msg').show();
                }
                else if ($(this).next('.password-field').val().length == "") {
                    $(this).next('.password-field').addClass('error');
                }
            };

        });

        $form.find('input.phone').each(function () {
            if ($(this).val() != $(this).attr("title")) {
                if (ValidatePhone($(this).val())) {
                    $(this).removeClass('error');
                    $(this).parents('.row').filter(':first').find('.errorbox-error-msg').hide();
                }
                else {
                    $(this).addClass('error');
                    $(this).parents('.row').filter(':first').find('.errorbox-error-msg').show();
                    isValid = false;
                }
            }
            else {
                //$(this).val("");
            }
        });

        return isValid;
  //  });
}

jQuery(document).ready(function ($) {

    //handlePasswordFields();

    $('input[type="text"], textarea').each(function () {
        if ($(this).val() != $(this).attr('title')) {
            $(this).val($(this).val());
        };
    });

    $('.blink').live('focus', function () {
        if ($(this).val() == $(this).attr('title')) {
            $(this).val('');
        }
    }).live('blur', function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
        }
        else if ($(this).attr("class").indexOf("phone") > 1 && $(this).val() != $(this).attr("title")) {
            if (ValidatePhone($(this).val())) {
                $(this).removeClass('error');
                $(this).parents('.row').filter(':first').find('.errorbox-error-msg').hide();
            }
            else {
                $(this).addClass('error');
                $(this).parents('.row').filter(':first').find('.errorbox-error-msg').show();
            }
        }
        else {
            $(this).removeClass('error');
            $(this).parents('.row').filter(':first').find('.errorbox-error-msg').hide();
        }
    });

    $('.password-clip').live('focus', function () {
        $(this).hide().next('.password-field').show().focus();
    })

    $('.password-clip').each(function () {
        $(this).val($(this).attr("title"));
    });

    $('.password-field').hide().live('blur', function () {
        if ($(this).val() == '') {
            var $pClip = $(this).hide().prev('.password-clip');
            $pClip.show();
            $pClip.val($pClip.attr("title"));
        }
        else {
            if ($(this).attr('class').indexOf('password-clip') > -1) {
                $(this).next('.password-field').removeClass('error');
            }
            $(this).removeClass('error');
            $(this).parents('.row').filter(':first').find('.errorbox-error-msg').hide();
        }
    })

    $('input.field-password-holder').live('focus', function () {
        $(this).hide().next('input.field-password').show().focus();
    });
    $('input.field-password').live('blur', function () {
        if ($(this).val() == '') {
            $(this).hide().prev('input.field-password-holder').show();
        };

    });

    $('.select').live('mouseover', function () {
        $(this).addClass('select-active');
    }).live('mouseout', function () {
        $(this).removeClass('select-active');
    });

    $('.dropdown').live('change', function () {
        if ($(this).val() != '') {
            $(this).removeClass('error');
            $(this).parents('.row').filter(':first').find('.errorbox-error-msg').hide();
        }
    });


    //this handles the home page slider
    if ($('#slider').length) {
        //remove initial slider dots, if present
        $('#slider .slider-controls a').remove();
        function disablePrevNext() {
            $('#slider .slider-navigation a.prev, #slider .slider-navigation a.next').attr('disabled', 'disabled');
            //console.log( 'disable' );
        }
        function enablePrevNext() {
            $('#slider .slider-navigation a.prev, #slider .slider-navigation a.next').removeAttr('disabled');
            //console.log( 'enable' );
        }
        $('#myLink').click(function (e) {
            e.preventDefault();
            //do other stuff when a click happens
        });

        $("#slider ul").cycle({
            fx: 'scrollHorz',
            speed: 1500,
            timeout: 10000,
            pager: '#slider .slider-controls',
            prev: '#slider .slider-navigation a.prev:not(disabled)',
            next: '#slider .slider-navigation a.next:not(disabled)',
            fit: true,
            pause: 1,
            before: disablePrevNext,
            after: enablePrevNext,
            manualTrump: false
        });

        //trying to fix a bug that JP discovered where an image goes missing when the window is resized
        $(window).resize(function () {
            $('#slider li').width($(this).width());
        });
    };

    //this is not the home-page slider. It may or may not exist elsewhere in the site.
    if ($('.featured-slider').length && $("#featured-slider-center ul li").length > 1) {

        // get current slide's number
        function currentSlide() {
            var hash = window.location.hash || '#photo-1';
            return parseInt(hash.replace(/[A-Za-z#\-\/!]/g, '') - 1);
        }

        // global vars	
        var cycleSelector = $('.featured-slider ul'),
			startSlide = currentSlide(),
			hasSlid = 0;

        // start jQuery Cycle	
        cycleSelector.cycle({
            startingSlide: startSlide,
            // when using the next/prev links
            onPrevNextEvent: function (isNext, idx, slide) {
                hasSlid = 1;
                window.location.hash = "photo-" + (parseInt(idx) + 1) + "";
                return false;
            },
            timeout: 0,
            next: '.slider-navigation .next',
            prev: '.slider-navigation .prev',
            speed: 300,
            fx: 'scrollHorz',
            manualTrump: false
        });

        // bind to the hashchange event
        $(window).bind('hashchange', function () {
            var slideNo = currentSlide();
            // we only want to fire the slide change if the next button or the pager hasn't done it for us
            if (hasSlid === 0) { cycleSelector.cycle(slideNo); }
            // return it back to zero
            hasSlid = 0;
        });

        // when the page loads, we need to trigger a hashchange
        $(window).trigger("hashchange");

        /*
        $(".featured-slider ul").jcarousel({
            scroll: 1,
            wrap: 'last',
            setupCallback: mycarousel2_initCallback
        });
        */
    };

    /*
    if ($('.featured-slider').length) {

    $(".featured-slider").jCarouselLite({
    btnNext: ".next",
    btnPrev: ".prev",
    visible: 1,
    scroll: 1,
    circular: true
    //beforeStart: mycarousel2_initCallback
    });

    };
    */

    $('.form select').select();

    $('.ul-holder ul').each(function () {
        if ($(this).height() > 200) {
            $(this).css('height', '200px');
            $(this).jScrollPane();
        } else {
            $(this).css('height', 'auto');
        };

    });
    $('.ul-holder').hide();

    //fancybox popups
    $('.fancybox.iframe').fancybox({
        href: $(this).attr('href'),
        type: 'iframe',
        overlayOpacity: 0.9,
        overlayColor: '#27446f',
        hideOnOverlayClick: true,
        scrolling: 'auto',
        onComplete: function () {
            $('#fancybox-frame').load(function () { // wait for frame to load and then gets it's height
                $('#fancybox-content').height($(this).contents().find('body').height());

                //set width of popup
                if ($(this).contents().find('#main').length) {
                    $('#fancybox-content').width($(this).contents().find('#main > div').outerWidth());
                    $('#fancybox-wrap').width($(this).contents().find('#main > div').outerWidth() + 20);
                } else {
                    $('#fancybox-content').width(800);
                    $('#fancybox-wrap').width(820);
                };

                $.fancybox.resize();
            });
        },
        onClosed: function () {
            if (jQuery().cycle) {
                $("#slider ul").cycle('resume');
            }
            if (fancyboxRedirectUrl.length > 0) {
                $(location).attr('href', fancyboxRedirectUrl);
            }
            //trying to fix a big in IE8 that messes up fonts
            $('#navigation').css('font-family', 'MuseoSans500');
        }
    });

    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        DD_belatedPNG.fix('#logo a, #header, .btn-contact-us, #slider .slider-controls a, .box-find-home, .homebuying101, .energy-promise, .bottom-cols, #fancybox-close, .box-find, .box-filter-results, .map-tooltip-b, .map-tooltip-t, .box-results .result-entry .flag, .box-results .result-entry .flag2, .box-find .field-search');
    };

    /*$('.box-results .btn-minimize').click(function () {
    $(this).toggleClass('expand');
    $(this).parent('.box-results-head').next('.box-results-body').toggle();
    return false;
    });*/

    if ($('.tt').length) {
        $('.tt').bt();
    };
    if ($('.icon-help').length) {
        $('.icon-help').bt({
            positions: 'right'
        });
    };
    if ($('.tt-orange').length) {
        $('.tt-orange').bt({
            fill: '#fa892f',
            width: '110px',
            padding: '10px 4px',
            positions: ['top'],
            spikeLength: 10,
            spikeGirth: 20,
            strokeWidth: '0',
            strokeStyle: "#336699",
            cornerRadius: 4,
            wrapperzIndex: 9997,
            shadow: false,
            shadowBlur: 5,
            shadowColor: 'rgba(0,0,0,0.5)',
            shadowOverlap: '-5',
            cssClass: 'tt-orange'
        });
    };

    $('.model-compare').click(function () {
        $(this).toggleClass('model-compare-active');
        return false;
    });

    $('.topbar .btn-search').click(function () {
        $(this).next('.search-dd').stop(true, true).slideDown();
        return false;
    });
    $('body').click(function (e) {
        if (!$(e.target).parents('.search').length) {
            $('.topbar .search-dd').stop(true, true).slideUp();
        };
    });

    $('a.submit').live('click', function () {
        $(this).parents('form').submit();
        return false;
    });

    $('.form-reset').live('click', function () {
        $(this).parents('form')[0].reset();
        $(this).parents('form').find('input[type="text"].required, input[type="password"].required, select.required, textarea.required').each(function () {
            $(this).removeClass('error');
        });
        $(this).parents('form').find('input[type="text"].required, input[type="password"].required, textarea.required').each(function () {
            $(this).val($(this).attr("title")).show();
        });
        $(this).parents('form').find(".errorbox-error-msg").each(function () {
            $(this).hide();
        });
        $(this).parents('form').find(".error-msg").each(function () {
            $(this).hide();
        });
        $(this).parents('form').find('.password-field').hide().end().find('.password-clip').each(function () {
            $(this).val($(this).attr("title")).show();
        });
        $(this).parents('form').find('.select .btn').each(function () {
            $(this).text($(this).siblings('select').attr('title') == '' || typeof ($(this).siblings('select').attr('title')) == 'undefined' ? $(this).siblings('select').val() : $(this).siblings('select').attr('title'));
        });
        return false;
    });

    /*
    $('.form-reset').live('click', function () {
    $(this).parents('form')[0].reset();
    $(this).parents('form').find('.select .btn').each(function () {
    $(this).text($(this).siblings('select').find('option').eq($(this).siblings('select')[0].selectedIndex).text());
    });
    $(this).parents('form').find('input').each(function () {
    $(this).val($(this).attr("title"));
    });
    return false;
    });
    */

    $('.featured-content .model').hover(
		function () {
		    $(this).addClass('model-hover');
		},
		function () {
		    $(this).removeClass('model-hover');
		}
	);

    $('.home-thumb').hover(
		function () {
		    $(this).addClass('home-thumb-hover');
		},
		function () {
		    $(this).removeClass('home-thumb-hover');
		}
	);
    $('.items .item').hover(
		function () {
		    $(this).addClass('item-hover');
		},
		function () {
		    $(this).removeClass('item-hover');
		}
	);

    $('.home-entry .show-more').click(function () {
        $(this).hide().next('.hidden').show();
        return false;
    });
    $('.home-entry .show-less').click(function () {
        $(this).parent('.hidden').hide().prev('.show-more').show();
        return false;
    });

    //delete this after 10-24-11 if the sign-in box is hiding and showing properly on its own
    /*$('.topbar li').hover(
    function () {
    if ($(this).find('.dd').length) {
    $(this).find('a:eq(0)').addClass('active');
    $(this).addClass('active').find('.dd').show();
    };

    },
    function () {
    if ($(this).find('.dd').length) {
    $(this).find('a:eq(0)').removeClass('active');
    $(this).find('.dd').hide();
    };
    }
    );*/

    $('.items .item-head .close').live('click', function () {
        $(this).next('.close-confirmation').show();
        return false;
    });
    $('.close-confirmation .close-yes').live('click', function () {
        $(this).parents('.item').remove();
        return false;
    });
    $('.close-confirmation .close-no').live('click', function () {
        $(this).parents('.close-confirmation').hide();
        return false;
    });

    if ($('.item .icon-move').length) {
        $('.items ul').sortable({
            handle: '.icon-move',
            placeholder: "placeholder"
        });
        $(".items ul").disableSelection();
    };

    $(window).load(function () {
        if (($.browser.msie && $.browser.version > 6) || !$.browser.msie) { // || !$.browser.webkit) {
            imgGrayScale('#featured-slider-left li img, #featured-slider-right li img');
        }
    });

    $('.box-results').draggable();

    /*
    $('.result-tabs-head li a').click(function () {
    var href = $(this).attr('href');
    $('.result-tabs-head li a').removeClass('active');
    $(this).addClass('active');

    $('.result-tabs-body .result-tab').hide();
    $(href).show();

    return false;
    });
    */

    $('.compare-confirmation .compare-close').live('click', function () {
        $(this).parents('.compare-confirmation').hide();
        return false;
    });

    $('#models-compare-button').live('click', function () {

        var marketingProductIds = "";
        $('.compare-confirmation').hide();

        if ($('.model-compare-active').length < 2 || $('.model-compare-active').length > 4) {
            $('.compare-confirmation').show();
            $('.compare-confirmation').parents('.item-head').css('height', 0);
        }
        else {
            $('.model-compare').each(function () {
                if ($(this).attr("class").indexOf("model-compare-active") > -1) {
                    marketingProductIds += $(this).attr("id") + ",";
                }
            });

            if (marketingProductIds.length > 1) {
                var compareType = $(this).attr("compareType") == undefined ? "mp" : $(this).attr("compareType");
                marketingProductIds = marketingProductIds.substr(0, marketingProductIds.length - 1);
                $("#fancybox-compare").attr("href", $(this).attr("href") + "?modelIds=" + marketingProductIds + "&compareType=" + compareType);
                $("#fancybox-compare").trigger("click");
                return false;
            }
        }

        return false;
    });


    $("input").keydown(function (event) {
        if (event.keyCode == 13) {
            $(this).parents("form").submit();
            return false
        };
    });

    //search filter reset delete this after 1/25/12
    // $('a.reset-link').not('#locations-search a.reset-link').click(function () {
        // $('#locations-search').data("submit-locked", true);
        // $(this).parents('.box-filter-results').find('ul li').each(function () {
            // $(this).find('.select .ul-holder li:first a').trigger('click');
        // });
        // $('#locations-search').data("submit-locked", false);
        // $('#locations-search').submit();
        // return false;
    // });

    $("a.video-player").click(function () { return false; })
        .each(function (i, item) {
            var srcUrl = $(this).attr("href");
            //fancybox popups
            $(this).fancybox({
                href: "/About/VideoPlayer?srcUrl=" + srcUrl,
                type: 'iframe',
                overlayOpacity: 0.9,
                overlayColor: '#27446f',
                scrolling: 'no',
                onComplete: function () {
                    $('#fancybox-frame').load(function () { // wait for frame to load and then gets it's height
                        $('#fancybox-content').height($(this).contents().find('body').height());
                        //set width of popup
                        if ($(this).contents().find('#main').length) {
                            $('#fancybox-content').width($(this).contents().find('#main > div').outerWidth());
                            $('#fancybox-wrap').width($(this).contents().find('#main > div').outerWidth() + 20);
                        } else {
                            $('#fancybox-content').width(800);
                            $('#fancybox-wrap').width(820);
                        };
                        $.fancybox.resize();
                    });
                },
                onClosed: function () {
                    $("#slider ul").cycle('resume');
                    if (fancyboxRedirectUrl.length > 0) {
                        $(location).attr('href', fancyboxRedirectUrl);
                    }
                }
            });
        });

    /*
    $("a.video-player").live("click", function () {
    var srcUrl = $(this).attr("href");
    //fancybox popups
    $(this).fancybox({
    href: "/About/VideoPlayer?srcUrl=" + srcUrl,
    type: 'iframe',
    overlayOpacity: 0.9,
    overlayColor: '#27446f',
    scrolling: 'no',
    onComplete: function () {
    $('#fancybox-frame').load(function () { // wait for frame to load and then gets it's height
    $('#fancybox-content').height($(this).contents().find('body').height());
    //set width of popup
    if ($(this).contents().find('#main').length) {
    $('#fancybox-content').width($(this).contents().find('#main > div').outerWidth());
    $('#fancybox-wrap').width($(this).contents().find('#main > div').outerWidth() + 20);
    } else {
    $('#fancybox-content').width(800);
    $('#fancybox-wrap').width(820);
    };
    $.fancybox.resize();
    });
    },
    onClosed: function () {
    $("#slider ul").cycle('resume');
    if (fancyboxRedirectUrl.length > 0) {
    $(location).attr('href', fancyboxRedirectUrl);
    }
    }
    });
    return false;
    });
    */



});

function mycarousel2_initCallback(carousel) {
    
	$('.featured-slider .slider-navigation a.next').click(function() {
		carousel.next();
		return false;
	});
	
	$('.featured-slider .slider-navigation a.prev').click(function() {
		carousel.prev();
		return false;
	});	
	
};

function mycarousel2_itemVisibleInCallback(carousel, li, idx, state ) {
	
	$('.featured-slider .caption').fadeOut();
	$(li).find('.caption').fadeIn('slow');
    
};

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

