
$(document).ready(function() {

    if($('.logout').length){
		//$('#navigation').css({'top':'45px','z-index':'29'});
		$('#header').css({'height':'185px'});
	};
	$('.field, textarea').focus(function() {
        if(this.title==this.value) {
            this.value = '';
        }
    }).blur(function(){
        if(this.value=='') {
            this.value = this.title;
        }
    });

    // Drop down

    $('#dd-nav > ul > li > .dd > ul').wrap('<div class="dd-bg" />').parent('.dd-bg').before('<div class="dd-t" />').after('<div class="dd-b" />');
    $('.footer-nav .mainbar .mainmenu:nth-child(1)').hide();
    $('.footer-nav .mainbar .mainmenu:nth-child(2)').css('background','none');
    $('#navigation .dd').each(function() {
        $parent = $(this).parent();
        $(this).css('left', -1 * ( ($(this).width() - $parent.width()) / 2 ) );
    });
    $('#navigation ul li').hover(function(){
        $(this).find('.dd:eq(0)').stop(true,true).slideDown();
        $(this).find('a:eq(0)').addClass('hover');
     },
     function(){  
        $(this).find('.dd').stop(true,true).slideUp();
        $(this).find('a:eq(0)').removeClass('hover');
    });
	
	if ($('.flexslider').length) {
        // Main homepage Slider   
        $(".flexslider li").each(function () {
            var img_src = 'url(' + $(this).find('img').attr('src') + ')';
            $(this).css({
                'background-image': img_src
            });
            $(this).find('img').hide();
        });
        $(".flexslider ul").innerfade({
            'exactChildren': $('.slider .flexslider li'),
            'effect': 'fade',
            'timeout': 6000,
            'speed': 1000,
            'containerheight': '711px'
        });

        /*$('.slider-nav li a').live('click', function() {
            var idx = parseInt($(this).parent('li').attr('class').split('slider-thumb-')[1]);
            $('.flex-image').fadeOut(1000);
            $('#flex-image-' + idx).fadeIn(1000);
            return false;
        });*/
    };

    if ($('.scroll-pane').length) {
        // Scroll Pane
        $('.scroll-pane').jScrollPane();
    };

    // Home page info box
    $('.slider-box-button a').click(function() {
        var sliderboxHeight = $('.slider-box').height();
        if ( sliderboxHeight < 450 ) {
            $('.slider-box').animate({
                height: '461px'
              }, 500)
            $(this).html('Close &gt;&gt;');
            $('.slider-content').fadeIn();
        } else if ( sliderboxHeight > 450 ) {
            $('.slider-box').animate({
                height: '170px'
             }, 500)
              $(this).html('More &gt;&gt;')
            $('.slider-content').fadeOut();
        };
        return false;
    });


    // Footer images 
    $('.footer-box .mini-gallery a').hover(function  () {
        $(this).find('img').stop(true,true).fadeTo('fast', 0.5)
    }, function function_name (argument) {
        $(this).find('img').fadeTo('fast',1)
    });

    $('.more-photos-link').click(function() {
        if ($(this).hasClass('photos-shown')) {
            $('.more-photos').animate({
                'height': '4px'
            }, 400);
            $(this).removeClass('photos-shown');
        } else {
            $('.more-photos').animate({
                'height': '123px'
            }, 400);
            $(this).addClass('photos-shown');
        };
        
        return false;
    });


    // Photo thumb Slider
    (function() {
        //photo thumb slider not needed if not enough thumbnails
        if ($('.slider-nav li').length * $('.slider-nav li').outerWidth(true) < $(document).width() ) return;


        var slider = $('.more-photos');
        var ul = slider.find('ul');
        
        var animation = null;
        
        ul.wrap('<div class="slider-wrapper" />');
        ul.each(function() {
            var ul = $(this);
            var lis = ul.find('li');
            
            
            ul.width(lis.length * lis.outerWidth(true) * 3).css('left',-1*lis.length * lis.outerWidth(true));
            lis.clone().appendTo(ul)
            lis.clone().prependTo(ul);
        });
        
        function animationStart() {
           
            animationStop();
            
            animation = setInterval(function() {

                var left = parseInt(ul.css('left'));
                if (Math.abs(left) * 3 > ul.width()) {
                    ul.css('left', 0 );
                } else {
                    ul.css('left', left - 1 + 'px');
                }


            }, 16);
        }

        function animationStartRight() {
            animationStop();
            
            animation = setInterval(function() {

                var left = parseInt(ul.css('left'));
                if ( left == 0 ) {
                    ul.css('left', -2 * ( ul.width()/3 ) );
                } else {
                    ul.css('left', left + 1 + 'px');
                }

            }, 16);
        }
        
        function animationStop() {
            clearInterval(animation);
            animation = false;
        }
        
        animationStart();
        
        ul.hover(function() {
            animationStop();
        }, function() {
            animationStart();
        });

        $('.more-photos .right-arrow').mouseover(function() {
           animationStart();
        });

        $('.more-photos .left-arrow').mouseover(function() {
           animationStartRight()      
        });
        
       
    })();



    // Contact form 
    /*$('.contact-form .field-row').each(function(i) {
        $(this).addClass('row-' + (i+1));
    });
    $('.contact-form .row-7').append('<p>I would you like to receive more info about these communities.</p>');*/
    
    /*var checkboxes_col_1 = $('.contact-form .row-8, .contact-form .row-9, .contact-form .row-10, .contact-form .row-11, .contact-form .row-12, .contact-form .row-13').clone(true, true);
    $('.contact-form .row-8, .contact-form .row-9, .contact-form .row-10, .contact-form .row-11, .contact-form .row-12, .contact-form .row-13').hide();
    $('.contact-form .row-7').after('<div class="checkboxes checkboxes-1"></div>').next('.checkboxes').append(checkboxes_col_1);

    var checkboxes_col_2 = $('.contact-form .row-14, .contact-form .row-15, .contact-form .row-16, .contact-form .row-17, .contact-form .row-18, .contact-form .row-19').clone(true, true);
    $('.contact-form .row-14, .contact-form .row-15, .contact-form .row-16, .contact-form .row-17, .contact-form .row-18, .contact-form .row-19').remove();
    $('.contact-form .checkboxes-1').after('<div class="checkboxes checkboxes-2"></div>').next('.checkboxes').append(checkboxes_col_2);

    var checkboxes_col_3 = $('.contact-form .row-20, .contact-form .row-21, .contact-form .row-22, .contact-form .row-23, .contact-form .row-24').clone(true, true);
    $('.contact-form .row-20, .contact-form .row-21, .contact-form .row-22, .contact-form .row-23, .contact-form .row-24').remove();
    $('.contact-form .checkboxes-2').after('<div class="checkboxes checkboxes-3"></div><div class="cl">&nbsp;</div>').next('.checkboxes').append(checkboxes_col_3);*/
	
	//NEW
    if ($('.contact-form').length) {
		$('.contact-form .field-row').each(function(i) {
			$(this).addClass('row-' + (i+1));
		});
		$('.contact-form .row-7').append('<p>I would you like to receive more info about these communities.</p>');
		
		var checkboxes = $('.field-row table td input[type="checkbox"]');
		checkboxes.first().parents('.field-row').hide();
		var checkboxLength = checkboxes.length;
		var firstCol = Math.ceil(checkboxLength/3);
		var secondCol = firstCol*2;
		$('.contact-form .row-7').after('<div class="checkboxes checkboxes-1"></div>');
		$('.contact-form .checkboxes-1').after('<div class="checkboxes checkboxes-2"></div>');
		$('.contact-form .checkboxes-2').after('<div class="checkboxes checkboxes-3"></div><div class="cl">&nbsp;</div>');
		for(i=0;i<firstCol;i++){
			var _this = checkboxes.eq(i);
			_this.add(_this.next('label')).wrapAll('<div class="field-row" />');
			_this.parent().clone(true,true).appendTo('.contact-form .checkboxes-1');
		};
		for(i=firstCol;i<secondCol;i++){
			var _this = checkboxes.eq(i);
			_this.add(_this.next('label')).wrapAll('<div class="field-row" />');
			_this.parent().clone(true,true).appendTo('.contact-form .checkboxes-2');
		};
		for(i=secondCol;i<checkboxLength;i++){
			var _this = checkboxes.eq(i);
			_this.add(_this.next('label')).wrapAll('<div class="field-row" />');
			_this.parent().clone(true,true).appendTo('.contact-form .checkboxes-3');
		};
		checkboxes.first().parents('.field-row').remove();
		
		$('.contact-form').jqTransform();
	};
    
    /*if ($('.contact-form').length) {
        $('.contact-form').jqTransform();
    };*/
    
    // Search Bar 
    if ($('.search-bar .form').length) {
        $('.search-bar .form').jqTransform();
    };
    


    // bottom nav
    var ulWidth = $('.bottom-nav ul').width();
    var navHolder = $('.bottom-nav .nav-holder').width();
    var centerNav = (navHolder - ulWidth) / 2;
    $('.bottom-nav ul').css('paddingLeft', centerNav);


    // Gallery 
    (function() {
        //Loading big images
        $('.single-gallery .big-image').css({
            'background-image': 'url(/resources/1/sk/images/ajax-loader.gif)',
            'background-repeat': 'no-repeat',
            'background-position': 'center center'
        })
        var images_length = $('.single-gallery .gallery-thumnails img').length;
        $('.single-gallery .gallery-thumnails img').each(function(i) {
            var src = $(this).parent().attr('href');

            $('<img src="' + src + '" alt="" />')
                .css('z-index', images_length-i)
                .appendTo('.single-gallery .big-image')
                .load(function() {
                    if (i == images_length-1) {
                        //Images are loaded
                        $('.single-gallery .big-image').css('background-image', 'none');
                        $('.single-gallery .big-image img:eq(0)').fadeIn();
                    };
                
                });
            
        });

        $('.gallery-thumnails ul li:eq(0) a:not(.editButton)').addClass('active');
		var imageTitleDiv = $('.single-gallery').find('.imageTitle');
		if(imageTitleDiv.length){
			var imageTitle = $('.gallery-thumnails ul li:eq(0) a:not(.editButton)').attr('rel');
			imageTitleDiv.text(imageTitle);
		};
        $('.gallery-thumnails ul li a:not(.editButton)').click(function() {
            var idx =  $(this).parent('li').index();
            $('.gallery-thumnails ul li a').removeClass('active');
            $(this).addClass('active');
            $('.big-image img').fadeOut(800);  
            $('.big-image img').eq(idx).fadeIn(800);
			var imageTitleDiv = $(this).parents('.single-gallery').find('.imageTitle');
			if(imageTitleDiv.length){
				var imageTitle = $(this).attr('rel');
				imageTitleDiv.text(imageTitle);
			};
            return false;
        });
    })();

    // Footer gallery
    
    if ($('.footer-box .mini-gallery a').length) {
        $('.footer-box .mini-gallery a:not(.editButton)').colorbox({
            //rel:'gal', 
            maxWidth: 900,
            photoLink: true,
            onLoad: function() {
                $('#colorbox').addClass('colorbox-style2');
            },
            onClosed: function() {
                $('#colorbox').removeClass('colorbox-style2');
            }
        });
    };

    if ($('.content p.more a').length) {
        $('.content p.more a').colorbox({
            inline:true,
            onLoad: function() {
                $('#colorbox').addClass('colorbox-nobg');
            },
            onClosed: function() {
                $('#colorbox').removeClass('colorbox-nobg');
            }
        });    
    };
    

    $('a.close-button').click(function  () {
        $('#cboxClose').trigger('click');
        return false;
    })

    if ($('a.colorbox').length) {
        $('a.colorbox').colorbox({
            maxWidth: 900,
            photoLink: true,
            onLoad: function() {
                $('#colorbox').addClass('colorbox-style2');
            },
            onClosed: function() {
                $('#colorbox').removeClass('colorbox-style2');
            }
        });
    };

    $('.slider-nav li a:not(.editButton)').mouseenter(function  () { 
          if ($(this).hasClass('colorbox')) return;

          var positionTop = parseInt($(this).offset().top) - 355 + 'px' , 
              positionLeft = parseInt($(this).offset().left) - 194 + 'px';

          $('.nav-popup').fadeIn();
          $('.nav-popup').css('left', positionLeft);
          $('.nav-popup').css('top', positionTop);

          $('.nav-popup img').attr('src', $(this).attr('rel') );
          $('.nav-popup p').html( $(this).attr('title') );

    }).mouseleave(function  () {
          if ($(this).hasClass('colorbox')) return;
          $('.nav-popup').hide();
    });

    $('.search-bar .submit').live('click', function() {

        //values from search bar
        var search = {
            'bedrooms': $('#select-bedrooms').val() == '' ? 0 : parseInt($('#select-bedrooms').val()),
            'baths': $('#select-baths').val() == '' ? 0 : parseFloat($('#select-baths').val()),
            'levels': $('#select-levels').val() == '' ? 0 : parseInt($('#select-levels').val()),
            'garages': $('#select-garages').val() == '' ? 0 : parseInt($('#select-garages').val()),
            'footage': $('#select-footage').val() == '' ? 0 : parseInt($('#select-footage').val())
        };

        var footage_bounds = [ 1000, 2000, 3000, 4000 ]; 

        $('.plans .communitie-post').each(function() {
            var $this = $(this);

            //values from each plan
            var plan = {
                'bedrooms': $(this).attr('data-bedrooms') == '' ? 0 : parseInt($(this).attr('data-bedrooms')),
                'baths': $(this).attr('data-baths') == '' ? 0 : parseFloat($(this).attr('data-baths')),
                'levels': $(this).attr('data-levels') == '' ? 0 : parseInt($(this).attr('data-levels')),
                'garages': $(this).attr('data-garages') == '' ? 0 : parseInt($(this).attr('data-garages')),
                'footage': $(this).attr('data-footage') == '' ? 0 : parseInt($(this).attr('data-footage').split(' - ')[0])
            };

            //flag showing if plan is in square footage bounds
            var is_in_footage_bounds = false;

            for (var i = 0; i < footage_bounds.length; i++) {
                if ( plan.footage >= footage_bounds[i] && plan.footage < footage_bounds[i+1] && search.footage == footage_bounds[i] ) {
                    is_in_footage_bounds = true;
                };
            };
            
            //if plan values are equal to search values OR search values are default ( 0 ), show current plan, otherwise hide it
            if (
                (plan.bedrooms == search.bedrooms || search.bedrooms == 0) && 
                (plan.baths == search.baths || search.baths == 0) && 
                (plan.levels == search.levels || search.levels == 0) && 
                (plan.garages == search.garages || search.garages == 0) && 
                (is_in_footage_bounds || search.footage == 0)
               )
            {
                $(this).show();
            } else {
                $(this).hide();
            };

        });
        
        return false;
    });


    //initial page drag movement
    var drag_min_left = 112;
    var drag_max_left = 421;
    var drag_move = false;

    function dragStart(e) { if ($(e.target).is('.drag')) drag_move = true; };
    function dragStop(e) { 
        drag_move = false; 
        if ( parseInt($('.drag').css('left')) == drag_min_left ) {
            window.location = 'http://' + window.location.host + '/sk.aspx';
        };
        if ( parseInt($('.drag').css('left')) == drag_max_left ) {
            window.location = 'http://' + window.location.host + '/ma.aspx';
        };
    };
    function dragMove(e) {
        if (drag_move) {
            var newLeft = e.pageX - $('#initial').offset().left ;

            if( newLeft < drag_min_left )
                newLeft = drag_min_left;

            if( newLeft > drag_max_left )
                newLeft = drag_max_left;

            $('.drag').css({
                left: newLeft
            })   
        };
        
    };

    $(document).mousedown(dragStart).mousemove(dragMove).mouseup(dragStop);

    
    //home plans ordered by square footage
    (function() {
        var plans_arr = new Array();
        var plans = $('.plans.pickPlans > .communitie-post').remove();
        var ordered_plans = $('<div class="ordered"></div');
        for (var i = 0; i < plans.length; i++) {
            plans_arr.push( [$(plans[i]).attr('data-footage'), $(plans[i])] );
        };
        plans_arr.sort(function(a,b) { return a[0] - b[0] });    
        for (var i = 0; i < plans_arr.length; i++) {
            ordered_plans.append(plans_arr[i][1]);
        };
        $('.plans.pickPlans').append(ordered_plans).fadeIn(1000);
    })();
    
});





